2 * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
3 * (C) Copyright 2009-2010 John J. Foerch
5 * Portions of this file are derived from Vimperator,
6 * (C) Copyright 2006-2007 Martin Stubenschrott.
8 * Use, modification, and distribution are subject to the terms specified in the
12 define_variable("active_img_hint_background_color", "#88FF00",
13 "Color for the active image hint background.");
15 define_variable("img_hint_background_color", "yellow",
16 "Color for inactive image hint backgrounds.");
18 define_variable("active_hint_background_color", "#88FF00",
19 "Color for the active hint background.");
21 define_variable("hint_background_color", "yellow",
22 "Color for the inactive hint.");
25 define_variable("hint_digits", null,
26 "Null or a string of the digits to use as the counting base "+
27 "for hint numbers, starting with the digit that represents zero "+
28 "and ascending. If null, base 10 will be used with the normal "+
29 "hindu-arabic numerals.");
33 * hints_enumerate is a generator of natural numbers in the base defined
36 function hints_enumerate () {
37 var base = hint_digits.length;
41 yield n.map(function (x) hint_digits[x]).join("");
44 while (n[i] >= base && i > 0) {
57 * hints_parse converts a string that represents a natural number to an
58 * int. When hint_digits is non-null, it defines the base for conversion.
60 function hints_parse (str) {
62 var base = hint_digits.length;
64 for (var i = 0, p = str.length - 1; p >= 0; i++, p--) {
65 n += hint_digits.indexOf(str[i]) * Math.pow(base, p);
73 * Register hints style sheet
75 const hints_stylesheet = "chrome://conkeror-gui/content/hints.css";
76 register_user_stylesheet(hints_stylesheet);
79 function hints_simple_text_match (text, pattern) {
80 var pos = text.indexOf(pattern);
83 return [pos, pos + pattern.length];
86 define_variable('hints_text_match', hints_simple_text_match,
87 "A function which takes a string and a pattern (another string) "+
88 "and returns an array of [start, end] indices if the pattern was "+
89 "found in the string, or false if it was not.");
93 * In the hints interaction, a node can be selected either by typing
94 * the number of its associated hint, or by typing substrings of the
95 * text content of the node. In the case of selecting by text
96 * content, multiple substrings can be given by separating them with
99 function hint_manager (window, xpath_expr, focused_frame, focused_element) {
100 this.window = window;
102 this.valid_hints = [];
103 this.xpath_expr = xpath_expr;
104 this.focused_frame = focused_frame;
105 this.focused_element = focused_element;
106 this.last_selected_hint = null;
109 this.generate_hints();
111 hint_manager.prototype = {
112 constructor: hint_manager,
113 current_hint_string: "",
114 current_hint_number: -1,
117 * Create an initially hidden hint span element absolutely
118 * positioned over each element that matches
119 * hint_xpath_expression. This is done recursively for all frames
120 * and iframes. Information about the resulting hints are also
121 * stored in the hints array.
123 generate_hints: function () {
124 var topwin = this.window;
125 var top_height = topwin.innerHeight;
126 var top_width = topwin.innerWidth;
127 var hints = this.hints;
128 var xpath_expr = this.xpath_expr;
129 var focused_frame_hint = null, focused_element_hint = null;
130 var focused_frame = this.focused_frame;
131 var focused_element = this.focused_element;
133 function helper (window, offsetX, offsetY) {
134 var win_height = window.height;
135 var win_width = window.width;
138 var minX = offsetX < 0 ? -offsetX : 0;
139 var minY = offsetY < 0 ? -offsetY : 0;
140 var maxX = offsetX + win_width > top_width ? top_width - offsetX : top_width;
141 var maxY = offsetY + win_height > top_height ? top_height - offsetY : top_height;
143 var scrollX = window.scrollX;
144 var scrollY = window.scrollY;
146 var doc = window.document;
147 if (! doc.documentElement)
149 var res = doc.evaluate(xpath_expr, doc, xpath_lookup_namespace,
150 Ci.nsIDOMXPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
151 null /* existing results */);
153 var base_node = doc.createElementNS(XHTML_NS, "span");
154 base_node.className = "__conkeror_hint";
156 var fragment = doc.createDocumentFragment();
157 var rect, elem, text, node, show_text;
158 for (var j = 0; j < res.snapshotLength; j++) {
159 elem = res.snapshotItem(j);
160 rect = elem.getBoundingClientRect();
161 if (elem instanceof Ci.nsIDOMHTMLAreaElement) {
162 rect = { top: rect.top,
167 var coords = elem.getAttribute("coords")
168 .match(/^\D*(-?\d+)\D+(-?\d+)/);
169 if (coords.length == 3) {
170 rect.left += parseInt(coords[1]);
171 rect.top += parseInt(coords[2]);
175 if (!rect || rect.left > maxX || rect.right < minX || rect.top > maxY || rect.bottom < minY)
177 let style = topwin.getComputedStyle(elem, "");
178 if (style.display == "none" || style.visibility == "hidden")
180 if (! (elem instanceof Ci.nsIDOMHTMLAreaElement))
181 rect = elem.getClientRects()[0];
184 var nchildren = elem.childNodes.length;
185 if (elem instanceof Ci.nsIDOMHTMLAnchorElement &&
186 rect.width == 0 && rect.height == 0)
188 for (var c = 0; c < nchildren; ++c) {
189 var cc = elem.childNodes.item(c);
190 if (cc.getBoundingClientRect) {
191 rect = cc.getBoundingClientRect();
197 if (elem instanceof Ci.nsIDOMHTMLInputElement || elem instanceof Ci.nsIDOMHTMLTextAreaElement)
199 else if (elem instanceof Ci.nsIDOMHTMLSelectElement) {
200 if (elem.selectedIndex >= 0)
201 text = elem.item(elem.selectedIndex).text;
204 } else if (elem instanceof Ci.nsIDOMHTMLFrameElement) {
205 text = elem.name ? elem.name : "";
206 } else if (/^\s*$/.test(elem.textContent) &&
208 elem.childNodes.item(0) instanceof Ci.nsIDOMHTMLImageElement) {
209 text = elem.childNodes.item(0).alt;
212 text = elem.textContent;
214 node = base_node.cloneNode(true);
215 node.style.left = (rect.left + scrollX) + "px";
216 node.style.top = (rect.top + scrollY) + "px";
217 fragment.appendChild(node);
219 let hint = { text: text,
220 ltext: text.toLowerCase(),
225 show_text: show_text };
227 hint.saved_color = elem.style.color;
228 hint.saved_bgcolor = elem.style.backgroundColor;
232 if (elem == focused_element)
233 focused_element_hint = hint;
234 else if ((elem instanceof Ci.nsIDOMHTMLFrameElement ||
235 elem instanceof Ci.nsIDOMHTMLIFrameElement) &&
236 elem.contentWindow == focused_frame)
237 focused_frame_hint = hint;
239 doc.documentElement.appendChild(fragment);
241 /* Recurse into any IFRAME or FRAME elements */
242 var frametag = "frame";
244 var frames = doc.getElementsByTagName(frametag);
245 for (var i = 0, nframes = frames.length; i < nframes; ++i) {
247 rect = elem.getBoundingClientRect();
248 if (!rect || rect.left > maxX || rect.right < minX || rect.top > maxY || rect.bottom < minY)
250 helper(elem.contentWindow, offsetX + rect.left, offsetY + rect.top);
252 if (frametag == "frame") frametag = "iframe"; else break;
255 helper(topwin, 0, 0);
256 this.last_selected_hint = focused_element_hint || focused_frame_hint;
259 /* Updates valid_hints and also re-numbers and re-displays all hints. */
260 update_valid_hints: function () {
261 this.valid_hints = [];
264 var number_generator = hints_enumerate();
265 var active_number = this.current_hint_number;
266 var tokens = this.current_hint_string.split(" ");
267 var case_sensitive = (this.current_hint_string !=
268 this.current_hint_string.toLowerCase());
269 var rect, text, img_hint, doc, scrollX, scrollY;
271 for (var i = 0, h; (h = this.hints[i]); ++i) {
276 for (var j = 0, ntokens = tokens.length; j < ntokens; ++j) {
277 if (! hints_text_match(text, tokens[j])) {
280 h.hint.style.display = "none";
282 h.img_hint.style.display = "none";
283 if (h.saved_color != null) {
284 h.elem.style.backgroundColor = h.saved_bgcolor;
285 h.elem.style.color = h.saved_color;
294 if (h == this.last_selected_hint && active_number == -1)
295 this.current_hint_number = active_number = cur_number;
299 if (text == "" && h.elem.firstChild &&
300 h.elem.firstChild instanceof Ci.nsIDOMHTMLImageElement)
301 img_elem = h.elem.firstChild;
302 else if (h.elem instanceof Ci.nsIDOMHTMLImageElement)
307 rect = img_elem.getBoundingClientRect();
309 doc = h.elem.ownerDocument;
310 scrollX = doc.defaultView.scrollX;
311 scrollY = doc.defaultView.scrollY;
312 img_hint = doc.createElementNS(XHTML_NS, "span");
313 img_hint.className = "__conkeror_img_hint";
314 img_hint.style.left = (rect.left + scrollX) + "px";
315 img_hint.style.top = (rect.top + scrollY) + "px";
316 img_hint.style.width = (rect.right - rect.left) + "px";
317 img_hint.style.height = (rect.bottom - rect.top) + "px";
318 h.img_hint = img_hint;
319 doc.documentElement.appendChild(img_hint);
324 var bgcolor = (active_number == cur_number) ?
325 active_img_hint_background_color : img_hint_background_color;
326 h.img_hint.style.backgroundColor = bgcolor;
327 h.img_hint.style.display = "inline";
331 if (!h.img_hint && h.elem.style)
332 h.elem.style.backgroundColor = (active_number == cur_number) ?
333 active_hint_background_color : hint_background_color;
336 h.elem.style.color = "black";
340 label = number_generator.next();
343 if (h.elem instanceof Ci.nsIDOMHTMLFrameElement) {
345 } else if (h.show_text && !/^\s*$/.test(text)) {
346 let substrs = [[0,4]];
347 for (j = 0; j < ntokens; ++j) {
348 let m = hints_text_match(text, tokens[j]);
349 if (m == false) continue;
350 splice_range(substrs, m[0], m[1] + 2);
352 label += " " + substrs.map(function (x) {
353 return text.substring(x[0],Math.min(x[1], text.length));
354 }).join("..") + "..";
356 h.hint.textContent = label;
357 h.hint.style.display = "inline";
358 this.valid_hints.push(h);
362 if (active_number == -1)
366 select_hint: function (index) {
367 var old_index = this.current_hint_number;
368 if (index == old_index)
370 var vh = this.valid_hints;
371 var vl = this.valid_hints.length;
372 if (old_index >= 1 && old_index <= vl) {
373 var h = vh[old_index - 1];
375 h.img_hint.style.backgroundColor = img_hint_background_color;
377 h.elem.style.backgroundColor = hint_background_color;
379 this.current_hint_number = index;
380 this.last_selected_hint = null;
381 if (index >= 1 && index <= vl) {
384 h.img_hint.style.backgroundColor = active_img_hint_background_color;
386 h.elem.style.backgroundColor = active_hint_background_color;
387 this.last_selected_hint = h;
391 hide_hints: function () {
392 for (var i = 0, h; h = this.hints[i]; ++i) {
395 if (h.saved_color != null) {
396 h.elem.style.color = h.saved_color;
397 h.elem.style.backgroundColor = h.saved_bgcolor;
400 h.img_hint.style.display = "none";
401 h.hint.style.display = "none";
406 remove: function () {
407 for (var i = 0, h; h = this.hints[i]; ++i) {
408 if (h.visible && h.saved_color != null) {
409 h.elem.style.color = h.saved_color;
410 h.elem.style.backgroundColor = h.saved_bgcolor;
413 h.img_hint.parentNode.removeChild(h.img_hint);
414 h.hint.parentNode.removeChild(h.hint);
417 this.valid_hints = [];
422 * Show panel with currently selected URL.
424 function hints_url_panel (hints, window) {
425 var g = new dom_generator(window.document, XUL_NS);
427 var p = g.element("hbox", "class", "panel url", "flex", "0");
428 g.element("label", p, "value", "URL:", "class", "url-panel-label");
429 var url_value = g.element("label", p, "class", "url-panel-value",
430 "crop", "end", "flex", "1");
431 window.minibuffer.insert_before(p);
433 p.update = function () {
435 if (hints.manager && hints.manager.last_selected_hint) {
436 var elem = hints.manager.last_selected_hint.elem;
437 if (elem.hasAttribute("onmousedown") ||
438 elem.hasAttribute("onclick"))
442 var tag = elem.localName.toLowerCase();
443 if ((tag == "input" || tag == "button") &&
444 elem.type == "submit" && elem.form && elem.form.action)
446 s.push((elem.form.method || "GET").toUpperCase() + ":" +
450 var spec = load_spec(elem);
451 var uri = load_spec_uri_string(spec);
457 url_value.value = s.join(" ");
460 p.destroy = function () {
461 this.parentNode.removeChild(this);
467 define_variable("hints_display_url_panel", false,
468 "When selecting a hint, the URL can be displayed in a panel above "+
469 "the minibuffer. This is useful for confirming that the correct "+
470 "link is selected and that the URL is not evil. This option is "+
471 "most useful when hints_auto_exit_delay is long or disabled.");
480 define_keywords("$keymap", "$auto", "$hint_xpath_expression", "$multiple");
481 function hints_minibuffer_state (minibuffer, continuation, buffer) {
482 keywords(arguments, $keymap = hint_keymap, $auto);
483 basic_minibuffer_state.call(this, minibuffer, $prompt = arguments.$prompt,
484 $keymap = arguments.$keymap);
485 if (hints_display_url_panel)
486 this.url_panel = hints_url_panel(this, buffer.window);
487 this.original_prompt = arguments.$prompt;
488 this.continuation = continuation;
489 this.auto_exit = arguments.$auto ? true : false;
490 this.xpath_expr = arguments.$hint_xpath_expression;
491 this.auto_exit_timer_ID = null;
492 this.multiple = arguments.$multiple;
493 this.focused_element = buffer.focused_element;
494 this.focused_frame = buffer.focused_frame;
496 hints_minibuffer_state.prototype = {
497 constructor: hints_minibuffer_state,
498 __proto__: basic_minibuffer_state.prototype,
503 basic_minibuffer_state.prototype.load.call(this);
505 var buf = this.minibuffer.window.buffers.current;
506 this.manager = new hint_manager(buf.top_frame, this.xpath_expr,
507 this.focused_frame, this.focused_element);
509 this.manager.update_valid_hints();
511 this.url_panel.update();
513 clear_auto_exit_timer: function () {
514 var window = this.minibuffer.window;
515 if (this.auto_exit_timer_ID != null) {
516 window.clearTimeout(this.auto_exit_timer_ID);
517 this.auto_exit_timer_ID = null;
520 unload: function () {
521 this.clear_auto_exit_timer();
522 this.manager.hide_hints();
523 basic_minibuffer_state.prototype.unload.call(this);
525 destroy: function () {
526 this.clear_auto_exit_timer();
527 this.manager.remove();
529 this.url_panel.destroy();
530 basic_minibuffer_state.prototype.destroy.call(this);
532 update_minibuffer: function (m) {
533 if (this.typed_number.length > 0)
534 m.prompt = this.original_prompt + " #" + this.typed_number;
536 m.prompt = this.original_prompt;
538 this.url_panel.update();
541 handle_auto_exit: function (ambiguous) {
542 var window = this.minibuffer.window;
543 var num = this.manager.current_hint_number;
547 let delay = ambiguous ? hints_ambiguous_auto_exit_delay : hints_auto_exit_delay;
549 this.auto_exit_timer_ID = window.setTimeout(function () { hints_exit(window, s); },
553 handle_input: function (m) {
554 this.clear_auto_exit_timer();
555 this.typed_number = "";
556 this.typed_string = m._input_text;
557 this.manager.current_hint_string = this.typed_string;
558 this.manager.current_hint_number = -1;
559 this.manager.update_valid_hints();
560 if (this.manager.valid_hints.length == 1)
561 this.handle_auto_exit(false /* unambiguous */);
562 else if (this.manager.valid_hints.length > 1)
563 this.handle_auto_exit(true /* ambiguous */);
564 this.update_minibuffer(m);
568 define_variable("hints_auto_exit_delay", 0,
569 "Delay (in milliseconds) after the most recent key stroke before a "+
570 "sole matching element is automatically selected. When zero, "+
571 "automatic selection is disabled. A value of 500 is a good "+
572 "starting point for an average-speed typist.");
574 define_variable("hints_ambiguous_auto_exit_delay", 0,
575 "Delay (in milliseconds) after the most recent key stroke before the "+
576 "first of an ambiguous match is automatically selected. If this is "+
577 "set to 0, automatic selection in ambiguous matches is disabled.");
580 define_key_match_predicate("match_hint_digit", "hint digit",
582 if (e.type != "keypress")
584 if (e.charCode == 48) //0 is special
587 if (hint_digits.indexOf(String.fromCharCode(e.charCode)) > -1)
589 } else if (e.charCode >= 49 && e.charCode <= 57)
594 interactive("hints-handle-number",
595 "This is the handler for numeric keys in hinting mode. Normally, "+
596 "that means '1' through '9' and '0', but the numeric base (and digits) "+
597 "can be configured via the user variable 'hint_digits'. No matter "+
598 "what numeric base is in effect, the character '0' is special, and "+
599 "will always be treated as a number 0, translated into the current "+
600 "base if necessary.",
602 let s = I.minibuffer.check_state(hints_minibuffer_state);
603 s.clear_auto_exit_timer();
604 var ch = String.fromCharCode(I.event.charCode);
605 if (hint_digits && ch == "0")
607 var auto_exit_ambiguous = null; // null -> no auto exit; false -> not ambiguous; true -> ambiguous
608 s.typed_number += ch;
609 s.manager.select_hint(hints_parse(s.typed_number));
610 var num = s.manager.current_hint_number;
611 if (num > 0 && num <= s.manager.valid_hints.length)
612 auto_exit_ambiguous = num * 10 > s.manager.valid_hints.length ? false : true;
615 hints_exit(I.window, s);
618 auto_exit_ambiguous = false;
620 if (auto_exit_ambiguous !== null)
621 s.handle_auto_exit(auto_exit_ambiguous);
622 s.update_minibuffer(I.minibuffer);
625 function hints_backspace (window, s) {
626 let m = window.minibuffer;
627 s.clear_auto_exit_timer();
628 var l = s.typed_number.length;
630 s.typed_number = s.typed_number.substring(0, --l);
631 var num = l > 0 ? hints_parse(s.typed_number) : 1;
632 s.manager.select_hint(num);
633 } else if (s.typed_string.length > 0) {
634 call_builtin_command(window, 'cmd_deleteCharBackward');
635 s.typed_string = m._input_text;
636 //m._set_selection();
637 s.manager.current_hint_string = s.typed_string;
638 s.manager.current_hint_number = -1;
639 s.manager.update_valid_hints();
641 s.update_minibuffer(m);
643 interactive("hints-backspace", null,
645 hints_backspace(I.window, I.minibuffer.check_state(hints_minibuffer_state));
648 function hints_next (window, s, count) {
649 s.clear_auto_exit_timer();
651 var cur = s.manager.current_hint_number - 1;
652 var vh = s.manager.valid_hints;
653 var vl = s.manager.valid_hints.length;
655 cur = (cur + count) % vl;
658 s.manager.select_hint(cur + 1);
660 s.update_minibuffer(window);
662 interactive("hints-next", null,
664 hints_next(I.window, I.minibuffer.check_state(hints_minibuffer_state), I.p);
667 interactive("hints-previous", null,
669 hints_next(I.window, I.minibuffer.check_state(hints_minibuffer_state), -I.p);
672 function hints_exit (window, s) {
673 var cur = s.manager.current_hint_number;
675 if (cur > 0 && cur <= s.manager.valid_hints.length)
676 elem = s.manager.valid_hints[cur - 1].elem;
678 elem = window.buffers.current.top_frame;
680 var c = s.continuation;
681 delete s.continuation;
682 window.minibuffer.pop_state();
688 interactive("hints-exit", null,
690 hints_exit(I.window, I.minibuffer.check_state(hints_minibuffer_state));
693 interactive("hints-quote-next", null,
695 I.overlay_keymap = hint_quote_next_keymap;
700 define_keywords("$buffer");
701 minibuffer.prototype.read_hinted_element = function () {
703 var buf = arguments.$buffer;
704 var s = new hints_minibuffer_state(this, (yield CONTINUATION), buf, forward_keywords(arguments));
706 var result = yield SUSPEND;
707 yield co_return(result);