/
sessionBookmarks.js
2383 lines (2314 loc) · 74.9 KB
/
sessionBookmarks.js
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
// http://infocatcher.ucoz.net/js/cb/sessionBookmarks.js
// https://forum.mozilla-russia.org/viewtopic.php?id=57871
// https://github.com/Infocatcher/Custom_Buttons/tree/master/Session_Bookmarks
// Session Bookmarks button for Custom Buttons
// (code for "initialization" section)
// (c) Infocatcher 2011-2015
// version 0.2.2pre6 - 2015-08-31
// Usage:
// Use middle-click or left+click with any modifier to add current tab
// Drag and drop any tab to add new bookmark
// Compatibility: Firefox 3.0+, SeaMonkey 2.0+
// Icon by FatCow Web Hosting: http://www.iconfinder.com/icondetails/36059/16/
// + Diagona Icons http://www.iconfinder.com/icondetails/14111/10/087_icon
var options = {
hideDropMarker: true, // Hide "v" after button's icon
showLabel: undefined, // Set to true/false to force show/hide button's label
addToEnd: true, // Add to end of list by default
loadInBackground: false, // Load tabs in background
leftClickCloseMenu: true, // Close menu after left-click
middleClickCloseMenu: 1,
// After middle-click:
// 0 - always stay menu open
// 1 - close only after click without modifiers
// 2 - always close
invertLoadBehavior: false, // true => left-click open bookmark in new tab
checkDuplicates: true, // Forbid duplicates
checkDuplicatesSession: true, // Also compare session data
allowToggleBookmark: false, // Remove already added bookmark using middle-click on button
deleteAfterOpen: false, // Delete opened bookmarks
removeAddedTab: false, // Remove tab after bookmark will be added
replaceCurrentTab: false, // Replace current tab with new one (and preserve position)
// Workaround, use only in case of problems with "open in current tab" feature
itemInPageContextMenu: false, // Show "Session Bookmark This Page" item in page context menu
showNotifications: 1, // Show notifications like "Bookmark added"
// 0 - don't show
// 1 - show only if menu is closed
// 2 - always show
notificationHideDelay: 1700,
preloadBookmarks: -1,
// 0 - disable preload feature (load bookmarks only after menu opening)
// -1 - preload on mouseover
// 1..N - preload after this time (in ms)
useSessions: true, // Save and restore session data
saveTabHistory: true, // Only for "useSessions: true"
// Save back/forward history of tab
saveTabPinnedState: false,
reloadSessions: true, // Only for "useSessions: true"
// Ignore cache during session restore (otherwise may be opened obsolete cached version of page)
undoLimit: 10 // Max length of undo/redo history
};
var _debug = false; // Show debug messages in error/browser console
function _localize(s, key) {
var strings = {
"Bookmark All Tabs": {
ru: "Добавить все вкладки в закладки"
},
bookmarkAllTabsKey: {
ru: "л"
},
"Update": {
ru: "Обновить"
},
updateKey: {
ru: "н"
},
"Update Location": {
ru: "Обновить адрес"
},
updateLocationKey: {
ru: "а"
},
"Delete All Bookmarks": {
ru: "Удалить все закладки"
},
deleteAllKey: {
ru: "в"
},
"Sort": {
ru: "Сортировать"
},
sortKey: {
ru: "С"
},
"By Name, A>Z": {
ru: "По имени, А>Я"
},
sortByNameAZKey: {
ru: "и"
},
"By Name, Z>A": {
ru: "По имени, Я>А"
},
sortByNameZAKey: {
ru: "и"
},
"By Base Domain, Host and Name, A>Z": {
ru: "По базовому домену, хосту и имени, А>Я"
},
sortByBaseDomainHostNameAZKey: {
ru: "б"
},
"By Base Domain, Host and Name, Z>A": {
ru: "По базовому домену, хосту и имени, Я>А"
},
sortByBaseDomainHostNameZAKey: {
ru: "б"
},
"By Host and Name, A>Z": {
ru: "По хосту и имени, А>Я"
},
sortByHostNameAZKey: {
ru: "х"
},
"By Host and Name, Z>A": {
ru: "По хосту и имени, Я>А"
},
sortByHostNameZAKey: {
ru: "х"
},
"Button Menu": {
ru: "Меню кнопки"
},
buttonMenuKey: {
ru: "М"
},
"Session Bookmark This Page": {
ru: "Добавить страницу в закладки-сессии"
},
"Button: %S": {
ru: "Кнопка: %S"
},
pageContextItemKey: {
ru: "с"
},
"Bookmark added": {
ru: "Закладка добавлена"
},
"Bookmarks added: %S": {
ru: "Закладки добавлены: %S"
},
"Bookmark already exists": {
ru: "Закладка уже существует"
},
"Bookmark removed": {
ru: "Закладка удалена"
},
"Session Bookmark Properties": {
ru: "Свойства закладки-сессии"
},
"Warning!": {
ru: "Внимание!"
},
"After location change all session data will be lost!": {
ru: "После изменения адреса вся информация о сессии будет потеряна!"
},
"Icon:": {
ru: "Иконка:"
},
iconKey: {
ru: "И"
}
};
var locale = (function() {
var prefs = "Services" in window && Services.prefs
|| Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
if(!prefs.getBoolPref("intl.locale.matchOS")) {
var locale = prefs.getCharPref("general.useragent.locale");
if(locale.substr(0, 9) != "chrome://")
return locale;
}
return Components.classes["@mozilla.org/chrome/chrome-registry;1"]
.getService(Components.interfaces.nsIXULChromeRegistry)
.getSelectedLocale("global");
})().match(/^[a-z]*/)[0];
_localize = !locale || locale == "en"
? function(s) {
return s;
}
: function(s, key) {
if(!key)
key = s;
return strings[key] && strings[key][locale] || s;
};
return _localize.apply(this, arguments);
}
this.onclick = function(e) {
if(e.target != this)
return;
if(e.button == 1 || e.button == 0 && this.bookmarks.hasModifier(e))
this.bookmarks.addBookmark();
};
this.onmouseover = function(e) {
if(e.target != this)
return;
var preload = this.bookmarks.options.preloadBookmarks;
if(
preload == -1
&& this.bookmarks.mp
&& this.bookmarks.mp.hasAttribute("onpopupshowing")
)
this.bookmarks.loadDelayed();
if(this.disabled)
return;
Array.some(
this.parentNode.getElementsByTagName("*"),
function(node) {
if(
node != this
&& node.namespaceURI == xulns
&& node.boxObject
// See https://github.com/Infocatcher/Custom_Buttons/issues/28
//&& node.boxObject instanceof Components.interfaces.nsIMenuBoxObject
&& "open" in node
&& node.open
&& node.getElementsByTagName("menupopup").length
) {
node.open = false;
this.open = true;
return true;
}
return false;
},
this
);
};
if(!this.hasOwnProperty("defaultContextId"))
this.defaultContextId = this.getAttribute("context") || "custombuttons-contextpopup";
this.onmousedown = function(e) {
if(e.target != this || e.button != 2)
return;
var showCbMenu = e.ctrlKey || e.shiftKey || e.altKey || e.metaKey;
if(!showCbMenu)
this.bookmarks.addContextMenu();
this.setAttribute("context", showCbMenu ? this.defaultContextId : this.bookmarks.cmId);
};
this.setAttribute("ondraggesture", "return this.bookmarks.handleDragStart(event);");
this.setAttribute("ondragover", "return this.bookmarks.handleDragOver(event);");
this.setAttribute("ondragexit", "return this.bookmarks.handleDragExit(event);");
this.setAttribute("ondragdrop", "return this.bookmarks.handleDrop(event);");
this.bookmarks = {
button: this,
options: options,
errPrefix: "[Custom Buttons :: Session Bookmarks]: ",
get openAllLabel() {
var sb = this.$("bundle_browser") || this.$("bundle_navigator");
if(sb) try {
var label = sb.getString("menuOpenAllInTabs.label");
}
catch(e) {
}
delete this.openAllLabel;
return this.openAllLabel = label || "Open All in Tabs";
},
getAttr: function(attr, id, defaultVal) {
var node = this.$(id);
return node && node.getAttribute(attr) || defaultVal;
},
getLabel: function(id, defaultVal) {
return this.getAttr("label", id, defaultVal);
},
getAccesskey: function(id, defaultVal) {
return this.getAttr("accesskey", id, defaultVal);
},
get ss() {
delete this.ss;
return this.ss = (
Components.classes["@mozilla.org/browser/sessionstore;1"]
|| Components.classes["@mozilla.org/suite/sessionstore;1"]
).getService(Components.interfaces.nsISessionStore);
},
get ios() {
delete this.ios;
return this.ios = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
},
get tld() {
delete this.tld;
return this.tld = Components.classes["@mozilla.org/network/effective-tld-service;1"]
.getService(Components.interfaces.nsIEffectiveTLDService);
},
get wm() {
delete this.wm;
return this.wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
},
get btnNum() {
delete this.btnNum;
return this.btnNum = this.button.id.match(/\d*$/)[0];
},
get file() {
var file = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties)
.get("ProfD", Components.interfaces.nsILocalFile || Components.interfaces.nsIFile);
file.append("custombuttons");
file.append("bookmarks-" + this.btnNum + ".txt");
file.QueryInterface(Components.interfaces.nsILocalFile || Components.interfaces.nsIFile);
this.ensureFilePermissions(file, this.PERMS_FILE_OWNER_WRITE);
delete this.file;
return this.file = file;
},
get backupFile() {
var file = this.file.clone();
file.leafName += ".bak";
file.QueryInterface(Components.interfaces.nsILocalFile || Components.interfaces.nsIFile);
this.ensureFilePermissions(file, this.PERMS_FILE_OWNER_WRITE);
delete this.backupFile;
return this.backupFile = file;
},
$: function(id) {
return document.getElementById(id);
},
initProxy: function() {
// Trick: wait for XBL binding tor [type="menu"]
_log("initProxy()");
var btn = this.button;
if("__initTimer" in btn)
clearTimeout(btn.__initTimer);
if(btn.type == "menu") {
_log("initProxy(): menu");
this.init();
return;
}
// This behavior may be changed (fixed?) later, so will initialize anyway after small delay
btn.__initTimer = setTimeout(function(_this) {
_log("initProxy() -> fallback timer");
if(btn.type == "menu")
_this.init();
}, 500, this);
},
init: function() {
_log("init()");
window.addEventListener("drop", this, true);
setTimeout(function(_this) {
_this.delayedInit();
}, 0, this);
},
delayedInit: function() {
_log("delayedInit()");
this.initIds();
var btn = this.button;
var mps = btn.getElementsByTagName("menupopup");
mps.length && mps[0].parentNode.removeChild(mps[0]); // Hack for SeaMonkey
var mp = this.mp = this.createElement("menupopup", {
context: this.cmId,
oncommand: "this.parentNode.bookmarks.openBookmark(event);",
onclick: "this.parentNode.bookmarks.openBookmark(event);",
onpopupshowing: "this.parentNode.bookmarks.load();",
onpopuphidden: "this.parentNode.bookmarks.checkUnsaved();"
});
mp.addEventListener("DOMMenuItemActive", this, false);
mp.addEventListener("DOMMenuItemInactive", this, false);
var tb = btn.parentNode;
if(tb.getAttribute("orient") == "vertical") {
// https://addons.mozilla.org/firefox/addon/vertical-toolbar/
var isRight = tb.parentNode.getAttribute("placement") == "right";
mp.setAttribute("position", isRight ? "start_before" : "end_before");
}
btn.appendChild(mp);
if(this.options.itemInPageContextMenu) setTimeout(function(_this) {
_this.initPageContextMenu();
}, 50, this);
var preload = this.options.preloadBookmarks;
if(preload > 0) setTimeout(function(_this) {
if(_this.mp.hasAttribute("onpopupshowing"))
_this.load();
}, preload, this);
if(this.noBookmarks())
btn.disabled = true;
},
loadDelayed: function(callback) {
setTimeout(function(_this) {
_this.load(callback);
}, 0, this);
},
load: function(callback) {
_log("load()");
var mp = this.mp;
if(mp.hasAttribute("onpopupshowing")) {
// Already called listener can't be removed without this
mp.setAttribute("onpopupshowing", "");
mp.removeAttribute("onpopupshowing");
}
var file = this.file;
if(file.exists()) {
this.readFromFileAsync(file, function(data) {
this.loadData(data);
callback && callback();
}, this);
}
else {
this.loadData("");
callback && callback();
}
},
ensureLoaded: function(callback, context, args) {
if(this._loaded)
return callback.apply(context, args);
return this.load(function() {
callback.apply(context, args);
});
},
_label: "label: ",
_uri: "uri: ",
_icon: "icon: ",
_session: "session: ",
_sep: "separator",
_loaded: false,
loadData: function(data) {
this._loaded = true;
this.addContextMenu();
var mp = this.mp;
if(mp.hasChildNodes()) {
_log("loadData(): menupopup isn't empty!");
mp.textContent = "";
}
var typeOffset = this._label.length;
data.split("\n\n").forEach(function(section, i) {
if(!section)
return;
var label, uri, icon, ssData, isSep;
section.split("\n").forEach(function(line, i) {
if(!line)
return;
var type = line.substr(0, typeOffset);
line = line.substr(typeOffset);
switch(type) {
case this._label: label = line; break;
case this._uri: uri = line; break;
case this._icon: icon = line; break;
case this._session: ssData = line; break;
case this._sep: isSep = true; return;
}
}, this);
if(isSep)
mp.appendChild(this.getSeparator());
else
mp.appendChild(this.getMenuitem(label, uri, icon, ssData));
}, this);
var sep = this.createElement("menuseparator", {
id: this.sepId
});
mp.appendChild(sep);
var openAll = this.createElement("menuitem", {
id: this.openAllId,
label: this.openAllLabel
});
mp.appendChild(openAll);
this.onBookmarksChanged();
},
destroy: function(force) {
_log("destroy(" + force + ")");
if(this.mp) {
this.mp.removeEventListener("DOMMenuItemActive", this, false);
this.mp.removeEventListener("DOMMenuItemInactive", this, false);
if(!force)
this.closePropertiesWindows();
}
if(force) {
this.closeAllPropertiesWindows();
this.markInsertionPoint(false);
}
if(this.options.itemInPageContextMenu)
this.destroyPageContextMenu(force);
window.removeEventListener("drop", this, true);
},
handleEvent: function(e) {
var type = e.type;
if(type == "popupshowing" && e.target == e.currentTarget)
this.updatePageContextItemVisibility();
else if(type == "drop")
this.handleBookmarkDrop(e);
else if(type == "DOMMenuItemActive" || type == "DOMMenuItemInactive")
this.showLink(e);
},
initIds: function() {
this.initIds = function() {};
var shortcuts = {
// Bookmarks menu
cmId: "-context",
sepId: "-separator",
openAllId: "-openAll",
// Bookmarks context menu
addBookmarkId: "-addBookmark",
addSepId: "-addSeparator",
bmAllSepId: "-separator-bookmarkAllTabs",
bmAllId: "-bookmarkAllTabs",
updateSepId: "-separator-update",
updateId: "-update",
updateURIId: "-updateURI",
deleteSepId: "-separator-delete",
deleteId: "-delete",
deleteAllId: "-deleteAll",
sortSepId: "-separator-sort",
sortId: "-sort",
undoId: "-undo",
redoId: "-redo",
propsSepId: "-separator-properties",
propsId: "-properties",
btnMenuSepId: "-separator-buttonMenu",
btnMenuId: "-buttonMenu",
__proto__: null
};
var btnId = this.button.id;
for(var p in shortcuts)
this[p] = btnId + shortcuts[p];
},
addContextMenu: function() {
_log("addContextMenu()");
this.addContextMenu = function() {};
var cm = this.$(this.cmId);
cm && cm.parentNode.removeChild(cm);
cm = this.cm = this.parseXULFromString('\
<menupopup xmlns="' + xulns + '"\
id="' + this.cmId + '"\
onpopupshowing="\
if(event.target != this)\
return true;\
document.popupNode = this.parentNode.triggerNode || document.popupNode;\
return this.bookmarks.initContextMenu(this.parentNode.triggerNode || document.popupNode);"\
onpopuphidden="if(event.target == this) document.popupNode = null;">\
<menuitem id="' + this.addBookmarkId + '"\
closemenu="single"\
oncommand="this.parentNode.bookmarks.addBookmark(this.parentNode.triggerNode || document.popupNode);"\
label="' + this.getLabel("placesContext_new:bookmark", "New Bookmark").replace(/…$/, "") + '"\
accesskey="' + this.getAccesskey("placesContext_new:bookmark", "B") + '" />\
<menuitem id="' + this.addSepId + '"\
closemenu="single"\
oncommand="this.parentNode.bookmarks.addSeparator(this.parentNode.triggerNode || document.popupNode);"\
label="' + this.getLabel("placesContext_new:separator", "New Separator") + '"\
accesskey="' + this.getAccesskey("placesContext_new:separator", "S") + '" />\
\
<menuseparator id="' + this.bmAllSepId + '" />\
<menuitem id="' + this.bmAllId + '"\
closemenu="single"\
oncommand="this.parentNode.bookmarks.bookmarkAllTabs(this.parentNode.triggerNode || document.popupNode);"\
label="' + _localize("Bookmark All Tabs") + '"\
accesskey="' + _localize("T", "bookmarkAllTabsKey") + '" />\
\
<menuseparator id="' + this.updateSepId + '" />\
<menuitem id="' + this.updateId + '"\
closemenu="single"\
oncommand="this.parentNode.bookmarks.updateBookmark(this.parentNode.triggerNode || document.popupNode);"\
label="' + _localize("Update") + '"\
accesskey="' + _localize("p", "updateKey") + '" />\
<menuitem id="' + this.updateURIId + '"\
closemenu="single"\
oncommand="this.parentNode.bookmarks.updateBookmark(this.parentNode.triggerNode || document.popupNode, true);"\
label="' + _localize("Update Location") + '"\
accesskey="' + _localize("L", "updateLocationKey") + '" />\
\
<menuseparator id="' + this.deleteSepId + '" />\
<menuitem id="' + this.deleteId + '"\
closemenu="single"\
oncommand="this.parentNode.bookmarks.deleteBookmark(this.parentNode.triggerNode || document.popupNode);"\
label="' + this.getLabel("placesContext_delete", "Delete") + '"\
accesskey="' + this.getAccesskey("placesContext_delete", "D") + '" />\
<menuitem id="' + this.deleteAllId + '"\
oncommand="this.parentNode.bookmarks.deleteAllBookmarks();"\
label="' + _localize("Delete All Bookmarks") + '"\
accesskey="' + _localize("A", "deleteAllKey") + '" />\
\
<menuseparator id="' + this.sortSepId + '" />\
<menu id="' + this.sortId + '"\
label="' + _localize("Sort") + '"\
accesskey="' + _localize("S", "sortKey") + '">\
<menupopup>\
<menuitem\
closemenu="single"\
oncommand="this.parentNode.parentNode.parentNode.bookmarks.sortBookmarks([\'name\']);"\
label="' + _localize("By Name, A>Z") + '"\
accesskey="' + _localize("N", "sortByNameAZKey") + '" />\
<menuitem\
closemenu="single"\
oncommand="this.parentNode.parentNode.parentNode.bookmarks.sortBookmarks([\'name\'], true);"\
label="' + _localize("By Name, Z>A") + '"\
accesskey="' + _localize("N", "sortByNameZAKey") + '" />\
<menuseparator />\
<menuitem\
closemenu="single"\
oncommand="this.parentNode.parentNode.parentNode.bookmarks.sortBookmarks([\'baseDomain\', \'host\', \'name\']);"\
label="' + _localize("By Base Domain, Host and Name, A>Z") + '"\
accesskey="' + _localize("B", "sortByBaseDomainHostNameAZKey") + '" />\
<menuitem\
closemenu="single"\
oncommand="this.parentNode.parentNode.parentNode.bookmarks.sortBookmarks([\'baseDomain\', \'host\', \'name\'], true);"\
label="' + _localize("By Base Domain, Host and Name, Z>A") + '"\
accesskey="' + _localize("B", "sortByBaseDomainHostNameZAKey") + '" />\
<menuseparator />\
<menuitem\
closemenu="single"\
oncommand="this.parentNode.parentNode.parentNode.bookmarks.sortBookmarks([\'host\', \'name\']);"\
label="' + _localize("By Host and Name, A>Z") + '"\
accesskey="' + _localize("H", "sortByHostNameAZKey") + '" />\
<menuitem\
closemenu="single"\
oncommand="this.parentNode.parentNode.parentNode.bookmarks.sortBookmarks([\'host\', \'name\'], true);"\
label="' + _localize("By Host and Name, Z>A") + '"\
accesskey="' + _localize("H", "sortByHostNameZAKey") + '" />\
</menupopup>\
</menu>\
\
<menuseparator />\
<menuitem id="' + this.undoId + '"\
closemenu="single"\
oncommand="this.parentNode.bookmarks.undo();"\
label="' + this.getLabel("menu_undo", this.getLabel("cmd_undo", "Undo")) + '"\
accesskey="' + this.getAccesskey("menu_undo", "U") + '" />\
<menuitem id="' + this.redoId + '"\
closemenu="single"\
oncommand="this.parentNode.bookmarks.redo();"\
label="' + this.getLabel("menu_redo", this.getLabel("cmd_redo", "Redo")) + '"\
accesskey="' + this.getAccesskey("menu_redo", "R") + '" />\
\
<menuseparator id="' + this.propsSepId + '" />\
<menuitem id="' + this.propsId + '"\
oncommand="this.parentNode.bookmarks.properties(this.parentNode.triggerNode || document.popupNode);"\
label="' + this.getLabel("placesContext_show:info", "Properties") + '"\
accesskey="' + this.getAccesskey("placesContext_show:info", "i") + '" />\
\
<menuseparator id="' + this.btnMenuSepId + '" />\
<menu id="' + this.btnMenuId + '"\
label="' + _localize("Button Menu") + '"\
accesskey="' + _localize("M", "buttonMenuKey") + '" />\
</menupopup>'
);
var cbPopup = this.$(this.button.defaultContextId);
if(!cbPopup)
Components.utils.reportError(this.errPrefix + "cb menu not found");
else {
cbPopup = cbPopup.cloneNode(true);
let id = "-" + this.btnNum + "-cloned";
cbPopup.id += id;
Array.slice(cbPopup.getElementsByAttribute("id", "*")).forEach(function(node) {
node.id += id;
});
let menu = cm.lastChild;
menu.appendChild(cbPopup);
}
cm.bookmarks = this;
this.$("mainPopupSet").appendChild(cm);
},
_hasPageContextItem: false,
get pageContextItem() {
this._hasPageContextItem = true;
var cbId = "sessionBookmarksPageContextItem";
var btnId = this.button.id;
Array.slice(document.getElementsByAttribute("cb_buttonId", btnId)).forEach(function(mi) {
mi.parentNode.removeChild(mi);
});
var mi = this.createElement("menuitem", {
label: _localize("Session Bookmark This Page"),
accesskey: _localize("S", "pageContextItemKey"),
tooltiptext: _localize("Button: %S")
.replace("%S", this.button.tooltipText || this.button.label),
oncommand: "this._bookmarks.addBookmark();",
cb_id: cbId,
cb_buttonId: btnId
});
mi._bookmarks = this;
var insPoint = this.bmItem.nextSibling;
while(insPoint && insPoint.getAttribute("cb_id") == cbId)
insPoint = insPoint.nextSibling;
this.bmPopup.insertBefore(mi, insPoint);
delete this.pageContextItem;
return this.pageContextItem = mi;
},
initPageContextMenu: function() {
var bmItem = this.bmItem = this.$("context-bookmarkpage");
if(!bmItem)
return;
_log("initPageContextMenu()");
var bmPopup = this.bmPopup = bmItem.parentNode;
bmPopup.addEventListener("popupshowing", this, true);
},
destroyPageContextMenu: function(force) {
_log("destroyPageContextMenu()");
this.bmPopup.removeEventListener("popupshowing", this, true);
if(force && this._hasPageContextItem && this.pageContextItem.parentNode)
this.bmPopup.removeChild(this.pageContextItem);
},
updatePageContextItemVisibility: function() {
var hidden = this.bmItem.hidden;
if(
!hidden
&& gContextMenu
&& gContextMenu.target
&& gContextMenu.target.ownerDocument.defaultView.top != content
)
hidden = true;
this.pageContextItem.hidden = hidden;
},
reload: function(data) {
this.mp.textContent = "";
this._undoStorage.length = 0;
this._undoPos = undefined;
if(data == undefined)
this.init();
else
this.loadData(data);
},
unsaved: false,
_saveInProgress: false,
_changed: false,
save: function() {
if(this._saveInProgress) {
this._changed = true;
return;
}
this._saveInProgress = true;
this._changed = false;
var data = [];
Array.forEach(
this.mp.getElementsByAttribute("cb_bookmarkItem", "*"),
function(mi) {
if(mi.localName == "menuseparator") {
data.push(this._sep);
return;
}
var section = [
this._label + this.escapeString(mi.getAttribute("label")),
this._uri + this.escapeString(mi.getAttribute("cb_uri"))
];
var icon = mi.getAttribute("image");
var ssData = mi.getAttribute("cb_ssData");
icon && section.push(this._icon + this.escapeString(icon));
ssData && section.push(this._session + this.escapeString(ssData));
data.push(section.join("\n"));
},
this
);
this.copyFileAsync(this.file, this.backupFile, function(status) {
if(!Components.isSuccessCode(status))
Components.utils.reportError(this.errPrefix + "copyFileAsync() failed");
// Backup failed? But we still can try save user data.
this.writeToFileAsync(data.join("\n\n"), this.file, function(status, data) {
if(!Components.isSuccessCode(status))
Components.utils.reportError(this.errPrefix + "writeToFileAsync() failed");
else {
// Private windows in SeaMonkey doesn't have "windowtype"
let isSeaMonkey = this.appName == "SeaMonkey";
let ws = this.wm.getEnumerator(isSeaMonkey ? null : "navigator:browser");
while(ws.hasMoreElements()) {
let w = ws.getNext();
if(w == window)
continue;
let btn = w.document.getElementById(this.button.id);
if(btn && btn.bookmarks) w.setTimeout(function(btn) {
btn.bookmarks.reload(data);
}, 0, btn);
}
}
this._saveInProgress = false;
if(this._changed) setTimeout(function(_this) {
_this.save();
}, 0, this);
}, this);
}, this);
this.unsaved = false;
},
scheduleSave: function() {
if(this.button.open || this.button.getAttribute("open") == "true")
this.unsaved = true;
else
this.save();
},
checkUnsaved: function() {
this.unsaved && this.save();
},
getMenuitem: function(label, uri, icon, ssData) {
if(!ssData)
ssData = "";
var mi = this.createElement("menuitem", {
"class": "menuitem-iconic bookmark-item menuitem-with-favicon",
closemenu: this.options.leftClickCloseMenu ? "auto" : "none",
label: label || "",
cb_uri: uri || "",
cb_ssData: ssData,
tooltiptext: this.decodeURI(uri || ""),
image: icon || "",
cb_bookmarkItem: "true"
});
// Faster way to check for "privateTab-isPrivate" in JSON.parse(ssData).attributes
if(ssData.indexOf('"privateTab-isPrivate":"true"') > 0)
mi.setAttribute("privateTab-isPrivate", "true");
return mi;
},
decodeURI: function(uri) {
if(uri) try {
return losslessDecodeURI(makeURI(uri));
}
catch(e) {
Components.utils.reportError(e);
}
return uri;
},
getSeparator: function() {
return this.createElement("menuseparator", {
cb_bookmarkItem: "true"
});
},
tabData: function(o) {
if(o) for(var p in o) if(o.hasOwnProperty(p))
this[p] = o[p];
},
getTabData: function(tab) {
if(tab instanceof this.tabData)
return tab;
if(!tab)
tab = gBrowser.selectedTab;
if(this.options.useSessions) {
var ssData = this.getTabState(tab);
if("JSON" in window) try {
let data = JSON.parse(ssData);
if(!this.options.saveTabHistory) {
data.entries = [data.entries[data.index - 1]];
data.index = 1;
}
this.cleanupSessionData(data);
ssData = JSON.stringify(data);
}
catch(e) {
Components.utils.reportError(this.errPrefix + "getTabData: session data tweaks failed");
Components.utils.reportError(e);
}
}
return new this.tabData({
label: tab.label,
uri: tab.linkedBrowser && tab.linkedBrowser.currentURI.spec,
icon: this.cachedIcon(tab.image),
ssData: ssData,
tab: tab
});
},
getTabState: function(tab) {
this.cleanupTabStateCache(tab);
return this.ss.getTabState(tab);
},
cleanupTabStateCache: function(tab) {
// Inspired by code from UnloadTab extension
// https://addons.mozilla.org/files/compare/233879...223485/file/chrome/content/unloadtab.js#L928
// Try flush cached data for tab to get correct scroll position
var scope = this.ssTabCacheScope;
if(scope && "TabStateCache" in scope && "delete" in scope.TabStateCache) try {
scope.TabStateCache.delete(tab);
return true;
}
catch(e) {
Components.utils.reportError(e);
}
_log("clearTabStateCache() failed!");
return false;
},
get ssTabCacheScope() {
var scope;
try { // Firefox 28+
scope = Components.utils.import("resource:///modules/sessionstore/TabStateCache.jsm", {});
}
catch(e) {
}
if(!scope || !("TabStateCache" in scope)) try {
scope = Components.utils.import("resource:///modules/sessionstore/SessionStore.jsm", {});
}
catch(e) {
}
if(scope && !("TabStateCache" in scope))
scope = null;
delete this.ssTabCacheScope;
return this.ssTabCacheScope = scope;
},
cleanupSessionData: function(data) {
if(!data)
return;
//_log("cleanupSessionData:\n" + JSON.stringify(data, null, " "));
if(!this.options.saveTabPinnedState)
delete data.pinned;
if("extData" in data) {
let extData = data.extData;
if(extData && typeof extData == "object") {
// Built-in Panorama
delete extData["tabview-tab"];
// Tree Style Tab https://addons.mozilla.org/firefox/addon/tree-style-tab/
delete extData["treestyletab-id"];
delete extData["treestyletab-children"];
delete extData["treestyletab-parent"];
delete extData["treestyletab-ancestors"];
delete extData["treestyletab-nest"];
delete extData["treestyletab-insert-before"];
delete extData["treestyletab-insert-after"];
delete extData["treestyletab-closed-set-id"];
delete extData["treestyletab-id-new"];
delete extData["treestyletab-id-restoring"];
delete extData["treestyletab-children-restoring"];
delete extData["treestyletab-collapsed"];
// Tab Utilities https://addons.mozilla.org/firefox/addon/tab-utilities/
delete extData.group;
delete extData["group-color"];
delete extData["group-collapsed"];
delete extData["group-counter"];
}
}
if("attributes" in data) {
let attrs = data.attributes;
if(attrs && typeof attrs == "object") {
// TabKit 2nd Edition https://addons.mozilla.org/firefox/addon/tabkit-2nd-edition/
delete attrs.tabid;
delete attrs.possibleparent;
delete attrs.outoforder;
delete attrs.uriKey;
delete attrs.groupid;
delete attrs.openerGroup;
delete attrs.uriGroup;
}
}
},
getItemByTabData: function(td, checkSession) {
var mis = this.mp.getElementsByAttribute("cb_uri", td.uri);
var mi = mis.length && mis[0];
if(
mi
&& mi.getAttribute("label") == td.label
&& mi.getAttribute("image") == td.icon
&& (
!checkSession
|| !this.options.useSessions
|| mi.getAttribute("cb_ssData") == td.ssData
)
)
return mi;
return null;
},
addBookmark: function() {
return this.ensureLoaded(this._addBookmark, this, arguments);
},
_addBookmark: function(insPoint, tab, undoBuffer) {
var canToggle = this.options.allowToggleBookmark
&& (!insPoint || insPoint == this.button);
var td = this.getTabData(tab);
if(canToggle || this.options.checkDuplicates) {
let checkSession = canToggle
? false
: this.options.checkDuplicatesSession;
let mi = this.getItemByTabData(td, checkSession);
if(mi) {
if(canToggle) {
this.blink(this.button, 0.05);
this.notify(_localize("Bookmark removed"));
this.deleteBookmark(mi);
return null;
}
this.blink(mi, 0.5);
this.notify(_localize("Bookmark already exists"));