Further adapt debian webjumps as suggested by John J. Foerch
[conkeror.git] / modules / hints.js
blob8496cb0f9c95464965b60f8b6ff5bd8c8980cbb9
1 /**
2  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
3  * (C) Copyright 2009 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 /**
28  * Register hints style sheet
29  */
30 const hints_stylesheet = "chrome://conkeror-gui/content/hints.css";
31 register_user_stylesheet(hints_stylesheet);
34 function hints_simple_text_match (text, pattern) {
35     var pos = text.indexOf(pattern);
36     if (pos == -1)
37         return false;
38     return [pos, pos + pattern.length];
41 define_variable('hints_text_match', hints_simple_text_match,
42     "A function which takes a string and a pattern (another string) "+
43     "and returns an array of [start, end] indices if the pattern was "+
44     "found in the string, or false if it was not.");
47 /**
48  *   In the hints interaction, a node can be selected either by typing
49  * the number of its associated hint, or by typing substrings of the
50  * text content of the node.  In the case of selecting by text
51  * content, multiple substrings can be given by separating them with
52  * spaces.
53  */
54 function hint_manager (window, xpath_expr, focused_frame, focused_element) {
55     this.window = window;
56     this.hints = [];
57     this.valid_hints = [];
58     this.xpath_expr = xpath_expr;
59     this.focused_frame = focused_frame;
60     this.focused_element = focused_element;
61     this.last_selected_hint = null;
63     // Generate
64     this.generate_hints();
67 hint_manager.prototype = {
68     current_hint_string: "",
69     current_hint_number: -1,
71     /**
72      * Create an initially hidden hint span element absolutely
73      * positioned over each element that matches
74      * hint_xpath_expression.  This is done recursively for all frames
75      * and iframes.  Information about the resulting hints are also
76      * stored in the hints array.
77      */
78     generate_hints: function () {
79         var topwin = this.window;
80         var top_height = topwin.innerHeight;
81         var top_width = topwin.innerWidth;
82         var hints = this.hints;
83         var xpath_expr = this.xpath_expr;
84         var focused_frame_hint = null, focused_element_hint = null;
85         var focused_frame = this.focused_frame;
86         var focused_element = this.focused_element;
88         function helper (window, offsetX, offsetY) {
89             var win_height = window.height;
90             var win_width = window.width;
92             // Bounds
93             var minX = offsetX < 0 ? -offsetX : 0;
94             var minY = offsetY < 0 ? -offsetY : 0;
95             var maxX = offsetX + win_width > top_width ? top_width - offsetX : top_width;
96             var maxY = offsetY + win_height > top_height ? top_height - offsetY : top_height;
98             var scrollX = window.scrollX;
99             var scrollY = window.scrollY;
101             var doc = window.document;
102             var res = doc.evaluate(xpath_expr, doc, xpath_lookup_namespace,
103                                    Ci.nsIDOMXPathResult.UNORDERED_NODE_ITERATOR_TYPE,
104                                    null /* existing results */);
106             var base_node = doc.createElementNS(XHTML_NS, "span");
107             base_node.className = "__conkeror_hint";
109             var fragment = doc.createDocumentFragment();
110             var rect, elem, text, node, show_text;
111             while (true) {
112                 try {
113                     elem = res.iterateNext();
114                     if (!elem)
115                         break;
116                 } catch (e) {
117                     break; // Iterator may have been invalidated by page load activity
118                 }
119                 rect = elem.getBoundingClientRect();
120                 if (elem instanceof Ci.nsIDOMHTMLAreaElement) {
121                     rect = { top: rect.top,
122                              left: rect.left,
123                              bottom: rect.bottom,
124                              right: rect.right };
125                     var coords = elem.getAttribute("coords")
126                         .match(/^(-?\d+)\D+(-?\d+)/);
127                     if (coords.length == 3) {
128                         rect.left += parseInt(coords[1]);
129                         rect.top += parseInt(coords[2]);
130                     }
131                 }
132                 if (!rect || rect.left > maxX || rect.right < minX || rect.top > maxY || rect.bottom < minY)
133                     continue;
134                 let style = topwin.getComputedStyle(elem, "");
135                 if (style.display == "none" || style.visibility == "hidden")
136                     continue;
137                 if (! (elem instanceof Ci.nsIDOMHTMLAreaElement))
138                     rect = elem.getClientRects()[0];
139                 if (!rect)
140                     continue;
141                 show_text = false;
142                 if (elem instanceof Ci.nsIDOMHTMLInputElement || elem instanceof Ci.nsIDOMHTMLTextAreaElement)
143                     text = elem.value;
144                 else if (elem instanceof Ci.nsIDOMHTMLSelectElement) {
145                     if (elem.selectedIndex >= 0)
146                         text = elem.item(elem.selectedIndex).text;
147                     else
148                         text = "";
149                 } else if (elem instanceof Ci.nsIDOMHTMLFrameElement) {
150                     text = elem.name ? elem.name : "";
151                 } else if (/^\s*$/.test(elem.textContent) &&
152                            elem.childNodes.length == 1 &&
153                            elem.childNodes.item(0) instanceof Ci.nsIDOMHTMLImageElement) {
154                     text = elem.childNodes.item(0).alt;
155                     show_text = true;
156                 } else
157                     text = elem.textContent;
158                 text = text.toLowerCase();
160                 node = base_node.cloneNode(true);
161                 node.style.left = (rect.left + scrollX) + "px";
162                 node.style.top = (rect.top + scrollY) + "px";
163                 fragment.appendChild(node);
165                 let hint = { text: text,
166                              elem: elem,
167                              hint: node,
168                              img_hint: null,
169                              visible: false,
170                              show_text: show_text };
171                 if (elem.style) {
172                     hint.saved_color = elem.style.color;
173                     hint.saved_bgcolor = elem.style.backgroundColor;
174                 }
175                 hints.push(hint);
177                 if (elem == focused_element)
178                     focused_element_hint = hint;
179                 else if ((elem instanceof Ci.nsIDOMHTMLFrameElement ||
180                           elem instanceof Ci.nsIDOMHTMLIFrameElement) &&
181                          elem.contentWindow == focused_frame)
182                     focused_frame_hint = hint;
183             }
184             doc.documentElement.appendChild(fragment);
186             /* Recurse into any IFRAME or FRAME elements */
187             var frametag = "frame";
188             while (true) {
189                 var frames = doc.getElementsByTagName(frametag);
190                 for (var i = 0, nframes = frames.length; i < nframes; ++i) {
191                     elem = frames[i];
192                     rect = elem.getBoundingClientRect();
193                     if (!rect || rect.left > maxX || rect.right < minX || rect.top > maxY || rect.bottom < minY)
194                         continue;
195                     helper(elem.contentWindow, offsetX + rect.left, offsetY + rect.top);
196                 }
197                 if (frametag == "frame") frametag = "iframe"; else break;
198             }
199         }
200         helper(topwin, 0, 0);
201         this.last_selected_hint = focused_element_hint || focused_frame_hint;
202     },
204     /* Updates valid_hints and also re-numbers and re-displays all hints. */
205     update_valid_hints: function () {
206         this.valid_hints = [];
207         var active_number = this.current_hint_number;
209         var tokens = this.current_hint_string.split(" ");
210         var rect, h, text, img_hint, doc, scrollX, scrollY;
211         var hints = this.hints;
213     outer:
214         for (var i = 0, nhints = hints.length; i < nhints; ++i) {
215             h = hints[i];
216             text = h.text;
217             for (var j = 0, ntokens = tokens.length; j < ntokens; ++j) {
218                 if (! hints_text_match(text, tokens[j])) {
219                     if (h.visible) {
220                         h.visible = false;
221                         h.hint.style.display = "none";
222                         if (h.img_hint)
223                             h.img_hint.style.display = "none";
224                         if (h.saved_color != null) {
225                             h.elem.style.backgroundColor = h.saved_bgcolor;
226                             h.elem.style.color = h.saved_color;
227                         }
228                     }
229                     continue outer;
230                 }
231             }
233             var cur_number = this.valid_hints.length + 1;
234             h.visible = true;
236             if (h == this.last_selected_hint && active_number == -1)
237                 this.current_hint_number = active_number = cur_number;
239             var img_elem = null;
241             if (text.length == 0 && h.elem.firstChild &&
242                 h.elem.firstChild instanceof Ci.nsIDOMHTMLImageElement)
243                 img_elem = h.elem.firstChild;
244             else if (h.elem instanceof Ci.nsIDOMHTMLImageElement)
245                 img_elem = h.elem;
247             if (img_elem) {
248                 if (!h.img_hint) {
249                     rect = img_elem.getBoundingClientRect();
250                     if (rect) {
251                         doc = h.elem.ownerDocument;
252                         scrollX = doc.defaultView.scrollX;
253                         scrollY = doc.defaultView.scrollY;
254                         img_hint = doc.createElementNS(XHTML_NS, "span");
255                         img_hint.className = "__conkeror_img_hint";
256                         img_hint.style.left = (rect.left + scrollX) + "px";
257                         img_hint.style.top = (rect.top + scrollY) + "px";
258                         img_hint.style.width = (rect.right - rect.left) + "px";
259                         img_hint.style.height = (rect.bottom - rect.top) + "px";
260                         h.img_hint = img_hint;
261                         doc.documentElement.appendChild(img_hint);
262                     } else
263                         img_elem = null;
264                 }
265                 if (img_elem) {
266                     var bgcolor = (active_number == cur_number) ?
267                         active_img_hint_background_color : img_hint_background_color;
268                     h.img_hint.style.backgroundColor = bgcolor;
269                     h.img_hint.style.display = "inline";
270                 }
271             }
273             if (!h.img_hint && h.elem.style)
274                 h.elem.style.backgroundColor = (active_number == cur_number) ?
275                     active_hint_background_color : hint_background_color;
277             if (h.elem.style)
278                 h.elem.style.color = "black";
280             var label = "" + cur_number;
281             if (h.elem instanceof Ci.nsIDOMHTMLFrameElement) {
282                 label +=  " " + text;
283             } else if (h.show_text && !/^\s*$/.test(text)) {
284                 let substrs = [[0,4]];
285                 for (j = 0; j < ntokens; ++j) {
286                     let m = hints_text_match(text, tokens[j]);
287                     if (m == false) continue;
288                     splice_range(substrs, m[0], m[1] + 2);
289                 }
290                 label += " " + substrs.map(function (x) {
291                     return text.substring(x[0],Math.min(x[1], text.length));
292                 }).join("..") + "..";
293             }
294             h.hint.textContent = label;
295             h.hint.style.display = "inline";
296             this.valid_hints.push(h);
297         }
299         if (active_number == -1)
300             this.select_hint(1);
301     },
303     select_hint: function (index) {
304         var old_index = this.current_hint_number;
305         if (index == old_index)
306             return;
307         var vh = this.valid_hints;
308         if (old_index >= 1 && old_index <= vh.length) {
309             var h = vh[old_index - 1];
310             if (h.img_hint)
311                 h.img_hint.style.backgroundColor = img_hint_background_color;
312             if (h.elem.style)
313                 h.elem.style.backgroundColor = hint_background_color;
314         }
315         this.current_hint_number = index;
316         if (index >= 1 && index <= vh.length) {
317             var h = vh[index - 1];
318             if (h.img_hint)
319                 h.img_hint.style.backgroundColor = active_img_hint_background_color;
320             if (h.elem.style)
321                 h.elem.style.backgroundColor = active_hint_background_color;
322             this.last_selected_hint = h;
323         }
324     },
326     hide_hints: function () {
327         for (var i = 0, nhints = this.hints.length; i < nhints; ++i) {
328             var h = this.hints[i];
329             if (h.visible) {
330                 h.visible = false;
331                 if (h.saved_color != null) {
332                     h.elem.style.color = h.saved_color;
333                     h.elem.style.backgroundColor = h.saved_bgcolor;
334                 }
335                 if (h.img_hint)
336                     h.img_hint.style.display = "none";
337                 h.hint.style.display = "none";
338             }
339         }
340     },
342     remove: function () {
343         for (var i = 0, nhints = this.hints.length; i < nhints; ++i) {
344             var h = this.hints[i];
345             if (h.visible && h.saved_color != null) {
346                 h.elem.style.color = h.saved_color;
347                 h.elem.style.backgroundColor = h.saved_bgcolor;
348             }
349             if (h.img_hint)
350                 h.img_hint.parentNode.removeChild(h.img_hint);
351             h.hint.parentNode.removeChild(h.hint);
352         }
353         this.hints = [];
354         this.valid_hints = [];
355     }
358 /* Show panel with currently selected URL. */
359 function hints_url_panel (hints, window) {
360     var g = new dom_generator(window.document, XUL_NS);
362     var p = g.element("hbox", "class", "panel url", "flex", "0");
363     g.element("label", p, "value", "URL:", "class", "url-panel-label");
364     var url_value = g.element("label", p, "class", "url-panel-value",
365                               "crop", "end", "flex", "1");
366     window.minibuffer.insert_before(p);
368     p.update = function () {
369         url_value.value = "";
370         if (hints.manager && hints.manager.last_selected_hint) {
371             var spec;
372             try {
373                 spec = load_spec(hints.manager.last_selected_hint.elem);
374             } catch (e) {}
375             if (spec) {
376                 var uri = load_spec_uri_string(spec);
377                 if (uri) url_value.value = uri;
378             }
379         }
380     };
382     p.destroy = function () {
383         this.parentNode.removeChild(this);
384     };
386     return p;
389 define_variable("hints_display_url_panel", false,
390     "When selecting a hint, the URL can be displayed in a panel above "+
391     "the minibuffer.  This is useful for confirming that the correct "+
392     "link is selected and that the URL is not evil.  This option is "+
393     "most useful when hints_auto_exit_delay is long or disabled.");
396  * keyword arguments:
398  * $prompt
399  * $callback
400  * $abort_callback
401  */
402 define_keywords("$keymap", "$auto", "$hint_xpath_expression", "$multiple");
403 function hints_minibuffer_state (window, continuation, buffer) {
404     keywords(arguments, $keymap = hint_keymap, $auto);
405     basic_minibuffer_state.call(this, window, $prompt = arguments.$prompt);
406     if (hints_display_url_panel)
407         this.url_panel = hints_url_panel(this, buffer.window);
408     this.original_prompt = arguments.$prompt;
409     this.continuation = continuation;
410     this.keymap = arguments.$keymap;
411     this.auto_exit = arguments.$auto ? true : false;
412     this.xpath_expr = arguments.$hint_xpath_expression;
413     this.auto_exit_timer_ID = null;
414     this.multiple = arguments.$multiple;
415     this.focused_element = buffer.focused_element;
416     this.focused_frame = buffer.focused_frame;
418 hints_minibuffer_state.prototype = {
419     __proto__: basic_minibuffer_state.prototype,
420     manager: null,
421     typed_string: "",
422     typed_number: "",
423     load: function (window) {
424         basic_minibuffer_state.prototype.load.call(this, window);
425         if (!this.manager) {
426             var buf = window.buffers.current;
427             this.manager = new hint_manager(buf.top_frame, this.xpath_expr,
428                                             this.focused_frame, this.focused_element);
429         }
430         this.manager.update_valid_hints();
431         this.window = window;
432         if (this.url_panel)
433             this.url_panel.update();
434     },
435     clear_auto_exit_timer: function () {
436         if (this.auto_exit_timer_ID != null) {
437             this.window.clearTimeout(this.auto_exit_timer_ID);
438             this.auto_exit_timer_ID = null;
439         }
440     },
441     unload: function (window) {
442         this.clear_auto_exit_timer();
443         this.manager.hide_hints();
444         delete this.window;
445         basic_minibuffer_state.prototype.unload.call(this, window);
446     },
447     destroy: function (window) {
448         this.clear_auto_exit_timer();
449         this.manager.remove();
450         if (this.url_panel)
451             this.url_panel.destroy();
452         basic_minibuffer_state.prototype.destroy.call(this, window);
453     },
454     update_minibuffer: function (m) {
455         if (this.typed_number.length > 0)
456             m.prompt = this.original_prompt + " #" + this.typed_number;
457         else
458             m.prompt = this.original_prompt;
459         if (this.url_panel)
460             this.url_panel.update();
461     },
463     handle_auto_exit: function (m, ambiguous) {
464         let window = m.window;
465         var num = this.manager.current_hint_number;
466         if (!this.auto_exit)
467             return;
468         let s = this;
469         let delay = ambiguous ? hints_ambiguous_auto_exit_delay : hints_auto_exit_delay;
470         if (delay > 0)
471             this.auto_exit_timer_ID = window.setTimeout(function () { hints_exit(window, s); },
472                                                         delay);
473     },
475     ran_minibuffer_command: function (m) {
476         this.handle_input(m);
477     },
479     handle_input: function (m) {
480         m._set_selection();
481         this.clear_auto_exit_timer();
482         this.typed_number = "";
483         this.typed_string = m._input_text;
484         this.manager.current_hint_string = this.typed_string;
485         this.manager.current_hint_number = -1;
486         this.manager.update_valid_hints();
487         if (this.manager.valid_hints.length == 1)
488             this.handle_auto_exit(m, false /* unambiguous */);
489         else if (this.manager.valid_hints.length > 1)
490         this.handle_auto_exit(m, true /* ambiguous */);
491         this.update_minibuffer(m);
492     }
495 define_variable("hints_auto_exit_delay", 0,
496     "Delay (in milliseconds) after the most recent key stroke before a "+
497     "sole matching element is automatically selected.  When zero, "+
498     "automatic selection is disabled.  A value of 500 is a good "+
499     "starting point for an average-speed typist.");
501 define_variable("hints_ambiguous_auto_exit_delay", 0,
502     "Delay (in milliseconds) after the most recent key stroke before the "+
503     "first of an ambiguous match is automatically selected.  If this is "+
504     "set to 0, automatic selection in ambiguous matches is disabled.");
506 interactive("hints-handle-number", null,
507     function (I) {
508         let s = I.minibuffer.check_state(hints_minibuffer_state);
509         s.clear_auto_exit_timer();
510         var ch = String.fromCharCode(I.event.charCode);
511         var auto_exit_ambiguous = null; // null -> no auto exit; false -> not ambiguous; true -> ambiguous
512         /* TODO: implement number escaping */
513         // Number entered
514         s.typed_number += ch;
516         s.manager.select_hint(parseInt(s.typed_number));
517         var num = s.manager.current_hint_number;
518         if (num > 0 && num <= s.manager.valid_hints.length)
519             auto_exit_ambiguous = num * 10 > s.manager.valid_hints.length ? false : true;
520         else if (num == 0) {
521             if (!s.multiple) {
522                 hints_exit(I.window, s);
523                 return;
524             }
525             auto_exit_ambiguous = false;
526         }
527         if (auto_exit_ambiguous !== null)
528             s.handle_auto_exit(I.minibuffer, auto_exit_ambiguous);
529         s.update_minibuffer(I.minibuffer);
530     });
532 function hints_backspace (window, s) {
533     let m = window.minibuffer;
534     s.clear_auto_exit_timer();
535     if (s.typed_number.length > 0) {
536         s.typed_number = s.typed_number.substring(0, s.typed_number.length - 1);
537         var num = s.typed_number.length > 0 ? parseInt(s.typed_number) : 1;
538         s.manager.select_hint(num);
539     } else if (s.typed_string.length > 0) {
540         s.typed_string = s.typed_string.substring(0, s.typed_string.length - 1);
541         m._input_text = s.typed_string;
542         m._set_selection();
543         s.manager.current_hint_string = s.typed_string;
544         s.manager.current_hint_number = -1;
545         s.manager.update_valid_hints();
546     }
547     s.update_minibuffer(m);
549 interactive("hints-backspace", null,
550     function (I) {
551         hints_backspace(I.window, I.minibuffer.check_state(hints_minibuffer_state));
552     });
554 function hints_next (window, s, count) {
555     s.clear_auto_exit_timer();
556     s.typed_number = "";
557     var cur = s.manager.current_hint_number - 1;
558     var vh = s.manager.valid_hints;
559     if (vh.length > 0) {
560         cur = (cur + count) % vh.length;
561         if (cur < 0)
562             cur += vh.length;
563         s.manager.select_hint(cur + 1);
564     }
565     s.update_minibuffer(window);
567 interactive("hints-next", null,
568     function (I) {
569         hints_next(I.window, I.minibuffer.check_state(hints_minibuffer_state), I.p);
570     });
572 interactive("hints-previous", null,
573     function (I) {
574         hints_next(I.window, I.minibuffer.check_state(hints_minibuffer_state), -I.p);
575     });
577 function hints_exit (window, s) {
578     var cur = s.manager.current_hint_number;
579     var elem = null;
580     if (cur > 0 && cur <= s.manager.valid_hints.length) {
581         elem = s.manager.valid_hints[cur - 1].elem;
582     } else if (cur == 0) {
583         elem = window.buffers.current.top_frame;
584     }
585     if (elem !== null) {
586         var c = s.continuation;
587         delete s.continuation;
588         window.minibuffer.pop_state();
589         if (c)
590             c(elem);
591     }
594 interactive("hints-exit", null,
595     function (I) {
596         hints_exit(I.window, I.minibuffer.check_state(hints_minibuffer_state));
597     });
600 define_keywords("$buffer");
601 minibuffer.prototype.read_hinted_element = function () {
602     keywords(arguments);
603     var buf = arguments.$buffer;
604     var s = new hints_minibuffer_state(this.window, (yield CONTINUATION), buf, forward_keywords(arguments));
605     this.push_state(s);
606     var result = yield SUSPEND;
607     yield co_return(result);
610 provide("hints");