components, modules: change deprecated replace flag
[conkeror.git] / modules / buffer.js
blob83f3f41fe86bf6f4cf4a62ba69417e0f91424235
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2012 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 var define_buffer_local_hook = local_hook_definer("window");
12 function define_current_buffer_hook (hook_name, existing_hook) {
13     define_buffer_local_hook(hook_name);
14     add_hook(existing_hook, function (buffer) {
15             if (!buffer.window.buffers || buffer != buffer.window.buffers.current)
16                 return;
17             var hook = conkeror[hook_name];
18             hook.run.apply(hook, Array.prototype.slice.call(arguments));
19         });
22 define_buffer_local_hook("buffer_title_change_hook");
23 define_buffer_local_hook("buffer_description_change_hook");
24 define_buffer_local_hook("buffer_icon_change_hook");
25 define_buffer_local_hook("select_buffer_hook");
26 define_buffer_local_hook("create_buffer_early_hook");
27 define_buffer_local_hook("create_buffer_late_hook");
28 define_buffer_local_hook("create_buffer_hook");
29 define_buffer_local_hook("kill_buffer_hook");
30 define_buffer_local_hook("move_buffer_hook");
31 define_buffer_local_hook("buffer_scroll_hook");
32 define_buffer_local_hook("buffer_dom_content_loaded_hook");
33 define_buffer_local_hook("buffer_loaded_hook");
34 define_buffer_local_hook("set_input_mode_hook");
35 define_buffer_local_hook("zoom_hook");
37 define_current_buffer_hook("current_buffer_title_change_hook", "buffer_title_change_hook");
38 define_current_buffer_hook("current_buffer_description_change_hook", "buffer_description_change_hook");
39 define_current_buffer_hook("current_buffer_icon_change_hook", "buffer_icon_change_hook");
40 define_current_buffer_hook("current_buffer_scroll_hook", "buffer_scroll_hook");
41 define_current_buffer_hook("current_buffer_dom_content_loaded_hook", "buffer_dom_content_loaded_hook");
42 define_current_buffer_hook("current_buffer_zoom_hook", "zoom_hook");
45 function buffer_position_before (container, b, i) {
46     return i;
49 function buffer_position_after (container, b, i) {
50     return i + 1;
53 function buffer_position_end (container, b, i) {
54     return container.count;
57 function buffer_position_end_by_type (container, b, i) {
58     // after last buffer of same type
59     var count = container.count;
60     var p = count - 1;
61     while (p >= 0 &&
62            container.get_buffer(p).constructor != b.constructor)
63     {
64         p--;
65     }
66     if (p == -1)
67         return count;
68     else
69         return p + 1;
72 define_variable("new_buffer_position", buffer_position_end,
73     "Used to compute the position in the buffer-list at which "+
74     "to insert new buffers which do not have an opener.  These "+
75     "include buffers created by typing an url or webjump, or "+
76     "buffers created via command-line remoting.  The value "+
77     "should be a number giving the index or a function of three "+
78     "arguments that returns the index at which to insert the "+
79     "new buffer.  The first argument is the buffer_container "+
80     "into which the new buffer is being inserted.  The second "+
81     "argument is the buffer to be inserted.  The third argument "+
82     "is the position of the currently selected buffer.  Several "+
83     "such functions are provided, including, buffer_position_before, "+
84     "buffer_position_after, buffer_position_end, and "+
85     "buffer_position_end_by_type.");
87 define_variable("new_buffer_with_opener_position", buffer_position_after,
88     "Used to compute the position in the buffer-list at which "+
89     "to insert new buffers which have an opener in the same "+
90     "window.  These include buffers created by following a link "+
91     "or frame, and contextual help buffers.  The allowed values "+
92     "are the same as those for `new_buffer_position', except that "+
93     "the second argument passed to the function is the index of "+
94     "the opener instead of the index of the current buffer (often "+
95     "one and the same).");
97 define_variable("bury_buffer_position", null,
98     "Used to compute the position in the buffer-list to move a "+
99     "buried buffer to.  A value of null prevents bury-buffer "+
100     "from moving the buffer at all.  Other allowed values are "+
101     "the same as those for `new_buffer_position', except that "+
102     "the second argument passed to the function is the index of "+
103     "the new buffer that will be selected after burying the "+
104     "current buffer.");
106 define_variable("allow_browser_window_close", true,
107     "If this is set to true, if a content buffer page calls " +
108     "window.close() from JavaScript and is not prevented by the " +
109     "normal Mozilla mechanism that restricts pages from closing " +
110     "a window that was not opened by a script, the buffer will be " +
111     "killed, deleting the window as well if it is the only buffer.");
113 define_keywords("$opener", "$position");
114 function buffer_creator (type) {
115     var args = forward_keywords(arguments);
116     return function (window) {
117         return new type(window, args);
118     };
121 function buffer_modality (buffer) {
122     buffer.keymaps.push(default_global_keymap);
125 function buffer (window) {
126     this.constructor_begin();
127     keywords(arguments, $position = this.default_position);
128     this.opener = arguments.$opener;
129     this.window = window;
130     var element = create_XUL(window, "vbox");
131     element.setAttribute("flex", "1");
132     var browser = create_XUL(window, "browser");
133     browser.setAttribute("type", "content");
134     browser.setAttribute("flex", "1");
135     browser.setAttribute("autocompletepopup", "popup_autocomplete");
136     element.appendChild(browser);
137     this.window.buffers.container.appendChild(element);
138     this.window.buffers.insert(this, arguments.$position, this.opener);
139     this.window.buffers.buffer_history.push(this);
140     this.element = element;
141     this.browser = element.firstChild;
142     this.element.conkeror_buffer_object = this;
144     this.local = { __proto__: conkeror };
145     this.page = null;
146     this.enabled_modes = [];
147     this.default_browser_object_classes = {};
149     var buffer = this;
151     this.browser.addEventListener("scroll", function (event) {
152             buffer_scroll_hook.run(buffer);
153         }, true /* capture */);
155     this.browser.addEventListener("DOMContentLoaded", function (event) {
156             buffer_dom_content_loaded_hook.run(buffer);
157         }, true /* capture */);
159     this.window.setTimeout(function () { create_buffer_late_hook.run(buffer); }, 0);
161     this.browser.addEventListener("load", function (event) {
162             if (event.target == buffer.document)
163                 buffer_loaded_hook.run(buffer);
164         }, true /* capture */);
166     this.browser.addEventListener("DOMWindowClose", function (event) {
167             /* This call to preventDefault is very important; without
168              * it, somehow Mozilla does something bad and as a result
169              * the window loses focus, causing keyboard commands to
170              * stop working. */
171             event.preventDefault();
173             if (allow_browser_window_close)
174                 kill_buffer(buffer, true);
175         }, true);
177     this.browser.addEventListener("focus", function (event) {
178         if (buffer.focusblocker &&
179             event.target instanceof Ci.nsIDOMHTMLElement &&
180             buffer.focusblocker(buffer, event))
181         {
182             event.target.blur();
183         } else
184             buffer.set_input_mode();
185     }, true);
187     this.browser.addEventListener("blur", function (event) {
188         buffer.set_input_mode();
189     }, true);
191     this.modalities = [buffer_modality];
193     // When create_buffer_early_hook runs, basic buffer properties
194     // will be available, but not the properties subclasses.
195     create_buffer_early_hook.run(this);
197     this.constructor_end();
199 buffer.prototype = {
200     constructor: buffer,
201     toString: function () "#<buffer>",
203     // default_position is the default value for the $position keyword to
204     // the buffer constructor.  This property can be set on the prototype
205     // of a subclass in order to override new_buffer_position and
206     // new_buffer_with_opener_position for specific types of buffers.
207     default_position: null,
209     /* Saved focus state */
210     saved_focused_frame: null,
211     saved_focused_element: null,
213     clear_saved_focus: function () {
214         this.saved_focused_frame = null;
215         this.saved_focused_element = null;
216     },
218     // get title ()   [must be defined by subclasses]
219     // get name ()    [must be defined by subclasses]
220     dead: false, /* This is set when the buffer is killed */
222     keymaps: null,
223     mark_active: false,
225     // The property focusblocker is available for an external module to
226     // put a function on which takes a buffer as its argument and returns
227     // true to block a focus event, or false to let normal processing
228     // occur.  Having this one property explicitly handled by the buffer
229     // class allows for otherwise modular focus-blockers.
230     focusblocker: null,
232     // icon is a string url of an icon to use for this buffer.  Setting it
233     // causes buffer_icon_change_hook to be run.
234     _icon: null,
235     get icon () this._icon,
236     set icon (x) {
237         if (this._icon != x) {
238             this._icon = x;
239             buffer_icon_change_hook.run(this);
240         }
241     },
243     default_message: "",
245     set_default_message: function (str) {
246         this.default_message = str;
247         if (this == this.window.buffers.current)
248             this.window.minibuffer.set_default_message(str);
249     },
251     constructors_running: 0,
253     constructor_begin: function () {
254         this.constructors_running++;
255     },
257     constructor_end: function () {
258         if (--this.constructors_running == 0) {
259             create_buffer_hook.run(this);
260             this.set_input_mode();
261             delete this.opener;
262         }
263     },
265     destroy: function () {
266         this.dead = true;
267         this.browser = null;
268         this.element = null;
269         this.saved_focused_frame = null;
270         this.saved_focused_element = null;
271         // prevent modalities from accessing dead browser
272         this.modalities = [];
273     },
275     set_input_mode: function () {
276         if (this != this.window.buffers.current)
277             return;
278         this.keymaps = [];
279         this.modalities.map(function (m) m(this), this);
280         set_input_mode_hook.run(this);
281     },
283     override_keymaps: function (keymaps) {
284         if (keymaps) {
285             this.keymaps = keymaps;
286             this.set_input_mode = function () {
287                 set_input_mode_hook.run(this);
288             };
289         } else
290             delete this.set_input_mode;
291         this.set_input_mode();
292     },
294     /* Browser accessors */
295     get top_frame () { return this.browser.contentWindow; },
296     get document () { return this.browser.contentDocument; },
297     get web_navigation () { return this.browser.webNavigation; },
298     get doc_shell () { return this.browser.docShell; },
299     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
300     get current_uri () { return this.browser.currentURI; },
302     is_child_element: function (element) {
303         return (element && this.is_child_frame(element.ownerDocument.defaultView));
304     },
306     is_child_frame: function (frame) {
307         return (frame && frame.top == this.top_frame);
308     },
310     // This method is like focused_frame, except that if no content
311     // frame actually has focus, this returns null.
312     get focused_frame_or_null () {
313         var frame = this.window.document.commandDispatcher.focusedWindow;
314         if (this.is_child_frame(frame))
315             return frame;
316         return null;
317     },
319     get focused_frame () {
320         var frame = this.window.document.commandDispatcher.focusedWindow;
321         if (this.is_child_frame(frame))
322             return frame;
323         return this.top_frame;
324     },
326     get focused_element () {
327         var element = this.window.document.commandDispatcher.focusedElement;
328         if (this.is_child_element(element))
329             return element;
330         return null;
331     },
333     get focused_selection_controller () {
334         return this.focused_frame
335             .QueryInterface(Ci.nsIInterfaceRequestor)
336             .getInterface(Ci.nsIWebNavigation)
337             .QueryInterface(Ci.nsIInterfaceRequestor)
338             .getInterface(Ci.nsISelectionDisplay)
339             .QueryInterface(Ci.nsISelectionController);
340     },
342     do_command: function (command) {
343         function attempt_command (element, command) {
344             var controller;
345             if (element.controllers
346                 && (controller = element.controllers.getControllerForCommand(command)) != null
347                 && controller.isCommandEnabled(command))
348             {
349                 controller.doCommand(command);
350                 return true;
351             }
352             return false;
353         }
355         var element = this.focused_element;
356         if (element && attempt_command(element, command))
357             return;
358         var win = this.focused_frame;
359         while (true) {
360             if (attempt_command(win, command))
361                 return;
362             if (!win.parent || win == win.parent)
363                 break;
364             win = win.parent;
365         }
366     }
369 function with_current_buffer (buffer, callback) {
370     return callback(new interactive_context(buffer));
373 function check_buffer (obj, type) {
374     if (!(obj instanceof type))
375         throw interactive_error("Buffer has invalid type.");
376     if (obj.dead)
377         throw interactive_error("Buffer has already been killed.");
378     return obj;
381 function caret_enabled (buffer) {
382     return buffer.browser.getAttribute('showcaret');
385 function clear_selection (buffer) {
386     let sel_ctrl = buffer.focused_selection_controller;
387     if (sel_ctrl) {
388         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
389         if (caret_enabled(buffer)) {
390             if (sel.anchorNode)
391                 sel.collapseToStart();
392         } else {
393             sel.removeAllRanges();
394         }
395     }
399 function buffer_container (window, create_initial_buffer) {
400     this.window = window;
401     this.container = window.document.getElementById("buffer-container");
402     this.buffer_list = [];
403     this.buffer_history = [];
405     // Stores the current buffer object, because
406     // this.container.selectedPanel may be temporarily invalid while
407     // killing a buffer.  Use the `this.current' getter rather than
408     // accessing this property directly.
409     this.current_buffer_object = null;
411     window.buffers = this;
412     create_initial_buffer(window);
414 buffer_container.prototype = {
415     constructor: buffer_container,
416     toString: function () "#<buffer_container>",
418     insert: function (buffer, position, opener) {
419         var i = this.index_of(opener);
420         if (position == null) {
421             if (i == null)
422                 position = new_buffer_position;
423             else
424                 position = new_buffer_with_opener_position;
425         }
426         if (i == null)
427             i = this.selected_index || 0;
428         try {
429             if (position instanceof Function)
430                 var p = position(this, buffer, i);
431             else
432                 p = position;
433             this.buffer_list.splice(p, 0, buffer);
434         } catch (e) {
435             this.buffer_list.splice(0, 0, buffer);
436             dumpln("Error inserting buffer, inserted at 0.");
437             dump_error(e);
438         }
439     },
441     get current () {
442         if (this.current_buffer_object)
443             return this.current_buffer_object;
444         return this.container.selectedPanel.conkeror_buffer_object;
445     },
447     set current (buffer) {
448         var old_value = this.current;
449         if (old_value == buffer)
450             return;
452         this.buffer_history.splice(this.buffer_history.indexOf(buffer), 1);
453         this.buffer_history.unshift(buffer);
455         this._switch_away_from(this.current);
456         this._switch_to(buffer);
458         // Run hooks
459         select_buffer_hook.run(buffer);
460     },
462     // Ensure the focus state for the current buffer is updated
463     save_focus: function () {
464         // If minibuffer is active, the focus is already saved, so leave that focus state as is
465         if (this.window.minibuffer.active)
466             return;
468         var b = this.current;
469         b.saved_focused_frame = b.focused_frame;
470         b.saved_focused_element = b.focused_element;
471     },
473     // Restore the focus state for the current buffer, unless the minibuffer is still active
474     restore_focus: function () {
475         /**
476          * This next focus call seems to be needed to avoid focus
477          * somehow getting lost (and the keypress handler therefore
478          * not getting called at all) when killing buffers.
479          */
480         this.window.focus();
482         // If the minibuffer is active, keep the saved focus state but don't
483         // restore it until the minibuffer becomes inactive
484         if (this.window.minibuffer.active)
485             return;
487         var b = this.current;
489         b.browser.focus();
491         var saved_focused_element = b.saved_focused_element;
492         var saved_focused_frame = b.saved_focused_frame;
493         b.clear_saved_focus();
495         if (saved_focused_element) {
496             try {
497                 if (saved_focused_element.focus) {
498                     set_focus_no_scroll(this.window, saved_focused_element);
499                     return;
500                 }
501             } catch (e) { /* saved_focused_element may be dead */ }
502         }
504         if (saved_focused_frame) {
505             try {
506                 set_focus_no_scroll(this.window, saved_focused_frame);
507             } catch (e) { /* saved_focused_frame may be dead */ }
508         }
509     },
511     // Note: old_value is still the current buffer when this is called
512     _switch_away_from: function (old_value) {
513         this.save_focus();
515         if ('isActive' in old_value.browser.docShell)
516             old_value.browser.docShell.isActive = false;
517         old_value.browser.setAttribute("type", "content");
518     },
520     _switch_to: function (buffer) {
521         // Select new buffer in the XUL deck
522         this.current_buffer_object = buffer;
523         this.container.selectedPanel = buffer.element;
525         buffer.browser.setAttribute("type", "content-primary");
526         if ('isActive' in buffer.browser.docShell)
527             buffer.browser.docShell.isActive = true;
529         this.restore_focus();
531         buffer.set_input_mode();
533         this.window.minibuffer.set_default_message(buffer.default_message);
534     },
536     get count () {
537         return this.buffer_list.length;
538     },
540     get_buffer: function (index) {
541         if (index >= 0 && index < this.count)
542             return this.buffer_list[index]
543         return null;
544     },
546     get selected_index () {
547         var nodes = this.buffer_list;
548         var count = nodes.length;
549         for (var i = 0; i < count; ++i)
550             if (nodes[i] == this.container.selectedPanel.conkeror_buffer_object)
551                 return i;
552         return null;
553     },
555     index_of: function (b) {
556         var nodes = this.buffer_list;
557         var count = nodes.length;
558         for (var i = 0; i < count; ++i)
559             if (nodes[i] == b)
560                 return i;
561         return null;
562     },
564     get unique_name_list () {
565         var existing_names = {};
566         var bufs = [];
567         this.for_each(function(b) {
568                 var base_name = b.name;
569                 var name = base_name;
570                 var index = 1;
571                 while (existing_names[name]) {
572                     ++index;
573                     name = base_name + "<" + index + ">";
574                 }
575                 existing_names[name] = true;
576                 bufs.push([name, b]);
577             });
578         return bufs;
579     },
581     kill_buffer: function (b) {
582         if (b.dead)
583             return true;
584         var count = this.count;
585         if (count <= 1)
586             return false;
587         var new_buffer = this.buffer_history[0];
588         var changed = false;
589         if (b == new_buffer) {
590             new_buffer = this.buffer_history[1];
591             changed = true;
592         }
593         this._switch_away_from(this.current);
594         // The removeChild call below may trigger events in progress
595         // listeners.  This call to `destroy' gives buffer subclasses a
596         // chance to remove such listeners, so that they cannot try to
597         // perform UI actions based upon a xul:browser that no longer
598         // exists.
599         var element = b.element;
600         b.destroy();
602         // Switch to new buffer before destroying this buffer so that
603         // there always remains a selected buffer
604         this._switch_to(new_buffer);
606         // In Gecko >= 25, the selectedIndex property of the xul:deck
607         // remains the same even after removing a child, which means
608         // if the removed child has a lower index than that of the new
609         // current buffer, the correct child will no longer be
610         // selected.  In the worst case, selectedIndex will fall out
611         // of the valid range, resulting in no buffer being selected
612         // which breaks Conkeror.  As a workaround, we reassign the
613         // selectedPanel immediately after removing the child.
614         var new_element = this.current.element;
615         this.container.removeChild(element);
616         this.container.selectedPanel = new_element;
619         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
620         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
621         if (changed) {
622             select_buffer_hook.run(new_buffer);
623             this.buffer_history.splice(this.buffer_history.indexOf(new_buffer), 1);
624             this.buffer_history.unshift(new_buffer);
625         }
626         kill_buffer_hook.run(b);
627         return true;
628     },
630     bury_buffer: function (b) {
631         var new_buffer = this.buffer_history[0];
632         if (b == new_buffer)
633             new_buffer = this.buffer_history[1];
634         if (! new_buffer)
635             throw interactive_error("No other buffer");
636         if (bury_buffer_position != null) {
637             this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
638             this.insert(b, bury_buffer_position, new_buffer);
639         }
640         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
641         this.buffer_history.push(b);
642         this.current = new_buffer;
643         if (bury_buffer_position != null)
644             move_buffer_hook.run(b);
645         return true;
646     },
648     unbury_buffer: function (b) {
649         var c = this.current;
650         if (bury_buffer_position != null) {
651             this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
652             this.buffer_list.splice(this.buffer_list.indexOf(c), 0, b);
653         }
654         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
655         this.buffer_history.unshift(b);
656         this.current = b;
657         if (bury_buffer_position != null)
658             move_buffer_hook.run(b);
659         return true;
660     },
662     for_each: function (f) {
663         var count = this.count;
664         for (var i = 0; i < count; ++i)
665             f(this.get_buffer(i));
666     }
669 function buffer_initialize_window_early (window) {
670     /**
671      * Use content_buffer by default to handle an unusual case where
672      * browser.chromeURI is used perhaps.  In general this default
673      * should not be needed.
674      */
675     var create_initial_buffer =
676         window.args.initial_buffer_creator || buffer_creator(content_buffer);
677     new buffer_container(window, create_initial_buffer);
680 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
684  * initialize_first_buffer_type is a workaround for a XULRunner bug that
685  * first appeared in version 2.0, manifested as missing scrollbars in the
686  * first buffer of any window.  It only affects content-primary browsers,
687  * and the workaround is to initialize the browser as type "content" then
688  * change it to content-primary after a delay.
689  */
690 function initialize_first_buffer_type (window) {
691     window.buffers.current.browser.setAttribute("type", "content-primary");
694 add_hook("window_initialize_late_hook", initialize_first_buffer_type);
697 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
698 function buffer_before_window_close (window) {
699     var bs = window.buffers;
700     var count = bs.count;
701     for (let i = 0; i < count; ++i) {
702         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
703             return false;
704     }
705     return true;
707 add_hook("window_before_close_hook", buffer_before_window_close);
709 function buffer_window_close_handler (window) {
710     var bs = window.buffers;
711     var count = bs.count;
712     for (let i = 0; i < count; ++i) {
713         let b = bs.get_buffer(i);
714         b.destroy();
715     }
717 add_hook("window_close_hook", buffer_window_close_handler);
719 /* open/follow targets */
720 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
721                                // buffer is a content_buffer.
722 const OPEN_NEW_BUFFER = 1;
723 const OPEN_NEW_BUFFER_BACKGROUND = 2;
724 const OPEN_NEW_WINDOW = 3;
726 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
727 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
729 var TARGET_PROMPTS = [" in current buffer",
730                       " in new buffer",
731                       " in new buffer (background)",
732                       " in new window",
733                       "",
734                       " in current frame"];
736 var TARGET_NAMES = ["current buffer",
737                     "new buffer",
738                     "new buffer (background)",
739                     "new window",
740                     "default",
741                     "current frame"];
744 function create_buffer (window, creator, target) {
745     switch (target) {
746     case OPEN_NEW_BUFFER:
747         window.buffers.current = creator(window, null);
748         break;
749     case OPEN_NEW_BUFFER_BACKGROUND:
750         creator(window, null);
751         break;
752     case OPEN_NEW_WINDOW:
753         make_window(creator);
754         break;
755     default:
756         throw new Error("invalid target");
757     }
761     let queued_buffer_creators = null;
762     var create_buffer_in_current_window =
763         function create_buffer_in_current_window (creator, target, focus_existing) {
764             function process_queued_buffer_creators (window) {
765                 for (var i = 0; i < queued_buffer_creators.length; ++i) {
766                     var x = queued_buffer_creators[i];
767                     create_buffer(window, x[0], x[1]);
768                 }
769                 queued_buffer_creators = null;
770             }
772             if (target == OPEN_NEW_WINDOW)
773                 throw new Error("invalid target");
774             var window = get_recent_conkeror_window();
775             if (window) {
776                 if (focus_existing)
777                     window.focus();
778                 create_buffer(window, creator, target);
779             } else if (queued_buffer_creators != null) {
780                 queued_buffer_creators.push([creator,target]);
781             } else {
782                 queued_buffer_creators = [];
783                 window = make_window(creator);
784                 add_hook.call(window, "window_initialize_late_hook",
785                               process_queued_buffer_creators);
786             }
787         }
792  * Read Buffer
793  */
794 define_variable("read_buffer_show_icons", false,
795     "Boolean which says whether read_buffer should show buffer "+
796     "icons in the completions list.\nNote, setting this variable "+
797     "alone does not cause favicons or other kinds of icons to be "+
798     "fetched.  For that, load the `favicon' (or similar other) "+
799     "library.");
801 minibuffer_auto_complete_preferences["buffer"] = true;
802 define_keywords("$buffers", "$default");
803 minibuffer.prototype.read_buffer = function () {
804     var window = this.window;
805     keywords(arguments, $prompt = "Buffer:",
806              $buffers = function (visitor) window.buffers.for_each(visitor),
807              $default = window.buffers.current,
808              $history = "buffer");
809     var completer = new all_word_completer(
810         $completions = arguments.$buffers,
811         $get_string = function (x) x.description,
812         $get_description = function (x) x.title,
813         $get_icon = (read_buffer_show_icons ?
814                      function (x) x.icon : null));
815     var result = yield this.read(
816         $keymap = read_buffer_keymap,
817         $prompt = arguments.$prompt,
818         $history = arguments.$history,
819         $completer = completer,
820         $enable_icons = read_buffer_show_icons,
821         $require_match = true,
822         $auto_complete = "buffer",
823         $auto_complete_initial = true,
824         $auto_complete_delay = 0,
825         $default_completion = arguments.$default);
826     yield co_return(result);
830 function buffer_move_forward (window, count) {
831     var buffers = window.buffers;
832     var index = buffers.selected_index;
833     var buffer = buffers.current
834     var total = buffers.count;
835     if (total == 1)
836         return;
837     var new_index = (index + count) % total;
838     if (new_index == index)
839         return;
840     if (new_index < 0)
841         new_index += total;
842     buffers.buffer_list.splice(index, 1);
843     buffers.buffer_list.splice(new_index, 0, buffer);
844     move_buffer_hook.run(buffer);
846 interactive("buffer-move-forward",
847     "Move the current buffer forward in the buffer order.",
848     function (I) { buffer_move_forward(I.window, I.p); });
850 interactive("buffer-move-backward",
851     "Move the current buffer backward in the buffer order.",
852     function (I) { buffer_move_forward(I.window, -I.p); });
855 function buffer_next (window, count) {
856     var index = window.buffers.selected_index;
857     var total = window.buffers.count;
858     if (total == 1)
859         throw new interactive_error("No other buffer");
860     index = (index + count) % total;
861     if (index < 0)
862         index += total;
863     window.buffers.current = window.buffers.get_buffer(index);
865 interactive("buffer-next",
866     "Switch to the next buffer.",
867     function (I) { buffer_next(I.window, I.p); });
868 interactive("buffer-previous",
869     "Switch to the previous buffer.",
870     function (I) { buffer_next(I.window, -I.p); });
872 function switch_to_buffer (window, buffer) {
873     if (buffer && !buffer.dead)
874         window.buffers.current = buffer;
876 interactive("switch-to-buffer",
877     "Prompt for a buffer and switch to it.",
878     function (I) {
879         switch_to_buffer(
880             I.window,
881             (yield I.minibuffer.read_buffer(
882                 $prompt = "Switch to buffer:",
883                 $default = (I.window.buffers.count > 1 ?
884                             I.window.buffers.buffer_history[1] :
885                             I.buffer))));
886     });
888 define_variable("can_kill_last_buffer", true,
889     "When true, kill-buffer can kill the last  buffer in a window, "+
890     "and close the window.");
892 function kill_other_buffers (buffer) {
893     if (!buffer)
894         return;
895     var bs = buffer.window.buffers;
896     var b;
897     while ((b = bs.get_buffer(0)) != buffer)
898         bs.kill_buffer(b);
899     var count = bs.count;
900     while (--count)
901         bs.kill_buffer(bs.get_buffer(1));
903 interactive("kill-other-buffers",
904     "Kill all buffers except current one.\n",
905     function (I) { kill_other_buffers(I.buffer); });
908 function kill_buffer (buffer, force) {
909     if (!buffer)
910         return;
911     var buffers = buffer.window.buffers;
912     if (buffers.count == 1 && buffer == buffers.current) {
913         if (can_kill_last_buffer || force) {
914             delete_window(buffer.window);
915             return;
916         } else
917             throw interactive_error("Can't kill last buffer.");
918     }
919     buffers.kill_buffer(buffer);
921 interactive("kill-buffer",
922     "Kill a buffer specified in the minibuffer.\n" +
923     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
924     "last remaining buffer in a window will cause the window to be closed.",
925     function (I) {
926         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
927     });
929 interactive("kill-current-buffer",
930     "Kill the current buffer.\n" +
931     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
932     "last remaining buffer in a window will cause the window to be closed.",
933     function (I) { kill_buffer(I.buffer); });
935 interactive("read-buffer-kill-buffer",
936     "Kill the current selected buffer in the completions list "+
937     "in a read buffer minibuffer interaction.",
938     function (I) {
939         var s = I.window.minibuffer.current_state;
940         var i = s.selected_completion_index;
941         var c = s.completions;
942         if (i == -1)
943             return;
944         kill_buffer(c.get_value(i));
945         s.completer.refresh();
946         s.handle_input(I.window.minibuffer);
947     });
949 interactive("bury-buffer",
950     "Bury the current buffer.\nPut the current buffer at the end of " +
951     "the buffer list, so that it is the least likely buffer to be " +
952     "selected by `switch-to-buffer'.",
953     function (I) { I.window.buffers.bury_buffer(I.buffer); });
955 interactive("unbury-buffer",
956     "Unbury the buffer lowest in the buffer-history list.\n"+
957     "With universal argument, prompt for a buffer.  When "+
958     "`bury_buffer_position` is non-null, move the buffer "+
959     "to the current position in the buffer list.",
960     function (I) {
961         var buffers = I.window.buffers;
962         if (I.prefix_argument)
963             var b = yield I.minibuffer.read_buffer(
964                 $prompt = "Switch to buffer:",
965                 $buffers = function (visitor) {
966                     var count = buffers.count;
967                     for (var i = count - 1; i >= 0; --i)
968                         visitor(buffers.buffer_history[i]);
969                 },
970                 $default = buffers.buffer_history[buffers.count - 1]);
971         else
972             b = buffers.buffer_history[buffers.count - 1];
973         buffers.unbury_buffer(b);
974     });
976 function change_directory (buffer, dir) {
977     if (buffer.page != null)
978         delete buffer.page.local.cwd;
979     buffer.local.cwd = make_file(dir);
981 interactive("change-directory",
982     "Change the current directory of the selected buffer.",
983     function (I) {
984         change_directory(
985             I.buffer,
986             (yield I.minibuffer.read_existing_directory_path(
987                 $prompt = "Change to directory:",
988                 $initial_value = make_file(I.local.cwd).path)));
989     });
991 interactive("shell-command", null,
992     function (I) {
993         var cwd = I.local.cwd;
994         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
995         yield shell_command(cmd, $cwd = cwd);
996     });
1000  * selection_is_embed_p is used to test whether the unfocus command can
1001  * unfocus an element, even though there is a selection.  This happens
1002  * when the focused element is an html:embed.
1003  */
1004 function selection_is_embed_p (sel, focused_element) {
1005     if (sel.rangeCount == 1) {
1006         try {
1007             var r = sel.getRangeAt(0);
1008             var a = r.startContainer.childNodes[r.startOffset];
1009             if ((a instanceof Ci.nsIDOMHTMLEmbedElement ||
1010                  a instanceof Ci.nsIDOMHTMLObjectElement) &&
1011                 a == focused_element)
1012             {
1013                 return true;
1014             }
1015         } catch (e) {}
1016     }
1017     return false;
1021  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
1022  * frames, iframes, plugins, and also clearing the selection.
1023  */
1024 define_buffer_local_hook("unfocus_hook");
1025 function unfocus (window, buffer) {
1026     // 1. if there is a selection, clear it.
1027     var selc = buffer.focused_selection_controller;
1028     if (selc) {
1029         var sel = selc.getSelection(selc.SELECTION_NORMAL);
1030         var active = ! sel.isCollapsed;
1031         var embed_p = selection_is_embed_p(sel, buffer.focused_element);
1032         clear_selection(buffer);
1033         if (active && !embed_p) {
1034             window.minibuffer.message("cleared selection");
1035             return;
1036         }
1037     }
1038     // 2. if there is a focused element, unfocus it.
1039     if (buffer.focused_element) {
1040         buffer.focused_element.blur();
1041         // if an element in a detached fragment has focus, blur() will
1042         // not work, and we need to take more drastic measures.  the
1043         // action taken was found through experiment, so it is possibly
1044         // not the most concise way to unfocus such an element.
1045         if (buffer.focused_element) {
1046             buffer.element.focus();
1047             buffer.top_frame.focus();
1048         }
1049         window.minibuffer.message("unfocused element");
1050         return;
1051     }
1052     // 3. if an iframe has focus, we must blur it.
1053     if (buffer.focused_frame_or_null &&
1054         buffer.focused_frame_or_null.frameElement)
1055     {
1056         buffer.focused_frame_or_null.frameElement.blur();
1057     }
1058     // 4. return focus to top-frame from subframes and plugins.
1059     buffer.top_frame.focus();
1060     buffer.top_frame.focus(); // needed to get focus back from plugins
1061     window.minibuffer.message("refocused top frame");
1062     // give page-modes an opportunity to set focus specially
1063     unfocus_hook.run(buffer);
1065 interactive("unfocus",
1066     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
1067     "frames, iframes, plugins, and also for clearing the selection.\n"+
1068     "The action that it takes is based on precedence.  If there is a "+
1069     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
1070     "there is a selection, it will clear the selection.  Otherwise, it "+
1071     "will return focus to the top frame from a focused frame, iframe, "+
1072     "or plugin.  In the case of plugins, since they steal keyboard "+
1073     "control away from Conkeror, the normal way to unfocus them is "+
1074     "to use command-line remoting externally: conkeror -batch -f "+
1075     "unfocus.  Page-modes also have an opportunity to alter the default"+
1076     "focus via the hook, `focus_hook'.",
1077     function (I) {
1078         unfocus(I.window, I.buffer);
1079     });
1082 function for_each_buffer (f) {
1083     for_each_window(function (w) { w.buffers.for_each(f); });
1088  * Buffer Modes
1089  */
1091 define_buffer_local_hook("buffer_mode_change_hook");
1092 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
1094 define_keywords("$display_name", "$doc");
1095 function buffer_mode (name, enable, disable) {
1096     keywords(arguments);
1097     this.hyphen_name = name;
1098     this.name = name.replace(/-/g, "_");
1099     if (enable) {
1100         this._enable = enable;
1101     }
1102     if (disable) {
1103         this._disable = disable;
1104     }
1105     this.display_name = arguments.$display_name;
1106     this.doc = arguments.$doc;
1107     this.enable_hook = this.name + "_enable_hook";
1108     this.disable_hook = this.name + "_disable_hook";
1110 buffer_mode.prototype = {
1111     constructor: buffer_mode,
1112     name: null,
1113     display_name: null,
1114     doc: null,
1115     enable_hook: null,
1116     disable_hook: null,
1117     _enable: null,
1118     _disable: null,
1119     enable: function (buffer) {
1120         try {
1121             if (this._enable)
1122                 this._enable(buffer);
1123         } finally {
1124             buffer.enabled_modes.push(this.name);
1125             if (conkeror[this.enable_hook])
1126                 conkeror[this.enable_hook].run(buffer);
1127             buffer_mode_change_hook.run(buffer);
1128         }
1129     },
1130     disable: function (buffer) {
1131         try {
1132             if (this._disable)
1133                 this._disable(buffer);
1134         } finally {
1135             var i = buffer.enabled_modes.indexOf(this.name);
1136             if (i > -1)
1137                 buffer.enabled_modes.splice(i, 1);
1138             if (conkeror[this.disable_hook])
1139                 conkeror[this.disable_hook].run(buffer);
1140             buffer_mode_change_hook.run(buffer);
1141         }
1142     }
1144 define_keywords("$constructor");
1145 function define_buffer_mode (name, enable, disable) {
1146     keywords(arguments, $constructor = buffer_mode, $doc = null);
1147     var constructor = arguments.$constructor;
1148     var m = new constructor(name, enable, disable, forward_keywords(arguments));
1149     name = m.name; // normalized
1150     conkeror[name] = m;
1151     define_buffer_local_hook(m.enable_hook);
1152     define_buffer_local_hook(m.disable_hook);
1153     interactive(m.hyphen_name,
1154         arguments.$doc,
1155         function (I) {
1156             var enabledp = (I.buffer.enabled_modes.indexOf(name) > -1);
1157             if (enabledp)
1158                 m.disable(I.buffer);
1159             else
1160                 m.enable(I.buffer);
1161             I.minibuffer.message(m.hyphen_name + (enabledp ? " disabled" : " enabled"));
1162         });
1164 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
1168  * Mode Display in Minibuffer
1169  */
1171 function minibuffer_mode_indicator (window) {
1172     this.window = window;
1173     var element = create_XUL(window, "label");
1174     element.setAttribute("id", "minibuffer-mode-indicator");
1175     element.setAttribute("class", "mode-text-widget");
1176     window.document.getElementById("minibuffer").appendChild(element);
1177     this.element = element;
1178     this.hook_function = method_caller(this, this.update);
1179     add_hook.call(window, "select_buffer_hook", this.hook_function);
1180     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_function);
1181     this.update();
1183 minibuffer_mode_indicator.prototype = {
1184     constructor: minibuffer_mode_indicator,
1185     window: null,
1186     element: null,
1187     hook_function: null,
1188     update: function () {
1189         var buffer = this.window.buffers.current;
1190         var str = buffer.enabled_modes.map(
1191             function (x) {
1192                 return (conkeror[x].display_name || null);
1193             }).filter(function (x) x != null).join(" ");
1194         this.element.value = str;
1195     },
1196     uninstall: function () {
1197         remove_hook.call(this.window, "select_buffer_hook", this.hook_function);
1198         remove_hook.call(this.window, "current_buffer_mode_change_hook", this.hook_function);
1199         this.element.parentNode.removeChild(this.element);
1200     }
1202 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
1203 minibuffer_mode_indicator_mode(true);
1207  * minibuffer-keymaps-display
1208  */
1209 function minibuffer_keymaps_display_update (buffer) {
1210     var element = buffer.window.document
1211         .getElementById("keymaps-display");
1212     if (element) {
1213         var str = buffer.keymaps.reduce(
1214             function (acc, kmap) {
1215                 if (kmap.display_name)
1216                     acc.push(kmap.display_name);
1217                 return acc;
1218             }, []).join("/");
1219         if (element.value != str)
1220             element.value = str;
1221     }
1224 function minibuffer_keymaps_display_initialize (window) {
1225     var element = create_XUL(window, "label");
1226     element.setAttribute("id", "keymaps-display");
1227     element.setAttribute("class", "mode-text-widget");
1228     element.setAttribute("value", "");
1229     var mb = window.document.getElementById("minibuffer");
1230     mb.appendChild(element);
1233 define_global_mode("minibuffer_keymaps_display_mode",
1234     function enable () {
1235         add_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1236         add_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1237         for_each_window(minibuffer_keymaps_display_initialize);
1238     },
1239     function disable () {
1240         remove_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1241         remove_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1242         for_each_window(function (w) {
1243             var element = w.document
1244                 .getElementById("keymaps-display");
1245             if (element)
1246                 element.parentNode.removeChild(element);
1247         });
1248     });
1250 minibuffer_keymaps_display_mode(true);
1254  * minibuffer-keymaps-highlight
1255  */
1256 function minibuffer_keymaps_highlight_update (buffer) {
1257     var mb = buffer.window.document.getElementById("minibuffer");
1258     if (buffer.keymaps.some(function (k) k.notify))
1259         dom_add_class(mb, "highlight");
1260     else
1261         dom_remove_class(mb, "highlight");
1264 define_global_mode("minibuffer_keymaps_highlight_mode",
1265     function enable () {
1266         add_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1267     },
1268     function disable () {
1269         remove_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1270         for_each_window(function (w) {
1271             var mb = w.document.getElementById("minibuffer");
1272             if (mb)
1273                 dom_remove_class("highlight");
1274         });
1275     });
1277 minibuffer_keymaps_highlight_mode(true);
1280 provide("buffer");