window.js: More reliably ensure that window.close() is intercepted so that hooks...
[conkeror.git] / modules / window.js
blob1837e61f79e17dc667e547086bd03e4e73de7bbd
1 /**
2  * (C) Copyright 2007 John J. Foerch
3  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
4  *
5  * Use, modification, and distribution are subject to the terms specified in the
6  * COPYING file.
7 **/
9 require("mode.js");
11 var define_window_local_hook = simple_local_hook_definer();
12 var define_window_local_coroutine_hook = simple_local_coroutine_hook_definer();
15 define_hook("make_window_hook");
17 var window_watcher = Cc["@mozilla.org/embedcomp/window-watcher;1"]
18     .getService(Ci.nsIWindowWatcher);
20 function generate_new_window_tag (tag) {
21     var existing = [];
22     var exact_match = false;
23     var en = window_watcher.getWindowEnumerator();
24     if (tag == '')
25         tag = null;
26     var re;
27     if (tag)
28         re = new RegExp ("^" + tag + "<(\\d+)>$");
29     else
30         re = new RegExp ("^(\\d+)$");
31     while (en.hasMoreElements()) {
32         var w = en.getNext().QueryInterface(Ci.nsIDOMWindow);
33         if ('tag' in w)  {
34             if (tag && w.tag == tag) {
35                 exact_match = true;
36                 continue;
37             }
38             var re_result = re.exec(w.tag);
39             if (re_result)
40                 existing.push(re_result[1]);
41         }
42     }
43     if (tag && ! exact_match)
44         return tag;
46     existing.sort(function (a, b) { return a - b; });
48     var n = 1;
49     for (var i = 0; i < existing.length; i++) {
50         if (existing[i] < n) continue;
51         if (existing[i] == n) { n++; continue; }
52         break;
53     }
54     if (tag)
55         return tag + "<" + n + ">";
56     else
57         return n;
60 function make_chrome_window (chrome_uri, args) {
61     return window_watcher.openWindow(null, chrome_uri, "_blank",
62                                      "chrome,dialog=no,all,resizable", args);
65 var conkeror_chrome_uri = "chrome://conkeror-gui/content/conkeror.xul";
67 /**
68  * This is called by Conkeror to explicitly create a conkeror.xul window.
69  * However, windows are sometimes created internally be Mozilla, for example due
70  * to the logic in content-buffer.js:browser_dom_window.openURI.  In that case,
71  * make_window is not called and Conkeror sees the window for the first time in
72  * window_initialize, which needs to take care of all of the initialization that
73  * would normally happen in make_window.
74  **/
75 function make_window (initial_buffer_creator, tag) {
76     var args = { tag: tag,
77                  initial_buffer_creator: initial_buffer_creator };
78     var result = make_chrome_window(conkeror_chrome_uri, null);
79     result.args = args;
80     make_window_hook.run(result);
81     window_install_close_intercept(result);
82     return result;
85 function window_install_close_intercept (window) {
86     var close = window.close;
87     window.close = function () {
88         function attempt_close () {
89             var res = yield window_before_close_hook.run(window);
90             if (res) {
91                 window_close_hook.run(window);
92                 close.call(window);
93             }
94         }
95         co_call(attempt_close());
96     };
99 function get_window_by_tag (tag) {
100     var en = window_watcher.getWindowEnumerator();
101     while (en.hasMoreElements()) {
102         var w = en.getNext().QueryInterface(Ci.nsIDOMWindow);
103         if ('tag' in w && w.tag == tag)
104             return w;
105     }
106     return null;
109 /* FIXME: decide if this should include not-fully-initialized windows  */
110 function for_each_window (func) {
111     var en = window_watcher.getWindowEnumerator();
112     while (en.hasMoreElements()) {
113         var w = en.getNext().QueryInterface(Ci.nsIDOMWindow);
114         if ('conkeror' in w)
115             func(w);
116     }
119 function get_recent_conkeror_window () {
120     var wm = Cc['@mozilla.org/appshell/window-mediator;1']
121        .getService(Ci.nsIWindowMediator);
122     var window = wm.getMostRecentWindow("navigator:browser");
123     if (window && ("conkeror" in window))
124         return window;
125     var en = window_watcher.getWindowEnumerator();
126     while (en.hasMoreElements()) {
127         window = en.getNext().QueryInterface(Ci.nsIDOMWindow);
128         if ('conkeror' in window)
129             return window;
130     }
131     return null;
134 define_window_local_hook("window_initialize_early_hook");
135 define_window_local_hook("window_initialize_hook");
136 define_window_local_hook("window_initialize_late_hook");
138 var window_extra_argument_list = [];
140 define_variable("window_extra_argument_max_delay", 100);
143  * Called by window_initialize.  If the window was created using make_window (as
144  * indicated by window.args having been set), nothing needs to be done.
145  * Otherwise, we need to perform the setup that would otherwise occur in
146  * make_window.
147  **/
148 function window_setup_args (window) {
149     if (window.args != null)
150         return;
152     window_install_close_intercept(window);
155     var cur_time = Date.now();
156     var i;
157     var result = null;
158     for (i = 0; i < window_extra_argument_list.length; ++i) {
159         var a = window_extra_argument_list[i];
160         if (a.time > cur_time - window_extra_argument_max_delay) {
161             delete a.time;
162             result = a;
163             i++;
164             break;
165         }
166     }
167     window_extra_argument_list = window_extra_argument_list.slice(i);
169     if (result == null)
170         window.args = {};
171     else
172         window.args = result;
175 function window_set_extra_arguments (args) {
176     args.time = Date.now();
177     window_extra_argument_list.push(args);
180 function window_get_this_browser () {
181     return this.buffers.current.browser;
184 function window_initialize (window) {
185     window.conkeror = conkeror;
187     // Used by get_window_from_frame to get an unwrapped window reference
188     window.escape_wrapper = function (x) { x(window); };
190     window_setup_args(window);
192     // Set tag
193     var tag = null;
194     if ('tag' in window.args)
195         tag = window.args.tag;
196     window.tag = generate_new_window_tag(tag);
198     // Add a getBrowser() and content to help certain extensions designed
199     // for Firefox work with conkeror
200     window.getBrowser = window_get_this_browser;
201     window.__defineGetter__('content',
202                             function () {
203                                 return this.buffers.current.browser.contentWindow;
204                             });
206     window_initialize_early_hook.run(window);
207     delete window.window_initialize_early_hook; // used only once
209     window_initialize_hook.run(window);
210     delete window.window_initialize_hook; // used only once
212     window.setTimeout(function () {
213             window_initialize_late_hook.run(window);
214             delete window.window_initialize_late_hook; // used only once
215             delete window.args; // get rid of args
216         }, 0);
218     window.addEventListener("close",
219                             function (event) {
220                                 event.preventDefault();
221                                 event.stopPropagation();
222                                 this.close();
223                             },
224                             true /* capture */);
227 define_window_local_coroutine_hook("window_before_close_hook",
228                                    RUN_HOOK_UNTIL_FAILURE);
229 define_window_local_hook("window_close_hook", RUN_HOOK);
232  * Window Modes
233  */
235 function define_global_window_mode (name, hook_name) {
236     keywords(arguments);
237     function install (window) {
238         if (name in window)
239             throw new Error(name + " already initialized for window");
240         window[name] = new conkeror[name](window);
241     }
242     function uninstall (window) {
243         if (!window[name])
244             throw new Error(name + " not initialized for window");
245         window[name].uninstall();
246         delete window[name];
247     }
248     define_global_mode(name + "_mode",
249                        function () { // enable
250                            add_hook(hook_name, install);
251                            for_each_window(install);
252                        },
253                        function () { // disable
254                            remove_hook(hook_name, install);
255                            for_each_window(uninstall);
256                        },
257                        forward_keywords(arguments));
259 ignore_function_for_get_caller_source_code_reference("define_global_window_mode");
264  * Window Title
265  */
268  * Default tile formatter.  The page url is ignored.  If there is a
269  * page_title, returns: "Page title - Conkeror".  Otherwise, it
270  * returns just: "Conkeror".
271  */
272 function default_title_formatter (window) {
273     var page_title = window.buffers.current.title;
275     if (page_title && page_title.length > 0)
276         return page_title + " - Conkeror";
277     else
278         return "Conkeror";
281 var title_format_fn = null;
283 function set_window_title (window) {
284     window.document.title = title_format_fn(window);
287 function init_window_title () {
288     title_format_fn = default_title_formatter;
290     add_hook("window_initialize_late_hook", set_window_title);
291     add_hook("current_content_buffer_location_change_hook",
292              function (buffer) {
293                  set_window_title(buffer.window);
294              });
295     add_hook("select_buffer_hook",
296              function (buffer) {
297                  set_window_title(buffer.window);
298              }, true);
299     add_hook("current_buffer_title_change_hook",
300              function (buffer) {
301                  set_window_title(buffer.window);
302              });
305 init_window_title();
308 function call_builtin_command (window, command, clear_mark) {
309     var m = window.minibuffer;
310     if (m.active && m._input_mode_enabled) {
311         m._restore_normal_state();
312         var e = m.input_element;
313         var c = e.controllers.getControllerForCommand(command);
314         try {
315             if (c && c.isCommandEnabled(command))
316                 c.doCommand(command);
317         } catch (e) {
318             // ignore errors
319         }
320         if (clear_mark)
321             m.current_state.mark_active = false;
322     } else {
323         function attempt_command (element) {
324             var c;
325             if (element.controllers
326                 && (c = element.controllers.getControllerForCommand(command)) != null
327                 && c.isCommandEnabled(command))
328             {
329                 try {
330                     c.doCommand(command);
331                 } catch (e) {
332                     // ignore errors
333                 }
334                 if (clear_mark)
335                     window.buffers.current.mark_active = false;
336                 return true;
337             }
338             return false;
339         }
340         var element = window.buffers.current.focused_element;
341         if (element && attempt_command(element, command))
342             return;
343         var win = window.buffers.current.focused_frame;
344         while (true) {
345             if (attempt_command(win, command))
346                 return;
347             if (!win.parent || win == win.parent)
348                 break;
349             win = win.parent;
350         }
351     }
356  * window_set_full_screen sets or toggles the fullScreen and hideChrome
357  * properties of the given window.  When fullscreen is a boolean, it sets
358  * it to that value.  When it is null or not given, it toggles the current
359  * value.
360  */
361 function window_set_full_screen (window, fullscreen) {
362     if (fullscreen === true || fullscreen === false) {
363         window.fullScreen = fullscreen;
364         window.hideChrome = fullscreen;
365     } else {
366         window.fullScreen = ! window.fullScreen;
367         window.hideChrome = window.fullScreen;
368     }
372 provide("window");