-
Notifications
You must be signed in to change notification settings - Fork 193
/
Copy pathbuffer.js
1873 lines (1616 loc) · 70.6 KB
/
buffer.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
// Copyright (c) 2006-2009 by Martin Stubenschrott <[email protected]>
// Copyright (c) 2007-2009 by Doug Kearns <[email protected]>
// Copyright (c) 2008-2010 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
Cu.import("resource://gre/modules/XPCOMUtils.jsm", modules);
const Point = Struct("x", "y");
/**
* A class to manage the primary web content buffer. The name comes
* from Vim's term, 'buffer', which signifies instances of open
* files.
* @instance buffer
*/
const Buffer = Module("buffer", {
requires: ["config"],
init: function () {
this.pageInfo = {};
this.addPageInfoSection("f", "Feeds", function (verbose) {
let doc = config.browser.contentDocument;
const feedTypes = {
"application/rss+xml": "RSS",
"application/atom+xml": "Atom",
"text/xml": "XML",
"application/xml": "XML",
"application/rdf+xml": "XML"
};
function isValidFeed(data, principal, isFeed) {
if (!data || !principal)
return false;
if (!isFeed) {
var type = data.type && data.type.toLowerCase();
type = type.replace(/^\s+|\s*(?:;.*)?$/g, "");
isFeed = ["application/rss+xml", "application/atom+xml"].indexOf(type) >= 0 ||
// really slimy: general XML types with magic letters in the title
type in feedTypes && /\brss\b/i.test(data.title);
}
if (isFeed) {
try {
window.urlSecurityCheck(data.href, principal,
Ci.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
}
catch (e) {
isFeed = false;
}
}
if (type)
data.type = type;
return isFeed;
}
let nFeed = 0;
for (let link in util.evaluateXPath(["link[@href and (@rel='feed' or (@rel='alternate' and @type))]"], doc)) {
let rel = link.rel.toLowerCase();
let feed = { title: link.title, href: link.href, type: link.type || "" };
if (isValidFeed(feed, doc.nodePrincipal, rel == "feed")) {
nFeed++;
let type = feedTypes[feed.type] || "RSS";
if (verbose)
yield [feed.title, xml`${template.highlightURL(feed.href, true)}<span class="extra-info"> (${type})</span>`];
}
}
if (!verbose && nFeed)
yield nFeed + " feed" + (nFeed > 1 ? "s" : "");
});
this.addPageInfoSection("g", "Document", function (verbose) {
let doc = config.browser.contentDocument;
// get file size
const ACCESS_READ = Ci.nsICache.ACCESS_READ;
let cacheKey = doc.location.toString().replace(/#.*$/, "");
for (let proto of ["HTTP", "FTP"]) {
try {
var cacheEntryDescriptor = services.get("cache").createSession(proto, 0, true)
.openCacheEntry(cacheKey, ACCESS_READ, false);
break;
}
catch (e) {}
}
let pageSize = []; // [0] bytes; [1] kbytes
if (cacheEntryDescriptor) {
pageSize[0] = util.formatBytes(cacheEntryDescriptor.dataSize, 0, false);
pageSize[1] = util.formatBytes(cacheEntryDescriptor.dataSize, 2, true);
if (pageSize[1] == pageSize[0])
pageSize.length = 1; // don't output "xx Bytes" twice
}
let lastModVerbose = new Date(doc.lastModified).toLocaleString();
let lastMod = new Date(doc.lastModified).toLocaleFormat("%x %X");
if (lastModVerbose == "Invalid Date" || new Date(doc.lastModified).getFullYear() == 1970)
lastModVerbose = lastMod = null;
if (!verbose) {
if (pageSize[0])
yield (pageSize[1] || pageSize[0]) + " bytes";
yield lastMod;
return;
}
yield ["Title", doc.title];
yield ["URL", template.highlightURL(doc.location.toString(), true)];
let ref = "referrer" in doc && doc.referrer;
if (ref)
yield ["Referrer", template.highlightURL(ref, true)];
if (pageSize[0])
yield ["File Size", pageSize[1] ? pageSize[1] + " (" + pageSize[0] + ")"
: pageSize[0]];
yield ["Mime-Type", doc.contentType];
yield ["Encoding", doc.characterSet];
yield ["Compatibility", doc.compatMode == "BackCompat" ? "Quirks Mode" : "Full/Almost Standards Mode"];
if (lastModVerbose)
yield ["Last Modified", lastModVerbose];
});
this.addPageInfoSection("m", "Meta Tags", function (verbose) {
// get meta tag data, sort and put into pageMeta[]
let metaNodes = config.browser.contentDocument.getElementsByTagName("meta");
return Array.map(metaNodes, function (node) [(node.name || node.httpEquiv), template.highlightURL(node.content)])
.sort(function (a, b) util.compareIgnoreCase(a[0], b[0]));
});
},
destroy: function () {
},
_triggerLoadAutocmd: function _triggerLoadAutocmd(name, doc) {
let args = {
url: doc.location.href,
title: doc.title
};
if (liberator.has("tabs")) {
args.tab = tabs.getContentIndex(doc) + 1;
args.doc = "tabs.getTab(" + (args.tab - 1) + ").linkedBrowser.contentDocument";
}
autocommands.trigger(name, args);
},
// called when the active document is scrolled
_updateBufferPosition: function _updateBufferPosition() {
statusline.updateField("position");
// modes.show();
},
onDOMContentLoaded: function onDOMContentLoaded(event) {
let doc = event.originalTarget;
if (doc instanceof HTMLDocument && !doc.defaultView.frameElement)
this._triggerLoadAutocmd("DOMLoad", doc);
},
// TODO: see what can be moved to onDOMContentLoaded()
// event listener which is is called on each page load, even if the
// page is loaded in a background tab
onPageLoad: function onPageLoad(event) {
if (event.originalTarget instanceof HTMLDocument) {
let doc = event.originalTarget;
// document is part of a frameset
if (doc.defaultView.frameElement) {
return;
}
// code which should happen for all (also background) newly loaded tabs goes here:
// mark the buffer as loaded, we can't use buffer.loaded
// since that always refers to the current buffer, while doc can be
// any buffer, even in a background tab
doc.pageIsFullyLoaded = 1;
// code which is only relevant if the page load is the current tab goes here:
if (doc == config.browser.contentDocument) {
// we want to stay in command mode after a page has loaded
// TODO: move somewhere else, as focusing can already happen earlier than on "load"
if (options.focuscontent) {
setTimeout(function () {
let focused = liberator.focus;
if (focused && (focused.value != null) && focused.value.length == 0)
focused.blur();
}, 0);
}
}
// else // background tab
// liberator.echomsg("Background tab loaded: " + doc.title || doc.location.href);
this._triggerLoadAutocmd("PageLoad", doc);
}
},
/**
* @property {Object} The document loading progress listener.
*/
progressListener: {
QueryInterface: XPCOMUtils.generateQI([Ci.nsISupportsWeakReference, Ci.nsIWebProgressListener, Ci.nsIMsgStatusFeedback, Ci.nsIActivityMgrListener, Ci.nsIActivityListener]),
// XXX: function may later be needed to detect a canceled synchronous openURL()
onStateChange: function onStateChange(webProgress, request, flags, status) {
onStateChange.superapply(this, arguments);
// STATE_IS_DOCUMENT | STATE_IS_WINDOW is important, because we also
// receive statechange events for loading images and other parts of the web page
if (flags & (Ci.nsIWebProgressListener.STATE_IS_DOCUMENT | Ci.nsIWebProgressListener.STATE_IS_WINDOW)) {
// This fires when the load event is initiated
// only thrown for the current tab, not when another tab changes
if (flags & Ci.nsIWebProgressListener.STATE_START) {
webProgress.DOMWindow.document.pageIsFullyLoaded = 0;
buffer.loaded = 0;
autocommands.trigger("PageLoadPre", { url: buffer.URL });
// don't reset mode if a frame of the frameset gets reloaded which
// is not the focused frame
if (document.commandDispatcher.focusedWindow == webProgress.DOMWindow) {
setTimeout(function () { modes.reset(false); },
liberator.mode == modes.HINTS ? 500 : 0);
}
}
else if (flags & Ci.nsIWebProgressListener.STATE_STOP) {
webProgress.DOMWindow.document.pageIsFullyLoaded = (status == 0 ? 1 : 2);
buffer.loaded = (status == 0 ? 1 : 2);
}
}
},
// for notifying the user about secure web pages
onSecurityChange: function onSecurityChange(webProgress, request, state) {
onSecurityChange.superapply(this, arguments);
statusline.updateField("ssl", state);
},
onStatusChange: function onStatusChange(webProgress, request, status, message) {
onStatusChange.superapply(this, arguments);
},
onProgressChange: function onProgressChange(webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress) {
onProgressChange.superapply(this, arguments);
},
// happens when the users switches tabs
onLocationChange: function onLocationChange() {
onLocationChange.superapply(this, arguments);
statusline.updateField("location");
statusline.updateField("bookmark");
statusline.updateField("history");
statusline.updateField("zoomlevel");
// This is a bit scary but we trigger ignore mode when the new URL is in the list
// of pages with ignored keys and then exit it on a new page but ONLY, if:
// a) The new page hasn't ignore as well and
// b) We initiated ignore mode, and not the user manually with <Insert>
if (modules.ignoreKeys != undefined) {
let ignoredKeyExceptions = ignoreKeys.hasIgnoredKeys(buffer.URL);
if (ignoredKeyExceptions !== null)
modes.passAllKeysExceptSome(ignoredKeyExceptions);
else if (modes._passKeysExceptions !== null)
modes.passAllKeys = false;
}
autocommands.trigger("LocationChange", { url: buffer.URL });
// if this is not delayed we get the position of the old buffer
setTimeout(function () { statusline.updateField("position"); }, 250);
},
// called at the very end of a page load
asyncUpdateUI: function asyncUpdateUI() {
asyncUpdateUI.superapply(this, arguments);
},
setOverLink: function setOverLink(link, b) {
let ssli = options.showstatuslinks;
if (ssli == 3) {
setOverLink.superapply(this, arguments);
return;
}
if (link && ssli) {
if (ssli == 1) {
statusline.updateField("location", "Link: " + link);
statusline.updateField("bookmark", link);
}
else if (ssli == 2)
liberator.echo("Link: " + link, commandline.DISALLOW_MULTILINE);
}
if (link == "") {
if (ssli == 1) {
statusline.updateField("location");
statusline.updateField("bookmark");
}
else if (ssli == 2)
modes.show();
}
},
},
/**
* @property {Array} The alternative style sheets for the current
* buffer. Only returns style sheets for the 'screen' media type.
*/
get alternateStyleSheets() {
let stylesheets = window.getAllStyleSheets(config.browser.contentWindow);
return stylesheets.filter(
function (stylesheet) /^(screen|all|)$/i.test(stylesheet.media.mediaText) && !/^\s*$/.test(stylesheet.title)
);
},
/**
* @property {Array[Window]} All frames in the current buffer.
*/
getAllFrames: function(win) {
let frames = [];
(function rec(frame) {
if (frame.document.body instanceof HTMLBodyElement)
frames.push(frame);
Array.forEach(frame.frames, rec);
})(win || config.browser.contentWindow);
return frames;
},
/**
* @property {Object} A map of page info sections to their
* content generating functions.
*/
pageInfo: null,
/**
* @property {number} A value indicating whether the buffer is loaded.
* Values may be:
* 0 - Loading.
* 1 - Fully loaded.
* 2 - Load failed.
*/
get loaded() {
let doc = config.browser.contentDocument;
if (doc.pageIsFullyLoaded !== undefined)
return doc.pageIsFullyLoaded;
return 0; // in doubt return "loading"
},
set loaded(value) {
config.browser.contentDocument.pageIsFullyLoaded = value;
},
/**
* @property {Object} The local state store for the currently selected
* tab.
*/
get localStore() {
let content = config.browser.contentWindow;
if (!content.liberatorStore)
content.liberatorStore = {};
return content.liberatorStore;
},
/**
* @property {Node} The last focused input field in the buffer. Used
* by the "gi" key binding.
*/
get lastInputField() config.browser.contentDocument.lastInputField || null,
set lastInputField(value) { config.browser.contentDocument.lastInputField = value; },
/**
* @property {string} The current top-level document's URL.
*/
get URL() window.content ? window.content.location.href : config.browser.currentURI.spec,
/**
* @property {string} The current top-level document's URL, sans any
* fragment identifier.
*/
get URI() {
let loc = config.browser.contentWindow.location;
return loc.href.substr(0, loc.href.length - loc.hash.length);
},
/**
* @property {String} The current document's character set
*/
get charset() {
try {
return config.browser.docShell.charset;
} catch (e) {
return "UTF-8";
}
},
/**
* @property {number} The buffer's height in pixels.
*/
get pageHeight() window.content ? window.content.innerHeight : config.browser.contentWindow.innerHeight,
/**
* @property {number} The current browser's text zoom level, as a
* percentage with 100 as 'normal'. Only affects text size.
*/
get textZoom() config.browser.markupDocumentViewer.textZoom * 100,
set textZoom(value) { Buffer.setZoom(value, false); },
/**
* @property {number} The current browser's zoom level, as a
* percentage with 100 as 'normal'.
*/
get zoomLevel() {
let v = config.browser.markupDocumentViewer;
if (v == null)
return this.ZoomManager.zoom * 100;
return v[v.textZoom == 1 ? "fullZoom" : "textZoom"] * 100;
},
/**
* @property {number} The current browser's text zoom level, as a
* percentage with 100 as 'normal'. Affects text size, as well as
* image size and block size.
*/
get fullZoom() config.browser.markupDocumentViewer.fullZoom * 100,
set fullZoom(value) { Buffer.setZoom(value, true); },
/**
* @property {string} The current document's title.
*/
get title() config.browser.contentTitle,
/**
* @property {number} The buffer's horizontal scroll percentile.
*/
get scrollXPercent() {
let win = Buffer.findScrollableWindow();
if (win.scrollMaxX > 0)
return Math.round(win.scrollX / win.scrollMaxX * 100);
else
return 0;
},
/**
* @property {number} The buffer's vertical scroll percentile.
*/
get scrollYPercent() {
let win = Buffer.findScrollableWindow();
if (win.scrollMaxY > 0)
return Math.round(win.scrollY / win.scrollMaxY * 100);
else
return 0;
},
/**
* Adds a new section to the page information output.
*
* @param {string} option The section's value in 'pageinfo'.
* @param {string} title The heading for this section's
* output.
* @param {function} func The function to generate this
* section's output.
*/
addPageInfoSection: function addPageInfoSection(option, title, func) {
this.pageInfo[option] = [func, title];
},
/**
* Returns the currently selected word. If the selection is
* null, it tries to guess the word that the caret is
* positioned in.
*
* NOTE: might change the selection
*
* @returns {string}
*/
// FIXME: getSelection() doesn't always preserve line endings, see:
// https://www.mozdev.org/bugs/show_bug.cgi?id=19303
getCurrentWord: function () {
function _getCurrentWord (win) {
let elem = win.frameElement;
if (elem && elem.getClientRects().length === 0)
return;
let selection = win.getSelection();
if (selection.rangeCount <= 0)
return;
let range = selection.getRangeAt(0);
if (selection.isCollapsed) {
let selController = buffer.selectionController;
let caretmode = selController.getCaretEnabled();
selController.setCaretEnabled(true);
// Only move backwards if the previous character is not a space.
if (range.startOffset > 0 && !/\s/.test(range.startContainer.textContent[range.startOffset - 1]))
selController.wordMove(false, false);
selController.wordMove(true, true);
selController.setCaretEnabled(caretmode);
return String.match(selection, /\w*/)[0];
}
if (util.computedStyle(range.startContainer).whiteSpace == "pre"
&& util.computedStyle(range.endContainer).whiteSpace == "pre")
return String(range);
return String(selection);
}
return util.Array.compact(buffer.getAllFrames().map(_getCurrentWord)).join("\n");
},
/**
* Focuses the given element. In contrast to a simple
* elem.focus() call, this function works for iframes and
* image maps.
*
* @param {Node} elem The element to focus.
*/
focusElement: function (elem) {
if (elem instanceof HTMLFrameElement || elem instanceof HTMLIFrameElement)
Buffer.focusedWindow = elem.contentWindow;
else if (elem instanceof HTMLInputElement && elem.type == "file") {
Buffer.openUploadPrompt(elem);
buffer.lastInputField = elem;
}
else if (elem instanceof HTMLLabelElement && elem.control) {
Buffer.focusElement(elem.control);
}
else {
elem.focus();
// for imagemap
if (elem instanceof HTMLAreaElement) {
let doc = config.browser.contentDocument;
try {
let [x, y] = elem.getAttribute("coords").split(",").map(parseFloat);
elem.dispatchEvent(events.create(doc, "mouseover", { screenX: x, screenY: y }));
}
catch (e) {}
}
}
},
/**
* Tries to guess links the like of "next" and "prev". Though it has a
* singularly horrendous name, it turns out to be quite useful.
*
* @param {string} rel The relationship to look for. Looks for
* links with matching @rel or @rev attributes, and,
* failing that, looks for an option named rel +
* "pattern", and finds the last link matching that
* RegExp.
*/
followDocumentRelationship: function (rel, ...synonyms) {
let regexes = options.get(rel + "pattern").values
.map(function (re) RegExp(re, "i"));
synonyms.unshift(rel);
function followFrame(frame) {
function* iter(elems) {
for (let i = 0; i < elems.length; i++)
for (let rel of synonyms)
if (elems[i].rel.toLowerCase() == rel || elems[i].rev.toLowerCase() == rel)
yield elems[i];
}
// <link>s have higher priority than normal <a> hrefs
let elems = frame.document.getElementsByTagName("link");
for (let elem of iter(elems)) {
liberator.open(elem.href);
return true;
}
// no links? ok, look for hrefs
elems = frame.document.getElementsByTagName("a");
for (let elem of iter(elems)) {
buffer.followLink(elem, liberator.CURRENT_TAB);
return true;
}
let res = util.evaluateXPath(options.get("hinttags").value, frame.document);
for (let regex of regexes) {
for (let i in util.range(res.snapshotLength, 0, -1)) {
let elem = res.snapshotItem(i);
if (regex.test(elem.textContent) || regex.test(elem.title) ||
Array.some(elem.childNodes, function (child) regex.test(child.alt))) {
if (elem.href
&& typeof history.session[history.session.index - 1] !== "undefined"
&& history.session[history.session.index - 1].URI.spec === elem.href) {
history.stepTo(-1);
return true;
}
if (elem.href
&& typeof history.session[history.session.index + 1] !== "undefined"
&& history.session[history.session.index + 1].URI.spec === elem.href) {
history.stepTo(1);
return true;
}
buffer.followLink(elem, liberator.CURRENT_TAB);
return true;
}
}
}
return false;
}
let ret = followFrame(config.browser.contentWindow);
if (!ret) {
// only loop through frames (ordered by size) if the main content didn't match
let frames = buffer.getAllFrames().slice(1)
.sort( function(a, b) {
return ((b.scrollMaxX+b.innerWidth)*(b.scrollMaxY+b.innerHeight)) - ((a.scrollMaxX+a.innerWidth)*(a.scrollMaxY+a.innerHeight))
} );
ret = Array.some(frames, followFrame);
}
if (!ret)
liberator.beep();
},
/**
* Fakes a click on a link.
*
* @param {Node} elem The element to click.
* @param {number} where Where to open the link. See
* {@link liberator.open}.
*/
followLink: function (elem, where) {
let doc = elem.ownerDocument;
let view = doc.defaultView;
let offsetX = 1;
let offsetY = 1;
if (elem instanceof HTMLFrameElement || elem instanceof HTMLIFrameElement) {
elem.contentWindow.focus();
return;
}
else if (elem instanceof HTMLAreaElement) { // for imagemap
let coords = elem.getAttribute("coords").split(",");
offsetX = Number(coords[0]) + 1;
offsetY = Number(coords[1]) + 1;
}
else if (elem instanceof HTMLInputElement && elem.type == "file") {
Buffer.openUploadPrompt(elem);
return;
}
else if (elem instanceof HTMLLabelElement && elem.control) {
buffer.followLink(elem.control, where);
return;
}
let ctrlKey = false, shiftKey = false;
switch (where) {
case liberator.NEW_TAB:
case liberator.NEW_BACKGROUND_TAB:
ctrlKey = true;
shiftKey = (where != liberator.NEW_BACKGROUND_TAB);
break;
case liberator.NEW_WINDOW:
shiftKey = true;
break;
case liberator.CURRENT_TAB:
break;
default:
liberator.echoerr("Invalid where argument for followLink(): " + where);
}
elem.focus();
options.withContext(function () {
options.setPref("browser.tabs.loadInBackground", true);
["mousedown", "mouseup", "click"].forEach(function (event) {
elem.dispatchEvent(events.create(doc, event, {
screenX: offsetX, screenY: offsetY,
ctrlKey: ctrlKey, shiftKey: shiftKey, metaKey: ctrlKey
}));
});
});
},
/**
* @property {nsISelectionController} The current document's selection
* controller.
*/
get selectionController() Buffer.focusedWindow
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShell)
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsISelectionDisplay)
.QueryInterface(Ci.nsISelectionController),
/**
* Opens the appropriate context menu for <b>elem</b>.
*
* @param {Node} elem The context element.
*/
openContextMenu: function (elem) {
let menu = document.getElementById("contentAreaContextMenu");
menu.showPopup(elem, -1, -1, "context", "bottomleft", "topleft");
},
/**
* Saves a page link to disk.
*
* @param {HTMLAnchorElement} elem The page link to save.
* @param {boolean} skipPrompt Whether to open the "Save Link As..."
* dialog.
*/
saveLink: function (elem, skipPrompt) {
let doc = elem.ownerDocument;
let url = window.makeURLAbsolute(elem.baseURI, elem.href ? elem.href : elem.src);
let text = elem.textContent;
try {
window.urlSecurityCheck(url, doc.nodePrincipal);
// we always want to save that link relative to the current working directory
options.setPref("browser.download.lastDir", io.getCurrentDirectory().path);
window.saveURL(url, text, null, true, skipPrompt, makeURI(url, doc.characterSet), doc);
}
catch (e) {
liberator.echoerr(e);
}
},
/**
* Scrolls to the bottom of the current buffer.
*/
scrollBottom: function () {
Buffer.scrollElemToPercent(null, null, 100);
},
/**
* Scrolls the buffer laterally <b>cols</b> columns.
*
* @param {number} cols The number of columns to scroll. A positive
* value scrolls right and a negative value left.
*/
scrollColumns: function (cols) {
Buffer.scrollHorizontal(null, "columns", cols);
},
/**
* Scrolls to the top of the current buffer.
*/
scrollEnd: function () {
Buffer.scrollElemToPercent(null, 100, null);
},
/**
* Scrolls the buffer vertically <b>lines</b> rows.
*
* @param {number} lines The number of lines to scroll. A positive
* value scrolls down and a negative value up.
*/
scrollLines: function (lines) {
Buffer.scrollVertical(null, "lines", lines);
},
/**
* Scrolls the buffer vertically <b>pages</b> pages.
*
* @param {number} pages The number of pages to scroll. A positive
* value scrolls down and a negative value up.
*/
scrollPages: function (pages) {
Buffer.scrollVertical(null, "pages", pages);
},
/**
* Scrolls the buffer vertically 'scroll' lines.
*
* @param {boolean} direction The direction to scroll. If true then
* scroll down and if false scroll up.
* @param {number} count The multiple of 'scroll' lines to scroll.
* @optional
*/
scrollByScrollSize: function (direction, count) {
direction = direction ? 1 : -1;
count = count || 1;
let elem = Buffer.findScrollable(direction, false);
if (options.scroll > 0)
this.scrollLines(options.scroll * direction);
else // scroll half a page down in pixels
elem.scrollTop += Buffer.findScrollableWindow().innerHeight / 2 * direction;
},
_scrollByScrollSize: function _scrollByScrollSize(count, direction) {
if (count > 0)
options.scroll = count;
buffer.scrollByScrollSize(direction);
},
/**
* Scrolls the buffer to the specified screen percentiles.
*
* @param {number} x The horizontal page percentile.
* @param {number} y The vertical page percentile.
*/
scrollToPercent: function (x, y) {
Buffer.scrollElemToPercent(null, x, y);
},
/**
* Scrolls the buffer to the specified screen pixels.
*
* @param {number} x The horizontal pixel.
* @param {number} y The vertical pixel.
*/
scrollTo: function (x, y) {
marks.add("'", true);
config.browser.contentWindow.scrollTo(x, y);
},
/**
* Scrolls the current buffer laterally to its leftmost.
*/
scrollStart: function () {
Buffer.scrollElemToPercent(null, 0, null);
},
/**
* Scrolls the current buffer vertically to the top.
*/
scrollTop: function () {
Buffer.scrollElemToPercent(null, null, 0);
},
// TODO: allow callback for filtering out unwanted frames? User defined?
/**
* Shifts the focus to another frame within the buffer. Each buffer
* contains at least one frame.
*
* @param {number} count The number of frames to skip through.
* @param {boolean} forward The direction of motion.
*/
shiftFrameFocus: function (count, forward) {
let content = config.browser.contentWindow;
if (!(content.document instanceof HTMLDocument))
return;
count = Math.max(count, 1);
let frames = [];
// find all frames - depth-first search
(function findFrames(frame) {
if (frame.document.body instanceof HTMLBodyElement)
frames.push(frame);
Array.forEach(frame.frames, findFrames);
})(content);
if (frames.length == 0) // currently top is always included
return;
// remove all unfocusable frames
// TODO: find a better way to do this - walking the tree is too slow
let start = document.commandDispatcher.focusedWindow;
frames = frames.filter(function (frame) {
frame.focus();
return document.commandDispatcher.focusedWindow == frame;
});
start.focus();
// find the currently focused frame index
// TODO: If the window is a frameset then the first _frame_ should be
// focused. Since this is not the current FF behaviour,
// we initialize current to -1 so the first call takes us to the
// first frame.
let current = frames.indexOf(document.commandDispatcher.focusedWindow);
// calculate the next frame to focus
let next = current;
if (forward) {
next = current + count;
if (next > frames.length - 1) {
if (current == frames.length - 1)
liberator.beep();
next = frames.length - 1; // still allow the frame indicator to be activated
}
}
else {
next = current - count;
if (next < 0) {
if (current == 0)
liberator.beep();
next = 0; // still allow the frame indicator to be activated
}
}
// focus next frame and scroll into view
frames[next].focus();
if (frames[next] != window.content)
frames[next].frameElement.scrollIntoView(false);
// add the frame indicator
let doc = frames[next].document;
let indicator = util.xmlToDom(xml`<div highlight="FrameIndicator"/>`, doc);
doc.body.appendChild(indicator);
setTimeout(function () { doc.body.removeChild(indicator); }, 500);
// Doesn't unattach
//doc.body.setAttributeNS(NS.uri, "activeframe", "true");
//setTimeout(function () { doc.body.removeAttributeNS(NS.uri, "activeframe"); }, 500);
},
// similar to pageInfo
// TODO: print more useful information, just like the DOM inspector
/**
* Displays information about the specified element.
*
* @param {Node} elem The element to query.
*/
showElementInfo: function (elem) {
liberator.echo(xml`Element:<br/>${util.objectToString(elem, true)}`, commandline.FORCE_MULTILINE);
},
/**
* Displays information about the current buffer.
*
* @param {boolean} verbose Display more verbose information.
* @param {string} sections A string limiting the displayed sections.
* @default The value of 'pageinfo'.
*/
showPageInfo: function (verbose, sections) {
// Ctrl-g single line output
if (!verbose) {
let content = config.browser.contentWindow;
let file = content.document.location.pathname.split("/").pop() || "[No Name]";
let title = content.document.title || "[No Title]";
let info = template.map2(xml, "gf",
function (opt) template.map2(xml, buffer.pageInfo[opt][0](), util.identity, ", "),
", ");
if (bookmarks.isBookmarked(this.URL))
xml["+="](info, ", bookmarked");
let pageInfoText = xml`${JSON.stringify(file)} [${info}] ${title}`;
liberator.echo(pageInfoText, commandline.FORCE_SINGLELINE);
return;
}
let option = sections || options.pageinfo;
let list = template.map2(xml, option, function (option) {
let opt = buffer.pageInfo[option];
return opt ? template.table2(xml, opt[1], opt[0](true)) : undefined;
}, xml`<br/>`);
liberator.echo(template.genericOutput("Page Information", list), commandline.FORCE_MULTILINE);
},
/**
* Opens a viewer to inspect the source of the currently selected
* range.
*/
viewSelectionSource: function () {
// copied (and tuned somebit) from browser.jar -> nsContextMenu.js
let focusedWindow = document.commandDispatcher.focusedWindow;
if (focusedWindow == window)
focusedWindow = config.browser.contentWindow;
let docCharset = null;
if (focusedWindow)
docCharset = "charset=" + focusedWindow.document.characterSet;
let reference = null;
reference = focusedWindow.getSelection();
let docUrl = null;
window.openDialog("chrome://global/content/viewPartialSource.xul",
"_blank", "scrollbars,resizable,chrome,dialog=no",
docUrl, docCharset, reference, "selection");
},
/**
* Opens a viewer to inspect the source of the current buffer or the
* specified <b>url</b>. Either the default viewer or the configured
* external editor is used.
*
* @param {string} url The URL of the source.
* @default The current buffer.
* @param {boolean} useExternalEditor View the source in the external editor.
*/
viewSource: function (url, useExternalEditor) {
url = url || buffer.URI;
if (useExternalEditor)