buffer.js, content-buffer.js: whitespace
[conkeror.git] / modules / content-buffer.js
blob11c02cb4be8c2a466e50c8c2084c5995d804e42c
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 &&
87         frame.document.designMode == "on")
88     {
89         richedit_input_mode(buffer, true);
90         return;
91     }
92     while (elem) {
93         switch (elem.contentEditable) {
94         case "true":
95             richedit_input_mode(buffer, true);
96             return;
97         case "false":
98             return;
99         default: // "inherit"
100             elem = elem.parentNode;
101         }
102     }
106 define_keywords("$load");
107 function content_buffer (window) {
108     keywords(arguments);
109     this.constructor_begin();
110     try {
111         conkeror.buffer.call(this, window, forward_keywords(arguments));
113         this.browser.addProgressListener(this);
114         var buffer = this;
115         this.browser.addEventListener("DOMTitleChanged", function (event) {
116             buffer_title_change_hook.run(buffer);
117         }, true /* capture */);
119         this.browser.addEventListener("scroll", function (event) {
120             buffer_scroll_hook.run(buffer);
121         }, true /* capture */);
123         this.browser.addEventListener("focus", function (event) {
124             content_buffer_focus_change_hook.run(buffer, event);
125         }, true /* capture */);
127         this.browser.addEventListener("mouseover", function (event) {
128             var node = event.target;
129             while (node && !(node instanceof Ci.nsIDOMHTMLAnchorElement))
130                 node = node.parentNode;
131             if (node) {
132                 content_buffer_overlink_change_hook.run(buffer, node.href);
133                 buffer.current_overlink = event.target;
134             }
135         }, true /* capture */);
137         this.browser.addEventListener("mouseout", function (event) {
138             if (buffer.current_overlink == event.target) {
139                 buffer.current_overlink = null;
140                 content_buffer_overlink_change_hook.run(buffer, "");
141             }
142         }, true /* capture */);
144         // initialize buffer.current_overlink in case mouseout happens
145         // before mouseover.
146         buffer.current_overlink = null;
148         this.browser.addEventListener("DOMLinkAdded", function (event) {
149             content_buffer_dom_link_added_hook.run(buffer, event);
150         }, true /* capture */);
152         this.browser.addEventListener("DOMPopupBlocked", function (event) {
153             dumpln("Blocked popup: " + event.popupWindowURI.spec);
154             content_buffer_popup_blocked_hook.run(buffer, event);
155         }, true /* capture */);
157         this.ignore_initial_blank = true;
159         var lspec = arguments.$load;
160         if (lspec) {
161             if (lspec.url == "about:blank")
162                 this.ignore_initial_blank = false;
163             else {
164                 /* Ensure that an existing load of about:blank is stopped */
165                 this.web_navigation.stop(Ci.nsIWebNavigation.STOP_ALL);
167                 this.load(lspec);
168             }
169         }
171         this.modalities.push(content_buffer_modality);
173     } finally {
174         this.constructor_end();
175     }
177 content_buffer.prototype = {
178     constructor: content_buffer,
180     destroy: function () {
181         this.browser.removeProgressListener(this);
182         buffer.prototype.destroy.call(this);
183     },
185     get scrollX () { return this.top_frame.scrollX; },
186     get scrollY () { return this.top_frame.scrollY; },
187     get scrollMaxX () { return this.top_frame.scrollMaxX; },
188     get scrollMaxY () { return this.top_frame.scrollMaxY; },
190     /* Used to display the correct URI when the buffer opens initially
191      * even before loading has progressed far enough for currentURI to
192      * contain the correct URI. */
193     _display_uri: null,
195     get display_uri_string () {
196         if (this._display_uri)
197             return this._display_uri;
198         if (this.current_uri)
199             return this.current_uri.spec;
200         return "";
201     },
203     get title () { return this.browser.contentTitle; },
204     get description () { return this.display_uri_string; },
206     load: function (load_spec) {
207         apply_load_spec(this, load_spec);
208     },
210     _request_count: 0,
212     loading: false,
214     /* nsIWebProgressListener */
215     QueryInterface: generate_QI(Ci.nsIWebProgressListener, Ci.nsISupportsWeakReference),
217     // This method is called to indicate state changes.
218     onStateChange: function (aWebProgress, aRequest, aStateFlags, aStatus) {
220         const WPL = Components.interfaces.nsIWebProgressListener;
222         var flagstr = "";
223         if (aStateFlags & WPL.STATE_START)
224             flagstr += ",start";
225         if (aStateFlags & WPL.STATE_STOP)
226             flagstr += ",stop";
227         if (aStateFlags & WPL.STATE_IS_REQUEST)
228             flagstr += ",request";
229         if (aStateFlags & WPL.STATE_IS_DOCUMENT)
230             flagstr += ",document";
231         if (aStateFlags & WPL.STATE_IS_NETWORK)
232             flagstr += ",network";
233         if (aStateFlags & WPL.STATE_IS_WINDOW)
234             flagstr += ",window";
235         dumpln("onStateChange: " + flagstr + ", status: " + aStatus);
237         if (!aRequest)
238             return;
240         if (aStateFlags & Ci.nsIWebProgressListener.STATE_START) {
241             this._request_count++;
242         } else if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) {
243             const NS_ERROR_UNKNOWN_HOST = 2152398878;
244             if (--this._request_count > 0 && aStatus == NS_ERROR_UNKNOWN_HOST) {
245                 // to prevent bug 235825: wait for the request handled
246                 // by the automatic keyword resolver
247                 return;
248             }
249             // since we (try to) only handle STATE_STOP of the last request,
250             // the count of open requests should now be 0
251             this._request_count = 0;
252         }
254         if (aStateFlags & Ci.nsIWebProgressListener.STATE_START &&
255             aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) {
256             // It's okay to clear what the user typed when we start
257             // loading a document. If the user types, this counter gets
258             // set to zero, if the document load ends without an
259             // onLocationChange, this counter gets decremented
260             // (so we keep it while switching tabs after failed loads)
261             //dumpln("*** started loading");
262             this.loading = true;
263             content_buffer_started_loading_hook.run(this);
264         } else if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
265                    aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) {
266             if (this.loading == true) {
267                 //dumpln("*** finished loading");
268                 this.loading = false;
269                 content_buffer_finished_loading_hook.run(this);
270             }
271         }
273         if (aStateFlags & (Ci.nsIWebProgressListener.STATE_STOP |
274                            Ci.nsIWebProgressListener.STATE_START)) {
275             if (!this.loading)
276                 this.set_default_message("Done");
277         }
278     },
280     /* This method is called to indicate progress changes for the currently
281        loading page. */
282     onProgressChange: function (webProgress, request, curSelf, maxSelf,
283                                 curTotal, maxTotal) {
284         content_buffer_progress_change_hook.run(this, request, curSelf, maxSelf, curTotal, maxTotal);
285     },
287     /* This method is called to indicate a change to the current location.
288        The url can be gotten as location.spec. */
289     onLocationChange: function (webProgress, request, location) {
290         /* Attempt to ignore onLocationChange calls due to the initial
291          * loading of about:blank by all xul:browser elements. */
292         if (location.spec == "about:blank" && this.ignore_initial_blank)
293             return;
295         this.ignore_initial_blank = false;
297         //dumpln("spec: " + location.spec  +" ;;; " + this.display_uri_string);
298         /* Use the real location URI now */
299         this._display_uri = null;
300         this.set_input_mode();
301         content_buffer_location_change_hook.run(this, request, location);
302         buffer_description_change_hook.run(this);
303     },
305     // This method is called to indicate a status changes for the currently
306     // loading page.  The message is already formatted for display.
307     // Status messages could be displayed in the minibuffer output area.
308     onStatusChange: function (webProgress, request, status, msg) {
309         this.set_default_message(msg);
310         content_buffer_status_change_hook.run(this, request, status, msg);
311     },
313     // This method is called when the security state of the browser changes.
314     onSecurityChange: function (webProgress, request, state) {
315         /* FIXME: currently this isn't used */
317         /*
318         const WPL = Components.interfaces.nsIWebProgressListener;
320         if (state & WPL.STATE_IS_INSECURE) {
321             // update visual indicator
322         } else {
323             var level = "unknown";
324             if (state & WPL.STATE_IS_SECURE) {
325                 if (state & WPL.STATE_SECURE_HIGH)
326                     level = "high";
327                 else if (state & WPL.STATE_SECURE_MED)
328                     level = "medium";
329                 else if (state & WPL.STATE_SECURE_LOW)
330                     level = "low";
331             } else if (state & WPL_STATE_IS_BROKEN) {
332                 level = "mixed";
333             }
334             // provide a visual indicator of the security state here.
335         }
336         */
337     },
339     /* 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) {
592         // Reference: http://www.xulplanet.com/references/xpcomref/ifaces/nsIBrowserDOMWindow.html
593         var target = this.next_target;
594         if (target == null || target == FOLLOW_DEFAULT)
595             target = browser_default_open_target;
596         this.next_target = null;
598         /* Determine the opener buffer */
599         var opener = get_buffer_from_frame(this.window, aOpener);
601         switch (browser_default_open_target) {
602         case OPEN_CURRENT_BUFFER:
603             return aOpener.top;
604         case FOLLOW_CURRENT_FRAME:
605             return aOpener;
606         case OPEN_NEW_BUFFER:
607             var buffer = new content_buffer(this.window, $opener = opener);
608             this.window.buffers.current = buffer;
609             return buffer.top_frame;
610         case OPEN_NEW_BUFFER_BACKGROUND:
611             var buffer = new content_buffer(this.window, $opener = opener);
612             return buffer.top_frame;
613         case OPEN_NEW_WINDOW:
614         default: /* shouldn't be needed */
616             /* We don't call make_window here, because that will result
617              * in the URL being loaded as the top-level document,
618              * instead of within a browser buffer.  Instead, we can
619              * rely on Mozilla using browser.chromeURL. */
620             window_set_extra_arguments(
621                 {initial_buffer_creator: buffer_creator(content_buffer, $opener = opener)}
622             );
623             return null;
624         }
625     }
628 add_hook("window_initialize_early_hook", initialize_browser_dom_window);
630 define_keywords("$display_name", "$enable", "$disable", "$doc");
631 function define_page_mode (name) {
632     keywords(arguments);
633     var display_name = arguments.$display_name;
634     var enable = arguments.$enable;
635     var disable = arguments.$disable;
636     var doc = arguments.$doc;
637     define_buffer_mode(name,
638                        $display_name = display_name,
639                        $class = "page_mode",
640                        $enable = function (buffer) {
641                            buffer.page = {
642                                local: { __proto__: buffer.local }
643                            };
644                            if (enable)
645                                enable(buffer);
646                            buffer.set_input_mode();
647                        },
648                        $disable = function (buffer) {
649                            if (disable)
650                                disable(buffer);
651                            buffer.page = null;
652                            buffer.default_browser_object_classes = {};
653                            buffer.set_input_mode();
654                        },
655                        $doc = doc);
657 ignore_function_for_get_caller_source_code_reference("define_page_mode");
660 define_variable("auto_mode_list", [],
661     "A list of mappings from URI regular expressions to page modes.");
663 function page_mode_auto_update (buffer) {
664     var uri = buffer.current_uri.spec;
665     var mode = predicate_alist_match(auto_mode_list, uri);
666     if (mode)
667         mode(buffer, true);
668     else if (buffer.page_mode)
669         conkeror[buffer.page_mode](buffer, false);
672 add_hook("content_buffer_location_change_hook", page_mode_auto_update);
674 provide("content-buffer");