point: buffer-outer-container overflow:hidden, buffer-container manually sized
[conkeror.git] / modules / buffer.js
blob3bc0cb410bec65c35b9070fda322f7458134171d
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_loaded_hook", "buffer_loaded_hook");
43 define_current_buffer_hook("current_buffer_zoom_hook", "zoom_hook");
46 function buffer_position_before (container, b, i) {
47     return i;
50 function buffer_position_after (container, b, i) {
51     return i + 1;
54 function buffer_position_end (container, b, i) {
55     return container.count;
58 function buffer_position_end_by_type (container, b, i) {
59     // after last buffer of same type
60     var count = container.count;
61     var p = count - 1;
62     while (p >= 0 &&
63            container.get_buffer(p).constructor != b.constructor)
64     {
65         p--;
66     }
67     if (p == -1)
68         return count;
69     else
70         return p + 1;
73 define_variable("new_buffer_position", buffer_position_end,
74     "Used to compute the position in the buffer-list at which "+
75     "to insert new buffers which do not have an opener.  These "+
76     "include buffers created by typing an url or webjump, or "+
77     "buffers created via command-line remoting.  The value "+
78     "should be a number giving the index or a function of three "+
79     "arguments that returns the index at which to insert the "+
80     "new buffer.  The first argument is the buffer_container "+
81     "into which the new buffer is being inserted.  The second "+
82     "argument is the buffer to be inserted.  The third argument "+
83     "is the position of the currently selected buffer.  Several "+
84     "such functions are provided, including, buffer_position_before, "+
85     "buffer_position_after, buffer_position_end, and "+
86     "buffer_position_end_by_type.");
88 define_variable("new_buffer_with_opener_position", buffer_position_after,
89     "Used to compute the position in the buffer-list at which "+
90     "to insert new buffers which have an opener in the same "+
91     "window.  These include buffers created by following a link "+
92     "or frame, and contextual help buffers.  The allowed values "+
93     "are the same as those for `new_buffer_position', except that "+
94     "the second argument passed to the function is the index of "+
95     "the opener instead of the index of the current buffer (often "+
96     "one and the same).");
98 define_variable("bury_buffer_position", null,
99     "Used to compute the position in the buffer-list to move a "+
100     "buried buffer to.  A value of null prevents bury-buffer "+
101     "from moving the buffer at all.  Other allowed values are "+
102     "the same as those for `new_buffer_position', except that "+
103     "the second argument passed to the function is the index of "+
104     "the new buffer that will be selected after burying the "+
105     "current buffer.");
107 define_variable("allow_browser_window_close", true,
108     "If this is set to true, if a content buffer page calls " +
109     "window.close() from JavaScript and is not prevented by the " +
110     "normal Mozilla mechanism that restricts pages from closing " +
111     "a window that was not opened by a script, the buffer will be " +
112     "killed, deleting the window as well if it is the only buffer.");
114 define_keywords("$opener", "$position");
115 function buffer_creator (type) {
116     var args = forward_keywords(arguments);
117     return function (window) {
118         return new type(window, args);
119     };
122 function point_state () {
124 point_state.prototype = {
125     constructor: point_state,
126     toString: function () "#<point_state>",
127     xpath: null,
128     top: 0,
129     left: 0,
130     width: 30,
131     height: 30
134 function point_update_element (b) {
135     var p = b.point;
136     if (p.xpath) {
137         var e = xpath_find_node(b.document, p.xpath);
138         if (e) {
139             var rect = e.getBoundingClientRect();
140             p.top = rect.top;
141             p.left = rect.left;
142             p.width = rect.width;
143             p.height = rect.height;
144         } else
145             b.point_history[b.point_history.index] = new point_state();
146         b.point_update();
147     }
149 add_hook("current_buffer_loaded_hook", point_update_element);
150 add_hook("current_buffer_dom_content_loaded_hook", point_update_element);
151 add_hook("current_buffer_scroll_hook", point_update_element);
153 function buffer_modality (buffer) {
154     buffer.keymaps.push(default_global_keymap);
157 function buffer (window) {
158     this.constructor_begin();
159     keywords(arguments, $position = this.default_position);
160     this.opener = arguments.$opener;
161     this.window = window;
162     var element = create_XUL(window, "vbox");
163     element.setAttribute("flex", "1");
164     var browser = create_XUL(window, "browser");
165     browser.setAttribute("type", "content");
166     browser.setAttribute("flex", "1");
167     browser.setAttribute("autocompletepopup", "popup_autocomplete");
168     element.appendChild(browser);
169     this.window.buffers.container.appendChild(element);
170     this.window.buffers.insert(this, arguments.$position, this.opener);
171     this.window.buffers.buffer_history.push(this);
172     this.element = element;
173     this.browser = element.firstChild;
174     this.element.conkeror_buffer_object = this;
176     this.local = { __proto__: conkeror };
177     this.page = null;
178     this.enabled_modes = [];
179     this.default_browser_object_classes = {};
181     var buffer = this;
183     this.browser.addEventListener("scroll", function (event) {
184             buffer_scroll_hook.run(buffer);
185         }, true /* capture */);
187     this.browser.addEventListener("DOMContentLoaded", function (event) {
188             buffer_dom_content_loaded_hook.run(buffer);
189         }, true /* capture */);
191     this.window.setTimeout(function () { create_buffer_late_hook.run(buffer); }, 0);
193     this.browser.addEventListener("load", function (event) {
194             if (event.target == buffer.document)
195                 buffer_loaded_hook.run(buffer);
196         }, true /* capture */);
198     this.browser.addEventListener("DOMWindowClose", function (event) {
199             /* This call to preventDefault is very important; without
200              * it, somehow Mozilla does something bad and as a result
201              * the window loses focus, causing keyboard commands to
202              * stop working. */
203             event.preventDefault();
205             if (allow_browser_window_close)
206                 kill_buffer(buffer, true);
207         }, true);
209     this.browser.addEventListener("focus", function (event) {
210         if (buffer.focusblocker &&
211             event.target instanceof Ci.nsIDOMHTMLElement &&
212             buffer.focusblocker(buffer, event))
213         {
214             event.target.blur();
215         } else
216             buffer.set_input_mode();
217     }, true);
219     this.browser.addEventListener("blur", function (event) {
220         buffer.set_input_mode();
221     }, true);
223     // point init
224     //
225     this.web_navigation.sessionHistory.addSHistoryListener(this);
226     this.point_history = [];
227     this.point_history.index = -1;
229     this.modalities = [buffer_modality];
231     // When create_buffer_early_hook runs, basic buffer properties
232     // will be available, but not the properties subclasses.
233     create_buffer_early_hook.run(this);
235     this.constructor_end();
237 buffer.prototype = {
238     constructor: buffer,
239     toString: function () "#<buffer>",
240     QueryInterface: generate_QI(Ci.nsISHistoryListener, Ci.nsISupportsWeakReference),
242     // default_position is the default value for the $position keyword to
243     // the buffer constructor.  This property can be set on the prototype
244     // of a subclass in order to override new_buffer_position and
245     // new_buffer_with_opener_position for specific types of buffers.
246     default_position: null,
248     /* Saved focus state */
249     saved_focused_frame: null,
250     saved_focused_element: null,
252     // get title ()   [must be defined by subclasses]
253     // get name ()    [must be defined by subclasses]
254     dead: false, /* This is set when the buffer is killed */
256     keymaps: null,
257     mark_active: false,
259     // The property focusblocker is available for an external module to
260     // put a function on which takes a buffer as its argument and returns
261     // true to block a focus event, or false to let normal processing
262     // occur.  Having this one property explicitly handled by the buffer
263     // class allows for otherwise modular focus-blockers.
264     focusblocker: null,
266     // icon is a string url of an icon to use for this buffer.  Setting it
267     // causes buffer_icon_change_hook to be run.
268     _icon: null,
269     get icon () this._icon,
270     set icon (x) {
271         if (this._icon != x) {
272             this._icon = x;
273             buffer_icon_change_hook.run(this);
274         }
275     },
277     default_message: "",
279     set_default_message: function (str) {
280         this.default_message = str;
281         if (this == this.window.buffers.current)
282             this.window.minibuffer.set_default_message(str);
283     },
285     constructors_running: 0,
287     constructor_begin: function () {
288         this.constructors_running++;
289     },
291     constructor_end: function () {
292         if (--this.constructors_running == 0) {
293             create_buffer_hook.run(this);
294             this.set_input_mode();
295             delete this.opener;
296         }
297     },
299     destroy: function () {
300         this.dead = true;
301         this.web_navigation.sessionHistory.removeSHistoryListener(this);
302         this.point_history = null;
303         this.browser = null;
304         this.element = null;
305         this.saved_focused_frame = null;
306         this.saved_focused_element = null;
307         // prevent modalities from accessing dead browser
308         this.modalities = [];
309     },
311     set_input_mode: function () {
312         if (this != this.window.buffers.current)
313             return;
314         this.keymaps = [];
315         this.modalities.map(function (m) m(this), this);
316         set_input_mode_hook.run(this);
317     },
319     override_keymaps: function (keymaps) {
320         if (keymaps) {
321             this.keymaps = keymaps;
322             this.set_input_mode = function () {
323                 set_input_mode_hook.run(this);
324             };
325         } else
326             delete this.set_input_mode;
327         this.set_input_mode();
328     },
330     /* Browser accessors */
331     get top_frame () { return this.browser.contentWindow; },
332     get document () { return this.browser.contentDocument; },
333     get web_navigation () { return this.browser.webNavigation; },
334     get doc_shell () { return this.browser.docShell; },
335     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
336     get current_uri () { return this.browser.currentURI; },
338     is_child_element: function (element) {
339         return (element && this.is_child_frame(element.ownerDocument.defaultView));
340     },
342     is_child_frame: function (frame) {
343         return (frame && frame.top == this.top_frame);
344     },
346     // This method is like focused_frame, except that if no content
347     // frame actually has focus, this returns null.
348     get focused_frame_or_null () {
349         var frame = this.window.document.commandDispatcher.focusedWindow;
350         if (this.is_child_frame(frame))
351             return frame;
352         return null;
353     },
355     get focused_frame () {
356         var frame = this.window.document.commandDispatcher.focusedWindow;
357         if (this.is_child_frame(frame))
358             return frame;
359         return this.top_frame;
360     },
362     get focused_element () {
363         var element = this.window.document.commandDispatcher.focusedElement;
364         if (this.is_child_element(element))
365             return element;
366         return null;
367     },
369     get focused_selection_controller () {
370         return this.focused_frame
371             .QueryInterface(Ci.nsIInterfaceRequestor)
372             .getInterface(Ci.nsIWebNavigation)
373             .QueryInterface(Ci.nsIInterfaceRequestor)
374             .getInterface(Ci.nsISelectionDisplay)
375             .QueryInterface(Ci.nsISelectionController);
376     },
378     do_command: function (command) {
379         function attempt_command (element, command) {
380             var controller;
381             if (element.controllers
382                 && (controller = element.controllers.getControllerForCommand(command)) != null
383                 && controller.isCommandEnabled(command))
384             {
385                 controller.doCommand(command);
386                 return true;
387             }
388             return false;
389         }
391         var element = this.focused_element;
392         if (element && attempt_command(element, command))
393             return;
394         var win = this.focused_frame;
395         while (true) {
396             if (attempt_command(win, command))
397                 return;
398             if (!win.parent || win == win.parent)
399                 break;
400             win = win.parent;
401         }
402     },
404     // nsISHistoryListener interface
405     //
406     point_history: null,
407     get point () {
408         return this.point_history[this.point_history.index]
409             || new point_state();
410     },
411     point_update: function () {
412         var p = this.point;
413         this.window.point.setAttribute("top", p.top);
414         this.window.point.setAttribute("left", p.left);
415         this.window.point.style.width = p.width + "px";
416         this.window.point.style.height = p.height + "px";
417     },
418     OnHistoryNewEntry: function (uri) {
419         dumpln("point_history_listener OnHistoryNewEntry");
420         this.point_history.push(new point_state());
421         this.point_history.index++;
422         this.point_update();
423     },
424     OnHistoryGoBack: function (uri) {
425         dumpln("point_history_listener OnHistoryGoBack");
426         this.point_history.index--;
427         this.point_update();
428         return true;
429     },
430     OnHistoryGoForward: function (uri) {
431         dumpln("point_history_listener OnHistoryGoForward");
432         this.point_history.index++;
433         this.point_update();
434         return true;
435     },
436     OnHistoryReload: function (uri, reload_flags) {
437         dumpln("point_history_listener OnHistoryReload");
438         return true;
439     },
440     OnHistoryGotoIndex: function (index, uri) {
441         dumpln("point_history_listener OnHistoryGotoIndex");
442         this.point_history.index = index;
443         this.point_update();
444         return true;
445     },
446     OnHistoryPurge: function (num_entries) {
447         dumpln("point_history_listener OnHistoryPurge");
448         this.point_history.splice(0, num_entries);
449         this.point_history.index -= num_entries;
450         return true;
451     }
454 function with_current_buffer (buffer, callback) {
455     return callback(new interactive_context(buffer));
458 function check_buffer (obj, type) {
459     if (!(obj instanceof type))
460         throw interactive_error("Buffer has invalid type.");
461     if (obj.dead)
462         throw interactive_error("Buffer has already been killed.");
463     return obj;
466 function caret_enabled (buffer) {
467     return buffer.browser.getAttribute('showcaret');
470 function clear_selection (buffer) {
471     let sel_ctrl = buffer.focused_selection_controller;
472     if (sel_ctrl) {
473         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
474         if (caret_enabled(buffer)) {
475             if (sel.anchorNode)
476                 sel.collapseToStart();
477         } else {
478             sel.removeAllRanges();
479         }
480     }
484 function buffer_container (window, create_initial_buffer) {
485     this.window = window;
486     this.container = window.document.getElementById("buffer-container");
487     this.buffer_list = [];
488     this.buffer_history = [];
489     window.buffers = this;
490     create_initial_buffer(window);
492 buffer_container.prototype = {
493     constructor: buffer_container,
494     toString: function () "#<buffer_container>",
496     insert: function (buffer, position, opener) {
497         var i = this.index_of(opener);
498         if (position == null) {
499             if (i == null)
500                 position = new_buffer_position;
501             else
502                 position = new_buffer_with_opener_position;
503         }
504         if (i == null)
505             i = this.selected_index || 0;
506         try {
507             if (position instanceof Function)
508                 var p = position(this, buffer, i);
509             else
510                 p = position;
511             this.buffer_list.splice(p, 0, buffer);
512         } catch (e) {
513             this.buffer_list.splice(0, 0, buffer);
514             dumpln("Error inserting buffer, inserted at 0.");
515             dump_error(e);
516         }
517     },
519     get current () {
520         return this.container.selectedPanel.conkeror_buffer_object;
521     },
523     set current (buffer) {
524         var old_value = this.current;
525         if (old_value == buffer)
526             return;
528         this.buffer_history.splice(this.buffer_history.indexOf(buffer), 1);
529         this.buffer_history.unshift(buffer);
531         this._switch_away_from(this.current);
532         this._switch_to(buffer);
534         // Run hooks
535         select_buffer_hook.run(buffer);
536     },
538     _switch_away_from: function (old_value) {
539         // Save focus state
540         old_value.saved_focused_frame = old_value.focused_frame;
541         old_value.saved_focused_element = old_value.focused_element;
543         if ('isActive' in old_value.browser.docShell)
544             old_value.browser.docShell.isActive = false;
545         old_value.browser.setAttribute("type", "content");
546     },
548     _switch_to: function (buffer) {
549         // Select new buffer in the XUL deck
550         this.container.selectedPanel = buffer.element;
552         buffer.browser.setAttribute("type", "content-primary");
553         if ('isActive' in buffer.browser.docShell)
554             buffer.browser.docShell.isActive = true;
556         /**
557          * This next focus call seems to be needed to avoid focus
558          * somehow getting lost (and the keypress handler therefore
559          * not getting called at all) when killing buffers.
560          */
561         this.window.focus();
563         // Restore focus state
564         buffer.browser.focus();
565         if (buffer.saved_focused_element)
566             set_focus_no_scroll(this.window, buffer.saved_focused_element);
567         else if (buffer.saved_focused_frame)
568             set_focus_no_scroll(this.window, buffer.saved_focused_frame);
570         buffer.saved_focused_element = null;
571         buffer.saved_focused_frame = null;
573         buffer.point_update();
575         buffer.set_input_mode();
577         this.window.minibuffer.set_default_message(buffer.default_message);
578     },
580     get count () {
581         return this.buffer_list.length;
582     },
584     get_buffer: function (index) {
585         if (index >= 0 && index < this.count)
586             return this.buffer_list[index]
587         return null;
588     },
590     get selected_index () {
591         var nodes = this.buffer_list;
592         var count = nodes.length;
593         for (var i = 0; i < count; ++i)
594             if (nodes[i] == this.container.selectedPanel.conkeror_buffer_object)
595                 return i;
596         return null;
597     },
599     index_of: function (b) {
600         var nodes = this.buffer_list;
601         var count = nodes.length;
602         for (var i = 0; i < count; ++i)
603             if (nodes[i] == b)
604                 return i;
605         return null;
606     },
608     get unique_name_list () {
609         var existing_names = {};
610         var bufs = [];
611         this.for_each(function(b) {
612                 var base_name = b.name;
613                 var name = base_name;
614                 var index = 1;
615                 while (existing_names[name]) {
616                     ++index;
617                     name = base_name + "<" + index + ">";
618                 }
619                 existing_names[name] = true;
620                 bufs.push([name, b]);
621             });
622         return bufs;
623     },
625     kill_buffer: function (b) {
626         if (b.dead)
627             return true;
628         var count = this.count;
629         if (count <= 1)
630             return false;
631         var new_buffer = this.buffer_history[0];
632         var changed = false;
633         if (b == new_buffer) {
634             new_buffer = this.buffer_history[1];
635             changed = true;
636         }
637         this._switch_away_from(this.current);
638         // The removeChild call below may trigger events in progress
639         // listeners.  This call to `destroy' gives buffer subclasses a
640         // chance to remove such listeners, so that they cannot try to
641         // perform UI actions based upon a xul:browser that no longer
642         // exists.
643         var element = b.element;
644         b.destroy();
645         this.container.removeChild(element);
646         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
647         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
648         this._switch_to(new_buffer);
649         if (changed) {
650             select_buffer_hook.run(new_buffer);
651             this.buffer_history.splice(this.buffer_history.indexOf(new_buffer), 1);
652             this.buffer_history.unshift(new_buffer);
653         }
654         kill_buffer_hook.run(b);
655         return true;
656     },
658     bury_buffer: function (b) {
659         var new_buffer = this.buffer_history[0];
660         if (b == new_buffer)
661             new_buffer = this.buffer_history[1];
662         if (! new_buffer)
663             throw interactive_error("No other buffer");
664         if (bury_buffer_position != null) {
665             this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
666             this.insert(b, bury_buffer_position, new_buffer);
667         }
668         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
669         this.buffer_history.push(b);
670         this.current = new_buffer;
671         if (bury_buffer_position != null)
672             move_buffer_hook.run(b);
673         return true;
674     },
676     unbury_buffer: function (b) {
677         var c = this.current;
678         if (bury_buffer_position != null) {
679             this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
680             this.buffer_list.splice(this.buffer_list.indexOf(c), 0, b);
681         }
682         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
683         this.buffer_history.unshift(b);
684         this.current = b;
685         if (bury_buffer_position != null)
686             move_buffer_hook.run(b);
687         return true;
688     },
690     for_each: function (f) {
691         var count = this.count;
692         for (var i = 0; i < count; ++i)
693             f(this.get_buffer(i));
694     }
697 function buffer_initialize_window_early (window) {
698     /**
699      * Use content_buffer by default to handle an unusual case where
700      * browser.chromeURI is used perhaps.  In general this default
701      * should not be needed.
702      */
703     var create_initial_buffer =
704         window.args.initial_buffer_creator || buffer_creator(content_buffer);
705     new buffer_container(window, create_initial_buffer);
708 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
712  * initialize_first_buffer_type is a workaround for a XULRunner bug that
713  * first appeared in version 2.0, manifested as missing scrollbars in the
714  * first buffer of any window.  It only affects content-primary browsers,
715  * and the workaround is to initialize the browser as type "content" then
716  * change it to content-primary after a delay.
717  */
718 function initialize_first_buffer_type (window) {
719     window.buffers.current.browser.setAttribute("type", "content-primary");
722 add_hook("window_initialize_late_hook", initialize_first_buffer_type);
725 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
726 function buffer_before_window_close (window) {
727     var bs = window.buffers;
728     var count = bs.count;
729     for (let i = 0; i < count; ++i) {
730         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
731             return false;
732     }
733     return true;
735 add_hook("window_before_close_hook", buffer_before_window_close);
737 function buffer_window_close_handler (window) {
738     var bs = window.buffers;
739     var count = bs.count;
740     for (let i = 0; i < count; ++i) {
741         let b = bs.get_buffer(i);
742         b.destroy();
743     }
745 add_hook("window_close_hook", buffer_window_close_handler);
747 /* open/follow targets */
748 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
749                                // buffer is a content_buffer.
750 const OPEN_NEW_BUFFER = 1;
751 const OPEN_NEW_BUFFER_BACKGROUND = 2;
752 const OPEN_NEW_WINDOW = 3;
754 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
755 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
757 var TARGET_PROMPTS = [" in current buffer",
758                       " in new buffer",
759                       " in new buffer (background)",
760                       " in new window",
761                       "",
762                       " in current frame"];
764 var TARGET_NAMES = ["current buffer",
765                     "new buffer",
766                     "new buffer (background)",
767                     "new window",
768                     "default",
769                     "current frame"];
772 function create_buffer (window, creator, target) {
773     switch (target) {
774     case OPEN_NEW_BUFFER:
775         window.buffers.current = creator(window, null);
776         break;
777     case OPEN_NEW_BUFFER_BACKGROUND:
778         creator(window, null);
779         break;
780     case OPEN_NEW_WINDOW:
781         make_window(creator);
782         break;
783     default:
784         throw new Error("invalid target");
785     }
788 let (queued_buffer_creators = null) {
789     function create_buffer_in_current_window (creator, target, focus_existing) {
790         function process_queued_buffer_creators (window) {
791             for (var i = 0; i < queued_buffer_creators.length; ++i) {
792                 var x = queued_buffer_creators[i];
793                 create_buffer(window, x[0], x[1]);
794             }
795             queued_buffer_creators = null;
796         }
798         if (target == OPEN_NEW_WINDOW)
799             throw new Error("invalid target");
800         var window = get_recent_conkeror_window();
801         if (window) {
802             if (focus_existing)
803                 window.focus();
804             create_buffer(window, creator, target);
805         } else if (queued_buffer_creators != null) {
806             queued_buffer_creators.push([creator,target]);
807         } else {
808             queued_buffer_creators = [];
809             window = make_window(creator);
810             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
811         }
812     }
817  * Read Buffer
818  */
819 define_variable("read_buffer_show_icons", false,
820     "Boolean which says whether read_buffer should show buffer "+
821     "icons in the completions list.\nNote, setting this variable "+
822     "alone does not cause favicons or other kinds of icons to be "+
823     "fetched.  For that, load the `favicon' (or similar other) "+
824     "library.");
826 minibuffer_auto_complete_preferences["buffer"] = true;
827 define_keywords("$buffers", "$default");
828 minibuffer.prototype.read_buffer = function () {
829     var window = this.window;
830     keywords(arguments, $prompt = "Buffer:",
831              $buffers = function (visitor) window.buffers.for_each(visitor),
832              $default = window.buffers.current,
833              $history = "buffer");
834     var completer = all_word_completer(
835         $completions = arguments.$buffers,
836         $get_string = function (x) x.description,
837         $get_description = function (x) x.title,
838         $get_icon = (read_buffer_show_icons ?
839                      function (x) x.icon : null));
840     var result = yield this.read(
841         $keymap = read_buffer_keymap,
842         $prompt = arguments.$prompt,
843         $history = arguments.$history,
844         $completer = completer,
845         $enable_icons = read_buffer_show_icons,
846         $match_required = true,
847         $auto_complete = "buffer",
848         $auto_complete_initial = true,
849         $auto_complete_delay = 0,
850         $default_completion = arguments.$default);
851     yield co_return(result);
855 function buffer_move_forward (window, count) {
856     var buffers = window.buffers;
857     var index = buffers.selected_index;
858     var buffer = buffers.current
859     var total = buffers.count;
860     if (total == 1)
861         return;
862     var new_index = (index + count) % total;
863     if (new_index == index)
864         return;
865     if (new_index < 0)
866         new_index += total;
867     buffers.buffer_list.splice(index, 1);
868     buffers.buffer_list.splice(new_index, 0, buffer);
869     move_buffer_hook.run(buffer);
871 interactive("buffer-move-forward",
872     "Move the current buffer forward in the buffer order.",
873     function (I) { buffer_move_forward(I.window, I.p); });
875 interactive("buffer-move-backward",
876     "Move the current buffer backward in the buffer order.",
877     function (I) { buffer_move_forward(I.window, -I.p); });
880 function buffer_next (window, count) {
881     var index = window.buffers.selected_index;
882     var total = window.buffers.count;
883     if (total == 1)
884         throw new interactive_error("No other buffer");
885     index = (index + count) % total;
886     if (index < 0)
887         index += total;
888     window.buffers.current = window.buffers.get_buffer(index);
890 interactive("buffer-next",
891     "Switch to the next buffer.",
892     function (I) { buffer_next(I.window, I.p); });
893 interactive("buffer-previous",
894     "Switch to the previous buffer.",
895     function (I) { buffer_next(I.window, -I.p); });
897 function switch_to_buffer (window, buffer) {
898     if (buffer && !buffer.dead)
899         window.buffers.current = buffer;
901 interactive("switch-to-buffer",
902     "Prompt for a buffer and switch to it.",
903     function (I) {
904         switch_to_buffer(
905             I.window,
906             (yield I.minibuffer.read_buffer(
907                 $prompt = "Switch to buffer:",
908                 $default = (I.window.buffers.count > 1 ?
909                             I.window.buffers.buffer_history[1] :
910                             I.buffer))));
911     });
913 define_variable("can_kill_last_buffer", true,
914     "When true, kill-buffer can kill the last  buffer in a window, "+
915     "and close the window.");
917 function kill_other_buffers (buffer) {
918     if (!buffer)
919         return;
920     var bs = buffer.window.buffers;
921     var b;
922     while ((b = bs.get_buffer(0)) != buffer)
923         bs.kill_buffer(b);
924     var count = bs.count;
925     while (--count)
926         bs.kill_buffer(bs.get_buffer(1));
928 interactive("kill-other-buffers",
929     "Kill all buffers except current one.\n",
930     function (I) { kill_other_buffers(I.buffer); });
933 function kill_buffer (buffer, force) {
934     if (!buffer)
935         return;
936     var buffers = buffer.window.buffers;
937     if (buffers.count == 1 && buffer == buffers.current) {
938         if (can_kill_last_buffer || force) {
939             delete_window(buffer.window);
940             return;
941         } else
942             throw interactive_error("Can't kill last buffer.");
943     }
944     buffers.kill_buffer(buffer);
946 interactive("kill-buffer",
947     "Kill a buffer specified in the minibuffer.\n" +
948     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
949     "last remaining buffer in a window will cause the window to be closed.",
950     function (I) {
951         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
952     });
954 interactive("kill-current-buffer",
955     "Kill the current buffer.\n" +
956     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
957     "last remaining buffer in a window will cause the window to be closed.",
958     function (I) { kill_buffer(I.buffer); });
960 interactive("read-buffer-kill-buffer",
961     "Kill the current selected buffer in the completions list "+
962     "in a read buffer minibuffer interaction.",
963     function (I) {
964         var s = I.window.minibuffer.current_state;
965         var i = s.selected_completion_index;
966         var c = s.completions;
967         if (i == -1)
968             return;
969         kill_buffer(c.get_value(i));
970         s.completer.refresh();
971         s.handle_input(I.window.minibuffer);
972     });
974 interactive("bury-buffer",
975     "Bury the current buffer.\nPut the current buffer at the end of " +
976     "the buffer list, so that it is the least likely buffer to be " +
977     "selected by `switch-to-buffer'.",
978     function (I) { I.window.buffers.bury_buffer(I.buffer); });
980 interactive("unbury-buffer",
981     "Unbury the buffer lowest in the buffer-history list.\n"+
982     "With universal argument, prompt for a buffer.  When "+
983     "`bury_buffer_position` is non-null, move the buffer "+
984     "to the current position in the buffer list.",
985     function (I) {
986         var buffers = I.window.buffers;
987         if (I.prefix_argument)
988             var b = yield I.minibuffer.read_buffer(
989                 $prompt = "Switch to buffer:",
990                 $buffers = function (visitor) {
991                     var count = buffers.count;
992                     for (var i = count - 1; i >= 0; --i)
993                         visitor(buffers.buffer_history[i]);
994                 },
995                 $default = buffers.buffer_history[buffers.count - 1]);
996         else
997             b = buffers.buffer_history[buffers.count - 1];
998         buffers.unbury_buffer(b);
999     });
1001 function change_directory (buffer, dir) {
1002     if (buffer.page != null)
1003         delete buffer.page.local.cwd;
1004     buffer.local.cwd = make_file(dir);
1006 interactive("change-directory",
1007     "Change the current directory of the selected buffer.",
1008     function (I) {
1009         change_directory(
1010             I.buffer,
1011             (yield I.minibuffer.read_existing_directory_path(
1012                 $prompt = "Change to directory:",
1013                 $initial_value = make_file(I.local.cwd).path)));
1014     });
1016 interactive("shell-command", null,
1017     function (I) {
1018         var cwd = I.local.cwd;
1019         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
1020         yield shell_command(cmd, $cwd = cwd);
1021     });
1025  * selection_is_embed_p is used to test whether the unfocus command can
1026  * unfocus an element, even though there is a selection.  This happens
1027  * when the focused element is an html:embed.
1028  */
1029 function selection_is_embed_p (sel, focused_element) {
1030     if (sel.rangeCount == 1) {
1031         try {
1032             var r = sel.getRangeAt(0);
1033             var a = r.startContainer.childNodes[r.startOffset];
1034             if ((a instanceof Ci.nsIDOMHTMLEmbedElement ||
1035                  a instanceof Ci.nsIDOMHTMLObjectElement) &&
1036                 a == focused_element)
1037             {
1038                 return true;
1039             }
1040         } catch (e) {}
1041     }
1042     return false;
1046  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
1047  * frames, iframes, plugins, and also clearing the selection.
1048  */
1049 define_buffer_local_hook("unfocus_hook");
1050 function unfocus (window, buffer) {
1051     // 1. if there is a selection, clear it.
1052     var selc = buffer.focused_selection_controller;
1053     if (selc) {
1054         var sel = selc.getSelection(selc.SELECTION_NORMAL);
1055         var active = ! sel.isCollapsed;
1056         var embed_p = selection_is_embed_p(sel, buffer.focused_element);
1057         clear_selection(buffer);
1058         if (active && !embed_p) {
1059             window.minibuffer.message("cleared selection");
1060             return;
1061         }
1062     }
1063     // 2. if there is a focused element, unfocus it.
1064     if (buffer.focused_element) {
1065         buffer.focused_element.blur();
1066         // if an element in a detached fragment has focus, blur() will
1067         // not work, and we need to take more drastic measures.  the
1068         // action taken was found through experiment, so it is possibly
1069         // not the most concise way to unfocus such an element.
1070         if (buffer.focused_element) {
1071             buffer.element.focus();
1072             buffer.top_frame.focus();
1073         }
1074         window.minibuffer.message("unfocused element");
1075         return;
1076     }
1077     // 3. if an iframe has focus, we must blur it.
1078     if (buffer.focused_frame_or_null &&
1079         buffer.focused_frame_or_null.frameElement)
1080     {
1081         buffer.focused_frame_or_null.frameElement.blur();
1082     }
1083     // 4. return focus to top-frame from subframes and plugins.
1084     buffer.top_frame.focus();
1085     buffer.top_frame.focus(); // needed to get focus back from plugins
1086     window.minibuffer.message("refocused top frame");
1087     // give page-modes an opportunity to set focus specially
1088     unfocus_hook.run(buffer);
1090 interactive("unfocus",
1091     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
1092     "frames, iframes, plugins, and also for clearing the selection.\n"+
1093     "The action that it takes is based on precedence.  If there is a "+
1094     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
1095     "there is a selection, it will clear the selection.  Otherwise, it "+
1096     "will return focus to the top frame from a focused frame, iframe, "+
1097     "or plugin.  In the case of plugins, since they steal keyboard "+
1098     "control away from Conkeror, the normal way to unfocus them is "+
1099     "to use command-line remoting externally: conkeror -batch -f "+
1100     "unfocus.  Page-modes also have an opportunity to alter the default"+
1101     "focus via the hook, `focus_hook'.",
1102     function (I) {
1103         unfocus(I.window, I.buffer);
1104     });
1107 function for_each_buffer (f) {
1108     for_each_window(function (w) { w.buffers.for_each(f); });
1113  * Buffer Modes
1114  */
1116 define_buffer_local_hook("buffer_mode_change_hook");
1117 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
1119 define_keywords("$display_name", "$doc");
1120 function buffer_mode (name, enable, disable) {
1121     keywords(arguments);
1122     this.name = name.replace("-","_","g");
1123     this.hyphen_name = name.replace("_","-","g");
1124     if (enable)
1125         this._enable = enable;
1126     if (disable)
1127         this._disable = disable;
1128     this.display_name = arguments.$display_name;
1129     this.doc = arguments.$doc;
1130     this.enable_hook = this.name + "_enable_hook";
1131     this.disable_hook = this.name + "_disable_hook";
1133 buffer_mode.prototype = {
1134     constructor: buffer_mode,
1135     name: null,
1136     display_name: null,
1137     doc: null,
1138     enable_hook: null,
1139     disable_hook: null,
1140     _enable: null,
1141     _disable: null,
1142     enable: function (buffer) {
1143         try {
1144             if (this._enable)
1145                 this._enable(buffer);
1146         } finally {
1147             buffer.enabled_modes.push(this.name);
1148             if (conkeror[this.enable_hook])
1149                 conkeror[this.enable_hook].run(buffer);
1150             buffer_mode_change_hook.run(buffer);
1151         }
1152     },
1153     disable: function (buffer) {
1154         try {
1155             if (this._disable)
1156                 this._disable(buffer);
1157         } finally {
1158             var i = buffer.enabled_modes.indexOf(this.name);
1159             if (i > -1)
1160                 buffer.enabled_modes.splice(i, 1);
1161             if (conkeror[this.disable_hook])
1162                 conkeror[this.disable_hook].run(buffer);
1163             buffer_mode_change_hook.run(buffer);
1164         }
1165     }
1167 define_keywords("$constructor");
1168 function define_buffer_mode (name, enable, disable) {
1169     keywords(arguments, $constructor = buffer_mode, $doc = null);
1170     var constructor = arguments.$constructor;
1171     var m = new constructor(name, enable, disable, forward_keywords(arguments));
1172     name = m.name; // normalized
1173     conkeror[name] = m;
1174     define_buffer_local_hook(m.enable_hook);
1175     define_buffer_local_hook(m.disable_hook);
1176     interactive(m.hyphen_name,
1177         arguments.$doc,
1178         function (I) {
1179             var enabledp = (I.buffer.enabled_modes.indexOf(name) > -1);
1180             if (enabledp)
1181                 m.disable(I.buffer);
1182             else
1183                 m.enable(I.buffer);
1184             I.minibuffer.message(m.hyphen_name + (enabledp ? " disabled" : " enabled"));
1185         });
1187 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
1191  * Mode Display in Minibuffer
1192  */
1194 function minibuffer_mode_indicator (window) {
1195     this.window = window;
1196     var element = create_XUL(window, "label");
1197     element.setAttribute("id", "minibuffer-mode-indicator");
1198     element.setAttribute("class", "mode-text-widget");
1199     window.document.getElementById("minibuffer").appendChild(element);
1200     this.element = element;
1201     this.hook_function = method_caller(this, this.update);
1202     add_hook.call(window, "select_buffer_hook", this.hook_function);
1203     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_function);
1204     this.update();
1206 minibuffer_mode_indicator.prototype = {
1207     constructor: minibuffer_mode_indicator,
1208     window: null,
1209     element: null,
1210     hook_function: null,
1211     update: function () {
1212         var buffer = this.window.buffers.current;
1213         var str = buffer.enabled_modes.map(
1214             function (x) {
1215                 return (conkeror[x].display_name || null);
1216             }).filter(function (x) x != null).join(" ");
1217         this.element.value = str;
1218     },
1219     uninstall: function () {
1220         remove_hook.call(this.window, "select_buffer_hook", this.hook_function);
1221         remove_hook.call(this.window, "current_buffer_mode_change_hook", this.hook_function);
1222         this.element.parentNode.removeChild(this.element);
1223     }
1225 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
1226 minibuffer_mode_indicator_mode(true);
1230  * minibuffer-keymaps-display
1231  */
1232 function minibuffer_keymaps_display_update (buffer) {
1233     var element = buffer.window.document
1234         .getElementById("keymaps-display");
1235     if (element) {
1236         var str = buffer.keymaps.reduce(
1237             function (acc, kmap) {
1238                 if (kmap.display_name)
1239                     acc.push(kmap.display_name);
1240                 return acc;
1241             }, []).join("/");
1242         if (element.value != str)
1243             element.value = str;
1244     }
1247 function minibuffer_keymaps_display_initialize (window) {
1248     var element = create_XUL(window, "label");
1249     element.setAttribute("id", "keymaps-display");
1250     element.setAttribute("class", "mode-text-widget");
1251     element.setAttribute("value", "");
1252     var mb = window.document.getElementById("minibuffer");
1253     mb.appendChild(element);
1256 define_global_mode("minibuffer_keymaps_display_mode",
1257     function enable () {
1258         add_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1259         add_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1260         for_each_window(minibuffer_keymaps_display_initialize);
1261     },
1262     function disable () {
1263         remove_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1264         remove_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1265         for_each_window(function (w) {
1266             var element = w.document
1267                 .getElementById("keymaps-display");
1268             if (element)
1269                 element.parentNode.removeChild(element);
1270         });
1271     });
1273 minibuffer_keymaps_display_mode(true);
1277  * minibuffer-keymaps-highlight
1278  */
1279 function minibuffer_keymaps_highlight_update (buffer) {
1280     var mb = buffer.window.document.getElementById("minibuffer");
1281     if (buffer.keymaps.some(function (k) k.notify))
1282         dom_add_class(mb, "highlight");
1283     else
1284         dom_remove_class(mb, "highlight");
1287 define_global_mode("minibuffer_keymaps_highlight_mode",
1288     function enable () {
1289         add_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1290     },
1291     function disable () {
1292         remove_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1293         for_each_window(function (w) {
1294             var mb = w.document.getElementById("minibuffer");
1295             if (mb)
1296                 dom_remove_class("highlight");
1297         });
1298     });
1300 minibuffer_keymaps_highlight_mode(true);
1303 provide("buffer");