youtube: update scraper for youtube.com change
[conkeror.git] / modules / buffer.js
blobb3ac5ea37dbbf4ce4ad3ddd10dc8bbbcb2fb2623
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         var child_docshells = this.doc_shell.getDocShellEnumerator(
241             Ci.nsIDocShellTreeItem.typeContent,
242             Ci.nsIDocShell.ENUMERATE_FORWARDS);
243         while (child_docshells.hasMoreElements()) {
244             let ds = child_docshells.getNext()
245                 .QueryInterface(Ci.nsIDocShell);
246             if (ds.hasFocus) {
247                 let display = ds.QueryInterface(Ci.nsIInterfaceRequestor)
248                     .getInterface(Ci.nsISelectionDisplay);
249                 if (! display)
250                     return null;
251                 return display.QueryInterface(Ci.nsISelectionController);
252             }
253         }
254         return this.doc_shell
255             .QueryInterface(Ci.nsIInterfaceRequestor)
256             .getInterface(Ci.nsISelectionDisplay)
257             .QueryInterface(Ci.nsISelectionController);
258     },
260     do_command: function (command) {
261         function attempt_command (element, command) {
262             var controller;
263             if (element.controllers
264                 && (controller = element.controllers.getControllerForCommand(command)) != null
265                 && controller.isCommandEnabled(command))
266             {
267                 controller.doCommand(command);
268                 return true;
269             }
270             return false;
271         }
273         var element = this.focused_element;
274         if (element && attempt_command(element, command))
275             return;
276         var win = this.focused_frame;
277         while (true) {
278             if (attempt_command(win, command))
279                 return;
280             if (!win.parent || win == win.parent)
281                 break;
282             win = win.parent;
283         }
284     }
287 function with_current_buffer (buffer, callback) {
288     return callback(new interactive_context(buffer));
291 function check_buffer (obj, type) {
292     if (!(obj instanceof type))
293         throw interactive_error("Buffer has invalid type.");
294     if (obj.dead)
295         throw interactive_error("Buffer has already been killed.");
296     return obj;
299 function caret_enabled (buffer) {
300     return buffer.browser.getAttribute('showcaret');
303 function clear_selection (buffer) {
304     let sel_ctrl = buffer.focused_selection_controller;
305     if (sel_ctrl) {
306         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
307         if (caret_enabled(buffer)) {
308             if (sel.anchorNode)
309                 sel.collapseToStart();
310         } else {
311             sel.removeAllRanges();
312         }
313     }
317 function buffer_container (window, create_initial_buffer) {
318     this.window = window;
319     this.container = window.document.getElementById("buffer-container");
320     this.buffer_list = [];
321     window.buffers = this;
322     create_initial_buffer(window);
324 buffer_container.prototype = {
325     constructor: buffer_container,
327     get current () {
328         return this.container.selectedPanel.conkeror_buffer_object;
329     },
331     set current (buffer) {
332         var old_value = this.current;
333         if (old_value == buffer)
334             return;
336         this.buffer_list.splice(this.buffer_list.indexOf(buffer), 1);
337         this.buffer_list.unshift(buffer);
339         this._switch_away_from(this.current);
340         this._switch_to(buffer);
342         // Run hooks
343         select_buffer_hook.run(buffer);
344     },
346     _switch_away_from: function (old_value) {
347         // Save focus state
348         old_value.saved_focused_frame = old_value.focused_frame;
349         old_value.saved_focused_element = old_value.focused_element;
351         old_value.browser.setAttribute("type", "content");
352     },
354     _switch_to: function (buffer) {
355         // Select new buffer in the XUL deck
356         this.container.selectedPanel = buffer.element;
358         buffer.browser.setAttribute("type", "content-primary");
360         /**
361          * This next focus call seems to be needed to avoid focus
362          * somehow getting lost (and the keypress handler therefore
363          * not getting called at all) when killing buffers.
364          */
365         this.window.focus();
367         // Restore focus state
368         buffer.browser.focus();
369         if (buffer.saved_focused_element)
370             set_focus_no_scroll(this.window, buffer.saved_focused_element);
371         else if (buffer.saved_focused_frame)
372             set_focus_no_scroll(this.window, buffer.saved_focused_frame);
374         buffer.saved_focused_element = null;
375         buffer.saved_focused_frame = null;
377         this.window.minibuffer.set_default_message(buffer.default_message);
378     },
380     get count () {
381         return this.container.childNodes.length;
382     },
384     get_buffer: function (index) {
385         if (index >= 0 && index < this.count)
386             return this.container.childNodes.item(index).conkeror_buffer_object;
387         return null;
388     },
390     get selected_index () {
391         var nodes = this.container.childNodes;
392         var count = nodes.length;
393         for (var i = 0; i < count; ++i)
394             if (nodes.item(i) == this.container.selectedPanel)
395                 return i;
396         return null;
397     },
399     index_of: function (b) {
400         var nodes = this.container.childNodes;
401         var count = nodes.length;
402         for (var i = 0; i < count; ++i)
403             if (nodes.item(i) == b.element)
404                 return i;
405         return null;
406     },
408     get unique_name_list () {
409         var existing_names = new string_hashset();
410         var bufs = [];
411         this.for_each(function(b) {
412                 var base_name = b.name;
413                 var name = base_name;
414                 var index = 1;
415                 while (existing_names.contains(name)) {
416                     ++index;
417                     name = base_name + "<" + index + ">";
418                 }
419                 existing_names.add(name);
420                 bufs.push([name, b]);
421             });
422         return bufs;
423     },
425     kill_buffer: function (b) {
426         if (b.dead)
427             return true;
428         var count = this.count;
429         if (count <= 1)
430             return false;
431         var new_buffer = this.buffer_list[0];
432         var changed = false;
433         if (b == new_buffer) {
434             new_buffer = this.buffer_list[1];
435             changed = true;
436         }
437         this._switch_away_from(this.current);
438         // The removeChild call below may trigger events in progress
439         // listeners.  This call to `destroy' gives buffer subclasses a
440         // chance to remove such listeners, so that they cannot try to
441         // perform UI actions based upon a xul:browser that no longer
442         // exists.
443         var element = b.element;
444         b.destroy();
445         this.container.removeChild(element);
446         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
447         this._switch_to(new_buffer);
448         if (changed) {
449             select_buffer_hook.run(new_buffer);
450             this.buffer_list.splice(this.buffer_list.indexOf(new_buffer), 1);
451             this.buffer_list.unshift(new_buffer);
452         }
453         kill_buffer_hook.run(b);
454         return true;
455     },
457     bury_buffer: function (b) {
458         var new_buffer = this.buffer_list[0];
459         if (b == new_buffer)
460             new_buffer = this.buffer_list[1];
461         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
462         this.buffer_list.push(b);
463         this.current = new_buffer;
464         return true;
465     },
467     for_each: function (f) {
468         var count = this.count;
469         for (var i = 0; i < count; ++i)
470             f(this.get_buffer(i));
471     }
474 function buffer_initialize_window_early (window) {
475     /**
476      * Use content_buffer by default to handle an unusual case where
477      * browser.chromeURI is used perhaps.  In general this default
478      * should not be needed.
479      */
480     var create_initial_buffer =
481         window.args.initial_buffer_creator || buffer_creator(content_buffer);
482     new buffer_container(window, create_initial_buffer);
485 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
488 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
489 function buffer_before_window_close (window) {
490     var bs = window.buffers;
491     var count = bs.count;
492     for (let i = 0; i < count; ++i) {
493         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
494             return false;
495     }
496     return true;
498 add_hook("window_before_close_hook", buffer_before_window_close);
500 function buffer_window_close_handler (window) {
501     var bs = window.buffers;
502     var count = bs.count;
503     for (let i = 0; i < count; ++i) {
504         let b = bs.get_buffer(i);
505         b.destroy();
506     }
508 add_hook("window_close_hook", buffer_window_close_handler);
510 /* open/follow targets */
511 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
512                                // buffer is a content_buffer.
513 const OPEN_NEW_BUFFER = 1;
514 const OPEN_NEW_BUFFER_BACKGROUND = 2;
515 const OPEN_NEW_WINDOW = 3;
517 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
518 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
520 var TARGET_PROMPTS = [" in current buffer",
521                       " in new buffer",
522                       " in new buffer (background)",
523                       " in new window",
524                       "",
525                       " in current frame"];
527 var TARGET_NAMES = ["current buffer",
528                     "new buffer",
529                     "new buffer (background)",
530                     "new window",
531                     "default",
532                     "current frame"];
535 function create_buffer (window, creator, target) {
536     switch (target) {
537     case OPEN_NEW_BUFFER:
538         window.buffers.current = creator(window, null);
539         break;
540     case OPEN_NEW_BUFFER_BACKGROUND:
541         creator(window, null);
542         break;
543     case OPEN_NEW_WINDOW:
544         make_window(creator);
545         break;
546     default:
547         throw new Error("invalid target");
548     }
551 let (queued_buffer_creators = null) {
552     function create_buffer_in_current_window (creator, target, focus_existing) {
553         function process_queued_buffer_creators (window) {
554             for (var i = 0; i < queued_buffer_creators.length; ++i) {
555                 var x = queued_buffer_creators[i];
556                 create_buffer(window, x[0], x[1]);
557             }
558             queued_buffer_creators = null;
559         }
561         if (target == OPEN_NEW_WINDOW)
562             throw new Error("invalid target");
563         var window = get_recent_conkeror_window();
564         if (window) {
565             if (focus_existing)
566                 window.focus();
567             create_buffer(window, creator, target);
568         } else if (queued_buffer_creators != null) {
569             queued_buffer_creators.push([creator,target]);
570         } else {
571             queued_buffer_creators = [];
572             window = make_window(creator);
573             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
574         }
575     }
580  * Read Buffer
581  */
582 minibuffer_auto_complete_preferences["buffer"] = true;
583 define_keywords("$default");
584 minibuffer.prototype.read_buffer = function () {
585     var window = this.window;
586     var buffer = this.window.buffers.current;
587     keywords(arguments, $prompt = "Buffer:",
588              $default = buffer,
589              $history = "buffer");
590     var completer = all_word_completer(
591         $completions = function (visitor) window.buffers.for_each(visitor),
592         $get_string = function (x) x.description,
593         $get_description = function (x) x.title);
594     var result = yield this.read(
595         $keymap = read_buffer_keymap,
596         $prompt = arguments.$prompt,
597         $history = arguments.$history,
598         $completer = completer,
599         $match_required = true,
600         $auto_complete = "buffer",
601         $auto_complete_initial = true,
602         $auto_complete_delay = 0,
603         $default_completion = arguments.$default);
604     yield co_return(result);
608 interactive("buffer-reset-input-mode",
609     "Force a reset of the input mode.  Used by quote-next.",
610     function (I) {
611         I.buffer.set_input_mode();
612     });
615 function buffer_next (window, count) {
616     var index = window.buffers.selected_index;
617     var total = window.buffers.count;
618     if (total == 1)
619         throw new interactive_error("No other buffer");
620     index = (index + count) % total;
621     if (index < 0)
622         index += total;
623     window.buffers.current = window.buffers.get_buffer(index);
625 interactive("buffer-next",
626     "Switch to the next buffer.",
627     function (I) { buffer_next(I.window, I.p); });
628 interactive("buffer-previous",
629     "Switch to the previous buffer.",
630     function (I) { buffer_next(I.window, -I.p); });
632 function switch_to_buffer (window, buffer) {
633     if (buffer && !buffer.dead)
634         window.buffers.current = buffer;
636 interactive("switch-to-buffer",
637     "Switch to a buffer specified in the minibuffer.",
638     function (I) {
639         switch_to_buffer(
640             I.window,
641             (yield I.minibuffer.read_buffer(
642                 $prompt = "Switch to buffer:",
643                 $default = (I.window.buffers.count > 1 ?
644                             I.window.buffers.buffer_list[1] :
645                             I.buffer))));
646     });
648 define_variable("can_kill_last_buffer", true,
649     "If this is set to true, kill-buffer can kill the last "+
650     "remaining buffer, and close the window.");
652 function kill_other_buffers (buffer) {
653     if (!buffer)
654         return;
655     var bs = buffer.window.buffers;
656     var b;
657     while ((b = bs.get_buffer(0)) != buffer)
658         bs.kill_buffer(b);
659     var count = bs.count;
660     while (--count)
661         bs.kill_buffer(bs.get_buffer(1));
663 interactive("kill-other-buffers",
664     "Kill all buffers except current one.\n",
665     function (I) { kill_other_buffers(I.buffer); });
668 function kill_buffer (buffer, force) {
669     if (!buffer)
670         return;
671     var buffers = buffer.window.buffers;
672     if (buffers.count == 1 && buffer == buffers.current) {
673         if (can_kill_last_buffer || force) {
674             delete_window(buffer.window);
675             return;
676         } else
677             throw interactive_error("Can't kill last buffer.");
678     }
679     buffers.kill_buffer(buffer);
681 interactive("kill-buffer",
682     "Kill a buffer specified in the minibuffer.\n" +
683     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
684     "last remaining buffer in a window will cause the window to be closed.",
685     function (I) {
686         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
687     });
689 interactive("kill-current-buffer",
690     "Kill the current buffer.\n" +
691     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
692     "last remaining buffer in a window will cause the window to be closed.",
693     function (I) { kill_buffer(I.buffer); });
695 interactive("read-buffer-kill-buffer",
696     "Kill the current selected buffer in the completions list "+
697     "in a read buffer minibuffer interaction.",
698     function (I) {
699         var s = I.window.minibuffer.current_state;
700         var i = s.selected_completion_index;
701         var c = s.completions;
702         if (i == -1)
703             return;
704         kill_buffer(c.get_value(i));
705         s.completer.refresh();
706         s.handle_input(I.window.minibuffer);
707     });
709 interactive("bury-buffer",
710     "Bury the current buffer.\n Put the current buffer at the end of " +
711     "the buffer list, so that it is the least likely buffer to be " +
712     "selected by `switch-to-buffer'.",
713     function (I) { I.window.buffers.bury_buffer(I.buffer); });
715 function change_directory (buffer, dir) {
716     if (buffer.page != null)
717         delete buffer.page.local.cwd;
718     buffer.local.cwd = make_file(dir);
720 interactive("change-directory",
721     "Change the current directory of the selected buffer.",
722     function (I) {
723         change_directory(
724             I.buffer,
725             (yield I.minibuffer.read_existing_directory_path(
726                 $prompt = "Change to directory:",
727                 $initial_value = make_file(I.local.cwd).path)));
728     });
730 interactive("shell-command", null,
731     function (I) {
732         var cwd = I.local.cwd;
733         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
734         yield shell_command(cmd, $cwd = cwd);
735     });
739  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
740  * frames, iframes, plugins, and also clearing the selection.
741  */
742 define_buffer_local_hook("unfocus_hook");
743 function unfocus (window, buffer) {
744     // 1. if there is a selection, clear it.
745     var selc = buffer.focused_selection_controller;
746     if (selc) {
747         var sel = selc.getSelection(selc.SELECTION_NORMAL);
748         var active = ! sel.isCollapsed;
749         clear_selection(buffer);
750         if (active) {
751             window.minibuffer.message("cleared selection");
752             return;
753         }
754     }
755     // 2. if there is a focused element, unfocus it.
756     if (buffer.focused_element) {
757         buffer.focused_element.blur();
758         // if an element in a detached fragment has focus, blur() will
759         // not work, and we need to take more drastic measures.  the
760         // action taken was found through experiment, so it is possibly
761         // not the most concise way to unfocus such an element.
762         if (buffer.focused_element) {
763             buffer.element.focus();
764             buffer.top_frame.focus();
765         }
766         window.minibuffer.message("unfocused element");
767         return;
768     }
769     // 3. if an iframe has focus, we must blur it.
770     if (buffer.focused_frame_or_null &&
771         buffer.focused_frame_or_null.frameElement)
772     {
773         buffer.focused_frame_or_null.frameElement.blur();
774     }
775     // 4. return focus to top-frame from subframes and plugins.
776     buffer.top_frame.focus();
777     buffer.top_frame.focus(); // needed to get focus back from plugins
778     window.minibuffer.message("refocused top frame");
779     // give page-modes an opportunity to set focus specially
780     unfocus_hook.run(buffer);
782 interactive("unfocus",
783     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
784     "frames, iframes, plugins, and also for clearing the selection.  "+
785     "The action that it takes is based on precedence.  If there is a "+
786     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
787     "there is a selection, it will clear the selection.  Otherwise, it "+
788     "will return focus to the top frame from a focused frame, iframe, "+
789     "or plugin.  In the case of plugins, since they steal keyboard "+
790     "control away from Conkeror, the normal way to unfocus them is "+
791     "to use command-line remoting externally: conkeror -batch -f "+
792     "unfocus.  Page-modes also have an opportunity to alter the default"+
793     "focus via the hook, `focus_hook'.",
794     function (I) {
795         unfocus(I.window, I.buffer);
796     });
799 function for_each_buffer (f) {
800     for_each_window(function (w) { w.buffers.for_each(f); });
805  * BUFFER MODES
806  */
808 var mode_functions = {};
809 var mode_display_names = {};
811 define_buffer_local_hook("buffer_mode_change_hook");
812 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
814 define_keywords("$display_name", "$class", "$enable", "$disable", "$doc");
815 function define_buffer_mode (name) {
816     keywords(arguments);
818     var hyphen_name = name.replace("_","-","g");
819     var display_name = arguments.$display_name;
820     var mode_class = arguments.$class;
821     var enable = arguments.$enable;
822     var disable = arguments.$disable;
824     mode_display_names[name] = display_name;
826     var can_disable;
828     if (disable == false) {
829         can_disable = false;
830         disable = null;
831     } else
832         can_disable = true;
834     var state = (mode_class != null) ? mode_class : (name + "_enabled");
835     var enable_hook_name = name + "_enable_hook";
836     var disable_hook_name = name + "_disable_hook";
837     define_buffer_local_hook(enable_hook_name);
838     define_buffer_local_hook(disable_hook_name);
840     var change_hook_name = null;
842     if (mode_class) {
843         mode_functions[name] = { enable: enable,
844                                  disable: disable,
845                                  mode_class: mode_class,
846                                  disable_hook_name: disable_hook_name };
847         change_hook_name = mode_class + "_change_hook";
848         define_buffer_local_hook(change_hook_name);
849     }
851     function func (buffer, arg) {
852         var old_state = buffer[state];
853         var cur_state = (old_state == name);
854         var new_state = (arg == null) ? !cur_state : (arg > 0);
855         if ((new_state == cur_state) || (!can_disable && !new_state))
856             // perhaps show a message if (!can_disable && !new_state)
857             // to tell the user that this mode cannot be disabled.  do
858             // we have any existing modes that would benefit by it?
859             return null;
860         if (new_state) {
861             if (mode_class && old_state != null)  {
862                 // Another buffer-mode of our same mode-class is
863                 // enabled.  Buffer-modes within a mode-class are
864                 // mutually exclusive, so turn the old one off.
865                 buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(old_state), 1);
866                 let x = mode_functions[old_state];
867                 let y = x.disable;
868                 if (y) y(buffer);
869                 conkeror[x.disable_hook_name].run(buffer);
870             }
871             buffer[state] = name;
872             if (enable)
873                 enable(buffer);
874             conkeror[enable_hook_name].run(buffer);
875             buffer.enabled_modes.push(name);
876         } else {
877             buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(name), 1);
878             disable(buffer);
879             conkeror[disable_hook_name].run(buffer);
880             buffer[state] = null;
881         }
882         if (change_hook_name)
883             conkeror[change_hook_name].run(buffer, buffer[state]);
884         buffer_mode_change_hook.run(buffer);
885         return new_state;
886     }
888     conkeror[name] = func;
889     interactive(hyphen_name, arguments.$doc, function (I) {
890         var arg = I.P;
891         var new_state = func(I.buffer, arg && univ_arg_to_number(arg));
892         I.minibuffer.message(hyphen_name + (new_state ? " enabled" : " disabled"));
893     });
895 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
898 function minibuffer_mode_indicator (window) {
899     this.window = window;
900     var element = create_XUL(window, "label");
901     element.setAttribute("id", "minibuffer-mode-indicator");
902     element.collapsed = true;
903     element.setAttribute("class", "minibuffer");
904     window.document.getElementById("minibuffer").appendChild(element);
905     this.element = element;
906     this.hook_func = method_caller(this, this.update);
907     add_hook.call(window, "select_buffer_hook", this.hook_func);
908     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_func);
909     this.update();
911 minibuffer_mode_indicator.prototype = {
912     constructor: minibuffer_mode_indicator,
913     update: function () {
914         var buf = this.window.buffers.current;
915         var modes = buf.enabled_modes;
916         var str = modes.map(
917             function (x) {
918                 let y = mode_display_names[x];
919                 if (y)
920                     return "[" + y + "]";
921                 else
922                     return null;
923             }).filter(function (x) x != null).join(" ");
924         this.element.collapsed = (str.length == 0);
925         this.element.value = str;
926     },
927     uninstall: function () {
928         remove_hook.call(window, "select_buffer_hook", this.hook_fun);
929         remove_hook.call(window, "current_buffer_mode_change_hook", this.hook_fun);
930         this.element.parentNode.removeChild(this.element);
931     }
933 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
934 minibuffer_mode_indicator_mode(true);
939  * INPUT MODES
940  */
941 define_current_buffer_hook("current_buffer_input_mode_change_hook", "input_mode_change_hook");
942 define_keywords("$display_name", "$doc");
943 function define_input_mode (base_name, keymap_name) {
944     keywords(arguments);
945     var name = base_name + "_input_mode";
946     define_buffer_mode(name,
947                        $class = "input_mode",
948                        $enable = function (buffer) {
949                            check_buffer(buffer, content_buffer);
950                            buffer.keymaps.push(conkeror[keymap_name]);
951                        },
952                        $disable = function (buffer) {
953                            var i = buffer.keymaps.indexOf(conkeror[keymap_name]);
954                            if (i > -1)
955                                buffer.keymaps.splice(i, 1);
956                        },
957                        forward_keywords(arguments));
959 ignore_function_for_get_caller_source_code_reference("define_input_mode");
962 function minibuffer_input_mode_indicator (window) {
963     this.window = window;
964     this.hook_func = method_caller(this, this.update);
965     add_hook.call(window, "select_buffer_hook", this.hook_func);
966     add_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
967     this.update();
969 minibuffer_input_mode_indicator.prototype = {
970     constructor: minibuffer_input_mode_indicator,
971     update: function () {
972         var buf = this.window.buffers.current;
973         var mode = buf.input_mode;
974         var classname = mode ? ("minibuffer-" + buf.input_mode.replace("_","-","g")) : "";
975         this.window.minibuffer.element.className = classname;
976     },
977     uninstall: function () {
978         remove_hook.call(window, "select_buffer_hook", this.hook_func);
979         remove_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
980     }
983 define_global_window_mode("minibuffer_input_mode_indicator", "window_initialize_hook");
984 minibuffer_input_mode_indicator_mode(true);
986 provide("buffer");