whitespace
[conkeror.git] / modules / hints.js
blob67720d0a0932b828cc021315c8b015d6ff4e121c
1 /**
2  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
3  * (C) Copyright 2009-2010 John J. Foerch
4  *
5  * Portions of this file are derived from Vimperator,
6  * (C) Copyright 2006-2007 Martin Stubenschrott.
7  *
8  * Use, modification, and distribution are subject to the terms specified in the
9  * COPYING file.
10 **/
12 in_module(null);
14 define_variable("active_img_hint_background_color", "#88FF00",
15     "Color for the active image hint background.");
17 define_variable("img_hint_background_color", "yellow",
18     "Color for inactive image hint backgrounds.");
20 define_variable("active_hint_background_color", "#88FF00",
21     "Color for the active hint background.");
23 define_variable("hint_background_color", "yellow",
24     "Color for the inactive hint.");
27 define_variable("hint_digits", null,
28     "Null or a string of the digits to use as the counting base "+
29     "for hint numbers, starting with the digit that represents zero "+
30     "and ascending.  If null, base 10 will be used with the normal "+
31     "hindu-arabic numerals.");
34 /**
35  * hints_enumerate is a generator of natural numbers in the base defined
36  * by hint_digits.
37  */
38 function hints_enumerate () {
39     var base = hint_digits.length;
40     var n = [1];
41     var p = 1;
42     while (true) {
43         yield n.map(function (x) hint_digits[x]).join("");
44         var i = p-1;
45         n[i]++;
46         while (n[i] >= base && i > 0) {
47             n[i] = 0;
48             n[--i]++;
49         }
50         if (n[0] >= base) {
51             n[0] = 0;
52             n.unshift(1);
53             p++;
54         }
55     }
58 /**
59  * hints_parse converts a string that represents a natural number to an
60  * int.  When hint_digits is non-null, it defines the base for conversion.
61  */
62 function hints_parse (str) {
63     if (hint_digits) {
64         var base = hint_digits.length;
65         var n = 0;
66         for (var i = 0, p = str.length - 1; p >= 0; i++, p--) {
67             n += hint_digits.indexOf(str[i]) * Math.pow(base, p);
68         }
69         return n;
70     } else
71         return parseInt(str);
74 /**
75  * Register hints style sheet
76  */
77 const hints_stylesheet = "chrome://conkeror-gui/content/hints.css";
78 register_user_stylesheet(hints_stylesheet);
81 function hints_simple_text_match (text, pattern) {
82     var pos = text.indexOf(pattern);
83     if (pos == -1)
84         return false;
85     return [pos, pos + pattern.length];
88 define_variable('hints_text_match', hints_simple_text_match,
89     "A function which takes a string and a pattern (another string) "+
90     "and returns an array of [start, end] indices if the pattern was "+
91     "found in the string, or false if it was not.");
94 /**
95  *   In the hints interaction, a node can be selected either by typing
96  * the number of its associated hint, or by typing substrings of the
97  * text content of the node.  In the case of selecting by text
98  * content, multiple substrings can be given by separating them with
99  * spaces.
100  */
101 function hint_manager (window, xpath_expr, focused_frame, focused_element) {
102     this.window = window;
103     this.hints = [];
104     this.valid_hints = [];
105     this.xpath_expr = xpath_expr;
106     this.focused_frame = focused_frame;
107     this.focused_element = focused_element;
108     this.last_selected_hint = null;
110     // Generate
111     this.generate_hints();
113 hint_manager.prototype = {
114     constructor: hint_manager,
115     current_hint_string: "",
116     current_hint_number: -1,
118     /**
119      * Create an initially hidden hint span element absolutely
120      * positioned over each element that matches
121      * hint_xpath_expression.  This is done recursively for all frames
122      * and iframes.  Information about the resulting hints are also
123      * stored in the hints array.
124      */
125     generate_hints: function () {
126         var topwin = this.window;
127         var top_height = topwin.innerHeight;
128         var top_width = topwin.innerWidth;
129         var hints = this.hints;
130         var xpath_expr = this.xpath_expr;
131         var focused_frame_hint = null, focused_element_hint = null;
132         var focused_frame = this.focused_frame;
133         var focused_element = this.focused_element;
135         function helper (window, offsetX, offsetY) {
136             var win_height = window.height;
137             var win_width = window.width;
139             // Bounds
140             var minX = offsetX < 0 ? -offsetX : 0;
141             var minY = offsetY < 0 ? -offsetY : 0;
142             var maxX = offsetX + win_width > top_width ? top_width - offsetX : top_width;
143             var maxY = offsetY + win_height > top_height ? top_height - offsetY : top_height;
145             var scrollX = window.scrollX;
146             var scrollY = window.scrollY;
148             var doc = window.document;
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,
163                              left: rect.left,
164                              bottom: rect.bottom,
165                              right: rect.right };
166                     try {
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]);
172                         }
173                     } catch (e) {}
174                 }
175                 if (!rect || rect.left > maxX || rect.right < minX || rect.top > maxY || rect.bottom < minY)
176                     continue;
177                 let style = topwin.getComputedStyle(elem, "");
178                 if (style.display == "none" || style.visibility == "hidden")
179                     continue;
180                 if (! (elem instanceof Ci.nsIDOMHTMLAreaElement))
181                     rect = elem.getClientRects()[0];
182                 if (!rect)
183                     continue;
184                 show_text = false;
185                 if (elem instanceof Ci.nsIDOMHTMLInputElement || elem instanceof Ci.nsIDOMHTMLTextAreaElement)
186                     text = elem.value;
187                 else if (elem instanceof Ci.nsIDOMHTMLSelectElement) {
188                     if (elem.selectedIndex >= 0)
189                         text = elem.item(elem.selectedIndex).text;
190                     else
191                         text = "";
192                 } else if (elem instanceof Ci.nsIDOMHTMLFrameElement) {
193                     text = elem.name ? elem.name : "";
194                 } else if (/^\s*$/.test(elem.textContent) &&
195                            elem.childNodes.length == 1 &&
196                            elem.childNodes.item(0) instanceof Ci.nsIDOMHTMLImageElement) {
197                     text = elem.childNodes.item(0).alt;
198                     show_text = true;
199                 } else
200                     text = elem.textContent;
202                 node = base_node.cloneNode(true);
203                 node.style.left = (rect.left + scrollX) + "px";
204                 node.style.top = (rect.top + scrollY) + "px";
205                 fragment.appendChild(node);
207                 let hint = { text: text,
208                              ltext: text.toLowerCase(),
209                              elem: elem,
210                              hint: node,
211                              img_hint: null,
212                              visible: false,
213                              show_text: show_text };
214                 if (elem.style) {
215                     hint.saved_color = elem.style.color;
216                     hint.saved_bgcolor = elem.style.backgroundColor;
217                 }
218                 hints.push(hint);
220                 if (elem == focused_element)
221                     focused_element_hint = hint;
222                 else if ((elem instanceof Ci.nsIDOMHTMLFrameElement ||
223                           elem instanceof Ci.nsIDOMHTMLIFrameElement) &&
224                          elem.contentWindow == focused_frame)
225                     focused_frame_hint = hint;
226             }
227             doc.documentElement.appendChild(fragment);
229             /* Recurse into any IFRAME or FRAME elements */
230             var frametag = "frame";
231             while (true) {
232                 var frames = doc.getElementsByTagName(frametag);
233                 for (var i = 0, nframes = frames.length; i < nframes; ++i) {
234                     elem = frames[i];
235                     rect = elem.getBoundingClientRect();
236                     if (!rect || rect.left > maxX || rect.right < minX || rect.top > maxY || rect.bottom < minY)
237                         continue;
238                     helper(elem.contentWindow, offsetX + rect.left, offsetY + rect.top);
239                 }
240                 if (frametag == "frame") frametag = "iframe"; else break;
241             }
242         }
243         helper(topwin, 0, 0);
244         this.last_selected_hint = focused_element_hint || focused_frame_hint;
245     },
247     /* Updates valid_hints and also re-numbers and re-displays all hints. */
248     update_valid_hints: function () {
249         this.valid_hints = [];
250         var cur_number = 1;
251         if (hint_digits)
252             var number_generator = hints_enumerate();
253         var active_number = this.current_hint_number;
254         var tokens = this.current_hint_string.split(" ");
255         var case_sensitive = (this.current_hint_string !=
256                               this.current_hint_string.toLowerCase());
257         var rect, text, img_hint, doc, scrollX, scrollY;
258     outer:
259         for (var i = 0, h; (h = this.hints[i]); ++i) {
260             if (case_sensitive)
261                 text = h.text;
262             else
263                 text = h.ltext;
264             for (var j = 0, ntokens = tokens.length; j < ntokens; ++j) {
265                 if (! hints_text_match(text, tokens[j])) {
266                     if (h.visible) {
267                         h.visible = false;
268                         h.hint.style.display = "none";
269                         if (h.img_hint)
270                             h.img_hint.style.display = "none";
271                         if (h.saved_color != null) {
272                             h.elem.style.backgroundColor = h.saved_bgcolor;
273                             h.elem.style.color = h.saved_color;
274                         }
275                     }
276                     continue outer;
277                 }
278             }
280             h.visible = true;
282             if (h == this.last_selected_hint && active_number == -1)
283                 this.current_hint_number = active_number = cur_number;
285             var img_elem = null;
287             if (text == "" && h.elem.firstChild &&
288                 h.elem.firstChild instanceof Ci.nsIDOMHTMLImageElement)
289                 img_elem = h.elem.firstChild;
290             else if (h.elem instanceof Ci.nsIDOMHTMLImageElement)
291                 img_elem = h.elem;
293             if (img_elem) {
294                 if (!h.img_hint) {
295                     rect = img_elem.getBoundingClientRect();
296                     if (rect) {
297                         doc = h.elem.ownerDocument;
298                         scrollX = doc.defaultView.scrollX;
299                         scrollY = doc.defaultView.scrollY;
300                         img_hint = doc.createElementNS(XHTML_NS, "span");
301                         img_hint.className = "__conkeror_img_hint";
302                         img_hint.style.left = (rect.left + scrollX) + "px";
303                         img_hint.style.top = (rect.top + scrollY) + "px";
304                         img_hint.style.width = (rect.right - rect.left) + "px";
305                         img_hint.style.height = (rect.bottom - rect.top) + "px";
306                         h.img_hint = img_hint;
307                         doc.documentElement.appendChild(img_hint);
308                     } else
309                         img_elem = null;
310                 }
311                 if (img_elem) {
312                     var bgcolor = (active_number == cur_number) ?
313                         active_img_hint_background_color : img_hint_background_color;
314                     h.img_hint.style.backgroundColor = bgcolor;
315                     h.img_hint.style.display = "inline";
316                 }
317             }
319             if (!h.img_hint && h.elem.style)
320                 h.elem.style.backgroundColor = (active_number == cur_number) ?
321                     active_hint_background_color : hint_background_color;
323             if (h.elem.style)
324                 h.elem.style.color = "black";
326             var label = "";
327             if (hint_digits)
328                 label = number_generator.next();
329             else
330                 label += cur_number;
331             if (h.elem instanceof Ci.nsIDOMHTMLFrameElement) {
332                 label +=  " " + text;
333             } else if (h.show_text && !/^\s*$/.test(text)) {
334                 let substrs = [[0,4]];
335                 for (j = 0; j < ntokens; ++j) {
336                     let m = hints_text_match(text, tokens[j]);
337                     if (m == false) continue;
338                     splice_range(substrs, m[0], m[1] + 2);
339                 }
340                 label += " " + substrs.map(function (x) {
341                     return text.substring(x[0],Math.min(x[1], text.length));
342                 }).join("..") + "..";
343             }
344             h.hint.textContent = label;
345             h.hint.style.display = "inline";
346             this.valid_hints.push(h);
347             cur_number++;
348         }
350         if (active_number == -1)
351             this.select_hint(1);
352     },
354     select_hint: function (index) {
355         var old_index = this.current_hint_number;
356         if (index == old_index)
357             return;
358         var vh = this.valid_hints;
359         var vl = this.valid_hints.length;
360         if (old_index >= 1 && old_index <= vl) {
361             var h = vh[old_index - 1];
362             if (h.img_hint)
363                 h.img_hint.style.backgroundColor = img_hint_background_color;
364             if (h.elem.style)
365                 h.elem.style.backgroundColor = hint_background_color;
366         }
367         this.current_hint_number = index;
368         this.last_selected_hint = null;
369         if (index >= 1 && index <= vl) {
370             h = vh[index - 1];
371             if (h.img_hint)
372                 h.img_hint.style.backgroundColor = active_img_hint_background_color;
373             if (h.elem.style)
374                 h.elem.style.backgroundColor = active_hint_background_color;
375             this.last_selected_hint = h;
376         }
377     },
379     hide_hints: function () {
380         for (var i = 0, h; h = this.hints[i]; ++i) {
381             if (h.visible) {
382                 h.visible = false;
383                 if (h.saved_color != null) {
384                     h.elem.style.color = h.saved_color;
385                     h.elem.style.backgroundColor = h.saved_bgcolor;
386                 }
387                 if (h.img_hint)
388                     h.img_hint.style.display = "none";
389                 h.hint.style.display = "none";
390             }
391         }
392     },
394     remove: function () {
395         for (var i = 0, h; h = this.hints[i]; ++i) {
396             if (h.visible && h.saved_color != null) {
397                 h.elem.style.color = h.saved_color;
398                 h.elem.style.backgroundColor = h.saved_bgcolor;
399             }
400             if (h.img_hint)
401                 h.img_hint.parentNode.removeChild(h.img_hint);
402             h.hint.parentNode.removeChild(h.hint);
403         }
404         this.hints = [];
405         this.valid_hints = [];
406     }
409 /* Show panel with currently selected URL. */
410 function hints_url_panel (hints, window) {
411     var g = new dom_generator(window.document, XUL_NS);
413     var p = g.element("hbox", "class", "panel url", "flex", "0");
414     g.element("label", p, "value", "URL:", "class", "url-panel-label");
415     var url_value = g.element("label", p, "class", "url-panel-value",
416                               "crop", "end", "flex", "1");
417     window.minibuffer.insert_before(p);
419     p.update = function () {
420         url_value.value = "";
421         if (hints.manager && hints.manager.last_selected_hint) {
422             var spec;
423             try {
424                 spec = load_spec(hints.manager.last_selected_hint.elem);
425             } catch (e) {}
426             if (spec) {
427                 var uri = load_spec_uri_string(spec);
428                 if (uri) url_value.value = uri;
429             }
430         }
431     };
433     p.destroy = function () {
434         this.parentNode.removeChild(this);
435     };
437     return p;
440 define_variable("hints_display_url_panel", false,
441     "When selecting a hint, the URL can be displayed in a panel above "+
442     "the minibuffer.  This is useful for confirming that the correct "+
443     "link is selected and that the URL is not evil.  This option is "+
444     "most useful when hints_auto_exit_delay is long or disabled.");
447  * keyword arguments:
449  * $prompt
450  * $callback
451  * $abort_callback
452  */
453 define_keywords("$keymap", "$auto", "$hint_xpath_expression", "$multiple");
454 function hints_minibuffer_state (minibuffer, continuation, buffer) {
455     keywords(arguments, $keymap = hint_keymap, $auto);
456     basic_minibuffer_state.call(this, minibuffer, $prompt = arguments.$prompt,
457                                 $keymap = arguments.$keymap);
458     if (hints_display_url_panel)
459         this.url_panel = hints_url_panel(this, buffer.window);
460     this.original_prompt = arguments.$prompt;
461     this.continuation = continuation;
462     this.auto_exit = arguments.$auto ? true : false;
463     this.xpath_expr = arguments.$hint_xpath_expression;
464     this.auto_exit_timer_ID = null;
465     this.multiple = arguments.$multiple;
466     this.focused_element = buffer.focused_element;
467     this.focused_frame = buffer.focused_frame;
469 hints_minibuffer_state.prototype = {
470     constructor: hints_minibuffer_state,
471     __proto__: basic_minibuffer_state.prototype,
472     manager: null,
473     typed_string: "",
474     typed_number: "",
475     load: function () {
476         basic_minibuffer_state.prototype.load.call(this);
477         if (!this.manager) {
478             var buf = this.minibuffer.window.buffers.current;
479             this.manager = new hint_manager(buf.top_frame, this.xpath_expr,
480                                             this.focused_frame, this.focused_element);
481         }
482         this.manager.update_valid_hints();
483         if (this.url_panel)
484             this.url_panel.update();
485     },
486     clear_auto_exit_timer: function () {
487         var window = this.minibuffer.window;
488         if (this.auto_exit_timer_ID != null) {
489             window.clearTimeout(this.auto_exit_timer_ID);
490             this.auto_exit_timer_ID = null;
491         }
492     },
493     unload: function () {
494         this.clear_auto_exit_timer();
495         this.manager.hide_hints();
496         basic_minibuffer_state.prototype.unload.call(this);
497     },
498     destroy: function () {
499         this.clear_auto_exit_timer();
500         this.manager.remove();
501         if (this.url_panel)
502             this.url_panel.destroy();
503         basic_minibuffer_state.prototype.destroy.call(this);
504     },
505     update_minibuffer: function (m) {
506         if (this.typed_number.length > 0)
507             m.prompt = this.original_prompt + " #" + this.typed_number;
508         else
509             m.prompt = this.original_prompt;
510         if (this.url_panel)
511             this.url_panel.update();
512     },
514     handle_auto_exit: function (ambiguous) {
515         var window = this.minibuffer.window;
516         var num = this.manager.current_hint_number;
517         if (!this.auto_exit)
518             return;
519         let s = this;
520         let delay = ambiguous ? hints_ambiguous_auto_exit_delay : hints_auto_exit_delay;
521         if (delay > 0)
522             this.auto_exit_timer_ID = window.setTimeout(function () { hints_exit(window, s); },
523                                                         delay);
524     },
526     handle_input: function (m) {
527         this.clear_auto_exit_timer();
528         this.typed_number = "";
529         this.typed_string = m._input_text;
530         this.manager.current_hint_string = this.typed_string;
531         this.manager.current_hint_number = -1;
532         this.manager.update_valid_hints();
533         if (this.manager.valid_hints.length == 1)
534             this.handle_auto_exit(false /* unambiguous */);
535         else if (this.manager.valid_hints.length > 1)
536         this.handle_auto_exit(true /* ambiguous */);
537         this.update_minibuffer(m);
538     }
541 define_variable("hints_auto_exit_delay", 0,
542     "Delay (in milliseconds) after the most recent key stroke before a "+
543     "sole matching element is automatically selected.  When zero, "+
544     "automatic selection is disabled.  A value of 500 is a good "+
545     "starting point for an average-speed typist.");
547 define_variable("hints_ambiguous_auto_exit_delay", 0,
548     "Delay (in milliseconds) after the most recent key stroke before the "+
549     "first of an ambiguous match is automatically selected.  If this is "+
550     "set to 0, automatic selection in ambiguous matches is disabled.");
553 define_key_match_predicate("match_hint_digit", "hint digit",
554     function (e) {
555         if (e.type != "keypress")
556             return false;
557         if (e.charCode == 48) //0 is special
558             return true;
559         if (hint_digits) {
560             if (hint_digits.indexOf(String.fromCharCode(e.charCode)) > -1)
561                 return true;
562         } else if (e.charCode >= 49 && e.charCode <= 57)
563             return true;
564         return false;
565     });
567 interactive("hints-handle-number",
568     "This is the handler for numeric keys in hinting mode.  Normally, "+
569     "that means '1' through '9' and '0', but the numeric base (and digits) "+
570     "can be configured via the user variable 'hint_digits'.  No matter "+
571     "what numeric base is in effect, the character '0' is special, and "+
572     "will always be treated as a number 0, translated into the current "+
573     "base if necessary.",
574     function (I) {
575         let s = I.minibuffer.check_state(hints_minibuffer_state);
576         s.clear_auto_exit_timer();
577         var ch = String.fromCharCode(I.event.charCode);
578         if (hint_digits && ch == "0")
579             ch = hint_digits[0];
580         var auto_exit_ambiguous = null; // null -> no auto exit; false -> not ambiguous; true -> ambiguous
581         s.typed_number += ch;
582         s.manager.select_hint(hints_parse(s.typed_number));
583         var num = s.manager.current_hint_number;
584         if (num > 0 && num <= s.manager.valid_hints.length)
585             auto_exit_ambiguous = num * 10 > s.manager.valid_hints.length ? false : true;
586         else if (num == 0) {
587             if (!s.multiple) {
588                 hints_exit(I.window, s);
589                 return;
590             }
591             auto_exit_ambiguous = false;
592         }
593         if (auto_exit_ambiguous !== null)
594             s.handle_auto_exit(auto_exit_ambiguous);
595         s.update_minibuffer(I.minibuffer);
596     });
598 function hints_backspace (window, s) {
599     let m = window.minibuffer;
600     s.clear_auto_exit_timer();
601     var l = s.typed_number.length;
602     if (l > 0) {
603         s.typed_number = s.typed_number.substring(0, --l);
604         var num = l > 0 ? hints_parse(s.typed_number) : 1;
605         s.manager.select_hint(num);
606     } else if (s.typed_string.length > 0) {
607         call_builtin_command(window, 'cmd_deleteCharBackward');
608         s.typed_string = m._input_text;
609         //m._set_selection();
610         s.manager.current_hint_string = s.typed_string;
611         s.manager.current_hint_number = -1;
612         s.manager.update_valid_hints();
613     }
614     s.update_minibuffer(m);
616 interactive("hints-backspace", null,
617     function (I) {
618         hints_backspace(I.window, I.minibuffer.check_state(hints_minibuffer_state));
619     });
621 function hints_next (window, s, count) {
622     s.clear_auto_exit_timer();
623     s.typed_number = "";
624     var cur = s.manager.current_hint_number - 1;
625     var vh = s.manager.valid_hints;
626     var vl = s.manager.valid_hints.length;
627     if (vl > 0) {
628         cur = (cur + count) % vl;
629         if (cur < 0)
630             cur += vl;
631         s.manager.select_hint(cur + 1);
632     }
633     s.update_minibuffer(window);
635 interactive("hints-next", null,
636     function (I) {
637         hints_next(I.window, I.minibuffer.check_state(hints_minibuffer_state), I.p);
638     });
640 interactive("hints-previous", null,
641     function (I) {
642         hints_next(I.window, I.minibuffer.check_state(hints_minibuffer_state), -I.p);
643     });
645 function hints_exit (window, s) {
646     var cur = s.manager.current_hint_number;
647     var elem = null;
648     if (cur > 0 && cur <= s.manager.valid_hints.length)
649         elem = s.manager.valid_hints[cur - 1].elem;
650     else if (cur == 0)
651         elem = window.buffers.current.top_frame;
652     if (elem !== null) {
653         var c = s.continuation;
654         delete s.continuation;
655         window.minibuffer.pop_state();
656         if (c)
657             c(elem);
658     }
661 interactive("hints-exit", null,
662     function (I) {
663         hints_exit(I.window, I.minibuffer.check_state(hints_minibuffer_state));
664     });
666 interactive("hints-quote-next", null,
667     function (I) {
668         I.overlay_keymap = hint_quote_next_keymap;
669     },
670     $prefix);
673 define_keywords("$buffer");
674 minibuffer.prototype.read_hinted_element = function () {
675     keywords(arguments);
676     var buf = arguments.$buffer;
677     var s = new hints_minibuffer_state(this, (yield CONTINUATION), buf, forward_keywords(arguments));
678     this.push_state(s);
679     var result = yield SUSPEND;
680     yield co_return(result);
683 provide("hints");