point-per-window design started
[conkeror.git] / modules / buffer.js
blobad409b0b313366822ab0c8afe5a090f4be683c94
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 point_state () {
123 point_state.prototype = {
124     constructor: point_state,
125     toString: function () "#<point_state>",
126     top: 0,
127     left: 0,
128     width: 30,
129     height: 30
132 function buffer_modality (buffer) {
133     buffer.keymaps.push(default_global_keymap);
136 function buffer (window) {
137     this.constructor_begin();
138     keywords(arguments, $position = this.default_position);
139     this.opener = arguments.$opener;
140     this.window = window;
141     var element = create_XUL(window, "vbox");
142     element.setAttribute("flex", "1");
143     var browser = create_XUL(window, "browser");
144     browser.setAttribute("type", "content");
145     browser.setAttribute("flex", "1");
146     browser.setAttribute("autocompletepopup", "popup_autocomplete");
147     element.appendChild(browser);
148     this.window.buffers.container.appendChild(element);
149     this.window.buffers.insert(this, arguments.$position, this.opener);
150     this.window.buffers.buffer_history.push(this);
151     this.element = element;
152     this.browser = element.firstChild;
153     this.element.conkeror_buffer_object = this;
155     this.local = { __proto__: conkeror };
156     this.page = null;
157     this.enabled_modes = [];
158     this.default_browser_object_classes = {};
160     var buffer = this;
162     this.browser.addEventListener("scroll", function (event) {
163             buffer_scroll_hook.run(buffer);
164         }, true /* capture */);
166     this.browser.addEventListener("DOMContentLoaded", function (event) {
167             buffer_dom_content_loaded_hook.run(buffer);
168         }, true /* capture */);
170     this.window.setTimeout(function () { create_buffer_late_hook.run(buffer); }, 0);
172     this.browser.addEventListener("load", function (event) {
173             if (event.target == buffer.document)
174                 buffer_loaded_hook.run(buffer);
175         }, true /* capture */);
177     this.browser.addEventListener("DOMWindowClose", function (event) {
178             /* This call to preventDefault is very important; without
179              * it, somehow Mozilla does something bad and as a result
180              * the window loses focus, causing keyboard commands to
181              * stop working. */
182             event.preventDefault();
184             if (allow_browser_window_close)
185                 kill_buffer(buffer, true);
186         }, true);
188     this.browser.addEventListener("focus", function (event) {
189         if (buffer.focusblocker &&
190             event.target instanceof Ci.nsIDOMHTMLElement &&
191             buffer.focusblocker(buffer, event))
192         {
193             event.target.blur();
194         } else
195             buffer.set_input_mode();
196     }, true);
198     this.browser.addEventListener("blur", function (event) {
199         buffer.set_input_mode();
200     }, true);
202     // point init
203     //
204     this.web_navigation.sessionHistory.addSHistoryListener(this);
205     this.point_history = [];
206     this.point_history.index = -1;
208     this.modalities = [buffer_modality];
210     // When create_buffer_early_hook runs, basic buffer properties
211     // will be available, but not the properties subclasses.
212     create_buffer_early_hook.run(this);
214     this.constructor_end();
216 buffer.prototype = {
217     constructor: buffer,
218     toString: function () "#<buffer>",
219     QueryInterface: generate_QI(Ci.nsISHistoryListener, Ci.nsISupportsWeakReference),
221     // default_position is the default value for the $position keyword to
222     // the buffer constructor.  This property can be set on the prototype
223     // of a subclass in order to override new_buffer_position and
224     // new_buffer_with_opener_position for specific types of buffers.
225     default_position: null,
227     /* Saved focus state */
228     saved_focused_frame: null,
229     saved_focused_element: null,
231     // get title ()   [must be defined by subclasses]
232     // get name ()    [must be defined by subclasses]
233     dead: false, /* This is set when the buffer is killed */
235     keymaps: null,
236     mark_active: false,
238     // The property focusblocker is available for an external module to
239     // put a function on which takes a buffer as its argument and returns
240     // true to block a focus event, or false to let normal processing
241     // occur.  Having this one property explicitly handled by the buffer
242     // class allows for otherwise modular focus-blockers.
243     focusblocker: null,
245     // icon is a string url of an icon to use for this buffer.  Setting it
246     // causes buffer_icon_change_hook to be run.
247     _icon: null,
248     get icon () this._icon,
249     set icon (x) {
250         if (this._icon != x) {
251             this._icon = x;
252             buffer_icon_change_hook.run(this);
253         }
254     },
256     default_message: "",
258     set_default_message: function (str) {
259         this.default_message = str;
260         if (this == this.window.buffers.current)
261             this.window.minibuffer.set_default_message(str);
262     },
264     constructors_running: 0,
266     constructor_begin: function () {
267         this.constructors_running++;
268     },
270     constructor_end: function () {
271         if (--this.constructors_running == 0) {
272             create_buffer_hook.run(this);
273             this.set_input_mode();
274             delete this.opener;
275         }
276     },
278     destroy: function () {
279         this.dead = true;
280         this.web_navigation.sessionHistory.removeSHistoryListener(this);
281         this.point_history = null;
282         this.browser = null;
283         this.element = null;
284         this.saved_focused_frame = null;
285         this.saved_focused_element = null;
286         // prevent modalities from accessing dead browser
287         this.modalities = [];
288     },
290     set_input_mode: function () {
291         if (this != this.window.buffers.current)
292             return;
293         this.keymaps = [];
294         this.modalities.map(function (m) m(this), this);
295         set_input_mode_hook.run(this);
296     },
298     override_keymaps: function (keymaps) {
299         if (keymaps) {
300             this.keymaps = keymaps;
301             this.set_input_mode = function () {
302                 set_input_mode_hook.run(this);
303             };
304         } else
305             delete this.set_input_mode;
306         this.set_input_mode();
307     },
309     /* Browser accessors */
310     get top_frame () { return this.browser.contentWindow; },
311     get document () { return this.browser.contentDocument; },
312     get web_navigation () { return this.browser.webNavigation; },
313     get doc_shell () { return this.browser.docShell; },
314     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
315     get current_uri () { return this.browser.currentURI; },
317     is_child_element: function (element) {
318         return (element && this.is_child_frame(element.ownerDocument.defaultView));
319     },
321     is_child_frame: function (frame) {
322         return (frame && frame.top == this.top_frame);
323     },
325     // This method is like focused_frame, except that if no content
326     // frame actually has focus, this returns null.
327     get focused_frame_or_null () {
328         var frame = this.window.document.commandDispatcher.focusedWindow;
329         if (this.is_child_frame(frame))
330             return frame;
331         return null;
332     },
334     get focused_frame () {
335         var frame = this.window.document.commandDispatcher.focusedWindow;
336         if (this.is_child_frame(frame))
337             return frame;
338         return this.top_frame;
339     },
341     get focused_element () {
342         var element = this.window.document.commandDispatcher.focusedElement;
343         if (this.is_child_element(element))
344             return element;
345         return null;
346     },
348     get focused_selection_controller () {
349         return this.focused_frame
350             .QueryInterface(Ci.nsIInterfaceRequestor)
351             .getInterface(Ci.nsIWebNavigation)
352             .QueryInterface(Ci.nsIInterfaceRequestor)
353             .getInterface(Ci.nsISelectionDisplay)
354             .QueryInterface(Ci.nsISelectionController);
355     },
357     do_command: function (command) {
358         function attempt_command (element, command) {
359             var controller;
360             if (element.controllers
361                 && (controller = element.controllers.getControllerForCommand(command)) != null
362                 && controller.isCommandEnabled(command))
363             {
364                 controller.doCommand(command);
365                 return true;
366             }
367             return false;
368         }
370         var element = this.focused_element;
371         if (element && attempt_command(element, command))
372             return;
373         var win = this.focused_frame;
374         while (true) {
375             if (attempt_command(win, command))
376                 return;
377             if (!win.parent || win == win.parent)
378                 break;
379             win = win.parent;
380         }
381     },
383     // nsISHistoryListener interface
384     //
385     point_history: null,
386     get point () this.point_history[this.point_history.index] || null,
387     point_update: function () {
388         var p = this.point_history[this.point_history.index];
389         this.window.point.setAttribute("top", p.top);
390         this.window.point.setAttribute("left", p.left);
391         this.window.point.style.width = p.width + "px";
392         this.window.point.style.height = p.height + "px";
393     },
394     OnHistoryNewEntry: function (uri) {
395         dumpln("point_history_listener OnHistoryNewEntry");
396         this.point_history.push(new point_state());
397         this.point_history.index++;
398         this.point_update();
399     },
400     OnHistoryGoBack: function (uri) {
401         dumpln("point_history_listener OnHistoryGoBack");
402         this.point_history.index--;
403         this.point_update();
404         return true;
405     },
406     OnHistoryGoForward: function (uri) {
407         dumpln("point_history_listener OnHistoryGoForward");
408         this.point_history.index++;
409         this.point_update();
410         return true;
411     },
412     OnHistoryReload: function (uri, reload_flags) {
413         dumpln("point_history_listener OnHistoryReload");
414         // perhaps save the xpath of any currently selected node so that
415         // we can attempt to reselect the same node after reload.
416         return true;
417     },
418     OnHistoryGotoIndex: function (index, uri) {
419         dumpln("point_history_listener OnHistoryGotoIndex");
420         this.point_history.index = index;
421         this.point_update();
422         return true;
423     },
424     OnHistoryPurge: function (num_entries) {
425         dumpln("point_history_listener OnHistoryPurge");
426         this.point_history.splice(0, num_entries);
427         this.point_history.index -= num_entries;
428         return true;
429     }
432 function with_current_buffer (buffer, callback) {
433     return callback(new interactive_context(buffer));
436 function check_buffer (obj, type) {
437     if (!(obj instanceof type))
438         throw interactive_error("Buffer has invalid type.");
439     if (obj.dead)
440         throw interactive_error("Buffer has already been killed.");
441     return obj;
444 function caret_enabled (buffer) {
445     return buffer.browser.getAttribute('showcaret');
448 function clear_selection (buffer) {
449     let sel_ctrl = buffer.focused_selection_controller;
450     if (sel_ctrl) {
451         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
452         if (caret_enabled(buffer)) {
453             if (sel.anchorNode)
454                 sel.collapseToStart();
455         } else {
456             sel.removeAllRanges();
457         }
458     }
462 function buffer_container (window, create_initial_buffer) {
463     this.window = window;
464     this.container = window.document.getElementById("buffer-container");
465     this.buffer_list = [];
466     this.buffer_history = [];
467     window.buffers = this;
468     create_initial_buffer(window);
470 buffer_container.prototype = {
471     constructor: buffer_container,
472     toString: function () "#<buffer_container>",
474     insert: function (buffer, position, opener) {
475         var i = this.index_of(opener);
476         if (position == null) {
477             if (i == null)
478                 position = new_buffer_position;
479             else
480                 position = new_buffer_with_opener_position;
481         }
482         if (i == null)
483             i = this.selected_index || 0;
484         try {
485             if (position instanceof Function)
486                 var p = position(this, buffer, i);
487             else
488                 p = position;
489             this.buffer_list.splice(p, 0, buffer);
490         } catch (e) {
491             this.buffer_list.splice(0, 0, buffer);
492             dumpln("Error inserting buffer, inserted at 0.");
493             dump_error(e);
494         }
495     },
497     get current () {
498         return this.container.selectedPanel.conkeror_buffer_object;
499     },
501     set current (buffer) {
502         var old_value = this.current;
503         if (old_value == buffer)
504             return;
506         this.buffer_history.splice(this.buffer_history.indexOf(buffer), 1);
507         this.buffer_history.unshift(buffer);
509         this._switch_away_from(this.current);
510         this._switch_to(buffer);
512         // Run hooks
513         select_buffer_hook.run(buffer);
514     },
516     _switch_away_from: function (old_value) {
517         // Save focus state
518         old_value.saved_focused_frame = old_value.focused_frame;
519         old_value.saved_focused_element = old_value.focused_element;
521         if ('isActive' in old_value.browser.docShell)
522             old_value.browser.docShell.isActive = false;
523         old_value.browser.setAttribute("type", "content");
524     },
526     _switch_to: function (buffer) {
527         // Select new buffer in the XUL deck
528         this.container.selectedPanel = buffer.element;
530         buffer.browser.setAttribute("type", "content-primary");
531         if ('isActive' in buffer.browser.docShell)
532             buffer.browser.docShell.isActive = true;
534         /**
535          * This next focus call seems to be needed to avoid focus
536          * somehow getting lost (and the keypress handler therefore
537          * not getting called at all) when killing buffers.
538          */
539         this.window.focus();
541         // Restore focus state
542         buffer.browser.focus();
543         if (buffer.saved_focused_element)
544             set_focus_no_scroll(this.window, buffer.saved_focused_element);
545         else if (buffer.saved_focused_frame)
546             set_focus_no_scroll(this.window, buffer.saved_focused_frame);
548         buffer.saved_focused_element = null;
549         buffer.saved_focused_frame = null;
551         if (buffer.point)
552             buffer.point_update();
554         buffer.set_input_mode();
556         this.window.minibuffer.set_default_message(buffer.default_message);
557     },
559     get count () {
560         return this.buffer_list.length;
561     },
563     get_buffer: function (index) {
564         if (index >= 0 && index < this.count)
565             return this.buffer_list[index]
566         return null;
567     },
569     get selected_index () {
570         var nodes = this.buffer_list;
571         var count = nodes.length;
572         for (var i = 0; i < count; ++i)
573             if (nodes[i] == this.container.selectedPanel.conkeror_buffer_object)
574                 return i;
575         return null;
576     },
578     index_of: function (b) {
579         var nodes = this.buffer_list;
580         var count = nodes.length;
581         for (var i = 0; i < count; ++i)
582             if (nodes[i] == b)
583                 return i;
584         return null;
585     },
587     get unique_name_list () {
588         var existing_names = {};
589         var bufs = [];
590         this.for_each(function(b) {
591                 var base_name = b.name;
592                 var name = base_name;
593                 var index = 1;
594                 while (existing_names[name]) {
595                     ++index;
596                     name = base_name + "<" + index + ">";
597                 }
598                 existing_names[name] = true;
599                 bufs.push([name, b]);
600             });
601         return bufs;
602     },
604     kill_buffer: function (b) {
605         if (b.dead)
606             return true;
607         var count = this.count;
608         if (count <= 1)
609             return false;
610         var new_buffer = this.buffer_history[0];
611         var changed = false;
612         if (b == new_buffer) {
613             new_buffer = this.buffer_history[1];
614             changed = true;
615         }
616         this._switch_away_from(this.current);
617         // The removeChild call below may trigger events in progress
618         // listeners.  This call to `destroy' gives buffer subclasses a
619         // chance to remove such listeners, so that they cannot try to
620         // perform UI actions based upon a xul:browser that no longer
621         // exists.
622         var element = b.element;
623         b.destroy();
624         this.container.removeChild(element);
625         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
626         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
627         this._switch_to(new_buffer);
628         if (changed) {
629             select_buffer_hook.run(new_buffer);
630             this.buffer_history.splice(this.buffer_history.indexOf(new_buffer), 1);
631             this.buffer_history.unshift(new_buffer);
632         }
633         kill_buffer_hook.run(b);
634         return true;
635     },
637     bury_buffer: function (b) {
638         var new_buffer = this.buffer_history[0];
639         if (b == new_buffer)
640             new_buffer = this.buffer_history[1];
641         if (! new_buffer)
642             throw interactive_error("No other buffer");
643         if (bury_buffer_position != null) {
644             this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
645             this.insert(b, bury_buffer_position, new_buffer);
646         }
647         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
648         this.buffer_history.push(b);
649         this.current = new_buffer;
650         if (bury_buffer_position != null)
651             move_buffer_hook.run(b);
652         return true;
653     },
655     unbury_buffer: function (b) {
656         var c = this.current;
657         if (bury_buffer_position != null) {
658             this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
659             this.buffer_list.splice(this.buffer_list.indexOf(c), 0, b);
660         }
661         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
662         this.buffer_history.unshift(b);
663         this.current = b;
664         if (bury_buffer_position != null)
665             move_buffer_hook.run(b);
666         return true;
667     },
669     for_each: function (f) {
670         var count = this.count;
671         for (var i = 0; i < count; ++i)
672             f(this.get_buffer(i));
673     }
676 function buffer_initialize_window_early (window) {
677     /**
678      * Use content_buffer by default to handle an unusual case where
679      * browser.chromeURI is used perhaps.  In general this default
680      * should not be needed.
681      */
682     var create_initial_buffer =
683         window.args.initial_buffer_creator || buffer_creator(content_buffer);
684     new buffer_container(window, create_initial_buffer);
687 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
691  * initialize_first_buffer_type is a workaround for a XULRunner bug that
692  * first appeared in version 2.0, manifested as missing scrollbars in the
693  * first buffer of any window.  It only affects content-primary browsers,
694  * and the workaround is to initialize the browser as type "content" then
695  * change it to content-primary after a delay.
696  */
697 function initialize_first_buffer_type (window) {
698     window.buffers.current.browser.setAttribute("type", "content-primary");
701 add_hook("window_initialize_late_hook", initialize_first_buffer_type);
704 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
705 function buffer_before_window_close (window) {
706     var bs = window.buffers;
707     var count = bs.count;
708     for (let i = 0; i < count; ++i) {
709         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
710             return false;
711     }
712     return true;
714 add_hook("window_before_close_hook", buffer_before_window_close);
716 function buffer_window_close_handler (window) {
717     var bs = window.buffers;
718     var count = bs.count;
719     for (let i = 0; i < count; ++i) {
720         let b = bs.get_buffer(i);
721         b.destroy();
722     }
724 add_hook("window_close_hook", buffer_window_close_handler);
726 /* open/follow targets */
727 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
728                                // buffer is a content_buffer.
729 const OPEN_NEW_BUFFER = 1;
730 const OPEN_NEW_BUFFER_BACKGROUND = 2;
731 const OPEN_NEW_WINDOW = 3;
733 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
734 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
736 var TARGET_PROMPTS = [" in current buffer",
737                       " in new buffer",
738                       " in new buffer (background)",
739                       " in new window",
740                       "",
741                       " in current frame"];
743 var TARGET_NAMES = ["current buffer",
744                     "new buffer",
745                     "new buffer (background)",
746                     "new window",
747                     "default",
748                     "current frame"];
751 function create_buffer (window, creator, target) {
752     switch (target) {
753     case OPEN_NEW_BUFFER:
754         window.buffers.current = creator(window, null);
755         break;
756     case OPEN_NEW_BUFFER_BACKGROUND:
757         creator(window, null);
758         break;
759     case OPEN_NEW_WINDOW:
760         make_window(creator);
761         break;
762     default:
763         throw new Error("invalid target");
764     }
767 let (queued_buffer_creators = null) {
768     function create_buffer_in_current_window (creator, target, focus_existing) {
769         function process_queued_buffer_creators (window) {
770             for (var i = 0; i < queued_buffer_creators.length; ++i) {
771                 var x = queued_buffer_creators[i];
772                 create_buffer(window, x[0], x[1]);
773             }
774             queued_buffer_creators = null;
775         }
777         if (target == OPEN_NEW_WINDOW)
778             throw new Error("invalid target");
779         var window = get_recent_conkeror_window();
780         if (window) {
781             if (focus_existing)
782                 window.focus();
783             create_buffer(window, creator, target);
784         } else if (queued_buffer_creators != null) {
785             queued_buffer_creators.push([creator,target]);
786         } else {
787             queued_buffer_creators = [];
788             window = make_window(creator);
789             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
790         }
791     }
796  * Read Buffer
797  */
798 define_variable("read_buffer_show_icons", false,
799     "Boolean which says whether read_buffer should show buffer "+
800     "icons in the completions list.\nNote, setting this variable "+
801     "alone does not cause favicons or other kinds of icons to be "+
802     "fetched.  For that, load the `favicon' (or similar other) "+
803     "library.");
805 minibuffer_auto_complete_preferences["buffer"] = true;
806 define_keywords("$buffers", "$default");
807 minibuffer.prototype.read_buffer = function () {
808     var window = this.window;
809     keywords(arguments, $prompt = "Buffer:",
810              $buffers = function (visitor) window.buffers.for_each(visitor),
811              $default = window.buffers.current,
812              $history = "buffer");
813     var completer = all_word_completer(
814         $completions = arguments.$buffers,
815         $get_string = function (x) x.description,
816         $get_description = function (x) x.title,
817         $get_icon = (read_buffer_show_icons ?
818                      function (x) x.icon : null));
819     var result = yield this.read(
820         $keymap = read_buffer_keymap,
821         $prompt = arguments.$prompt,
822         $history = arguments.$history,
823         $completer = completer,
824         $enable_icons = read_buffer_show_icons,
825         $match_required = true,
826         $auto_complete = "buffer",
827         $auto_complete_initial = true,
828         $auto_complete_delay = 0,
829         $default_completion = arguments.$default);
830     yield co_return(result);
834 function buffer_move_forward (window, count) {
835     var buffers = window.buffers;
836     var index = buffers.selected_index;
837     var buffer = buffers.current
838     var total = buffers.count;
839     if (total == 1)
840         return;
841     var new_index = (index + count) % total;
842     if (new_index == index)
843         return;
844     if (new_index < 0)
845         new_index += total;
846     buffers.buffer_list.splice(index, 1);
847     buffers.buffer_list.splice(new_index, 0, buffer);
848     move_buffer_hook.run(buffer);
850 interactive("buffer-move-forward",
851     "Move the current buffer forward in the buffer order.",
852     function (I) { buffer_move_forward(I.window, I.p); });
854 interactive("buffer-move-backward",
855     "Move the current buffer backward in the buffer order.",
856     function (I) { buffer_move_forward(I.window, -I.p); });
859 function buffer_next (window, count) {
860     var index = window.buffers.selected_index;
861     var total = window.buffers.count;
862     if (total == 1)
863         throw new interactive_error("No other buffer");
864     index = (index + count) % total;
865     if (index < 0)
866         index += total;
867     window.buffers.current = window.buffers.get_buffer(index);
869 interactive("buffer-next",
870     "Switch to the next buffer.",
871     function (I) { buffer_next(I.window, I.p); });
872 interactive("buffer-previous",
873     "Switch to the previous buffer.",
874     function (I) { buffer_next(I.window, -I.p); });
876 function switch_to_buffer (window, buffer) {
877     if (buffer && !buffer.dead)
878         window.buffers.current = buffer;
880 interactive("switch-to-buffer",
881     "Prompt for a buffer and switch to it.",
882     function (I) {
883         switch_to_buffer(
884             I.window,
885             (yield I.minibuffer.read_buffer(
886                 $prompt = "Switch to buffer:",
887                 $default = (I.window.buffers.count > 1 ?
888                             I.window.buffers.buffer_history[1] :
889                             I.buffer))));
890     });
892 define_variable("can_kill_last_buffer", true,
893     "When true, kill-buffer can kill the last  buffer in a window, "+
894     "and close the window.");
896 function kill_other_buffers (buffer) {
897     if (!buffer)
898         return;
899     var bs = buffer.window.buffers;
900     var b;
901     while ((b = bs.get_buffer(0)) != buffer)
902         bs.kill_buffer(b);
903     var count = bs.count;
904     while (--count)
905         bs.kill_buffer(bs.get_buffer(1));
907 interactive("kill-other-buffers",
908     "Kill all buffers except current one.\n",
909     function (I) { kill_other_buffers(I.buffer); });
912 function kill_buffer (buffer, force) {
913     if (!buffer)
914         return;
915     var buffers = buffer.window.buffers;
916     if (buffers.count == 1 && buffer == buffers.current) {
917         if (can_kill_last_buffer || force) {
918             delete_window(buffer.window);
919             return;
920         } else
921             throw interactive_error("Can't kill last buffer.");
922     }
923     buffers.kill_buffer(buffer);
925 interactive("kill-buffer",
926     "Kill a buffer specified in the minibuffer.\n" +
927     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
928     "last remaining buffer in a window will cause the window to be closed.",
929     function (I) {
930         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
931     });
933 interactive("kill-current-buffer",
934     "Kill the current buffer.\n" +
935     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
936     "last remaining buffer in a window will cause the window to be closed.",
937     function (I) { kill_buffer(I.buffer); });
939 interactive("read-buffer-kill-buffer",
940     "Kill the current selected buffer in the completions list "+
941     "in a read buffer minibuffer interaction.",
942     function (I) {
943         var s = I.window.minibuffer.current_state;
944         var i = s.selected_completion_index;
945         var c = s.completions;
946         if (i == -1)
947             return;
948         kill_buffer(c.get_value(i));
949         s.completer.refresh();
950         s.handle_input(I.window.minibuffer);
951     });
953 interactive("bury-buffer",
954     "Bury the current buffer.\nPut the current buffer at the end of " +
955     "the buffer list, so that it is the least likely buffer to be " +
956     "selected by `switch-to-buffer'.",
957     function (I) { I.window.buffers.bury_buffer(I.buffer); });
959 interactive("unbury-buffer",
960     "Unbury the buffer lowest in the buffer-history list.\n"+
961     "With universal argument, prompt for a buffer.  When "+
962     "`bury_buffer_position` is non-null, move the buffer "+
963     "to the current position in the buffer list.",
964     function (I) {
965         var buffers = I.window.buffers;
966         if (I.prefix_argument)
967             var b = yield I.minibuffer.read_buffer(
968                 $prompt = "Switch to buffer:",
969                 $buffers = function (visitor) {
970                     var count = buffers.count;
971                     for (var i = count - 1; i >= 0; --i)
972                         visitor(buffers.buffer_history[i]);
973                 },
974                 $default = buffers.buffer_history[buffers.count - 1]);
975         else
976             b = buffers.buffer_history[buffers.count - 1];
977         buffers.unbury_buffer(b);
978     });
980 function change_directory (buffer, dir) {
981     if (buffer.page != null)
982         delete buffer.page.local.cwd;
983     buffer.local.cwd = make_file(dir);
985 interactive("change-directory",
986     "Change the current directory of the selected buffer.",
987     function (I) {
988         change_directory(
989             I.buffer,
990             (yield I.minibuffer.read_existing_directory_path(
991                 $prompt = "Change to directory:",
992                 $initial_value = make_file(I.local.cwd).path)));
993     });
995 interactive("shell-command", null,
996     function (I) {
997         var cwd = I.local.cwd;
998         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
999         yield shell_command(cmd, $cwd = cwd);
1000     });
1004  * selection_is_embed_p is used to test whether the unfocus command can
1005  * unfocus an element, even though there is a selection.  This happens
1006  * when the focused element is an html:embed.
1007  */
1008 function selection_is_embed_p (sel, focused_element) {
1009     if (sel.rangeCount == 1) {
1010         try {
1011             var r = sel.getRangeAt(0);
1012             var a = r.startContainer.childNodes[r.startOffset];
1013             if ((a instanceof Ci.nsIDOMHTMLEmbedElement ||
1014                  a instanceof Ci.nsIDOMHTMLObjectElement) &&
1015                 a == focused_element)
1016             {
1017                 return true;
1018             }
1019         } catch (e) {}
1020     }
1021     return false;
1025  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
1026  * frames, iframes, plugins, and also clearing the selection.
1027  */
1028 define_buffer_local_hook("unfocus_hook");
1029 function unfocus (window, buffer) {
1030     // 1. if there is a selection, clear it.
1031     var selc = buffer.focused_selection_controller;
1032     if (selc) {
1033         var sel = selc.getSelection(selc.SELECTION_NORMAL);
1034         var active = ! sel.isCollapsed;
1035         var embed_p = selection_is_embed_p(sel, buffer.focused_element);
1036         clear_selection(buffer);
1037         if (active && !embed_p) {
1038             window.minibuffer.message("cleared selection");
1039             return;
1040         }
1041     }
1042     // 2. if there is a focused element, unfocus it.
1043     if (buffer.focused_element) {
1044         buffer.focused_element.blur();
1045         // if an element in a detached fragment has focus, blur() will
1046         // not work, and we need to take more drastic measures.  the
1047         // action taken was found through experiment, so it is possibly
1048         // not the most concise way to unfocus such an element.
1049         if (buffer.focused_element) {
1050             buffer.element.focus();
1051             buffer.top_frame.focus();
1052         }
1053         window.minibuffer.message("unfocused element");
1054         return;
1055     }
1056     // 3. if an iframe has focus, we must blur it.
1057     if (buffer.focused_frame_or_null &&
1058         buffer.focused_frame_or_null.frameElement)
1059     {
1060         buffer.focused_frame_or_null.frameElement.blur();
1061     }
1062     // 4. return focus to top-frame from subframes and plugins.
1063     buffer.top_frame.focus();
1064     buffer.top_frame.focus(); // needed to get focus back from plugins
1065     window.minibuffer.message("refocused top frame");
1066     // give page-modes an opportunity to set focus specially
1067     unfocus_hook.run(buffer);
1069 interactive("unfocus",
1070     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
1071     "frames, iframes, plugins, and also for clearing the selection.\n"+
1072     "The action that it takes is based on precedence.  If there is a "+
1073     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
1074     "there is a selection, it will clear the selection.  Otherwise, it "+
1075     "will return focus to the top frame from a focused frame, iframe, "+
1076     "or plugin.  In the case of plugins, since they steal keyboard "+
1077     "control away from Conkeror, the normal way to unfocus them is "+
1078     "to use command-line remoting externally: conkeror -batch -f "+
1079     "unfocus.  Page-modes also have an opportunity to alter the default"+
1080     "focus via the hook, `focus_hook'.",
1081     function (I) {
1082         unfocus(I.window, I.buffer);
1083     });
1086 function for_each_buffer (f) {
1087     for_each_window(function (w) { w.buffers.for_each(f); });
1092  * Buffer Modes
1093  */
1095 define_buffer_local_hook("buffer_mode_change_hook");
1096 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
1098 define_keywords("$display_name", "$doc");
1099 function buffer_mode (name, enable, disable) {
1100     keywords(arguments);
1101     this.name = name.replace("-","_","g");
1102     this.hyphen_name = name.replace("_","-","g");
1103     if (enable)
1104         this._enable = enable;
1105     if (disable)
1106         this._disable = disable;
1107     this.display_name = arguments.$display_name;
1108     this.doc = arguments.$doc;
1109     this.enable_hook = this.name + "_enable_hook";
1110     this.disable_hook = this.name + "_disable_hook";
1112 buffer_mode.prototype = {
1113     constructor: buffer_mode,
1114     name: null,
1115     display_name: null,
1116     doc: null,
1117     enable_hook: null,
1118     disable_hook: null,
1119     _enable: null,
1120     _disable: null,
1121     enable: function (buffer) {
1122         try {
1123             if (this._enable)
1124                 this._enable(buffer);
1125         } finally {
1126             buffer.enabled_modes.push(this.name);
1127             if (conkeror[this.enable_hook])
1128                 conkeror[this.enable_hook].run(buffer);
1129             buffer_mode_change_hook.run(buffer);
1130         }
1131     },
1132     disable: function (buffer) {
1133         try {
1134             if (this._disable)
1135                 this._disable(buffer);
1136         } finally {
1137             var i = buffer.enabled_modes.indexOf(this.name);
1138             if (i > -1)
1139                 buffer.enabled_modes.splice(i, 1);
1140             if (conkeror[this.disable_hook])
1141                 conkeror[this.disable_hook].run(buffer);
1142             buffer_mode_change_hook.run(buffer);
1143         }
1144     }
1146 define_keywords("$constructor");
1147 function define_buffer_mode (name, enable, disable) {
1148     keywords(arguments, $constructor = buffer_mode, $doc = null);
1149     var constructor = arguments.$constructor;
1150     var m = new constructor(name, enable, disable, forward_keywords(arguments));
1151     name = m.name; // normalized
1152     conkeror[name] = m;
1153     define_buffer_local_hook(m.enable_hook);
1154     define_buffer_local_hook(m.disable_hook);
1155     interactive(m.hyphen_name,
1156         arguments.$doc,
1157         function (I) {
1158             var enabledp = (I.buffer.enabled_modes.indexOf(name) > -1);
1159             if (enabledp)
1160                 m.disable(I.buffer);
1161             else
1162                 m.enable(I.buffer);
1163             I.minibuffer.message(m.hyphen_name + (enabledp ? " disabled" : " enabled"));
1164         });
1166 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
1170  * Mode Display in Minibuffer
1171  */
1173 function minibuffer_mode_indicator (window) {
1174     this.window = window;
1175     var element = create_XUL(window, "label");
1176     element.setAttribute("id", "minibuffer-mode-indicator");
1177     element.setAttribute("class", "mode-text-widget");
1178     window.document.getElementById("minibuffer").appendChild(element);
1179     this.element = element;
1180     this.hook_function = method_caller(this, this.update);
1181     add_hook.call(window, "select_buffer_hook", this.hook_function);
1182     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_function);
1183     this.update();
1185 minibuffer_mode_indicator.prototype = {
1186     constructor: minibuffer_mode_indicator,
1187     window: null,
1188     element: null,
1189     hook_function: null,
1190     update: function () {
1191         var buffer = this.window.buffers.current;
1192         var str = buffer.enabled_modes.map(
1193             function (x) {
1194                 return (conkeror[x].display_name || null);
1195             }).filter(function (x) x != null).join(" ");
1196         this.element.value = str;
1197     },
1198     uninstall: function () {
1199         remove_hook.call(this.window, "select_buffer_hook", this.hook_function);
1200         remove_hook.call(this.window, "current_buffer_mode_change_hook", this.hook_function);
1201         this.element.parentNode.removeChild(this.element);
1202     }
1204 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
1205 minibuffer_mode_indicator_mode(true);
1209  * minibuffer-keymaps-display
1210  */
1211 function minibuffer_keymaps_display_update (buffer) {
1212     var element = buffer.window.document
1213         .getElementById("keymaps-display");
1214     if (element) {
1215         var str = buffer.keymaps.reduce(
1216             function (acc, kmap) {
1217                 if (kmap.display_name)
1218                     acc.push(kmap.display_name);
1219                 return acc;
1220             }, []).join("/");
1221         if (element.value != str)
1222             element.value = str;
1223     }
1226 function minibuffer_keymaps_display_initialize (window) {
1227     var element = create_XUL(window, "label");
1228     element.setAttribute("id", "keymaps-display");
1229     element.setAttribute("class", "mode-text-widget");
1230     element.setAttribute("value", "");
1231     var mb = window.document.getElementById("minibuffer");
1232     mb.appendChild(element);
1235 define_global_mode("minibuffer_keymaps_display_mode",
1236     function enable () {
1237         add_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1238         add_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1239         for_each_window(minibuffer_keymaps_display_initialize);
1240     },
1241     function disable () {
1242         remove_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1243         remove_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1244         for_each_window(function (w) {
1245             var element = w.document
1246                 .getElementById("keymaps-display");
1247             if (element)
1248                 element.parentNode.removeChild(element);
1249         });
1250     });
1252 minibuffer_keymaps_display_mode(true);
1256  * minibuffer-keymaps-highlight
1257  */
1258 function minibuffer_keymaps_highlight_update (buffer) {
1259     var mb = buffer.window.document.getElementById("minibuffer");
1260     if (buffer.keymaps.some(function (k) k.notify))
1261         dom_add_class(mb, "highlight");
1262     else
1263         dom_remove_class(mb, "highlight");
1266 define_global_mode("minibuffer_keymaps_highlight_mode",
1267     function enable () {
1268         add_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1269     },
1270     function disable () {
1271         remove_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1272         for_each_window(function (w) {
1273             var mb = w.document.getElementById("minibuffer");
1274             if (mb)
1275                 dom_remove_class("highlight");
1276         });
1277     });
1279 minibuffer_keymaps_highlight_mode(true);
1282 provide("buffer");