-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathCopyCat.uc.js
More file actions
1426 lines (1333 loc) · 64.1 KB
/
Copy pathCopyCat.uc.js
File metadata and controls
1426 lines (1333 loc) · 64.1 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 CopyCat.uc.js
// @description CopyCat 资源管理
// @author Ryan
// @version 0.3.4
// @compatibility Firefox 80
// @sandbox true
// @include chrome://browser/content/browser.xhtml
// @include chrome://browser/content/browser.xul
// @shutdown window.CopyCat.destroy();
// @homepageURL https://github.com/benzBrake/FirefoxCustomize
// @note 0.3.4 去除 0.3.3 的修改,使用 @sandbox 注解,修复 PlacesUtils.favicons.getFaviconDataForPage undefined 的问题
// @note 0.3.3 fix unsave eval 使用 sandbox 替代 eval
// @note 0.3.2 修复 precommand / postcommand 触发,修复 pref 菜单 defaultValue 无效,修复 onCommand 兜底失效
// @note 0.3.1 修复重复绑定事件
// @note 0.3.0 整理代码,移除 tool 属性支持,减小 css 影响范围,修复移动主菜单栏项目事件失效,增加多语言支持
// @note 2026-03-29 归档:不再更新
// ==/UserScript==
(async function (CSS, SS_SERVICE, DEFINED_MENUS_OBJ, SEPARATOR_TYPE, OPTION_TYPE, PATH_ATTRS) {
const AUTOFIT_POPUP_POSITION = true;
const CustomizableUI = globalThis.CustomizableUI || Cu.import("resource:///modules/CustomizableUI.jsm").CustomizableUI;
const Services = globalThis.Services || Cu.import("resource://gre/modules/Services.jsm").Services;
const PlacesUtils = globalThis.PlacesUtils || ChromeUtils.importESModule("resource://gre/modules/PlacesUtils.sys.mjs").PlacesUtils;
const alt = (aMsg, aTitle) => Services.prompt.alert(window, aTitle ?? Services.appinfo.name, aMsg)
const xPref = {
get: function (prefPath, defaultValue) {
const sPrefs = Services.prefs;
try {
switch (sPrefs.getPrefType(prefPath)) {
case 0:
return defaultValue;
case 32:
return sPrefs.getStringPref(prefPath);
case 64:
return sPrefs.getIntPref(prefPath);
case 128:
return sPrefs.getBoolPref(prefPath);
}
} catch (ex) {
return defaultValue;
}
return
},
getType: function (prefPath) {
const sPrefs = Services.prefs;
const map = {
0: undefined,
32: 'string',
64: 'int',
128: 'boolean'
}
try {
return map[sPrefs.getPrefType(prefPath)];
} catch (ex) {
return map[0];
}
},
set: function (prefPath, value) {
const sPrefs = Services.prefs;
switch (typeof value) {
case 'string':
return sPrefs.setCharPref(prefPath, value) || value;
case 'number':
return sPrefs.setIntPref(prefPath, value) || value;
case 'boolean':
return sPrefs.setBoolPref(prefPath, value) || value;
}
return;
},
addListener: (a, b) => {
let o = (q, w, e) => (b(xPref.get(e), e));
Services.prefs.addObserver(a, o);
return { pref: a, observer: o }
},
removeListener: (a) => (Services.prefs.removeObserver(a.pref, a.observer))
};
const CopyCat = {
_style: null,
get PLATFORM() {
delete this.PLATFORM;
return this.PLATFORM = AppConstants.platform;
},
get DEGUG() {
return xPref.get("extensions.CopyCat.debug", false);
},
get FILE() {
var path = xPref.get("userChromeJS.CopyCat.FILE_PATH", "_copycat.js")
var aFile = Services.dirsvc.get("UChrm", Ci.nsIFile);
aFile.appendRelativePath(path);
if (!aFile.exists()) {
const that = this;
alerts(this.MESSAGES.format("copycat-config-file-is-empty"), null, function () {
that.edit(aFile.path);
});
}
delete this.FILE;
return this.FILE = aFile;
},
CUSTOM_SHOWINGS: [],
EXEC_BMS: false,
STYLE: {
url: makeURI("data:text/css;charset=utf-8," + encodeURIComponent(CSS)),
type: Services.vc.compare(Services.appinfo.version, "118.0.2") ? SS_SERVICE.USER_SHEET : SS_SERVICE.AUTHOR_SHEET
},
init: async function () {
// 载入样式
if (!SS_SERVICE.sheetRegistered(this.STYLE.url, this.STYLE.type)) {
SS_SERVICE.loadAndRegisterSheet(this.STYLE.url, this.STYLE.type);
}
let _messages = {
"copycat-button": "CopyCat Button",
"copycat-open-chrome-folder": "Open chrome folder",
"copycat-menu-restart": "Restart Firefox",
"copycat-edit-config": "Modify CopyCat config",
"copycat-reload-config": "Reload CopyCat config",
"copycat-about": "About CopyCat",
"copycat-reload-config-success": "Config reloaded successfully!",
"copycat-config-file-is-empty": "Config file is empty, Click to edit!",
"copycat-please-set-editor-path": "Please set editor path, please choose a text editor after clicking confirm.",
"copycat-choose-a-text-editor": "Choose a text editor",
"copycat-config-error-message": "Please check config file by line %s"
};
if (typeof userChrome_js === "object" && "L10nRegistry" in userChrome_js) {
this.l10n = new DOMLocalization(["CopyCat.ftl"], false, userChrome_js.L10nRegistry);
let keys = Object.keys(_messages);
let messages = await this.l10n.formatValues(keys);
this.MESSAGES = (() => {
let obj = {};
for (let index of messages.keys()) {
obj[keys[index]] = messages[index];
}
return obj;
})();
} else {
this.l10n = {
formatValue: async function () {
return "";
},
formatMessages: async function () {
return "";
},
translateRoots() { },
connectRoot() { }
}
this.MESSAGES = _messages;
}
this.MESSAGES.format = function (str_key, ...args) {
let str;
if (str_key in this) {
str = this[str_key];
str = sprintf(str, ...args);
} else {
str = ''
}
return str;
}
// 避免第二个窗口报错
try {
CustomizableUI.createWidget({
id: 'CopyCat-Btn',
removable: true,
defaultArea: CustomizableUI.AREA_NAVBAR,
type: "custom",
onBuild: doc => this.createButton(doc)
});
} catch (ex) { }
this.btn = CustomizableUI.getWidget('CopyCat-Btn').forWindow(window)?.node;
if (!this.btn) return;
this.l10n.connectRoot(this.btn);
this.btn.appendChild(this.createDefaultPopup(this.btn.ownerDocument));
this.setPopupPosition();
window.addEventListener("aftercustomization", this, false);
await this.rebuild();
},
createButton: function (doc) {
let btn = createElement(doc, 'toolbarbutton', {
id: 'CopyCat-Btn',
label: 'CopyCat Button',
'data-l10n-id': 'copycat-button',
type: 'menu',
class: 'toolbarbutton-1 chromeclass-toolbar-additional',
onclick: function (event) {
if (event.target.id !== "CopyCat-Btn") return;
if (event.button === 2) {
if (window.AM_Helper) {
event.preventDefault();
event.stopPropagation();
const b = 'openAddonsMgr';
if (parseInt(Services.appinfo.version) < 126) {
BrowserOpenAddonsMgr("addons://list/userchromejs");
} else {
BrowserAddonUI.openAddonsMgr("addons://list/userchromejs");
}
}
}
}
});
return btn;
},
createDefaultPopup: function (doc) {
let mp = createElement(doc, "menupopup", {
id: "CopyCat-Popup",
class: "CopyCat-Popup",
});
if (Array.isArray(DEFINED_MENUS_OBJ)) {
DEFINED_MENUS_OBJ.forEach(obj => {
let menuitem = this.newMenuitem(doc, obj);
mp.appendChild(menuitem);
});
}
mp.addEventListener("popupshowing", this, false);
mp.addEventListener("popuphiding", this, false);
return mp;
},
setPopupPosition: function () {
if (!AUTOFIT_POPUP_POSITION) return;
if (!this.btn) return;
const { btn } = this;
let mp = $("#CopyCat-Popup", btn);
if (!mp) return;
// 获取按钮的位置信息
const rect = btn.getBoundingClientRect();
// 获取窗口的宽度和高度
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const x = rect.left + rect.width / 2; // 按钮的水平中心点
const y = rect.top + rect.height / 2; // 按钮的垂直中心点
if (x < windowWidth / 2 && y < windowHeight / 2) {
mp.removeAttribute("position");
} else if (x >= windowWidth / 2 && y < windowHeight / 2) {
mp.setAttribute("position", "after_end");
} else if (x >= windowWidth / 2 && y >= windowHeight / 2) {
mp.setAttribute("position", "before_end");
} else {
mp.setAttribute("position", "before_start");
}
},
handleEvent: function (event) {
if (typeof this["on" + event.type] === "function") {
this["on" + event.type](event);
} else {
this.log('[handleEvent] Unhandled event: ' + event.type);
}
},
onpopupshowing: async function (event) {
let mp = event.target;
if (mp.id !== "CopyCat-Popup") return;
mp.setAttribute("HideNoneDynamicItems", xPref.get("userChromeJS.CopyCat.hideInternal", false));
this.CUSTOM_SHOWINGS.filter(o => !o.disabled).forEach(function (obj) {
var curItem = obj.item;
try {
let fn = createFunction(obj.fnSource, 'curItem');
fn.call(obj, curItem);
} catch (ex) {
console.error('Custom showing method error', obj.fnSource, ex);
}
if (obj.once) obj.disabled = true;
});
},
onaftercustomization: function (event) {
this.setPopupPosition();
},
newMenugroup: function (doc, obj) {
if (!doc || !obj) return;
let group = createElement(doc, "menugroup", obj, ["group"]);
group.classList.add("CopyCat-Group");
obj.group.forEach(o => {
group.appendChild(this.newMenuitem(doc, o));
})
this.log("[newMenugroup] Creating Menugroup: " + (obj.label || "<empty label>"), group);
return group;
},
newMenupopup: function (doc, obj) {
if (!doc || !obj) return;
let aItem;
aItem = createElement(doc, "menu", obj, ["popup", "onbuild"]);
this.log("[newMenupopup] Creating Menu " + (obj.label || "<empty label>"), aItem);
aItem.classList.add("menu-iconic");
let menupopup = aItem.appendChild(createElement(doc, "menupopup"));
obj.popup.forEach(mObj => menupopup.appendChild(this.newMenuitem(doc, mObj)));
if (obj.onbuild) {
let fn = createFunction(obj.onBuild, 'doc', 'aItem');
fn.call(window, doc, aItem);
}
return aItem;
},
newMenuitem: function (doc, obj) {
if (!doc || !obj) return;
if (obj.group) {
return this.newMenugroup(doc, obj);
}
if (obj.popup) {
return this.newMenupopup(doc, obj);
}
let classList = [], tagName = obj.type || "menuitem", noDefaultLabel = !obj.label;
// 分隔符
if (SEPARATOR_TYPE.includes(obj.type) || obj.label === "separator" || !obj.group && !obj.popup && noDefaultLabel && !obj.tooltiptext && !obj.image && !obj.content && !obj.url && !obj.command && !obj.pref && !obj['data-l10n-id']) {
return createElement(doc, "menuseparator", obj, ['type', 'group', 'popup']);
}
if (OPTION_TYPE.includes(obj.type)) tagName = "menuitem";
if (obj.class) obj.class.split(' ').forEach(c => {
if (!classList.includes(c)) classList.push(c);
});
if (obj.type && obj.type.startsWith("html:")) {
tagName = obj.type;
delete obj.type;
}
if (tagName === "menuitem") {
classList.push("menuitem-iconic");
} else if (tagName === "menu") {
classList.push("menu-iconic");
}
// process relative path
PATH_ATTRS.forEach(attr => {
if (obj[attr]) {
obj[attr] = handleRelativePath(obj[attr]);
}
});
if (obj.command) {
// 移动菜单
obj.clone = obj.clone || false;
let org = $(obj.command, doc),
dest;
if (org) {
dest = dest = obj.clone ? org.cloneNode(true) : org;
if (!obj.clone) {
// Save original attributes
const attrs = {};
dest.getAttributeNames().forEach(n => attrs[n] = dest.getAttribute(n));
dest.originalAttrs = attrs;
}
if (dest.localName === "menu") {
// fix close menu
if (dest.hasAttribute('closemenu'))
dest.setAttribute('closemenu', 'none');
if (obj.clone && obj['fix-id']) {
// fix id
if (dest.id) {
dest.id += '_clone';
}
dest.querySelectorAll('menu,menupopup,menuseparator').forEach(item => {
if (item.id) item.id += '_clone';
});
// add command
let menuitems = dest.querySelectorAll('menuitem');
for (let i = 0; i < menuitems.length; i++) {
let item = menuitems[i];
if (item.localName === 'menuitem') {
command_id = item.getAttribute('id');
if (command_id && !dest.getAttribute('command')) {
item.setAttribute('id', command_id + '_clone');
item.setAttribute('command', command_id);
item.addEventListener("command", function (e) {
window.CopyCat.onCommand(e);
}, false);
}
}
}
}
}
// Firefox 130 + need to bind events after move menuitem from main-menubar
if (org.closest('#main-menubar')) {
this.EXEC_BMS = true;
}
// fix menupopup indicator
if ($(':scope>.menubar-text', dest)) {
dest.setAttribute('menuright', true);
}
// convert class
if (obj.class) {
dest.setAttribute('class', obj.class.replace('...', dest.getAttribute('class') || ""));
}
// Support attribute insert for clone node
["image", "style", "label", "tooltiptext", "type"].forEach(attr => {
if (attr in obj) {
dest.setAttribute(attr, obj[attr]);
}
});
// fix menuitem without icon struct
if (dest.hasAttribute('image') && (!dest.hasAttribute('menu-iconic') && !dest.hasAttribute('menuitem-iconic'))) {
this.CUSTOM_SHOWINGS.push({
item: dest,
fnSource: function (item) {
if (item.hasAttribute("image")) {
if (item.querySelector(':scope>.menu-text, :scope>.menubar-text')) {
item.style.setProperty('--menu-image', `url(${item.getAttribute('image')})`);
}
}
}.toString(),
once: true
});
}
let replacement = createElement(doc, 'menuseparator', {
hidden: true, class: 'CopyCat-Replacement', 'original-id': obj.command
});
if (!obj.clone) {
dest.setAttribute('restoreBeforeUnload', 'true');
dest.restoreHolder = replacement;
dest.parentNode.insertBefore(replacement, dest);
this.log('Moving Item: ' + obj.command, dest);
} else {
this.log('Cloning Item: ' + obj.command, dest);
}
} else {
return;
}
if ('onBuild' in obj && typeof dest !== 'undefined') {
let fn = createFunction(obj.onBuild, 'doc', 'aItem');
fn.call(window, doc, dest);
}
return dest;
} else {
item = createElement(doc, tagName, obj, ['popup', 'class', 'group', 'onBuild', 'precommand', 'postcommand']);
if (classList.length) item.setAttribute('class', classList.join(' '));
let label = obj.label || obj.command || obj.oncommand || obj.url || "";
if (label)
item.setAttribute('label', label);
if (obj.pref) {
let type = obj.type || xPref.getType(obj.pref) || 'prompt';
const defaultVal = {
string: '',
prompt: '',
radio: '',
int: 0,
bool: false,
boolean: false
}
item.setAttribute('type', type);
// 设置默认值
if (!("defaultValue" in obj)) item.setAttribute('defaultValue', defaultVal[type]);
if (type === 'checkbox') {
item.setAttribute('checked', !!xPref.get(obj.pref, obj.defaultValue !== undefined ? obj.default : false));
} else {
let value = xPref.get(obj.pref);
if (type === "prompt") {
item.setAttribute('value', value);
item.setAttribute('label', sprintf(obj.labelRef || obj.label, value));
}
}
}
}
if (noDefaultLabel && obj['data-l10n-href'] && obj["data-l10n-href"].endsWith(".ftl") && obj['data-l10n-id']) {
// Localization 支持
let strings = new Localization([obj["data-l10n-href"]], true); // 第二个参数为 true 则是同步返回
item.setAttribute('label', strings.formatValueSync([obj['data-l10n-id']]) || item.getAttribute("label"));
}
if (obj.content) {
item.innerHTML = obj.content;
item.removeAttribute('content');
}
if (obj.oncommand || obj.command) return item;
item.addEventListener('command', function (e) {
window.CopyCat.onCommand(e);
}, false);
// 可能ならばアイコンを付ける
this.setIcon(item, obj);
this.log("Creating Item: ", (item.label || "<empty label>"), item);
return item;
},
setIcon: function (menu, obj) {
if (OPTION_TYPE.includes(menu.getAttribute("type") || "other")) return;
if (menu.hasAttribute("src") || menu.hasAttribute("icon")) return;
if (obj.image) {
return setMenuImage(menu, obj.image);
}
if (obj.edit || obj.exec) {
var aFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
try {
aFile.initWithPath(handleRelativePath(obj.edit) || obj.exec);
} catch (e) {
this.error(e);
return;
}
// if (!aFile.exists() || !aFile.isExecutable()) {
if (!aFile.exists()) {
menu.setAttribute("disabled", "true");
} else {
if (aFile.isFile()) {
setMenuImage(menu, "moz-icon://" + getURLSpecFromFile(aFile) + "?size=16");
} else {
setMenuImage(menu, "chrome://global/skin/icons/folder.svg");
}
}
return;
}
if (obj.keyword) {
let engine = obj.keyword === "@default" ? Services.search.getDefault() : Services.search.getEngineByAlias(obj.keyword);
if (engine) {
if (engine.iconURI) {
engine.then(function (engine) {
setMenuImage(menu, getIconURL(engine));
});
}
return;
function getIconURL(engine) {
// Bug 1870644 - Provide a single function for obtaining icon URLs from search engines
return (engine._iconURI || engine.iconURI)?.spec || "chrome://browser/skin/search-engine-placeholder.png";
}
}
}
var setIconCallback = function (url) {
const { favicons, toURI } = PlacesUtils;
let uri, iconURI;
try {
uri = toURI(url);
} catch (e) { }
if (!uri) return;
menu.setAttribute("scheme", uri.scheme);
try {
favicons.getFaviconForPage(uri).then(({ dataURI }) => {
setMenuImage(menu, dataURI.schemeIs('data') ? dataURI.spec : "page-icon:" + dataURI.spec);
})
} catch (e) {
PlacesUtils.favicons.getFaviconDataForPage(uri, {
onComplete: function (aURI, aDataLen, aData, aMimeType) {
try {
// javascript: URI の host にアクセスするとエラー
let iconURL = aURI && aURI.spec ?
"page-icon:" + aURI.spec :
"page-icon:" + uri.spec;
setMenuImage(menu, iconURL);
} catch (e) { }
}
});
}
}
PlacesUtils.keywords.fetch(obj.keyword || '').then(entry => {
let url;
if (entry) {
url = entry.url.href;
} else {
url = (obj.url + '').replace(this.regexp, "");
}
setIconCallback(url);
}, e => {
console.error(e)
}).catch(e => {
console.error(e)
});
},
onCommand: function (event) {
event.stopPropagation();
let item = event.target;
pref = item.getAttribute("pref") || "",
text = item.getAttribute("text") || "",
exec = item.getAttribute("exec") || "",
edit = item.getAttribute("edit") || "",
url = item.getAttribute("url") || "",
where = item.getAttribute("where") || "";
const preCommandEvent = new Event('precommand', {
bubbles: true,
cancelable: true
});
item.dispatchEvent(preCommandEvent);
if (pref)
this.handlePref(event, pref);
else if (edit)
this.edit(edit);
else if (exec)
this.exec(exec, text);
else if (url)
this.openCommand(event, url, where);
const postCommandEvent = new Event('postcommand', {
bubbles: true,
cancelable: true
});
item.dispatchEvent(postCommandEvent);
if (event.button !== 2 && event.target.getAttribute("closemenu") !== "none") {
closeMenus(event.target.closest("menupopup"));
}
},
handlePref: function (event, pref) {
let item = event.target;
if (item.getAttribute('type') === 'checkbox') {
let setVal = xPref.get(pref, false, !!item.getAttribute('defaultValue'));
xPref.set(pref, !setVal);
item.setAttribute('checked', !setVal);
} else if (item.getAttribute('type') === 'radio') {
if (item.hasAttribute('value')) {
xPref.set(pref, item.getAttribute('value'));
}
} else if (item.getAttribute('type') === 'prompt') {
let type = item.getAttribute('valueType') || 'string',
val = prompt(item.getAttribute('label'), xPref.get(pref, item.getAttribute('default') || ""));
if (val) {
switch (type) {
case 'int':
val = parseInt(val);
break;
case 'boolean':
val = !!val;
break;
case 'string':
default:
val = "" + val;
break;
}
xPref.set(pref, val);
}
}
},
openCommand: function (event, url, aWhere, aAllowThirdPartyFixup = {}, aPostData, aReferrerInfo) {
const isJavaScriptURL = url.startsWith("javascript:");
const isWebURL = /^(f|ht)tps?:/.test(url);
if (aWhere?.indexOf('tab') >= 0 && gBrowser.selectedTab.isEmpty) {
// remove 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.getAttribute("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;
}
const userContextId = isWebURL ? allowThirdPartyFixup.userContextId : null;
return isWebURL ?
Services.scriptSecurityManager.createNullPrincipal({ 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()
});
}
},
editConfig: function () {
this.edit(this.FILE.path);
},
edit: function (path, aLineNumber) {
let aFile = getFile(path), editor;
if (!aFile) {
this.error("[edit] Param is invalid: " + path);
return;
}
try {
editor = Services.prefs.getComplexValue("view_source.editor.path", Ci.nsIFile);
} catch (e) { }
if (!editor || !editor.exists()) {
alt(this.MESSAGES.format("copycat-please-set-editor-path"));
let fp = Cc['@mozilla.org/filepicker;1'].createInstance(Ci.nsIFilePicker);
// Bug 1878401 Always pass BrowsingContext to nsIFilePicker::Init
fp.init(!("inIsolatedMozBrowser" in window.browsingContext.originAttributes)
? window.browsingContext
: window, this.MESSAGES.format("copycat-choose-a-text-editor"), fp.modeOpen);
fp.appendFilters(Ci.nsIFilePicker.filterApps);
var isCompleted = false;
if (typeof fp.show !== 'undefined') {
if (fp.show() == fp.returnCancel || !fp.file)
return;
else {
editor = fp.file;
Services.prefs.setCharPref("view_source.editor.path", editor.path);
isCompleted = true;
}
} else {
fp.open(res => {
if (res != Ci.nsIFilePicker.returnOK) return;
editor = fp.file;
Services.prefs.setCharPref("view_source.editor.path", editor.path);
isCompleted = true;
});
}
var thread = Cc['@mozilla.org/thread-manager;1'].getService().mainThread;
while (!isCompleted) {
thread.processNextEvent(true);
}
}
let aURL = getURLSpecFromFile(aFile);
let aDocument = null;
let aCallBack = null;
let aPageDescriptor = null;
gViewSourceUtils.openInExternalEditor({
URL: aURL,
lineNumber: aLineNumber
}, aPageDescriptor, aDocument, aLineNumber, aCallBack);
},
exec: function (path, arg = []) {
let aFile = getFile(path);
if (!aFile) return this.error(`[exec] path is invalid: ${path}`);
const process = Cc['@mozilla.org/process/util;1'].createInstance(Ci.nsIProcess);
try {
let a = Array.isArray(arg)
? arg
: typeof arg === 'string' && arg.trim()
? arg.split(/\s+/)
: [arg];
if (!aFile.exists()) return console.error("[exec] file not found", path);
// 检查是否为可执行文件,非目录情况下初始化进程
if (!aFile.isDirectory() && aFile.isExecutable()) {
process.init(aFile);
process.runw(false, a, a.length);
} else {
aFile.launch();
}
} catch (e) {
this.error(e);
}
},
rebuild: async function (isAlert = false) {
if (this.initializing) return;
this.initializing = true;
this.uninit();
this.btn.appendChild(this.createDefaultPopup(this.btn.ownerDocument));
this.setPopupPosition();
let isError = !await this.makeMenus();
if (!isError) {
if (isAlert || this.NEED_ALERT) {
this.NEED_ALERT = false;
alerts(this.MESSAGES.format("copycat-reload-config-success"));
}
}
this.initializing = false;
},
makeMenus: async function () {
let mp = $('#CopyCat-Popup', this.btn);
if (!mp) return;
if (!this.FILE.exists()) {
await IOUtils.writeUTF8(this.FILE.path, '');
}
let d = await IOUtils.readUTF8(this.FILE.path);
if (!d) return;
let sandbox = new Cu.Sandbox(window, {
sandboxPrototype: window,
sameZoneAs: window,
});
Object.assign(sandbox, {
_menus: [], _css: []
});
sandbox.menus = itemObj => ps(itemObj, sandbox._menus);
function ps(item, array) {
("join" in item && "unshift" in item) ? [].push.apply(array, item) : array.push(item);
}
try {
var lineFinder = new Error();
Cu.evalInSandbox("function css(code){ this._css.push(code+'') };\nfunction lang(obj) { Object.assign(this._lang, obj); }" + d, sandbox, "1.8"); 3
} catch (e) {
let line = e.lineNumber - lineFinder.lineNumber - 1;
alerts(e + this.MESSAGES.format("copycat-config-error-message", line), null, function () {
this.edit(this.FILE, line);
});
console.error(e);
return false;
}
let { ownerDocument: aDoc } = mp;
sandbox._menus.forEach((itemObj) => {
this.insertMenuitem(aDoc, itemObj, this.newMenuitem(aDoc, itemObj));
});
if (sandbox._css.length) {
this.MENU_STYLE = addStyle(sandbox._css.join('\n'));
}
if (this.EXEC_BMS && $('#main-menubar > script')) {
Object.assign(sandbox, {
AppConstants, gBrowser, SessionStore
});
["chrome://browser/content/places/controller.js", "chrome://browser/content/places/browserPlacesViews.js", "chrome://browser/content/browser-places.js"].forEach(url => {
try {
Services.scriptloader.loadSubScript(url, globalThis);
} catch (e) { }
})
let hisPop = document.querySelector("#CopyCat-Popup #historyMenuPopup");
if (hisPop) {
hisPop.addEventListener('popupshowing', (event) => {
if (!event.target.parentNode._placesView) {
new HistoryMenu(event);
}
});
hisPop.addEventListener('command', function (event) {
// Handle commands/clicks on the descending menuitems that are
// history entries.
let historyMenu = document.querySelector("#CopyCat-Popup #history-menu");
historyMenu._placesView._onCommand(event);
});
}
document.querySelector("#CopyCat-Popup").addEventListener('command', (event) => bm_command(event));
function bm_command(event) {
if (event.target !== event.currentTarget && event.target.matches('menuitem:not([command])')) {
switch (event.target.id) {
// == edit-menu ==
case "menu_preferences":
openPreferences(undefined);
break;
// == view-menu ==
case "menu_pageStyleNoStyle":
gPageStyleMenu.disableStyle();
break;
case "menu_pageStylePersistentOnly":
gPageStyleMenu.switchStyleSheet(null);
break;
case "repair-text-encoding":
BrowserCommands.forceEncodingDetection();
break;
case "documentDirection-swap":
gBrowser.selectedBrowser.sendMessageToActor(
"SwitchDocumentDirection",
{},
"SwitchDocumentDirection",
"roots"
);
break;
// == history-menu ==
case "sync-tabs-menuitem":
gSync.openSyncedTabsPanel();
break;
case "hiddenTabsMenu":
gTabsPanel.showHiddenTabsPanel(event, "hidden-tabs-menuitem");
break;
case "sync-setup":
gSync.openPrefs("menubar");
break;
case "sync-enable":
gSync.openPrefs("menubar");
break;
case "sync-unverifieditem":
gSync.openPrefs("menubar");
break;
case "sync-syncnowitem":
gSync.doSync(event);
break;
case "sync-reauthitem":
gSync.openSignInAgainPage("menubar");
break;
case "menu_openFirefoxView":
FirefoxViewHandler.openTab();
break;
case "hiddenUndoCloseWindow":
undoCloseWindow(0);
break;
// == menu_HelpPopup ==
// (Duplicated in PanelUI._onHelpCommand)
case "menu_openHelp":
openHelpLink("firefox-help");
break;
case "menu_layout_debugger":
toOpenWindowByType(
"mozapp:layoutdebug",
"chrome://layoutdebug/content/layoutdebug.xhtml"
);
break;
case "feedbackPage":
openFeedbackPage();
break;
case "helpSafeMode":
safeModeRestart();
break;
case "troubleShooting":
openTroubleshootingPage();
break;
case "menu_HelpPopup_reportPhishingtoolmenu":
openUILink(gSafeBrowsing.getReportURL("Phish"), event, {
triggeringPrincipal:
Services.scriptSecurityManager.createNullPrincipal({}),
});
break;
case "menu_HelpPopup_reportPhishingErrortoolmenu":
gSafeBrowsing.reportFalseDeceptiveSite();
break;
case "helpSwitchDevice":
openSwitchingDevicesPage();
break;
case "aboutName":
openAboutDialog();
break;
case "helpPolicySupport":
openTrustedLinkIn(Services.policies.getSupportMenu().URL.href, "tab");
break;
}
}
}
this.EXEC_BMS = false;
}
return true;
},
insertMenuitem(doc, obj, item) {
if (!item) {
this.log("[insertMenuitem] Item to be inserted is null!");
return;
} else {
this.log("[insertMenuitem] Inserting item: " + item.getAttribute('label'), item);
}
if (item.getAttribute('restoreBeforeUnload') !== 'true') {
item.classList.add('CopyCat-Dynamic');
}
const aPopup = $('CopyCat-Popup', doc);
if (obj && obj.insertBefore && $(obj.insertBefore, doc)) {
$(obj.insertBefore, doc).before(item)
} else if (obj && obj.insertAfter && $(obj.insertAfter, doc)) {
$(obj.insertAfter, doc).after(item)
} else if ($('#CopyCat-InsertPoint', aPopup)) {
aPopup.insertBefore(item, $('#CopyCat-InsertPoint', aPopup));
} else {
aPopup.appendChild(item);
}
},
uninit() {
this.CUSTOM_SHOWINGS = [];
let mp = $('#CopyCat-Popup', this.btn);
if (mp) {
mp.removeEventListener("popupshowing", this, false);
mp.removeEventListener("popuphiding", this, false);
rmip(mp);
/**
* 删除菜单具体函数,根据菜单属性判定是移回原位还是直接删除
*
* @param {HTMLElement} mp 弹出菜单对象
*/
function rmip(mp) {
$$('[restoreBeforeUnload="true"]', mp, item => {
if (item.originalAttrs) {
const originalKeys = Object.keys(item.originalAttrs);
// remove attrs not in originalAttrs
item.getAttributeNames().forEach(attr => {
if (!originalKeys.includes(attr)) item.removeAttribute(attr);