buffer.destroy: prevent modalities from accessing dead browser
[conkeror.git] / modules / buffer.js
blobf1b9ea33f57e911daf6f386b2bd836b14812f840
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2010 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 var define_buffer_local_hook = local_hook_definer("window");
14 function define_current_buffer_hook (hook_name, existing_hook) {
15     define_buffer_local_hook(hook_name);
16     add_hook(existing_hook, function (buffer) {
17             if (!buffer.window.buffers || buffer != buffer.window.buffers.current)
18                 return;
19             var hook = conkeror[hook_name];
20             hook.run.apply(hook, Array.prototype.slice.call(arguments));
21         });
24 define_buffer_local_hook("buffer_title_change_hook");
25 define_buffer_local_hook("buffer_description_change_hook");
26 define_buffer_local_hook("select_buffer_hook");
27 define_buffer_local_hook("create_buffer_early_hook");
28 define_buffer_local_hook("create_buffer_hook");
29 define_buffer_local_hook("kill_buffer_hook");
30 define_buffer_local_hook("buffer_scroll_hook");
31 define_buffer_local_hook("buffer_dom_content_loaded_hook");
32 define_buffer_local_hook("buffer_loaded_hook");
34 define_current_buffer_hook("current_buffer_title_change_hook", "buffer_title_change_hook");
35 define_current_buffer_hook("current_buffer_description_change_hook", "buffer_description_change_hook");
36 define_current_buffer_hook("current_buffer_scroll_hook", "buffer_scroll_hook");
37 define_current_buffer_hook("current_buffer_dom_content_loaded_hook", "buffer_dom_content_loaded_hook");
40 define_keywords("$element", "$opener");
41 function buffer_creator (type) {
42     var args = forward_keywords(arguments);
43     return function (window, element) {
44         return new type(window, element, args);
45     };
48 define_variable("allow_browser_window_close", true,
49     "If this is set to true, if a content buffer page calls " +
50     "window.close() from JavaScript and is not prevented by the " +
51     "normal Mozilla mechanism that restricts pages from closing " +
52     "a window that was not opened by a script, the buffer will be " +
53     "killed, deleting the window as well if it is the only buffer.");
55 function buffer (window, element) {
56     this.constructor_begin();
57     keywords(arguments);
58     this.opener = arguments.$opener;
59     this.window = window;
60     if (element == null) {
61         element = create_XUL(window, "vbox");
62         element.setAttribute("flex", "1");
63         var browser = create_XUL(window, "browser");
64         browser.setAttribute("type", "content");
65         browser.setAttribute("flex", "1");
66         browser.setAttribute("autocompletepopup", "popup_autocomplete");
67         element.appendChild(browser);
68         this.window.buffers.container.appendChild(element);
69     } else {
70         /* Manually set up session history.
71          *
72          * This is needed because when constructor for the XBL binding
73          * (mozilla/toolkit/content/widgets/browser.xml#browser) for
74          * the initial browser element of the window is called, the
75          * docShell is not yet initialized and setting up the session
76          * history will fail.  To work around this problem, we do as
77          * tabbrowser.xml (Firefox) does and set the initial browser
78          * to have the disablehistory=true attribute, and then repeat
79          * the work that would normally be done in the XBL
80          * constructor.
81          */
83         // This code is taken from mozilla/browser/base/content/browser.js
84         let browser = element.firstChild;
85         browser.webNavigation.sessionHistory =
86             Cc["@mozilla.org/browser/shistory;1"].createInstance(Ci.nsISHistory);
87         observer_service.addObserver(browser, "browser:purge-session-history", false);
89         // remove the disablehistory attribute so the browser cleans up, as
90         // though it had done this work itself
91         browser.removeAttribute("disablehistory");
93         // enable global history
94         browser.docShell.QueryInterface(Ci.nsIDocShellHistory).useGlobalHistory = true;
95     }
96     this.window.buffers.buffer_list.push(this);
97     this.element = element;
98     this.browser = element.firstChild;
99     this.element.conkeror_buffer_object = this;
101     this.local = { __proto__: conkeror };
102     this.page = null;
103     this.enabled_modes = [];
104     this.default_browser_object_classes = {};
106     var buffer = this;
108     this.browser.addEventListener("scroll", function (event) {
109             buffer_scroll_hook.run(buffer);
110         }, true /* capture */);
112     this.browser.addEventListener("DOMContentLoaded", function (event) {
113             buffer_dom_content_loaded_hook.run(buffer);
114         }, true /* capture */);
116     this.browser.addEventListener("load", function (event) {
117             buffer_loaded_hook.run(buffer);
118         }, true /* capture */);
120     this.browser.addEventListener("DOMWindowClose", function (event) {
121             /* This call to preventDefault is very important; without
122              * it, somehow Mozilla does something bad and as a result
123              * the window loses focus, causing keyboard commands to
124              * stop working. */
125             event.preventDefault();
127             if (allow_browser_window_close)
128                 kill_buffer(buffer, true);
129         }, true);
131     this.browser.addEventListener("focus", function (event) {
132         if (buffer.focusblocker &&
133             event.target instanceof Ci.nsIDOMHTMLElement &&
134             buffer.focusblocker(buffer, event))
135         {
136             event.target.blur();
137         } else
138             buffer.set_input_mode();
139     }, true);
141     this.browser.addEventListener("blur", function (event) {
142         buffer.set_input_mode();
143     }, true);
145     this.modalities = [];
147     this.override_keymaps = [];
149     // When create_buffer_hook_early runs, basic buffer properties
150     // will be available, but not the properties subclasses.
151     create_buffer_early_hook.run(this);
153     this.constructor_end();
156 buffer.prototype = {
157     /* Saved focus state */
158     saved_focused_frame: null,
159     saved_focused_element: null,
161     // get title ()   [must be defined by subclasses]
162     // get name ()    [must be defined by subclasses]
163     dead: false, /* This is set when the buffer is killed */
165     keymaps: null,
166     mark_active: false,
168     // The property focusblocker is available for an external module to
169     // put a function on which takes a buffer as its argument and returns
170     // true to block a focus event, or false to let normal processing
171     // occur.  Having this one property explicitly handled by the buffer
172     // class allows for otherwise modular focus-blockers.
173     focusblocker: null,
175     default_message: "",
177     set_default_message: function (str) {
178         this.default_message = str;
179         if (this == this.window.buffers.current)
180             this.window.minibuffer.set_default_message(str);
181     },
183     constructors_running: 0,
185     constructor_begin : function () {
186         this.constructors_running++;
187     },
189     constructor_end: function () {
190         if (--this.constructors_running == 0) {
191             create_buffer_hook.run(this);
192             this.set_input_mode();
193             delete this.opener;
194         }
195     },
197     destroy: function () {
198         // prevent modalities from accessing dead browser
199         this.modalities = [];
200     },
202     set_input_mode: function () {
203         if (this.input_mode)
204             conkeror[this.input_mode](this, false);
205         this.keymaps = [];
206         this.modalities.map(function (m) m(this), this);
207     },
209     /* Browser accessors */
210     get top_frame () { return this.browser.contentWindow; },
211     get document () { return this.browser.contentDocument; },
212     get web_navigation () { return this.browser.webNavigation; },
213     get doc_shell () { return this.browser.docShell; },
214     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
215     get current_uri () { return this.browser.currentURI; },
217     is_child_element: function (element) {
218         return (element && this.is_child_frame(element.ownerDocument.defaultView));
219     },
221     is_child_frame: function (frame) {
222         return (frame && frame.top == this.top_frame);
223     },
225     // This method is like focused_frame, except that if no content
226     // frame actually has focus, this returns null.
227     get focused_frame_or_null () {
228         var frame = this.window.document.commandDispatcher.focusedWindow;
229         var top = this.top_frame;
230         if (this.is_child_frame(frame))
231             return frame;
232         return null;
233     },
235     get focused_frame () {
236         var frame = this.window.document.commandDispatcher.focusedWindow;
237         var top = this.top_frame;
238         if (this.is_child_frame(frame))
239             return frame;
240         return this.top_frame;
241     },
243     get focused_element () {
244         var element = this.window.document.commandDispatcher.focusedElement;
245         if (this.is_child_element(element))
246             return element;
247         return null;
248     },
250     get focused_selection_controller () {
251         var child_docshells = this.doc_shell.getDocShellEnumerator(
252             Ci.nsIDocShellTreeItem.typeContent,
253             Ci.nsIDocShell.ENUMERATE_FORWARDS);
254         while (child_docshells.hasMoreElements()) {
255             let ds = child_docshells.getNext()
256                 .QueryInterface(Ci.nsIDocShell);
257             if (ds.hasFocus) {
258                 let display = ds.QueryInterface(Ci.nsIInterfaceRequestor)
259                     .getInterface(Ci.nsISelectionDisplay);
260                 if (! display)
261                     return null;
262                 return display.QueryInterface(Ci.nsISelectionController);
263             }
264         }
265         return this.doc_shell
266             .QueryInterface(Ci.nsIInterfaceRequestor)
267             .getInterface(Ci.nsISelectionDisplay)
268             .QueryInterface(Ci.nsISelectionController);
269     },
271     do_command: function (command) {
272         function attempt_command (element, command) {
273             var controller;
274             if (element.controllers
275                 && (controller = element.controllers.getControllerForCommand(command)) != null
276                 && controller.isCommandEnabled(command))
277             {
278                 controller.doCommand(command);
279                 return true;
280             }
281             return false;
282         }
284         var element = this.focused_element;
285         if (element && attempt_command(element, command))
286             return;
287         var win = this.focused_frame;
288         while (true) {
289             if (attempt_command(win, command))
290                 return;
291             if (!win.parent || win == win.parent)
292                 break;
293             win = win.parent;
294         }
295     },
297     handle_kill: function () {
298         this.dead = true;
299         this.browser = null;
300         this.element = null;
301         this.saved_focused_frame = null;
302         this.saved_focused_element = null;
303         kill_buffer_hook.run(this);
304     }
307 function with_current_buffer (buffer, callback) {
308     return callback(new interactive_context(buffer));
311 function check_buffer (obj, type) {
312     if (!(obj instanceof type))
313         throw interactive_error("Buffer has invalid type.");
314     if (obj.dead)
315         throw interactive_error("Buffer has already been killed.");
316     return obj;
319 function caret_enabled (buffer) {
320     return buffer.browser.getAttribute('showcaret');
323 function clear_selection (buffer) {
324     let sel_ctrl = buffer.focused_selection_controller;
325     if (sel_ctrl) {
326         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
327         if (caret_enabled(buffer)) {
328             if (sel.anchorNode)
329                 sel.collapseToStart();
330         } else {
331             sel.removeAllRanges();
332         }
333     }
337 function buffer_container (window, create_initial_buffer) {
338     this.window = window;
339     this.container = window.document.getElementById("buffer-container");
340     this.buffer_list = [];
341     window.buffers = this;
342     create_initial_buffer(window, this.container.firstChild);
345 buffer_container.prototype = {
346     constructor: buffer_container,
348     get current () {
349         return this.container.selectedPanel.conkeror_buffer_object;
350     },
352     set current (buffer) {
353         var old_value = this.current;
354         if (old_value == buffer)
355             return;
357         this.buffer_list.splice(this.buffer_list.indexOf(buffer), 1);
358         this.buffer_list.unshift(buffer);
360         this._switch_away_from(this.current);
361         this._switch_to(buffer);
363         // Run hooks
364         select_buffer_hook.run(buffer);
365     },
367     _switch_away_from: function (old_value) {
368         // Save focus state
369         old_value.saved_focused_frame = old_value.focused_frame;
370         old_value.saved_focused_element = old_value.focused_element;
372         old_value.browser.setAttribute("type", "content");
373     },
375     _switch_to: function (buffer) {
376         // Select new buffer in the XUL deck
377         this.container.selectedPanel = buffer.element;
379         buffer.browser.setAttribute("type", "content-primary");
381         /**
382          * This next focus call seems to be needed to avoid focus
383          * somehow getting lost (and the keypress handler therefore
384          * not getting called at all) when killing buffers.
385          */
386         this.window.focus();
388         // Restore focus state
389         buffer.browser.focus();
390         if (buffer.saved_focused_element)
391             set_focus_no_scroll(this.window, buffer.saved_focused_element);
392         else if (buffer.saved_focused_frame)
393             set_focus_no_scroll(this.window, buffer.saved_focused_frame);
395         buffer.saved_focused_element = null;
396         buffer.saved_focused_frame = null;
398         this.window.minibuffer.set_default_message(buffer.default_message);
399     },
401     get count () {
402         return this.container.childNodes.length;
403     },
405     get_buffer: function (index) {
406         if (index >= 0 && index < this.count)
407             return this.container.childNodes.item(index).conkeror_buffer_object;
408         return null;
409     },
411     get selected_index () {
412         var nodes = this.container.childNodes;
413         var count = nodes.length;
414         for (var i = 0; i < count; ++i)
415             if (nodes.item(i) == this.container.selectedPanel)
416                 return i;
417         return null;
418     },
420     index_of: function (b) {
421         var nodes = this.container.childNodes;
422         var count = nodes.length;
423         for (var i = 0; i < count; ++i)
424             if (nodes.item(i) == b.element)
425                 return i;
426         return null;
427     },
429     get unique_name_list () {
430         var existing_names = new string_hashset();
431         var bufs = [];
432         this.for_each(function(b) {
433                 var base_name = b.name;
434                 var name = base_name;
435                 var index = 1;
436                 while (existing_names.contains(name)) {
437                     ++index;
438                     name = base_name + "<" + index + ">";
439                 }
440                 existing_names.add(name);
441                 bufs.push([name, b]);
442             });
443         return bufs;
444     },
446     kill_buffer: function (b) {
447         if (b.dead)
448             return true;
449         var count = this.count;
450         if (count <= 1)
451             return false;
452         var new_buffer = this.buffer_list[0];
453         var changed = false;
454         if (b == new_buffer) {
455             new_buffer = this.buffer_list[1];
456             changed = true;
457         }
458         this._switch_away_from(this.current);
459         // The removeChild call below may trigger events in progress
460         // listeners.  This call to `destroy' gives buffer subclasses a
461         // chance to remove such listeners, so that they cannot try to
462         // perform UI actions based upon a xul:browser that no longer
463         // exists.
464         b.destroy();
465         this.container.removeChild(b.element);
466         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
467         this._switch_to(new_buffer);
468         if (changed) {
469             select_buffer_hook.run(new_buffer);
470             this.buffer_list.splice(this.buffer_list.indexOf(new_buffer), 1);
471             this.buffer_list.unshift(new_buffer);
472         }
473         b.handle_kill();
474         return true;
475     },
477     bury_buffer: function (b) {
478         var new_buffer = this.buffer_list[0];
479         if (b == new_buffer)
480             new_buffer = this.buffer_list[1];
481         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
482         this.buffer_list.push(b);
483         this.current = new_buffer;
484         return true;
485     },
487     for_each: function (f) {
488         var count = this.count;
489         for (var i = 0; i < count; ++i)
490             f(this.get_buffer(i));
491     }
494 function buffer_initialize_window_early (window) {
495     /**
496      * Use content_buffer by default to handle an unusual case where
497      * browser.chromeURI is used perhaps.  In general this default
498      * should not be needed.
499      */
500     var create_initial_buffer =
501         window.args.initial_buffer_creator || buffer_creator(content_buffer);
502     new buffer_container(window, create_initial_buffer);
505 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
508 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
509 function buffer_before_window_close (window) {
510     var bs = window.buffers;
511     var count = bs.count;
512     for (let i = 0; i < count; ++i) {
513         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
514             return false;
515     }
516     return true;
518 add_hook("window_before_close_hook", buffer_before_window_close);
520 function buffer_window_close_handler (window) {
521     var bs = window.buffers;
522     var count = bs.count;
523     for (let i = 0; i < count; ++i) {
524         let b = bs.get_buffer(i);
525         b.handle_kill();
526     }
528 add_hook("window_close_hook", buffer_window_close_handler);
530 /* open/follow targets */
531 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
532                                // buffer is a content_buffer.
533 const OPEN_NEW_BUFFER = 1;
534 const OPEN_NEW_BUFFER_BACKGROUND = 2;
535 const OPEN_NEW_WINDOW = 3;
537 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
538 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
540 var TARGET_PROMPTS = [" in current buffer",
541                       " in new buffer",
542                       " in new buffer (background)",
543                       " in new window",
544                       "",
545                       " in current frame"];
547 var TARGET_NAMES = ["current buffer",
548                     "new buffer",
549                     "new buffer (background)",
550                     "new window",
551                     "default",
552                     "current frame"];
555 function create_buffer (window, creator, target) {
556     switch (target) {
557     case OPEN_NEW_BUFFER:
558         window.buffers.current = creator(window, null);
559         break;
560     case OPEN_NEW_BUFFER_BACKGROUND:
561         creator(window, null);
562         break;
563     case OPEN_NEW_WINDOW:
564         make_window(creator);
565         break;
566     default:
567         throw new Error("invalid target");
568     }
571 let (queued_buffer_creators = null) {
572     function create_buffer_in_current_window (creator, target, focus_existing) {
573         function process_queued_buffer_creators (window) {
574             for (var i = 0; i < queued_buffer_creators.length; ++i) {
575                 var x = queued_buffer_creators[i];
576                 create_buffer(window, x[0], x[1]);
577             }
578             queued_buffer_creators = null;
579         }
581         if (target == OPEN_NEW_WINDOW)
582             throw new Error("invalid target");
583         var window = get_recent_conkeror_window();
584         if (window) {
585             if (focus_existing)
586                 window.focus();
587             create_buffer(window, creator, target);
588         } else if (queued_buffer_creators != null) {
589             queued_buffer_creators.push([creator,target]);
590         } else {
591             queued_buffer_creators = [];
592             window = make_window(creator);
593             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
594         }
595     }
600  * Read Buffer
601  */
602 minibuffer_auto_complete_preferences["buffer"] = true;
603 define_keywords("$default");
604 minibuffer.prototype.read_buffer = function () {
605     var window = this.window;
606     var buffer = this.window.buffers.current;
607     keywords(arguments, $prompt = "Buffer:",
608              $default = buffer,
609              $history = "buffer");
610     var completer = all_word_completer(
611         $completions = function (visitor) window.buffers.for_each(visitor),
612         $get_string = function (x) x.description,
613         $get_description = function (x) x.title);
614     var result = yield this.read(
615         $keymap = read_buffer_keymap,
616         $prompt = arguments.$prompt,
617         $history = arguments.$history,
618         $completer = completer,
619         $match_required = true,
620         $auto_complete = "buffer",
621         $auto_complete_initial = true,
622         $auto_complete_delay = 0,
623         $default_completion = arguments.$default);
624     yield co_return(result);
628 interactive("buffer-reset-input-mode",
629     "Force a reset of the input mode.  Used by quote-next.",
630     function (I) {
631         I.buffer.set_input_mode();
632     });
635 function buffer_next (window, count) {
636     var index = window.buffers.selected_index;
637     var total = window.buffers.count;
638     if (total == 1)
639         throw new interactive_error("No other buffer");
640     index = (index + count) % total;
641     if (index < 0)
642         index += total;
643     window.buffers.current = window.buffers.get_buffer(index);
645 interactive("buffer-next",
646     "Switch to the next buffer.",
647     function (I) { buffer_next(I.window, I.p); });
648 interactive("buffer-previous",
649     "Switch to the previous buffer.",
650     function (I) { buffer_next(I.window, -I.p); });
652 function switch_to_buffer (window, buffer) {
653     if (buffer && !buffer.dead)
654         window.buffers.current = buffer;
656 interactive("switch-to-buffer",
657     "Switch to a buffer specified in the minibuffer.",
658     function (I) {
659         switch_to_buffer(
660             I.window,
661             (yield I.minibuffer.read_buffer(
662                 $prompt = "Switch to buffer:",
663                 $default = (I.window.buffers.count > 1 ?
664                             I.window.buffers.buffer_list[1] :
665                             I.buffer))));
666     });
668 define_variable("can_kill_last_buffer", true,
669     "If this is set to true, kill-buffer can kill the last "+
670     "remaining buffer, and close the window.");
672 function kill_other_buffers (buffer) {
673     if (!buffer)
674         return;
675     var bs = buffer.window.buffers;
676     var b;
677     while ((b = bs.get_buffer(0)) != buffer)
678         bs.kill_buffer(b);
679     var count = bs.count;
680     while (--count)
681         bs.kill_buffer(bs.get_buffer(1));
683 interactive("kill-other-buffers",
684     "Kill all buffers except current one.\n",
685     function (I) { kill_other_buffers(I.buffer); });
688 function kill_buffer (buffer, force) {
689     if (!buffer)
690         return;
691     var buffers = buffer.window.buffers;
692     if (buffers.count == 1 && buffer == buffers.current) {
693         if (can_kill_last_buffer || force) {
694             delete_window(buffer.window);
695             return;
696         } else
697             throw interactive_error("Can't kill last buffer.");
698     }
699     buffers.kill_buffer(buffer);
701 interactive("kill-buffer",
702     "Kill a buffer specified in the minibuffer.\n" +
703     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
704     "last remaining buffer in a window will cause the window to be closed.",
705     function (I) {
706         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
707     });
709 interactive("kill-current-buffer",
710     "Kill the current buffer.\n" +
711     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
712     "last remaining buffer in a window will cause the window to be closed.",
713     function (I) { kill_buffer(I.buffer); });
715 interactive("read-buffer-kill-buffer",
716     "Kill the current selected buffer in the completions list "+
717     "in a read buffer minibuffer interaction.",
718     function (I) {
719         var s = I.window.minibuffer.current_state;
720         var i = s.selected_completion_index;
721         var c = s.completions;
722         if (i == -1)
723             return;
724         kill_buffer(c.get_value(i));
725         s.completer.refresh();
726         s.handle_input(I.window.minibuffer);
727     });
729 interactive("bury-buffer",
730     "Bury the current buffer.\n Put the current buffer at the end of " +
731     "the buffer list, so that it is the least likely buffer to be " +
732     "selected by `switch-to-buffer'.",
733     function (I) { I.window.buffers.bury_buffer(I.buffer); });
735 function change_directory (buffer, dir) {
736     if (buffer.page != null)
737         delete buffer.page.local.cwd;
738     buffer.local.cwd = make_file(dir);
740 interactive("change-directory",
741     "Change the current directory of the selected buffer.",
742     function (I) {
743         change_directory(
744             I.buffer,
745             (yield I.minibuffer.read_existing_directory_path(
746                 $prompt = "Change to directory:",
747                 $initial_value = make_file(I.local.cwd).path)));
748     });
750 interactive("shell-command", null,
751     function (I) {
752         var cwd = I.local.cwd;
753         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
754         yield shell_command(cmd, $cwd = cwd);
755     });
759  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
760  * frames, iframes, plugins, and also clearing the selection.
761  */
762 define_buffer_local_hook("unfocus_hook");
763 function unfocus (window, buffer) {
764     // 1. if there is a selection, clear it.
765     var selc = buffer.focused_selection_controller;
766     if (selc) {
767         var sel = selc.getSelection(selc.SELECTION_NORMAL);
768         var active = ! sel.isCollapsed;
769         clear_selection(buffer);
770         if (active) {
771             window.minibuffer.message("cleared selection");
772             return;
773         }
774     }
775     // 2. if there is a focused element, unfocus it.
776     if (buffer.focused_element) {
777         buffer.focused_element.blur();
778         // if an element in a detached fragment has focus, blur() will
779         // not work, and we need to take more drastic measures.  the
780         // action taken was found through experiment, so it is possibly
781         // not the most concise way to unfocus such an element.
782         if (buffer.focused_element) {
783             buffer.element.focus();
784             buffer.top_frame.focus();
785         }
786         window.minibuffer.message("unfocused element");
787         return;
788     }
789     // 3. if an iframe has focus, we must blur it.
790     if (buffer.focused_frame_or_null &&
791         buffer.focused_frame_or_null.frameElement)
792     {
793         buffer.focused_frame_or_null.frameElement.blur();
794     }
795     // 4. return focus to top-frame from subframes and plugins.
796     buffer.top_frame.focus();
797     buffer.top_frame.focus(); // needed to get focus back from plugins
798     window.minibuffer.message("refocused top frame");
799     // give page-modes an opportunity to set focus specially
800     unfocus_hook.run(buffer);
802 interactive("unfocus",
803     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
804     "frames, iframes, plugins, and also for clearing the selection.  "+
805     "The action that it takes is based on precedence.  If there is a "+
806     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
807     "there is a selection, it will clear the selection.  Otherwise, it "+
808     "will return focus to the top frame from a focused frame, iframe, "+
809     "or plugin.  In the case of plugins, since they steal keyboard "+
810     "control away from Conkeror, the normal way to unfocus them is "+
811     "to use command-line remoting externally: conkeror -batch -f "+
812     "unfocus.  Page-modes also have an opportunity to alter the default"+
813     "focus via the hook, `focus_hook'.",
814     function (I) {
815         unfocus(I.window, I.buffer);
816     });
819 function for_each_buffer (f) {
820     for_each_window(function (w) { w.buffers.for_each(f); });
825  * BUFFER MODES
826  */
828 var mode_functions = {};
829 var mode_display_names = {};
831 define_buffer_local_hook("buffer_mode_change_hook");
832 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
834 define_keywords("$display_name", "$class", "$enable", "$disable", "$doc");
835 function define_buffer_mode (name) {
836     keywords(arguments);
838     var hyphen_name = name.replace("_","-","g");
839     var display_name = arguments.$display_name;
840     var mode_class = arguments.$class;
841     var enable = arguments.$enable;
842     var disable = arguments.$disable;
844     mode_display_names[name] = display_name;
846     var can_disable;
848     if (disable == false) {
849         can_disable = false;
850         disable = null;
851     } else
852         can_disable = true;
854     var state = (mode_class != null) ? mode_class : (name + "_enabled");
855     var enable_hook_name = name + "_enable_hook";
856     var disable_hook_name = name + "_disable_hook";
857     define_buffer_local_hook(enable_hook_name);
858     define_buffer_local_hook(disable_hook_name);
860     var change_hook_name = null;
862     if (mode_class) {
863         mode_functions[name] = { enable: enable,
864                                  disable: disable,
865                                  mode_class: mode_class,
866                                  disable_hook_name: disable_hook_name };
867         change_hook_name = mode_class + "_change_hook";
868         define_buffer_local_hook(change_hook_name);
869     }
871     function func (buffer, arg) {
872         var old_state = buffer[state];
873         var cur_state = (old_state == name);
874         var new_state = (arg == null) ? !cur_state : (arg > 0);
875         if ((new_state == cur_state) || (!can_disable && !new_state))
876             // perhaps show a message if (!can_disable && !new_state)
877             // to tell the user that this mode cannot be disabled.  do
878             // we have any existing modes that would benefit by it?
879             return null;
880         if (new_state) {
881             if (mode_class && old_state != null)  {
882                 // Another buffer-mode of our same mode-class is
883                 // enabled.  Buffer-modes within a mode-class are
884                 // mutually exclusive, so turn the old one off.
885                 buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(old_state), 1);
886                 let x = mode_functions[old_state];
887                 let y = x.disable;
888                 if (y) y(buffer);
889                 conkeror[x.disable_hook_name].run(buffer);
890             }
891             buffer[state] = name;
892             if (enable)
893                 enable(buffer);
894             conkeror[enable_hook_name].run(buffer);
895             buffer.enabled_modes.push(name);
896         } else {
897             buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(name), 1);
898             disable(buffer);
899             conkeror[disable_hook_name].run(buffer);
900             buffer[state] = null;
901         }
902         if (change_hook_name)
903             conkeror[change_hook_name].run(buffer, buffer[state]);
904         buffer_mode_change_hook.run(buffer);
905         return new_state;
906     }
908     conkeror[name] = func;
909     interactive(hyphen_name, arguments.$doc, function (I) {
910         var arg = I.P;
911         var new_state = func(I.buffer, arg && univ_arg_to_number(arg));
912         I.minibuffer.message(hyphen_name + (new_state ? " enabled" : " disabled"));
913     });
915 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
918 function minibuffer_mode_indicator (window) {
919     this.window = window;
920     var element = create_XUL(window, "label");
921     element.setAttribute("id", "minibuffer-mode-indicator");
922     element.collapsed = true;
923     element.setAttribute("class", "minibuffer");
924     window.document.getElementById("minibuffer").appendChild(element);
925     this.element = element;
926     this.hook_func = method_caller(this, this.update);
927     add_hook.call(window, "select_buffer_hook", this.hook_func);
928     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_func);
929     this.update();
931 minibuffer_mode_indicator.prototype = {
932     update: function () {
933         var buf = this.window.buffers.current;
934         var modes = buf.enabled_modes;
935         var str = modes.map(
936             function (x) {
937                 let y = mode_display_names[x];
938                 if (y)
939                     return "[" + y + "]";
940                 else
941                     return null;
942             }).filter(function (x) x != null).join(" ");
943         this.element.collapsed = (str.length == 0);
944         this.element.value = str;
945     },
946     uninstall: function () {
947         remove_hook.call(window, "select_buffer_hook", this.hook_fun);
948         remove_hook.call(window, "current_buffer_mode_change_hook", this.hook_fun);
949         this.element.parentNode.removeChild(this.element);
950     }
952 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
953 minibuffer_mode_indicator_mode(true);
958  * INPUT MODES
959  */
960 define_current_buffer_hook("current_buffer_input_mode_change_hook", "input_mode_change_hook");
961 define_keywords("$display_name", "$doc");
962 function define_input_mode (base_name, keymap_name) {
963     keywords(arguments);
964     var name = base_name + "_input_mode";
965     define_buffer_mode(name,
966                        $class = "input_mode",
967                        $enable = function (buffer) {
968                            check_buffer(buffer, content_buffer);
969                            buffer.keymaps.push(conkeror[keymap_name]);
970                        },
971                        $disable = function (buffer) {
972                            var i = buffer.keymaps.indexOf(conkeror[keymap_name]);
973                            if (i > -1)
974                                buffer.keymaps.splice(i, 1);
975                        },
976                        forward_keywords(arguments));
978 ignore_function_for_get_caller_source_code_reference("define_input_mode");
981 function minibuffer_input_mode_indicator (window) {
982     this.window = window;
983     this.hook_func = method_caller(this, this.update);
984     add_hook.call(window, "select_buffer_hook", this.hook_func);
985     add_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
986     this.update();
989 minibuffer_input_mode_indicator.prototype = {
990     update: function () {
991         var buf = this.window.buffers.current;
992         var mode = buf.input_mode;
993         var classname = mode ? ("minibuffer-" + buf.input_mode.replace("_","-","g")) : "";
994         this.window.minibuffer.element.className = classname;
995     },
996     uninstall: function () {
997         remove_hook.call(window, "select_buffer_hook", this.hook_func);
998         remove_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
999     }
1002 define_global_window_mode("minibuffer_input_mode_indicator", "window_initialize_hook");
1003 minibuffer_input_mode_indicator_mode(true);
1005 provide("buffer");