buffer.focused_selection_controller: update for new focus system
[conkeror.git] / modules / buffer.js
blob0830ddc6f9de87209e6eb606242b52de4664be3e
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("$opener");
41 function buffer_creator (type) {
42     var args = forward_keywords(arguments);
43     return function (window) {
44         return new type(window, 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) {
56     this.constructor_begin();
57     keywords(arguments);
58     this.opener = arguments.$opener;
59     this.window = window;
60     var element = create_XUL(window, "vbox");
61     element.setAttribute("flex", "1");
62     var browser = create_XUL(window, "browser");
63     if (window.buffers.count == 0)
64         browser.setAttribute("type", "content-primary");
65     else
66         browser.setAttribute("type", "content");
67     browser.setAttribute("flex", "1");
68     browser.setAttribute("autocompletepopup", "popup_autocomplete");
69     element.appendChild(browser);
70     this.window.buffers.container.appendChild(element);
71     this.window.buffers.buffer_list.push(this);
72     this.element = element;
73     this.browser = element.firstChild;
74     this.element.conkeror_buffer_object = this;
76     this.local = { __proto__: conkeror };
77     this.page = null;
78     this.enabled_modes = [];
79     this.default_browser_object_classes = {};
81     var buffer = this;
83     this.browser.addEventListener("scroll", function (event) {
84             buffer_scroll_hook.run(buffer);
85         }, true /* capture */);
87     this.browser.addEventListener("DOMContentLoaded", function (event) {
88             buffer_dom_content_loaded_hook.run(buffer);
89         }, true /* capture */);
91     this.browser.addEventListener("load", function (event) {
92             buffer_loaded_hook.run(buffer);
93         }, true /* capture */);
95     this.browser.addEventListener("DOMWindowClose", function (event) {
96             /* This call to preventDefault is very important; without
97              * it, somehow Mozilla does something bad and as a result
98              * the window loses focus, causing keyboard commands to
99              * stop working. */
100             event.preventDefault();
102             if (allow_browser_window_close)
103                 kill_buffer(buffer, true);
104         }, true);
106     this.browser.addEventListener("focus", function (event) {
107         if (buffer.focusblocker &&
108             event.target instanceof Ci.nsIDOMHTMLElement &&
109             buffer.focusblocker(buffer, event))
110         {
111             event.target.blur();
112         } else
113             buffer.set_input_mode();
114     }, true);
116     this.browser.addEventListener("blur", function (event) {
117         buffer.set_input_mode();
118     }, true);
120     this.modalities = [];
122     // When create_buffer_hook_early runs, basic buffer properties
123     // will be available, but not the properties subclasses.
124     create_buffer_early_hook.run(this);
126     this.constructor_end();
128 buffer.prototype = {
129     constructor: buffer,
131     /* Saved focus state */
132     saved_focused_frame: null,
133     saved_focused_element: null,
135     // get title ()   [must be defined by subclasses]
136     // get name ()    [must be defined by subclasses]
137     dead: false, /* This is set when the buffer is killed */
139     keymaps: null,
140     mark_active: false,
142     // The property focusblocker is available for an external module to
143     // put a function on which takes a buffer as its argument and returns
144     // true to block a focus event, or false to let normal processing
145     // occur.  Having this one property explicitly handled by the buffer
146     // class allows for otherwise modular focus-blockers.
147     focusblocker: null,
149     default_message: "",
151     set_default_message: function (str) {
152         this.default_message = str;
153         if (this == this.window.buffers.current)
154             this.window.minibuffer.set_default_message(str);
155     },
157     constructors_running: 0,
159     constructor_begin: function () {
160         this.constructors_running++;
161     },
163     constructor_end: function () {
164         if (--this.constructors_running == 0) {
165             create_buffer_hook.run(this);
166             this.set_input_mode();
167             delete this.opener;
168         }
169     },
171     destroy: function () {
172         this.dead = true;
173         this.browser = null;
174         this.element = null;
175         this.saved_focused_frame = null;
176         this.saved_focused_element = null;
177         // prevent modalities from accessing dead browser
178         this.modalities = [];
179     },
181     set_input_mode: function () {
182         if (this.input_mode)
183             conkeror[this.input_mode](this, false);
184         this.keymaps = [];
185         this.modalities.map(function (m) m(this), this);
186     },
188     override_keymaps: function (keymaps) {
189         if (keymaps) {
190             this.keymaps = keymaps;
191             this.set_input_mode = function () {};
192             if (this.input_mode)
193                 conkeror[this.input_mode](this, false);
194         } else {
195             delete this.set_input_mode;
196             this.set_input_mode();
197         }
198     },
200     /* Browser accessors */
201     get top_frame () { return this.browser.contentWindow; },
202     get document () { return this.browser.contentDocument; },
203     get web_navigation () { return this.browser.webNavigation; },
204     get doc_shell () { return this.browser.docShell; },
205     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
206     get current_uri () { return this.browser.currentURI; },
208     is_child_element: function (element) {
209         return (element && this.is_child_frame(element.ownerDocument.defaultView));
210     },
212     is_child_frame: function (frame) {
213         return (frame && frame.top == this.top_frame);
214     },
216     // This method is like focused_frame, except that if no content
217     // frame actually has focus, this returns null.
218     get focused_frame_or_null () {
219         var frame = this.window.document.commandDispatcher.focusedWindow;
220         if (this.is_child_frame(frame))
221             return frame;
222         return null;
223     },
225     get focused_frame () {
226         var frame = this.window.document.commandDispatcher.focusedWindow;
227         if (this.is_child_frame(frame))
228             return frame;
229         return this.top_frame;
230     },
232     get focused_element () {
233         var element = this.window.document.commandDispatcher.focusedElement;
234         if (this.is_child_element(element))
235             return element;
236         return null;
237     },
239     get focused_selection_controller () {
240         return this.focused_frame
241             .QueryInterface(Ci.nsIInterfaceRequestor)
242             .getInterface(Ci.nsIWebNavigation)
243             .QueryInterface(Ci.nsIInterfaceRequestor)
244             .getInterface(Ci.nsISelectionDisplay)
245             .QueryInterface(Ci.nsISelectionController);
246     },
248     do_command: function (command) {
249         function attempt_command (element, command) {
250             var controller;
251             if (element.controllers
252                 && (controller = element.controllers.getControllerForCommand(command)) != null
253                 && controller.isCommandEnabled(command))
254             {
255                 controller.doCommand(command);
256                 return true;
257             }
258             return false;
259         }
261         var element = this.focused_element;
262         if (element && attempt_command(element, command))
263             return;
264         var win = this.focused_frame;
265         while (true) {
266             if (attempt_command(win, command))
267                 return;
268             if (!win.parent || win == win.parent)
269                 break;
270             win = win.parent;
271         }
272     }
275 function with_current_buffer (buffer, callback) {
276     return callback(new interactive_context(buffer));
279 function check_buffer (obj, type) {
280     if (!(obj instanceof type))
281         throw interactive_error("Buffer has invalid type.");
282     if (obj.dead)
283         throw interactive_error("Buffer has already been killed.");
284     return obj;
287 function caret_enabled (buffer) {
288     return buffer.browser.getAttribute('showcaret');
291 function clear_selection (buffer) {
292     let sel_ctrl = buffer.focused_selection_controller;
293     if (sel_ctrl) {
294         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
295         if (caret_enabled(buffer)) {
296             if (sel.anchorNode)
297                 sel.collapseToStart();
298         } else {
299             sel.removeAllRanges();
300         }
301     }
305 function buffer_container (window, create_initial_buffer) {
306     this.window = window;
307     this.container = window.document.getElementById("buffer-container");
308     this.buffer_list = [];
309     window.buffers = this;
310     create_initial_buffer(window);
312 buffer_container.prototype = {
313     constructor: buffer_container,
315     get current () {
316         return this.container.selectedPanel.conkeror_buffer_object;
317     },
319     set current (buffer) {
320         var old_value = this.current;
321         if (old_value == buffer)
322             return;
324         this.buffer_list.splice(this.buffer_list.indexOf(buffer), 1);
325         this.buffer_list.unshift(buffer);
327         this._switch_away_from(this.current);
328         this._switch_to(buffer);
330         // Run hooks
331         select_buffer_hook.run(buffer);
332     },
334     _switch_away_from: function (old_value) {
335         // Save focus state
336         old_value.saved_focused_frame = old_value.focused_frame;
337         old_value.saved_focused_element = old_value.focused_element;
339         old_value.browser.setAttribute("type", "content");
340     },
342     _switch_to: function (buffer) {
343         // Select new buffer in the XUL deck
344         this.container.selectedPanel = buffer.element;
346         buffer.browser.setAttribute("type", "content-primary");
348         /**
349          * This next focus call seems to be needed to avoid focus
350          * somehow getting lost (and the keypress handler therefore
351          * not getting called at all) when killing buffers.
352          */
353         this.window.focus();
355         // Restore focus state
356         buffer.browser.focus();
357         if (buffer.saved_focused_element)
358             set_focus_no_scroll(this.window, buffer.saved_focused_element);
359         else if (buffer.saved_focused_frame)
360             set_focus_no_scroll(this.window, buffer.saved_focused_frame);
362         buffer.saved_focused_element = null;
363         buffer.saved_focused_frame = null;
365         this.window.minibuffer.set_default_message(buffer.default_message);
366     },
368     get count () {
369         return this.container.childNodes.length;
370     },
372     get_buffer: function (index) {
373         if (index >= 0 && index < this.count)
374             return this.container.childNodes.item(index).conkeror_buffer_object;
375         return null;
376     },
378     get selected_index () {
379         var nodes = this.container.childNodes;
380         var count = nodes.length;
381         for (var i = 0; i < count; ++i)
382             if (nodes.item(i) == this.container.selectedPanel)
383                 return i;
384         return null;
385     },
387     index_of: function (b) {
388         var nodes = this.container.childNodes;
389         var count = nodes.length;
390         for (var i = 0; i < count; ++i)
391             if (nodes.item(i) == b.element)
392                 return i;
393         return null;
394     },
396     get unique_name_list () {
397         var existing_names = new string_hashset();
398         var bufs = [];
399         this.for_each(function(b) {
400                 var base_name = b.name;
401                 var name = base_name;
402                 var index = 1;
403                 while (existing_names.contains(name)) {
404                     ++index;
405                     name = base_name + "<" + index + ">";
406                 }
407                 existing_names.add(name);
408                 bufs.push([name, b]);
409             });
410         return bufs;
411     },
413     kill_buffer: function (b) {
414         if (b.dead)
415             return true;
416         var count = this.count;
417         if (count <= 1)
418             return false;
419         var new_buffer = this.buffer_list[0];
420         var changed = false;
421         if (b == new_buffer) {
422             new_buffer = this.buffer_list[1];
423             changed = true;
424         }
425         this._switch_away_from(this.current);
426         // The removeChild call below may trigger events in progress
427         // listeners.  This call to `destroy' gives buffer subclasses a
428         // chance to remove such listeners, so that they cannot try to
429         // perform UI actions based upon a xul:browser that no longer
430         // exists.
431         var element = b.element;
432         b.destroy();
433         this.container.removeChild(element);
434         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
435         this._switch_to(new_buffer);
436         if (changed) {
437             select_buffer_hook.run(new_buffer);
438             this.buffer_list.splice(this.buffer_list.indexOf(new_buffer), 1);
439             this.buffer_list.unshift(new_buffer);
440         }
441         kill_buffer_hook.run(b);
442         return true;
443     },
445     bury_buffer: function (b) {
446         var new_buffer = this.buffer_list[0];
447         if (b == new_buffer)
448             new_buffer = this.buffer_list[1];
449         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
450         this.buffer_list.push(b);
451         this.current = new_buffer;
452         return true;
453     },
455     for_each: function (f) {
456         var count = this.count;
457         for (var i = 0; i < count; ++i)
458             f(this.get_buffer(i));
459     }
462 function buffer_initialize_window_early (window) {
463     /**
464      * Use content_buffer by default to handle an unusual case where
465      * browser.chromeURI is used perhaps.  In general this default
466      * should not be needed.
467      */
468     var create_initial_buffer =
469         window.args.initial_buffer_creator || buffer_creator(content_buffer);
470     new buffer_container(window, create_initial_buffer);
473 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
476 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
477 function buffer_before_window_close (window) {
478     var bs = window.buffers;
479     var count = bs.count;
480     for (let i = 0; i < count; ++i) {
481         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
482             return false;
483     }
484     return true;
486 add_hook("window_before_close_hook", buffer_before_window_close);
488 function buffer_window_close_handler (window) {
489     var bs = window.buffers;
490     var count = bs.count;
491     for (let i = 0; i < count; ++i) {
492         let b = bs.get_buffer(i);
493         b.destroy();
494     }
496 add_hook("window_close_hook", buffer_window_close_handler);
498 /* open/follow targets */
499 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
500                                // buffer is a content_buffer.
501 const OPEN_NEW_BUFFER = 1;
502 const OPEN_NEW_BUFFER_BACKGROUND = 2;
503 const OPEN_NEW_WINDOW = 3;
505 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
506 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
508 var TARGET_PROMPTS = [" in current buffer",
509                       " in new buffer",
510                       " in new buffer (background)",
511                       " in new window",
512                       "",
513                       " in current frame"];
515 var TARGET_NAMES = ["current buffer",
516                     "new buffer",
517                     "new buffer (background)",
518                     "new window",
519                     "default",
520                     "current frame"];
523 function create_buffer (window, creator, target) {
524     switch (target) {
525     case OPEN_NEW_BUFFER:
526         window.buffers.current = creator(window, null);
527         break;
528     case OPEN_NEW_BUFFER_BACKGROUND:
529         creator(window, null);
530         break;
531     case OPEN_NEW_WINDOW:
532         make_window(creator);
533         break;
534     default:
535         throw new Error("invalid target");
536     }
539 let (queued_buffer_creators = null) {
540     function create_buffer_in_current_window (creator, target, focus_existing) {
541         function process_queued_buffer_creators (window) {
542             for (var i = 0; i < queued_buffer_creators.length; ++i) {
543                 var x = queued_buffer_creators[i];
544                 create_buffer(window, x[0], x[1]);
545             }
546             queued_buffer_creators = null;
547         }
549         if (target == OPEN_NEW_WINDOW)
550             throw new Error("invalid target");
551         var window = get_recent_conkeror_window();
552         if (window) {
553             if (focus_existing)
554                 window.focus();
555             create_buffer(window, creator, target);
556         } else if (queued_buffer_creators != null) {
557             queued_buffer_creators.push([creator,target]);
558         } else {
559             queued_buffer_creators = [];
560             window = make_window(creator);
561             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
562         }
563     }
568  * Read Buffer
569  */
570 minibuffer_auto_complete_preferences["buffer"] = true;
571 define_keywords("$default");
572 minibuffer.prototype.read_buffer = function () {
573     var window = this.window;
574     var buffer = this.window.buffers.current;
575     keywords(arguments, $prompt = "Buffer:",
576              $default = buffer,
577              $history = "buffer");
578     var completer = all_word_completer(
579         $completions = function (visitor) window.buffers.for_each(visitor),
580         $get_string = function (x) x.description,
581         $get_description = function (x) x.title);
582     var result = yield this.read(
583         $keymap = read_buffer_keymap,
584         $prompt = arguments.$prompt,
585         $history = arguments.$history,
586         $completer = completer,
587         $match_required = true,
588         $auto_complete = "buffer",
589         $auto_complete_initial = true,
590         $auto_complete_delay = 0,
591         $default_completion = arguments.$default);
592     yield co_return(result);
596 interactive("buffer-reset-input-mode",
597     "Force a reset of the input mode.  Used by quote-next.",
598     function (I) {
599         I.buffer.set_input_mode();
600     });
603 function buffer_next (window, count) {
604     var index = window.buffers.selected_index;
605     var total = window.buffers.count;
606     if (total == 1)
607         throw new interactive_error("No other buffer");
608     index = (index + count) % total;
609     if (index < 0)
610         index += total;
611     window.buffers.current = window.buffers.get_buffer(index);
613 interactive("buffer-next",
614     "Switch to the next buffer.",
615     function (I) { buffer_next(I.window, I.p); });
616 interactive("buffer-previous",
617     "Switch to the previous buffer.",
618     function (I) { buffer_next(I.window, -I.p); });
620 function switch_to_buffer (window, buffer) {
621     if (buffer && !buffer.dead)
622         window.buffers.current = buffer;
624 interactive("switch-to-buffer",
625     "Switch to a buffer specified in the minibuffer.",
626     function (I) {
627         switch_to_buffer(
628             I.window,
629             (yield I.minibuffer.read_buffer(
630                 $prompt = "Switch to buffer:",
631                 $default = (I.window.buffers.count > 1 ?
632                             I.window.buffers.buffer_list[1] :
633                             I.buffer))));
634     });
636 define_variable("can_kill_last_buffer", true,
637     "If this is set to true, kill-buffer can kill the last "+
638     "remaining buffer, and close the window.");
640 function kill_other_buffers (buffer) {
641     if (!buffer)
642         return;
643     var bs = buffer.window.buffers;
644     var b;
645     while ((b = bs.get_buffer(0)) != buffer)
646         bs.kill_buffer(b);
647     var count = bs.count;
648     while (--count)
649         bs.kill_buffer(bs.get_buffer(1));
651 interactive("kill-other-buffers",
652     "Kill all buffers except current one.\n",
653     function (I) { kill_other_buffers(I.buffer); });
656 function kill_buffer (buffer, force) {
657     if (!buffer)
658         return;
659     var buffers = buffer.window.buffers;
660     if (buffers.count == 1 && buffer == buffers.current) {
661         if (can_kill_last_buffer || force) {
662             delete_window(buffer.window);
663             return;
664         } else
665             throw interactive_error("Can't kill last buffer.");
666     }
667     buffers.kill_buffer(buffer);
669 interactive("kill-buffer",
670     "Kill a buffer specified in the minibuffer.\n" +
671     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
672     "last remaining buffer in a window will cause the window to be closed.",
673     function (I) {
674         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
675     });
677 interactive("kill-current-buffer",
678     "Kill the current buffer.\n" +
679     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
680     "last remaining buffer in a window will cause the window to be closed.",
681     function (I) { kill_buffer(I.buffer); });
683 interactive("read-buffer-kill-buffer",
684     "Kill the current selected buffer in the completions list "+
685     "in a read buffer minibuffer interaction.",
686     function (I) {
687         var s = I.window.minibuffer.current_state;
688         var i = s.selected_completion_index;
689         var c = s.completions;
690         if (i == -1)
691             return;
692         kill_buffer(c.get_value(i));
693         s.completer.refresh();
694         s.handle_input(I.window.minibuffer);
695     });
697 interactive("bury-buffer",
698     "Bury the current buffer.\n Put the current buffer at the end of " +
699     "the buffer list, so that it is the least likely buffer to be " +
700     "selected by `switch-to-buffer'.",
701     function (I) { I.window.buffers.bury_buffer(I.buffer); });
703 function change_directory (buffer, dir) {
704     if (buffer.page != null)
705         delete buffer.page.local.cwd;
706     buffer.local.cwd = make_file(dir);
708 interactive("change-directory",
709     "Change the current directory of the selected buffer.",
710     function (I) {
711         change_directory(
712             I.buffer,
713             (yield I.minibuffer.read_existing_directory_path(
714                 $prompt = "Change to directory:",
715                 $initial_value = make_file(I.local.cwd).path)));
716     });
718 interactive("shell-command", null,
719     function (I) {
720         var cwd = I.local.cwd;
721         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
722         yield shell_command(cmd, $cwd = cwd);
723     });
727  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
728  * frames, iframes, plugins, and also clearing the selection.
729  */
730 define_buffer_local_hook("unfocus_hook");
731 function unfocus (window, buffer) {
732     // 1. if there is a selection, clear it.
733     var selc = buffer.focused_selection_controller;
734     if (selc) {
735         var sel = selc.getSelection(selc.SELECTION_NORMAL);
736         var active = ! sel.isCollapsed;
737         clear_selection(buffer);
738         if (active) {
739             window.minibuffer.message("cleared selection");
740             return;
741         }
742     }
743     // 2. if there is a focused element, unfocus it.
744     if (buffer.focused_element) {
745         buffer.focused_element.blur();
746         // if an element in a detached fragment has focus, blur() will
747         // not work, and we need to take more drastic measures.  the
748         // action taken was found through experiment, so it is possibly
749         // not the most concise way to unfocus such an element.
750         if (buffer.focused_element) {
751             buffer.element.focus();
752             buffer.top_frame.focus();
753         }
754         window.minibuffer.message("unfocused element");
755         return;
756     }
757     // 3. if an iframe has focus, we must blur it.
758     if (buffer.focused_frame_or_null &&
759         buffer.focused_frame_or_null.frameElement)
760     {
761         buffer.focused_frame_or_null.frameElement.blur();
762     }
763     // 4. return focus to top-frame from subframes and plugins.
764     buffer.top_frame.focus();
765     buffer.top_frame.focus(); // needed to get focus back from plugins
766     window.minibuffer.message("refocused top frame");
767     // give page-modes an opportunity to set focus specially
768     unfocus_hook.run(buffer);
770 interactive("unfocus",
771     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
772     "frames, iframes, plugins, and also for clearing the selection.  "+
773     "The action that it takes is based on precedence.  If there is a "+
774     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
775     "there is a selection, it will clear the selection.  Otherwise, it "+
776     "will return focus to the top frame from a focused frame, iframe, "+
777     "or plugin.  In the case of plugins, since they steal keyboard "+
778     "control away from Conkeror, the normal way to unfocus them is "+
779     "to use command-line remoting externally: conkeror -batch -f "+
780     "unfocus.  Page-modes also have an opportunity to alter the default"+
781     "focus via the hook, `focus_hook'.",
782     function (I) {
783         unfocus(I.window, I.buffer);
784     });
787 function for_each_buffer (f) {
788     for_each_window(function (w) { w.buffers.for_each(f); });
793  * BUFFER MODES
794  */
796 var mode_functions = {};
797 var mode_display_names = {};
799 define_buffer_local_hook("buffer_mode_change_hook");
800 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
802 define_keywords("$display_name", "$class", "$enable", "$disable", "$doc");
803 function define_buffer_mode (name) {
804     keywords(arguments);
806     var hyphen_name = name.replace("_","-","g");
807     var display_name = arguments.$display_name;
808     var mode_class = arguments.$class;
809     var enable = arguments.$enable;
810     var disable = arguments.$disable;
812     mode_display_names[name] = display_name;
814     var can_disable;
816     if (disable == false) {
817         can_disable = false;
818         disable = null;
819     } else
820         can_disable = true;
822     var state = (mode_class != null) ? mode_class : (name + "_enabled");
823     var enable_hook_name = name + "_enable_hook";
824     var disable_hook_name = name + "_disable_hook";
825     define_buffer_local_hook(enable_hook_name);
826     define_buffer_local_hook(disable_hook_name);
828     var change_hook_name = null;
830     if (mode_class) {
831         mode_functions[name] = { enable: enable,
832                                  disable: disable,
833                                  mode_class: mode_class,
834                                  disable_hook_name: disable_hook_name };
835         change_hook_name = mode_class + "_change_hook";
836         define_buffer_local_hook(change_hook_name);
837     }
839     function func (buffer, arg) {
840         var old_state = buffer[state];
841         var cur_state = (old_state == name);
842         var new_state = (arg == null) ? !cur_state : (arg > 0);
843         if ((new_state == cur_state) || (!can_disable && !new_state))
844             // perhaps show a message if (!can_disable && !new_state)
845             // to tell the user that this mode cannot be disabled.  do
846             // we have any existing modes that would benefit by it?
847             return null;
848         if (new_state) {
849             if (mode_class && old_state != null)  {
850                 // Another buffer-mode of our same mode-class is
851                 // enabled.  Buffer-modes within a mode-class are
852                 // mutually exclusive, so turn the old one off.
853                 buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(old_state), 1);
854                 let x = mode_functions[old_state];
855                 let y = x.disable;
856                 if (y) y(buffer);
857                 conkeror[x.disable_hook_name].run(buffer);
858             }
859             buffer[state] = name;
860             if (enable)
861                 enable(buffer);
862             conkeror[enable_hook_name].run(buffer);
863             buffer.enabled_modes.push(name);
864         } else {
865             buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(name), 1);
866             disable(buffer);
867             conkeror[disable_hook_name].run(buffer);
868             buffer[state] = null;
869         }
870         if (change_hook_name)
871             conkeror[change_hook_name].run(buffer, buffer[state]);
872         buffer_mode_change_hook.run(buffer);
873         return new_state;
874     }
876     conkeror[name] = func;
877     interactive(hyphen_name, arguments.$doc, function (I) {
878         var arg = I.P;
879         var new_state = func(I.buffer, arg && univ_arg_to_number(arg));
880         I.minibuffer.message(hyphen_name + (new_state ? " enabled" : " disabled"));
881     });
883 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
886 function minibuffer_mode_indicator (window) {
887     this.window = window;
888     var element = create_XUL(window, "label");
889     element.setAttribute("id", "minibuffer-mode-indicator");
890     element.collapsed = true;
891     element.setAttribute("class", "minibuffer");
892     window.document.getElementById("minibuffer").appendChild(element);
893     this.element = element;
894     this.hook_func = method_caller(this, this.update);
895     add_hook.call(window, "select_buffer_hook", this.hook_func);
896     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_func);
897     this.update();
899 minibuffer_mode_indicator.prototype = {
900     constructor: minibuffer_mode_indicator,
901     update: function () {
902         var buf = this.window.buffers.current;
903         var modes = buf.enabled_modes;
904         var str = modes.map(
905             function (x) {
906                 let y = mode_display_names[x];
907                 if (y)
908                     return "[" + y + "]";
909                 else
910                     return null;
911             }).filter(function (x) x != null).join(" ");
912         this.element.collapsed = (str.length == 0);
913         this.element.value = str;
914     },
915     uninstall: function () {
916         remove_hook.call(window, "select_buffer_hook", this.hook_fun);
917         remove_hook.call(window, "current_buffer_mode_change_hook", this.hook_fun);
918         this.element.parentNode.removeChild(this.element);
919     }
921 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
922 minibuffer_mode_indicator_mode(true);
927  * INPUT MODES
928  */
929 define_current_buffer_hook("current_buffer_input_mode_change_hook", "input_mode_change_hook");
930 define_keywords("$display_name", "$doc");
931 function define_input_mode (base_name, keymap_name) {
932     keywords(arguments);
933     var name = base_name + "_input_mode";
934     define_buffer_mode(name,
935                        $class = "input_mode",
936                        $enable = function (buffer) {
937                            check_buffer(buffer, content_buffer);
938                            buffer.keymaps.push(conkeror[keymap_name]);
939                        },
940                        $disable = function (buffer) {
941                            var i = buffer.keymaps.indexOf(conkeror[keymap_name]);
942                            if (i > -1)
943                                buffer.keymaps.splice(i, 1);
944                        },
945                        forward_keywords(arguments));
947 ignore_function_for_get_caller_source_code_reference("define_input_mode");
950 function minibuffer_input_mode_indicator (window) {
951     this.window = window;
952     this.hook_func = method_caller(this, this.update);
953     add_hook.call(window, "select_buffer_hook", this.hook_func);
954     add_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
955     this.update();
957 minibuffer_input_mode_indicator.prototype = {
958     constructor: minibuffer_input_mode_indicator,
959     update: function () {
960         var buf = this.window.buffers.current;
961         var mode = buf.input_mode;
962         var classname = mode ? ("minibuffer-" + buf.input_mode.replace("_","-","g")) : "";
963         this.window.minibuffer.element.className = classname;
964     },
965     uninstall: function () {
966         remove_hook.call(window, "select_buffer_hook", this.hook_func);
967         remove_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
968     }
971 define_global_window_mode("minibuffer_input_mode_indicator", "window_initialize_hook");
972 minibuffer_input_mode_indicator_mode(true);
974 provide("buffer");