tab_bar.prototype.destroy delete window.tab_bar.
[conkeror.git] / modules / buffer.js
blob8a70bf859fc4fb28cb9771f267b7cbf979e94dac
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2010 John J. Foerch
4  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
5  *
6  * Use, modification, and distribution are subject to the terms specified in the
7  * COPYING file.
8 **/
10 in_module(null);
12 var define_buffer_local_hook = local_hook_definer("window");
14 function define_current_buffer_hook (hook_name, existing_hook) {
15     define_buffer_local_hook(hook_name);
16     add_hook(existing_hook, function (buffer) {
17             if (!buffer.window.buffers || buffer != buffer.window.buffers.current)
18                 return;
19             var hook = conkeror[hook_name];
20             hook.run.apply(hook, Array.prototype.slice.call(arguments));
21         });
24 define_buffer_local_hook("buffer_title_change_hook");
25 define_buffer_local_hook("buffer_description_change_hook");
26 define_buffer_local_hook("buffer_icon_change_hook");
27 define_buffer_local_hook("select_buffer_hook");
28 define_buffer_local_hook("create_buffer_early_hook");
29 define_buffer_local_hook("create_buffer_late_hook");
30 define_buffer_local_hook("create_buffer_hook");
31 define_buffer_local_hook("kill_buffer_hook");
32 define_buffer_local_hook("buffer_scroll_hook");
33 define_buffer_local_hook("buffer_dom_content_loaded_hook");
34 define_buffer_local_hook("buffer_loaded_hook");
35 define_buffer_local_hook("set_input_mode_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");
44 define_keywords("$opener");
45 function buffer_creator (type) {
46     var args = forward_keywords(arguments);
47     return function (window) {
48         return new type(window, args);
49     };
52 define_variable("allow_browser_window_close", true,
53     "If this is set to true, if a content buffer page calls " +
54     "window.close() from JavaScript and is not prevented by the " +
55     "normal Mozilla mechanism that restricts pages from closing " +
56     "a window that was not opened by a script, the buffer will be " +
57     "killed, deleting the window as well if it is the only buffer.");
59 function buffer_modality (buffer) {
60     buffer.keymaps.push(default_global_keymap);
63 function buffer (window) {
64     this.constructor_begin();
65     keywords(arguments);
66     this.opener = arguments.$opener;
67     this.window = window;
68     var element = create_XUL(window, "vbox");
69     element.setAttribute("flex", "1");
70     var browser = create_XUL(window, "browser");
71     if (window.buffers.count == 0)
72         browser.setAttribute("type", "content-primary");
73     else
74         browser.setAttribute("type", "content");
75     browser.setAttribute("flex", "1");
76     browser.setAttribute("autocompletepopup", "popup_autocomplete");
77     element.appendChild(browser);
78     this.window.buffers.container.appendChild(element);
79     this.window.buffers.buffer_list.push(this);
80     this.element = element;
81     this.browser = element.firstChild;
82     this.element.conkeror_buffer_object = this;
84     this.local = { __proto__: conkeror };
85     this.page = null;
86     this.enabled_modes = [];
87     this.default_browser_object_classes = {};
89     var buffer = this;
91     this.browser.addEventListener("scroll", function (event) {
92             buffer_scroll_hook.run(buffer);
93         }, true /* capture */);
95     this.browser.addEventListener("DOMContentLoaded", function (event) {
96             buffer_dom_content_loaded_hook.run(buffer);
97         }, true /* capture */);
99     this.window.setTimeout(function() { create_buffer_late_hook.run(buffer); }, 0);
101     this.browser.addEventListener("load", function (event) {
102             buffer_loaded_hook.run(buffer);
103         }, true /* capture */);
105     this.browser.addEventListener("DOMWindowClose", function (event) {
106             /* This call to preventDefault is very important; without
107              * it, somehow Mozilla does something bad and as a result
108              * the window loses focus, causing keyboard commands to
109              * stop working. */
110             event.preventDefault();
112             if (allow_browser_window_close)
113                 kill_buffer(buffer, true);
114         }, true);
116     this.browser.addEventListener("focus", function (event) {
117         if (buffer.focusblocker &&
118             event.target instanceof Ci.nsIDOMHTMLElement &&
119             buffer.focusblocker(buffer, event))
120         {
121             event.target.blur();
122         } else
123             buffer.set_input_mode();
124     }, true);
126     this.browser.addEventListener("blur", function (event) {
127         buffer.set_input_mode();
128     }, true);
130     this.modalities = [buffer_modality];
132     // When create_buffer_hook_early runs, basic buffer properties
133     // will be available, but not the properties subclasses.
134     create_buffer_early_hook.run(this);
136     this.constructor_end();
138 buffer.prototype = {
139     constructor: buffer,
141     /* Saved focus state */
142     saved_focused_frame: null,
143     saved_focused_element: null,
145     // get title ()   [must be defined by subclasses]
146     // get name ()    [must be defined by subclasses]
147     dead: false, /* This is set when the buffer is killed */
149     keymaps: null,
150     mark_active: false,
152     // The property focusblocker is available for an external module to
153     // put a function on which takes a buffer as its argument and returns
154     // true to block a focus event, or false to let normal processing
155     // occur.  Having this one property explicitly handled by the buffer
156     // class allows for otherwise modular focus-blockers.
157     focusblocker: null,
159     // icon is a string url of an icon to use for this buffer.  Setting it
160     // causes buffer_icon_change_hook to be run.
161     _icon: null,
162     get icon () this._icon,
163     set icon (x) {
164         if (this._icon != x) {
165             this._icon = x;
166             buffer_icon_change_hook.run(this);
167         }
168     },
170     default_message: "",
172     set_default_message: function (str) {
173         this.default_message = str;
174         if (this == this.window.buffers.current)
175             this.window.minibuffer.set_default_message(str);
176     },
178     constructors_running: 0,
180     constructor_begin: function () {
181         this.constructors_running++;
182     },
184     constructor_end: function () {
185         if (--this.constructors_running == 0) {
186             create_buffer_hook.run(this);
187             this.set_input_mode();
188             delete this.opener;
189         }
190     },
192     destroy: function () {
193         this.dead = true;
194         this.browser = null;
195         this.element = null;
196         this.saved_focused_frame = null;
197         this.saved_focused_element = null;
198         // prevent modalities from accessing dead browser
199         this.modalities = [];
200     },
202     set_input_mode: function () {
203         if (this != this.window.buffers.current)
204             return;
205         this.keymaps = [];
206         this.modalities.map(function (m) m(this), this);
207         set_input_mode_hook.run(this);
208     },
210     override_keymaps: function (keymaps) {
211         if (keymaps) {
212             this.keymaps = keymaps;
213             this.set_input_mode = function () {
214                 set_input_mode_hook.run(this);
215             };
216         } else
217             delete this.set_input_mode;
218         this.set_input_mode();
219     },
221     /* Browser accessors */
222     get top_frame () { return this.browser.contentWindow; },
223     get document () { return this.browser.contentDocument; },
224     get web_navigation () { return this.browser.webNavigation; },
225     get doc_shell () { return this.browser.docShell; },
226     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
227     get current_uri () { return this.browser.currentURI; },
229     is_child_element: function (element) {
230         return (element && this.is_child_frame(element.ownerDocument.defaultView));
231     },
233     is_child_frame: function (frame) {
234         return (frame && frame.top == this.top_frame);
235     },
237     // This method is like focused_frame, except that if no content
238     // frame actually has focus, this returns null.
239     get focused_frame_or_null () {
240         var frame = this.window.document.commandDispatcher.focusedWindow;
241         if (this.is_child_frame(frame))
242             return frame;
243         return null;
244     },
246     get focused_frame () {
247         var frame = this.window.document.commandDispatcher.focusedWindow;
248         if (this.is_child_frame(frame))
249             return frame;
250         return this.top_frame;
251     },
253     get focused_element () {
254         var element = this.window.document.commandDispatcher.focusedElement;
255         if (this.is_child_element(element))
256             return element;
257         return null;
258     },
260     get focused_selection_controller () {
261         return this.focused_frame
262             .QueryInterface(Ci.nsIInterfaceRequestor)
263             .getInterface(Ci.nsIWebNavigation)
264             .QueryInterface(Ci.nsIInterfaceRequestor)
265             .getInterface(Ci.nsISelectionDisplay)
266             .QueryInterface(Ci.nsISelectionController);
267     },
269     do_command: function (command) {
270         function attempt_command (element, command) {
271             var controller;
272             if (element.controllers
273                 && (controller = element.controllers.getControllerForCommand(command)) != null
274                 && controller.isCommandEnabled(command))
275             {
276                 controller.doCommand(command);
277                 return true;
278             }
279             return false;
280         }
282         var element = this.focused_element;
283         if (element && attempt_command(element, command))
284             return;
285         var win = this.focused_frame;
286         while (true) {
287             if (attempt_command(win, command))
288                 return;
289             if (!win.parent || win == win.parent)
290                 break;
291             win = win.parent;
292         }
293     }
296 function with_current_buffer (buffer, callback) {
297     return callback(new interactive_context(buffer));
300 function check_buffer (obj, type) {
301     if (!(obj instanceof type))
302         throw interactive_error("Buffer has invalid type.");
303     if (obj.dead)
304         throw interactive_error("Buffer has already been killed.");
305     return obj;
308 function caret_enabled (buffer) {
309     return buffer.browser.getAttribute('showcaret');
312 function clear_selection (buffer) {
313     let sel_ctrl = buffer.focused_selection_controller;
314     if (sel_ctrl) {
315         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
316         if (caret_enabled(buffer)) {
317             if (sel.anchorNode)
318                 sel.collapseToStart();
319         } else {
320             sel.removeAllRanges();
321         }
322     }
326 function buffer_container (window, create_initial_buffer) {
327     this.window = window;
328     this.container = window.document.getElementById("buffer-container");
329     this.buffer_list = [];
330     window.buffers = this;
331     create_initial_buffer(window);
333 buffer_container.prototype = {
334     constructor: buffer_container,
336     get current () {
337         return this.container.selectedPanel.conkeror_buffer_object;
338     },
340     set current (buffer) {
341         var old_value = this.current;
342         if (old_value == buffer)
343             return;
345         this.buffer_list.splice(this.buffer_list.indexOf(buffer), 1);
346         this.buffer_list.unshift(buffer);
348         this._switch_away_from(this.current);
349         this._switch_to(buffer);
351         // Run hooks
352         select_buffer_hook.run(buffer);
353     },
355     _switch_away_from: function (old_value) {
356         // Save focus state
357         old_value.saved_focused_frame = old_value.focused_frame;
358         old_value.saved_focused_element = old_value.focused_element;
360         old_value.browser.setAttribute("type", "content");
361     },
363     _switch_to: function (buffer) {
364         // Select new buffer in the XUL deck
365         this.container.selectedPanel = buffer.element;
367         buffer.browser.setAttribute("type", "content-primary");
369         /**
370          * This next focus call seems to be needed to avoid focus
371          * somehow getting lost (and the keypress handler therefore
372          * not getting called at all) when killing buffers.
373          */
374         this.window.focus();
376         // Restore focus state
377         buffer.browser.focus();
378         if (buffer.saved_focused_element)
379             set_focus_no_scroll(this.window, buffer.saved_focused_element);
380         else if (buffer.saved_focused_frame)
381             set_focus_no_scroll(this.window, buffer.saved_focused_frame);
383         buffer.saved_focused_element = null;
384         buffer.saved_focused_frame = null;
386         buffer.set_input_mode();
388         this.window.minibuffer.set_default_message(buffer.default_message);
389     },
391     get count () {
392         return this.container.childNodes.length;
393     },
395     get_buffer: function (index) {
396         if (index >= 0 && index < this.count)
397             return this.container.childNodes.item(index).conkeror_buffer_object;
398         return null;
399     },
401     get selected_index () {
402         var nodes = this.container.childNodes;
403         var count = nodes.length;
404         for (var i = 0; i < count; ++i)
405             if (nodes.item(i) == this.container.selectedPanel)
406                 return i;
407         return null;
408     },
410     index_of: function (b) {
411         var nodes = this.container.childNodes;
412         var count = nodes.length;
413         for (var i = 0; i < count; ++i)
414             if (nodes.item(i) == b.element)
415                 return i;
416         return null;
417     },
419     get unique_name_list () {
420         var existing_names = new string_hashset();
421         var bufs = [];
422         this.for_each(function(b) {
423                 var base_name = b.name;
424                 var name = base_name;
425                 var index = 1;
426                 while (existing_names.contains(name)) {
427                     ++index;
428                     name = base_name + "<" + index + ">";
429                 }
430                 existing_names.add(name);
431                 bufs.push([name, b]);
432             });
433         return bufs;
434     },
436     kill_buffer: function (b) {
437         if (b.dead)
438             return true;
439         var count = this.count;
440         if (count <= 1)
441             return false;
442         var new_buffer = this.buffer_list[0];
443         var changed = false;
444         if (b == new_buffer) {
445             new_buffer = this.buffer_list[1];
446             changed = true;
447         }
448         this._switch_away_from(this.current);
449         // The removeChild call below may trigger events in progress
450         // listeners.  This call to `destroy' gives buffer subclasses a
451         // chance to remove such listeners, so that they cannot try to
452         // perform UI actions based upon a xul:browser that no longer
453         // exists.
454         var element = b.element;
455         b.destroy();
456         this.container.removeChild(element);
457         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
458         this._switch_to(new_buffer);
459         if (changed) {
460             select_buffer_hook.run(new_buffer);
461             this.buffer_list.splice(this.buffer_list.indexOf(new_buffer), 1);
462             this.buffer_list.unshift(new_buffer);
463         }
464         kill_buffer_hook.run(b);
465         return true;
466     },
468     bury_buffer: function (b) {
469         var new_buffer = this.buffer_list[0];
470         if (b == new_buffer)
471             new_buffer = this.buffer_list[1];
472         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
473         this.buffer_list.push(b);
474         this.current = new_buffer;
475         return true;
476     },
478     for_each: function (f) {
479         var count = this.count;
480         for (var i = 0; i < count; ++i)
481             f(this.get_buffer(i));
482     }
485 function buffer_initialize_window_early (window) {
486     /**
487      * Use content_buffer by default to handle an unusual case where
488      * browser.chromeURI is used perhaps.  In general this default
489      * should not be needed.
490      */
491     var create_initial_buffer =
492         window.args.initial_buffer_creator || buffer_creator(content_buffer);
493     new buffer_container(window, create_initial_buffer);
496 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
499 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
500 function buffer_before_window_close (window) {
501     var bs = window.buffers;
502     var count = bs.count;
503     for (let i = 0; i < count; ++i) {
504         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
505             return false;
506     }
507     return true;
509 add_hook("window_before_close_hook", buffer_before_window_close);
511 function buffer_window_close_handler (window) {
512     var bs = window.buffers;
513     var count = bs.count;
514     for (let i = 0; i < count; ++i) {
515         let b = bs.get_buffer(i);
516         b.destroy();
517     }
519 add_hook("window_close_hook", buffer_window_close_handler);
521 /* open/follow targets */
522 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
523                                // buffer is a content_buffer.
524 const OPEN_NEW_BUFFER = 1;
525 const OPEN_NEW_BUFFER_BACKGROUND = 2;
526 const OPEN_NEW_WINDOW = 3;
528 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
529 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
531 var TARGET_PROMPTS = [" in current buffer",
532                       " in new buffer",
533                       " in new buffer (background)",
534                       " in new window",
535                       "",
536                       " in current frame"];
538 var TARGET_NAMES = ["current buffer",
539                     "new buffer",
540                     "new buffer (background)",
541                     "new window",
542                     "default",
543                     "current frame"];
546 function create_buffer (window, creator, target) {
547     switch (target) {
548     case OPEN_NEW_BUFFER:
549         window.buffers.current = creator(window, null);
550         break;
551     case OPEN_NEW_BUFFER_BACKGROUND:
552         creator(window, null);
553         break;
554     case OPEN_NEW_WINDOW:
555         make_window(creator);
556         break;
557     default:
558         throw new Error("invalid target");
559     }
562 let (queued_buffer_creators = null) {
563     function create_buffer_in_current_window (creator, target, focus_existing) {
564         function process_queued_buffer_creators (window) {
565             for (var i = 0; i < queued_buffer_creators.length; ++i) {
566                 var x = queued_buffer_creators[i];
567                 create_buffer(window, x[0], x[1]);
568             }
569             queued_buffer_creators = null;
570         }
572         if (target == OPEN_NEW_WINDOW)
573             throw new Error("invalid target");
574         var window = get_recent_conkeror_window();
575         if (window) {
576             if (focus_existing)
577                 window.focus();
578             create_buffer(window, creator, target);
579         } else if (queued_buffer_creators != null) {
580             queued_buffer_creators.push([creator,target]);
581         } else {
582             queued_buffer_creators = [];
583             window = make_window(creator);
584             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
585         }
586     }
591  * Read Buffer
592  */
593 define_variable("read_buffer_show_icons", false,
594     "Boolean which says whether read_buffer should show buffer "+
595     "icons in the completions list.\nNote, setting this variable "+
596     "alone does not cause favicons or other kinds of icons to be "+
597     "fetched.  For that, load the `favicon' (or similar other) "+
598     "library.");
600 minibuffer_auto_complete_preferences["buffer"] = true;
601 define_keywords("$default");
602 minibuffer.prototype.read_buffer = function () {
603     var window = this.window;
604     var buffer = this.window.buffers.current;
605     keywords(arguments, $prompt = "Buffer:",
606              $default = buffer,
607              $history = "buffer");
608     var completer = all_word_completer(
609         $completions = function (visitor) window.buffers.for_each(visitor),
610         $get_string = function (x) x.description,
611         $get_description = function (x) x.title,
612         $get_icon = (read_buffer_show_icons ?
613                      function (x) x.icon : null));
614     var result = yield this.read(
615         $keymap = read_buffer_keymap,
616         $prompt = arguments.$prompt,
617         $history = arguments.$history,
618         $completer = completer,
619         $enable_icons = read_buffer_show_icons,
620         $match_required = true,
621         $auto_complete = "buffer",
622         $auto_complete_initial = true,
623         $auto_complete_delay = 0,
624         $default_completion = arguments.$default);
625     yield co_return(result);
629 function buffer_next (window, count) {
630     var index = window.buffers.selected_index;
631     var total = window.buffers.count;
632     if (total == 1)
633         throw new interactive_error("No other buffer");
634     index = (index + count) % total;
635     if (index < 0)
636         index += total;
637     window.buffers.current = window.buffers.get_buffer(index);
639 interactive("buffer-next",
640     "Switch to the next buffer.",
641     function (I) { buffer_next(I.window, I.p); });
642 interactive("buffer-previous",
643     "Switch to the previous buffer.",
644     function (I) { buffer_next(I.window, -I.p); });
646 function switch_to_buffer (window, buffer) {
647     if (buffer && !buffer.dead)
648         window.buffers.current = buffer;
650 interactive("switch-to-buffer",
651     "Switch to a buffer specified in the minibuffer.",
652     function (I) {
653         switch_to_buffer(
654             I.window,
655             (yield I.minibuffer.read_buffer(
656                 $prompt = "Switch to buffer:",
657                 $default = (I.window.buffers.count > 1 ?
658                             I.window.buffers.buffer_list[1] :
659                             I.buffer))));
660     });
662 define_variable("can_kill_last_buffer", true,
663     "If this is set to true, kill-buffer can kill the last "+
664     "remaining buffer, and close the window.");
666 function kill_other_buffers (buffer) {
667     if (!buffer)
668         return;
669     var bs = buffer.window.buffers;
670     var b;
671     while ((b = bs.get_buffer(0)) != buffer)
672         bs.kill_buffer(b);
673     var count = bs.count;
674     while (--count)
675         bs.kill_buffer(bs.get_buffer(1));
677 interactive("kill-other-buffers",
678     "Kill all buffers except current one.\n",
679     function (I) { kill_other_buffers(I.buffer); });
682 function kill_buffer (buffer, force) {
683     if (!buffer)
684         return;
685     var buffers = buffer.window.buffers;
686     if (buffers.count == 1 && buffer == buffers.current) {
687         if (can_kill_last_buffer || force) {
688             delete_window(buffer.window);
689             return;
690         } else
691             throw interactive_error("Can't kill last buffer.");
692     }
693     buffers.kill_buffer(buffer);
695 interactive("kill-buffer",
696     "Kill a buffer specified in the minibuffer.\n" +
697     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
698     "last remaining buffer in a window will cause the window to be closed.",
699     function (I) {
700         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
701     });
703 interactive("kill-current-buffer",
704     "Kill the current buffer.\n" +
705     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
706     "last remaining buffer in a window will cause the window to be closed.",
707     function (I) { kill_buffer(I.buffer); });
709 interactive("read-buffer-kill-buffer",
710     "Kill the current selected buffer in the completions list "+
711     "in a read buffer minibuffer interaction.",
712     function (I) {
713         var s = I.window.minibuffer.current_state;
714         var i = s.selected_completion_index;
715         var c = s.completions;
716         if (i == -1)
717             return;
718         kill_buffer(c.get_value(i));
719         s.completer.refresh();
720         s.handle_input(I.window.minibuffer);
721     });
723 interactive("bury-buffer",
724     "Bury the current buffer.\n Put the current buffer at the end of " +
725     "the buffer list, so that it is the least likely buffer to be " +
726     "selected by `switch-to-buffer'.",
727     function (I) { I.window.buffers.bury_buffer(I.buffer); });
729 function change_directory (buffer, dir) {
730     if (buffer.page != null)
731         delete buffer.page.local.cwd;
732     buffer.local.cwd = make_file(dir);
734 interactive("change-directory",
735     "Change the current directory of the selected buffer.",
736     function (I) {
737         change_directory(
738             I.buffer,
739             (yield I.minibuffer.read_existing_directory_path(
740                 $prompt = "Change to directory:",
741                 $initial_value = make_file(I.local.cwd).path)));
742     });
744 interactive("shell-command", null,
745     function (I) {
746         var cwd = I.local.cwd;
747         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
748         yield shell_command(cmd, $cwd = cwd);
749     });
753  * selection_is_embed_p is used to test whether the unfocus command can
754  * unfocus an element, even though there is a selection.  This happens
755  * when the focused element is an html:embed.
756  */
757 function selection_is_embed_p (sel, focused_element) {
758     if (sel.rangeCount == 1) {
759         try {
760             var r = sel.getRangeAt(0);
761             var a = r.startContainer.childNodes[r.startOffset];
762             if ((a instanceof Ci.nsIDOMHTMLEmbedElement ||
763                  a instanceof Ci.nsIDOMHTMLObjectElement) &&
764                 a == focused_element)
765             {
766                 return true;
767             }
768         } catch (e) {}
769     }
770     return false;
774  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
775  * frames, iframes, plugins, and also clearing the selection.
776  */
777 define_buffer_local_hook("unfocus_hook");
778 function unfocus (window, buffer) {
779     // 1. if there is a selection, clear it.
780     var selc = buffer.focused_selection_controller;
781     if (selc) {
782         var sel = selc.getSelection(selc.SELECTION_NORMAL);
783         var active = ! sel.isCollapsed;
784         var embed_p = selection_is_embed_p(sel, buffer.focused_element);
785         clear_selection(buffer);
786         if (active && !embed_p) {
787             window.minibuffer.message("cleared selection");
788             return;
789         }
790     }
791     // 2. if there is a focused element, unfocus it.
792     if (buffer.focused_element) {
793         buffer.focused_element.blur();
794         // if an element in a detached fragment has focus, blur() will
795         // not work, and we need to take more drastic measures.  the
796         // action taken was found through experiment, so it is possibly
797         // not the most concise way to unfocus such an element.
798         if (buffer.focused_element) {
799             buffer.element.focus();
800             buffer.top_frame.focus();
801         }
802         window.minibuffer.message("unfocused element");
803         return;
804     }
805     // 3. if an iframe has focus, we must blur it.
806     if (buffer.focused_frame_or_null &&
807         buffer.focused_frame_or_null.frameElement)
808     {
809         buffer.focused_frame_or_null.frameElement.blur();
810     }
811     // 4. return focus to top-frame from subframes and plugins.
812     buffer.top_frame.focus();
813     buffer.top_frame.focus(); // needed to get focus back from plugins
814     window.minibuffer.message("refocused top frame");
815     // give page-modes an opportunity to set focus specially
816     unfocus_hook.run(buffer);
818 interactive("unfocus",
819     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
820     "frames, iframes, plugins, and also for clearing the selection.\n"+
821     "The action that it takes is based on precedence.  If there is a "+
822     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
823     "there is a selection, it will clear the selection.  Otherwise, it "+
824     "will return focus to the top frame from a focused frame, iframe, "+
825     "or plugin.  In the case of plugins, since they steal keyboard "+
826     "control away from Conkeror, the normal way to unfocus them is "+
827     "to use command-line remoting externally: conkeror -batch -f "+
828     "unfocus.  Page-modes also have an opportunity to alter the default"+
829     "focus via the hook, `focus_hook'.",
830     function (I) {
831         unfocus(I.window, I.buffer);
832     });
835 function for_each_buffer (f) {
836     for_each_window(function (w) { w.buffers.for_each(f); });
841  * BUFFER MODES
842  */
844 var mode_functions = {};
845 var mode_display_names = {};
847 define_buffer_local_hook("buffer_mode_change_hook");
848 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
850 define_keywords("$display_name", "$class", "$enable", "$disable", "$doc");
851 function define_buffer_mode (name) {
852     keywords(arguments);
854     var hyphen_name = name.replace("_","-","g");
855     var display_name = arguments.$display_name;
856     var mode_class = arguments.$class;
857     var enable = arguments.$enable;
858     var disable = arguments.$disable;
860     mode_display_names[name] = display_name;
862     var can_disable;
864     if (disable == false) {
865         can_disable = false;
866         disable = null;
867     } else
868         can_disable = true;
870     var state = (mode_class != null) ? mode_class : (name + "_enabled");
871     var enable_hook_name = name + "_enable_hook";
872     var disable_hook_name = name + "_disable_hook";
873     define_buffer_local_hook(enable_hook_name);
874     define_buffer_local_hook(disable_hook_name);
876     var change_hook_name = null;
878     if (mode_class) {
879         mode_functions[name] = { enable: enable,
880                                  disable: disable,
881                                  mode_class: mode_class,
882                                  disable_hook_name: disable_hook_name };
883         change_hook_name = mode_class + "_change_hook";
884         define_buffer_local_hook(change_hook_name);
885     }
887     function func (buffer, arg) {
888         var old_state = buffer[state];
889         var cur_state = (old_state == name);
890         var new_state = (arg == null) ? !cur_state : (arg > 0);
891         if ((new_state == cur_state) || (!can_disable && !new_state))
892             // perhaps show a message if (!can_disable && !new_state)
893             // to tell the user that this mode cannot be disabled.  do
894             // we have any existing modes that would benefit by it?
895             return null;
896         if (new_state) {
897             if (mode_class && old_state != null)  {
898                 // Another buffer-mode of our same mode-class is
899                 // enabled.  Buffer-modes within a mode-class are
900                 // mutually exclusive, so turn the old one off.
901                 buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(old_state), 1);
902                 let x = mode_functions[old_state];
903                 let y = x.disable;
904                 if (y) y(buffer);
905                 conkeror[x.disable_hook_name].run(buffer);
906             }
907             buffer[state] = name;
908             if (enable)
909                 enable(buffer);
910             conkeror[enable_hook_name].run(buffer);
911             buffer.enabled_modes.push(name);
912         } else {
913             buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(name), 1);
914             disable(buffer);
915             conkeror[disable_hook_name].run(buffer);
916             buffer[state] = null;
917         }
918         if (change_hook_name)
919             conkeror[change_hook_name].run(buffer, buffer[state]);
920         buffer_mode_change_hook.run(buffer);
921         return new_state;
922     }
924     conkeror[name] = func;
925     interactive(hyphen_name, arguments.$doc, function (I) {
926         var arg = I.P;
927         var new_state = func(I.buffer, arg && univ_arg_to_number(arg));
928         I.minibuffer.message(hyphen_name + (new_state ? " enabled" : " disabled"));
929     });
931 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
934 function minibuffer_mode_indicator (window) {
935     this.window = window;
936     var element = create_XUL(window, "label");
937     element.setAttribute("id", "minibuffer-mode-indicator");
938     element.setAttribute("class", "mode-text-widget");
939     window.document.getElementById("minibuffer").appendChild(element);
940     this.element = element;
941     this.hook_func = method_caller(this, this.update);
942     add_hook.call(window, "select_buffer_hook", this.hook_func);
943     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_func);
944     this.update();
946 minibuffer_mode_indicator.prototype = {
947     constructor: minibuffer_mode_indicator,
948     update: function () {
949         var buf = this.window.buffers.current;
950         var modes = buf.enabled_modes;
951         var str = modes.map(
952             function (x) {
953                 let y = mode_display_names[x];
954                 if (y)
955                     return y;
956                 else
957                     return null;
958             }).filter(function (x) x != null).join(" ");
959         this.element.value = str;
960     },
961     uninstall: function () {
962         remove_hook.call(this.window, "select_buffer_hook", this.hook_fun);
963         remove_hook.call(this.window, "current_buffer_mode_change_hook", this.hook_fun);
964         this.element.parentNode.removeChild(this.element);
965     }
967 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
968 minibuffer_mode_indicator_mode(true);
972  * minibuffer-keymaps-display
973  */
974 function minibuffer_keymaps_display_update (buffer) {
975     var element = buffer.window.document
976         .getElementById("keymaps-display");
977     if (element) {
978         var str = buffer.keymaps.reduce(
979             function (acc, kmap) {
980                 if (kmap.display_name)
981                     acc.push(kmap.display_name);
982                 return acc;
983             }, []).join("/");
984         if (element.value != str)
985             element.value = str;
986     }
989 function minibuffer_keymaps_display_initialize (window) {
990     var element = create_XUL(window, "label");
991     element.setAttribute("id", "keymaps-display");
992     element.setAttribute("class", "mode-text-widget");
993     element.setAttribute("value", "");
994     var mb = window.document.getElementById("minibuffer");
995     mb.appendChild(element);
998 define_global_mode("minibuffer_keymaps_display_mode",
999     function enable () {
1000         add_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1001         add_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1002         for_each_window(minibuffer_keymaps_display_initialize);
1003     },
1004     function disable () {
1005         remove_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1006         remove_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1007         for_each_window(function (w) {
1008             var element = w.document
1009                 .getElementById("keymaps-display");
1010             if (element)
1011                 element.parentNode.removeChild(element);
1012         });
1013     });
1015 minibuffer_keymaps_display_mode(true);
1019  * minibuffer-keymaps-highlight
1020  */
1021 function minibuffer_keymaps_highlight_update (buffer) {
1022     var mb = buffer.window.document.getElementById("minibuffer");
1023     if (buffer.keymaps.some(function (k) k.notify))
1024         dom_add_class(mb, "highlight");
1025     else
1026         dom_remove_class(mb, "highlight");
1029 define_global_mode("minibuffer_keymaps_highlight_mode",
1030     function enable () {
1031         add_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1032     },
1033     function disable () {
1034         remove_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1035         for_each_window(function (w) {
1036             var mb = w.document.getElementById("minibuffer");
1037             if (mb)
1038                 dom_remove_class("highlight");
1039         });
1040     });
1042 minibuffer_keymaps_highlight_mode(true);
1045 provide("buffer");