fix focus problem http://bugs.conkeror.org/issue263
[conkeror.git] / modules / content-buffer.js
blobe2c848efbbe20a058b36235262bb05ef88a46c41
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2009 John J. Foerch
4  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
5  *
6  * Use, modification, and distribution are subject to the terms specified in the
7  * COPYING file.
8 **/
10 in_module(null);
12 require("buffer.js");
13 require("load-spec.js");
15 define_variable("homepage", "chrome://conkeror-help/content/help.html",
16                 "The url loaded by default for new content buffers.");
18 define_buffer_local_hook("content_buffer_finished_loading_hook");
19 define_buffer_local_hook("content_buffer_started_loading_hook");
20 define_buffer_local_hook("content_buffer_progress_change_hook");
21 define_buffer_local_hook("content_buffer_location_change_hook");
22 define_buffer_local_hook("content_buffer_status_change_hook");
23 define_buffer_local_hook("content_buffer_focus_change_hook");
24 define_buffer_local_hook("content_buffer_overlink_change_hook");
25 define_buffer_local_hook("content_buffer_dom_link_added_hook");
26 define_buffer_local_hook("content_buffer_popup_blocked_hook");
28 define_current_buffer_hook("current_content_buffer_finished_loading_hook", "content_buffer_finished_loading_hook");
29 define_current_buffer_hook("current_content_buffer_progress_change_hook", "content_buffer_progress_change_hook");
30 define_current_buffer_hook("current_content_buffer_location_change_hook", "content_buffer_location_change_hook");
31 define_current_buffer_hook("current_content_buffer_status_change_hook", "content_buffer_status_change_hook");
32 define_current_buffer_hook("current_content_buffer_focus_change_hook", "content_buffer_focus_change_hook");
33 define_current_buffer_hook("current_content_buffer_overlink_change_hook", "content_buffer_overlink_change_hook");
36 define_input_mode("text", "content_buffer_text_keymap", $display_name = "input:TEXT");
37 define_input_mode("textarea", "content_buffer_textarea_keymap", $display_name = "input:TEXTAREA");
38 define_input_mode("richedit", "content_buffer_richedit_keymap", $display_name = "input:RICHEDIT");
39 define_input_mode("select", "content_buffer_select_keymap", $display_name = "input:SELECT");
40 define_input_mode("checkbox", "content_buffer_checkbox_keymap", $display_name = "input:CHECKBOX/RADIOBUTTON");
41 define_input_mode("button", "content_buffer_button_keymap", $display_name = "input:BUTTON");
43 function content_buffer_modality (buffer) {
44     var elem = buffer.focused_element;
45     buffer.keymaps.push(content_buffer_normal_keymap);
46     if (elem) {
47         let p = elem.parentNode;
48         while (p && !(p instanceof Ci.nsIDOMHTMLFormElement))
49             p = p.parentNode;
50         if (p)
51             buffer.keymaps.push(content_buffer_form_keymap);
52     }
53     if (elem instanceof Ci.nsIDOMHTMLInputElement) {
54         switch ((elem.getAttribute("type") || "").toLowerCase()) {
55         case "checkbox":
56             checkbox_input_mode(buffer, true);
57             break;
58         case "radio":
59             checkbox_input_mode(buffer, true);
60             break;
61         case "submit":
62             button_input_mode(buffer, true);
63             break;
64         case "reset":
65             button_input_mode(buffer, true);
66             break;
67         default:
68             text_input_mode(buffer, true);
69             break;
70         }
71         return;
72     }
73     if (elem instanceof Ci.nsIDOMHTMLTextAreaElement) {
74         textarea_input_mode(buffer, true);
75         return;
76     }
77     if (elem instanceof Ci.nsIDOMHTMLSelectElement) {
78         select_input_mode(buffer, true);
79         return;
80     }
81     if (elem instanceof Ci.nsIDOMHTMLAnchorElement) {
82         buffer.keymaps.push(content_buffer_anchor_keymap);
83         return;
84     }
85     var frame = buffer.focused_frame;
86     if (frame && frame.document.designMode == "on") {
87         richedit_input_mode(buffer, true);
88         return;
89     }
90     while (elem) {
91         switch (elem.contentEditable) {
92         case "true":
93             richedit_input_mode(buffer, true);
94             return;
95         case "false":
96             return;
97         default: // "inherit"
98             elem = elem.parentNode;
99         }
100     }
104 /* If browser is null, create a new browser */
105 define_keywords("$load");
106 function content_buffer (window, element) {
107     keywords(arguments);
108     this.constructor_begin();
109     try {
110         conkeror.buffer.call(this, window, element, forward_keywords(arguments));
112         this.browser.addProgressListener(this);
113         var buffer = this;
114         this.browser.addEventListener("DOMTitleChanged", function (event) {
115             buffer_title_change_hook.run(buffer);
116         }, true /* capture */);
118         this.browser.addEventListener("scroll", function (event) {
119             buffer_scroll_hook.run(buffer);
120         }, true /* capture */);
122         this.browser.addEventListener("focus", function (event) {
123             content_buffer_focus_change_hook.run(buffer, event);
124         }, true /* capture */);
126         this.browser.addEventListener("mouseover", function (event) {
127             var node = event.target;
128             while (node && !(node instanceof Ci.nsIDOMHTMLAnchorElement))
129                 node = node.parentNode;
130             if (node) {
131                 content_buffer_overlink_change_hook.run(buffer, node.href);
132                 buffer.current_overlink = event.target;
133             }
134         }, true /* capture */);
136         this.browser.addEventListener("mouseout", function (event) {
137             if (buffer.current_overlink == event.target) {
138                 buffer.current_overlink = null;
139                 content_buffer_overlink_change_hook.run(buffer, "");
140             }
141         }, true /* capture */);
143         // initialize buffer.current_overlink in case mouseout happens
144         // before mouseover.
145         buffer.current_overlink = null;
147         this.browser.addEventListener("DOMLinkAdded", function (event) {
148             content_buffer_dom_link_added_hook.run(buffer, event);
149         }, true /* capture */);
151         this.browser.addEventListener("DOMPopupBlocked", function (event) {
152             dumpln("Blocked popup: " + event.popupWindowURI.spec);
153             content_buffer_popup_blocked_hook.run(buffer, event);
154         }, true /* capture */);
156         this.ignore_initial_blank = true;
158         var lspec = arguments.$load;
159         if (lspec) {
160             if (lspec.url == "about:blank")
161                 this.ignore_initial_blank = false;
162             else {
163                 /* Ensure that an existing load of about:blank is stopped */
164                 this.web_navigation.stop(Ci.nsIWebNavigation.STOP_ALL);
166                 this.load(lspec);
167             }
168         }
170         this.modalities.push(content_buffer_modality);
172     } finally {
173         this.constructor_end();
174     }
176 content_buffer.prototype = {
177     constructor : content_buffer,
179     destroy: function () {
180         this.browser.removeProgressListener(this);
181         buffer.prototype.destroy.call(this);
182     },
184     get scrollX () { return this.top_frame.scrollX; },
185     get scrollY () { return this.top_frame.scrollY; },
186     get scrollMaxX () { return this.top_frame.scrollMaxX; },
187     get scrollMaxY () { return this.top_frame.scrollMaxY; },
189     /* Used to display the correct URI when the buffer opens initially
190      * even before loading has progressed far enough for currentURI to
191      * contain the correct URI. */
192     _display_uri : null,
194     get display_uri_string () {
195         if (this._display_uri)
196             return this._display_uri;
197         if (this.current_uri)
198             return this.current_uri.spec;
199         return "";
200     },
202     get title () { return this.browser.contentTitle; },
203     get description () { return this.display_uri_string; },
205     load : function (load_spec) {
206         apply_load_spec(this, load_spec);
207     },
209     _request_count: 0,
211     loading : false,
213     /* nsIWebProgressListener */
214     QueryInterface: generate_QI(Ci.nsIWebProgressListener, Ci.nsISupportsWeakReference),
216     // This method is called to indicate state changes.
217     onStateChange: function (aWebProgress, aRequest, aStateFlags, aStatus) {
219         const WPL = Components.interfaces.nsIWebProgressListener;
221         var flagstr = "";
222         if (aStateFlags & WPL.STATE_START)
223             flagstr += ",start";
224         if (aStateFlags & WPL.STATE_STOP)
225             flagstr += ",stop";
226         if (aStateFlags & WPL.STATE_IS_REQUEST)
227             flagstr += ",request";
228         if (aStateFlags & WPL.STATE_IS_DOCUMENT)
229             flagstr += ",document";
230         if (aStateFlags & WPL.STATE_IS_NETWORK)
231             flagstr += ",network";
232         if (aStateFlags & WPL.STATE_IS_WINDOW)
233             flagstr += ",window";
234         dumpln("onStateChange: " + flagstr + ", status: " + aStatus);
236         if (!aRequest)
237             return;
239         if (aStateFlags & Ci.nsIWebProgressListener.STATE_START) {
240             this._request_count++;
241         } else if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) {
242             const NS_ERROR_UNKNOWN_HOST = 2152398878;
243             if (--this._request_count > 0 && aStatus == NS_ERROR_UNKNOWN_HOST) {
244                 // to prevent bug 235825: wait for the request handled
245                 // by the automatic keyword resolver
246                 return;
247             }
248             // since we (try to) only handle STATE_STOP of the last request,
249             // the count of open requests should now be 0
250             this._request_count = 0;
251         }
253         if (aStateFlags & Ci.nsIWebProgressListener.STATE_START &&
254             aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) {
255             // It's okay to clear what the user typed when we start
256             // loading a document. If the user types, this counter gets
257             // set to zero, if the document load ends without an
258             // onLocationChange, this counter gets decremented
259             // (so we keep it while switching tabs after failed loads)
260             //dumpln("*** started loading");
261             this.loading = true;
262             content_buffer_started_loading_hook.run(this);
263         } else if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
264                    aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) {
265             if (this.loading == true) {
266                 //dumpln("*** finished loading");
267                 this.loading = false;
268                 content_buffer_finished_loading_hook.run(this);
269             }
270         }
272         if (aStateFlags & (Ci.nsIWebProgressListener.STATE_STOP |
273                            Ci.nsIWebProgressListener.STATE_START)) {
274             if (!this.loading)
275                 this.set_default_message("Done");
276         }
277     },
279     /* This method is called to indicate progress changes for the currently
280        loading page. */
281     onProgressChange: function (webProgress, request, curSelf, maxSelf,
282                                 curTotal, maxTotal) {
283         content_buffer_progress_change_hook.run(this, request, curSelf, maxSelf, curTotal, maxTotal);
284     },
286     /* This method is called to indicate a change to the current location.
287        The url can be gotten as location.spec. */
288     onLocationChange : function (webProgress, request, location) {
289         /* Attempt to ignore onLocationChange calls due to the initial
290          * loading of about:blank by all xul:browser elements. */
291         if (location.spec == "about:blank" && this.ignore_initial_blank)
292             return;
294         this.ignore_initial_blank = false;
296         //dumpln("spec: " + location.spec  +" ;;; " + this.display_uri_string);
297         /* Use the real location URI now */
298         this._display_uri = null;
299         this.set_input_mode();
300         content_buffer_location_change_hook.run(this, request, location);
301         buffer_description_change_hook.run(this);
302     },
304     // This method is called to indicate a status changes for the currently
305     // loading page.  The message is already formatted for display.
306     // Status messages could be displayed in the minibuffer output area.
307     onStatusChange: function (webProgress, request, status, msg) {
308         this.set_default_message(msg);
309         content_buffer_status_change_hook.run(this, request, status, msg);
310     },
312     // This method is called when the security state of the browser changes.
313     onSecurityChange: function (webProgress, request, state) {
314         /* FIXME: currently this isn't used */
316         /*
317         const WPL = Components.interfaces.nsIWebProgressListener;
319         if (state & WPL.STATE_IS_INSECURE) {
320             // update visual indicator
321         } else {
322             var level = "unknown";
323             if (state & WPL.STATE_IS_SECURE) {
324                 if (state & WPL.STATE_SECURE_HIGH)
325                     level = "high";
326                 else if (state & WPL.STATE_SECURE_MED)
327                     level = "medium";
328                 else if (state & WPL.STATE_SECURE_LOW)
329                     level = "low";
330             } else if (state & WPL_STATE_IS_BROKEN) {
331                 level = "mixed";
332             }
333             // provide a visual indicator of the security state here.
334         }
335         */
336     },
338     /* Inherit from buffer */
340     __proto__ : buffer.prototype
344 add_hook("current_content_buffer_finished_loading_hook",
345          function (buffer) {
346                  buffer.window.minibuffer.show("Done");
347          });
349 add_hook("current_content_buffer_status_change_hook",
350          function (buffer, request, status, msg) {
351              buffer.set_default_message(msg);
352          });
356 define_variable("read_url_handler_list", [],
357     "A list of handler functions which transform a typed url into a valid " +
358     "url or webjump.  If the typed input is not valid then each function " +
359     "on this list is tried in turn.  The handler function is called with " +
360     "a single string argument and it should return either a string or " +
361     "null.  The result of the first function on the list that returns a " +
362     "string is used in place of the input.");
365  * read_url_make_default_webjump_handler returns a function that
366  * transforms any input into the given webjump.  It should be the last
367  * handler on read_url_handler_list (because any input is
368  * accepted).
369  */
370 function read_url_make_default_webjump_handler (default_webjump) {
371     return function (input) {
372         return default_webjump + " " + input;
373     };
377  * read_url_make_blank_url_handler returns a function that replaces a
378  * blank (empty) input with the given url (or webjump).  The url may
379  * perform some function, eg. "javascript:location.reload()".
380  */
381 function read_url_make_blank_url_handler (url) {
382     return function (input) {
383         if (input.length == 0)
384             return url;
385         return null;
386     };
389 minibuffer.prototype.try_read_url_handlers = function (input) {
390     var result;
391     for (var i = 0; i < read_url_handler_list.length; ++i) {
392         if ((result = read_url_handler_list[i](input)))
393             return result;
394     }
395     return input;
398 define_variable("url_completion_use_webjumps", true,
399     "Specifies whether URL completion should complete webjumps.");
401 define_variable("url_completion_use_bookmarks", true,
402     "Specifies whether URL completion should complete bookmarks.");
404 define_variable("url_completion_use_history", false,
405     "Specifies whether URL completion should complete using browser "+
406     "history.");
408 define_variable("minibuffer_read_url_select_initial", true,
409     "Specifies whether a URL  presented in the minibuffer for editing "+
410     "should be selected.  This affects find-alternate-url.");
413 minibuffer_auto_complete_preferences["url"] = true;
414 minibuffer.prototype.read_url = function () {
415     keywords(arguments, $prompt = "URL:", $history = "url", $initial_value = "",
416              $use_webjumps = url_completion_use_webjumps,
417              $use_history = url_completion_use_history,
418              $use_bookmarks = url_completion_use_bookmarks);
419     var completer = url_completer($use_webjumps = arguments.$use_webjumps,
420         $use_bookmarks = arguments.$use_bookmarks,
421         $use_history = arguments.$use_history);
422     var result = yield this.read(
423         $prompt = arguments.$prompt,
424         $history = arguments.$history,
425         $completer = completer,
426         $initial_value = arguments.$initial_value,
427         $auto_complete = "url",
428         $select = minibuffer_read_url_select_initial,
429         $match_required = false);
430     if (!possibly_valid_url(result) && !get_webjump(result))
431         result = this.try_read_url_handlers(result);
432     if (result == "") // well-formedness check. (could be better!)
433         throw ("invalid url or webjump (\""+ result +"\")");
434     yield co_return(load_spec(result));
437 I.content_charset = interactive_method(
438     $sync = function (ctx) {
439         var buffer = ctx.buffer;
440         if (!(buffer instanceof content_buffer))
441             throw new Error("Current buffer is of invalid type");
442         // -- Charset of content area of focusedWindow
443         var focusedWindow = buffer.focused_frame;
444         if (focusedWindow)
445             return focusedWindow.document.characterSet;
446         else
447             return null;
448     });
451 I.content_selection = interactive_method(
452     $sync = function (ctx) {
453         // -- Selection of content area of focusedWindow
454         var focusedWindow = this.buffers.current.focused_frame;
455         return focusedWindow.getSelection ();
456     });
458 function overlink_update_status (buffer, text) {
459     if (text.length > 0)
460         buffer.window.minibuffer.show("Link: " + text);
461     else
462         buffer.window.minibuffer.show("");
465 define_global_mode("overlink_mode", function () {
466     add_hook("current_content_buffer_overlink_change_hook", overlink_update_status);
467 }, function () {
468     remove_hook("current_content_buffer_overlink_change_hook", overlink_update_status);
471 overlink_mode(true);
474 function go_back (b, prefix) {
475     if (prefix < 0)
476         go_forward(b, -prefix);
478     check_buffer(b, content_buffer);
480     if (b.web_navigation.canGoBack) {
481         var hist = b.web_navigation.sessionHistory;
482         var idx = hist.index - prefix;
483         if (idx < 0)
484             idx = 0;
485         b.web_navigation.gotoIndex(idx);
486     } else
487         throw interactive_error("Can't go back");
490 interactive("back",
491     "Go back in the session history for the current buffer.",
492     function (I) {go_back(I.buffer, I.p);});
495 function go_forward (b, prefix) {
496     if (prefix < 0)
497         go_back(b, -prefix);
499     check_buffer(b, content_buffer);
501     if (b.web_navigation.canGoForward) {
502         var hist = b.web_navigation.sessionHistory;
503         var idx = hist.index + prefix;
504         if (idx >= hist.count) idx = hist.count-1;
505         b.web_navigation.gotoIndex(idx);
506     } else
507         throw interactive_error("Can't go forward");
510 interactive("forward",
511             "Go forward in the session history for the current buffer.",
512             function (I) {go_forward(I.buffer, I.p);});
515 function stop_loading (b) {
516     check_buffer(b, content_buffer);
517     b.web_navigation.stop(Ci.nsIWebNavigation.STOP_NETWORK);
520 interactive("stop-loading",
521             "Stop loading the current document.",
522             function (I) {stop_loading(I.buffer);});
525 function reload (b, bypass_cache, element, forced_charset) {
526     check_buffer(b, content_buffer);
527     if (element) {
528         if (element instanceof Ci.nsIDOMHTMLImageElement) {
529             try {
530                 var cache = Cc['@mozilla.org/image/cache;1']
531                     .getService(Ci.imgICache);
532                 cache.removeEntry(make_uri(element.src));
533             } catch (e) {}
534         }
535         element.parentNode.replaceChild(element.cloneNode(true), element);
536     } else {
537         var flags = bypass_cache == null ?
538             Ci.nsIWebNavigation.LOAD_FLAGS_NONE :
539             Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
541         if (! forced_charset && forced_charset_list)
542             forced_charset = predicate_alist_match(forced_charset_list,
543                                                    b.current_uri.spec);
545         if (forced_charset) {
546             try {
547                 var atomservice = Cc['@mozilla.org/atom-service;1']
548                     .getService(Ci.nsIAtomService);
549                 b.web_navigation.documentCharsetInfo.forcedCharset =
550                     atomservice.getAtom(forced_charset);
551             } catch (e) {}
552         }
553         b.web_navigation.reload(flags);
554     }
557 interactive("reload",
558     "Reload the current document.\n" +
559     "If a prefix argument is specified, the cache is bypassed.  If a "+
560     "DOM node is supplied via browser object, that node will be "+
561     "reloaded.",
562     function (I) {
563         check_buffer(I.buffer, content_buffer);
564         var element = yield read_browser_object(I);
565         reload(I.buffer, I.P, element, I.forced_charset);
566     });
569  * browserDOMWindow: intercept window opening
570  */
571 function initialize_browser_dom_window (window) {
572     window.QueryInterface(Ci.nsIDOMChromeWindow).browserDOMWindow =
573         new browser_dom_window(window);
576 define_variable("browser_default_open_target", OPEN_NEW_BUFFER,
577     "Specifies how new window requests by content pages (e.g. by "+
578     "window.open from JavaScript or by using the target attribute of "+
579     "anchor and form elements) will be handled.  This will generally "+
580     "be `OPEN_NEW_BUFFER', `OPEN_NEW_BUFFER_BACKGROUND', or "+
581     "`OPEN_NEW_WINDOW'.");
584 function browser_dom_window (window) {
585     this.window = window;
586     this.next_target = null;
588 browser_dom_window.prototype = {
589     QueryInterface: generate_QI(Ci.nsIBrowserDOMWindow),
591     openURI : function (aURI, aOpener, aWhere, aContext) {
593         // Reference: http://www.xulplanet.com/references/xpcomref/ifaces/nsIBrowserDOMWindow.html
594         var target = this.next_target;
595         if (target == null || target == FOLLOW_DEFAULT)
596             target = browser_default_open_target;
597         this.next_target = null;
599         /* Determine the opener buffer */
600         var opener = get_buffer_from_frame(this.window, aOpener);
602         switch (browser_default_open_target) {
603         case OPEN_CURRENT_BUFFER:
604             return aOpener.top;
605         case FOLLOW_CURRENT_FRAME:
606             return aOpener;
607         case OPEN_NEW_BUFFER:
608             var buffer = new content_buffer(this.window, null /* element */, $opener = opener);
609             this.window.buffers.current = buffer;
610             return buffer.top_frame;
611         case OPEN_NEW_BUFFER_BACKGROUND:
612             var buffer = new content_buffer(this.window, null /* element */, $opener = opener);
613             return buffer.top_frame;
614         case OPEN_NEW_WINDOW:
615         default: /* shouldn't be needed */
617             /* We don't call make_window here, because that will result
618              * in the URL being loaded as the top-level document,
619              * instead of within a browser buffer.  Instead, we can
620              * rely on Mozilla using browser.chromeURL. */
621             window_set_extra_arguments(
622                 {initial_buffer_creator: buffer_creator(content_buffer, $opener = opener)}
623             );
624             return null;
625         }
626     }
629 add_hook("window_initialize_early_hook", initialize_browser_dom_window);
631 define_keywords("$display_name", "$enable", "$disable", "$doc");
632 function define_page_mode (name) {
633     keywords(arguments);
634     var display_name = arguments.$display_name;
635     var enable = arguments.$enable;
636     var disable = arguments.$disable;
637     var doc = arguments.$doc;
638     define_buffer_mode(name,
639                        $display_name = display_name,
640                        $class = "page_mode",
641                        $enable = function (buffer) {
642                            buffer.page = {
643                                local: { __proto__: buffer.local }
644                            };
645                            if (enable)
646                                enable(buffer);
647                            buffer.set_input_mode();
648                        },
649                        $disable = function (buffer) {
650                            if (disable)
651                                disable(buffer);
652                            buffer.page = null;
653                            buffer.default_browser_object_classes = {};
654                            buffer.set_input_mode();
655                        },
656                        $doc = doc);
658 ignore_function_for_get_caller_source_code_reference("define_page_mode");
661 define_variable("auto_mode_list", [],
662     "A list of mappings from URI regular expressions to page modes.");
664 function page_mode_auto_update (buffer) {
665     var uri = buffer.current_uri.spec;
666     var mode = predicate_alist_match(auto_mode_list, uri);
667     if (mode)
668         mode(buffer, true);
669     else if (buffer.page_mode)
670         conkeror[buffer.page_mode](buffer, false);
673 add_hook("content_buffer_location_change_hook", page_mode_auto_update);
675 provide("content-buffer");