b515e832feb8e8c259cb1d6d23aca407803d226d
[mandelbrot.git] / xulapp / chrome / mandelbrot / content / mandelbrot.js
1 /* ***** BEGIN LICENSE BLOCK *****
2  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3  *
4  * The contents of this file are subject to the Mozilla Public License Version
5  * 1.1 (the "License"); you may not use this file except in compliance with
6  * the License. You may obtain a copy of the License at
7  * http://www.mozilla.org/MPL/
8  *
9  * Software distributed under the License is distributed on an "AS IS" basis,
10  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11  * for the specific language governing rights and limitations under the
12  * License.
13  *
14  * The Original Code is KaiRo.at Mandelbrot, XULRunner version.
15  *
16  * The Initial Developer of the Original Code is
17  * Robert Kaiser <kairo@kairo.at>.
18  * Portions created by the Initial Developer are Copyright (C) 2008
19  * the Initial Developer. All Rights Reserved.
20  *
21  * Contributor(s):
22  *   Robert Kaiser <kairo@kairo.at>
23  *
24  * Alternatively, the contents of this file may be used under the terms of
25  * either the GNU General Public License Version 2 or later (the "GPL"), or
26  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27  * in which case the provisions of the GPL or the LGPL are applicable instead
28  * of those above. If you wish to allow use of your version of this file only
29  * under the terms of either the GPL or the LGPL, and not to allow others to
30  * use your version of this file under the terms of the MPL, indicate your
31  * decision by deleting the provisions above and replace them with the notice
32  * and other provisions required by the GPL or the LGPL. If you do not delete
33  * the provisions above, a recipient may use your version of this file under
34  * the terms of any one of the MPL, the GPL or the LGPL.
35  *
36  * ***** END LICENSE BLOCK ***** */
37
38 var gColorPalette = [];
39 var gPref = Components.classes["@mozilla.org/preferences-service;1"]
40                       .getService(Components.interfaces.nsIPrefService)
41                       .getBranch(null);
42 var gStartTime = 0;
43
44 function Startup() {
45   updateIterMenu();
46   updatePaletteMenu();
47   document.getElementById("statusLabel").value =
48       document.getElementById("mbrotBundle").getString("statusEmpty");
49 }
50
51 function drawImage() {
52   let canvas = document.getElementById("mbrotImage");
53   let context = canvas.getContext("2d");
54
55   document.getElementById("drawButton").hidden = true;
56
57   document.getElementById("statusLabel").value =
58       document.getElementById("mbrotBundle").getString("statusDrawing");
59
60   let Cr_min = -2.0;
61   let Cr_max = 1.0;
62   try {
63     Cr_min = parseFloat(gPref.getCharPref("mandelbrot.last_image.Cr_min"));
64     Cr_max = parseFloat(gPref.getCharPref("mandelbrot.last_image.Cr_max"));
65   }
66   catch (e) { }
67   if ((Cr_min < -2) || (Cr_min > 2) ||
68       (Cr_max < -2) || (Cr_max > 2) || (Cr_min >= Cr_max)) {
69     Cr_min = -2.0; Cr_max = 1.0;
70   }
71   gPref.setCharPref("mandelbrot.last_image.Cr_min", Cr_min);
72   gPref.setCharPref("mandelbrot.last_image.Cr_max", Cr_max);
73
74   let Ci_min = -1.5;
75   let Ci_max = 1.5;
76   try {
77     Ci_min = parseFloat(gPref.getCharPref("mandelbrot.last_image.Ci_min"));
78     Ci_max = parseFloat(gPref.getCharPref("mandelbrot.last_image.Ci_max"));
79   }
80   catch (e) { }
81   if ((Ci_min < -2) || (Ci_min > 2) ||
82       (Ci_max < -2) || (Ci_max > 2) || (Ci_min >= Ci_max)) {
83     Ci_min = -2.0; Ci_max = 1.0;
84   }
85   gPref.setCharPref("mandelbrot.last_image.Ci_min", Ci_min);
86   gPref.setCharPref("mandelbrot.last_image.Ci_max", Ci_max);
87
88   let iterMax = gPref.getIntPref("mandelbrot.iteration_max");
89   let algorithm = gPref.getCharPref("mandelbrot.use_algorithm");
90
91   let iWidth = 0;
92   try {
93     iWidth = gPref.getIntPref("mandelbrot.image.width");
94   }
95   catch (e) { }
96   if ((iWidth < 10) || (iWidth > 5000)) {
97     iWidth = 300;
98     gPref.setIntPref("mandelbrot.image.width", iWidth);
99   }
100   let iHeight = 0;
101   try {
102     iHeight = gPref.getIntPref("mandelbrot.image.height");
103   }
104   catch (e) { }
105   if ((iHeight < 10) || (iHeight > 5000)) {
106     iHeight = 300;
107     gPref.setIntPref("mandelbrot.image.height", iHeight);
108   }
109
110   canvas.width = iWidth;
111   canvas.height = iHeight;
112
113   context.fillStyle = "rgba(255, 255, 255, 127)";
114   context.fillRect(0, 0, canvas.width, canvas.height);
115
116   gStartTime = new Date();
117
118   drawLine(0, [Cr_min, Cr_max, Ci_min, Ci_max],
119               canvas, context, iterMax, algorithm);
120 }
121
122 function drawLine(line, dimensions, canvas, context, iterMax, algorithm) {
123     let Cr_min = dimensions[0];
124     let Cr_max = dimensions[1];
125     let Cr_scale = Cr_max - Cr_min;
126
127     let Ci_min = dimensions[2];
128     let Ci_max = dimensions[3];
129     let Ci_scale = Ci_max - Ci_min;
130
131     let pixels = [];
132     for (var img_y = line; img_y < canvas.height && img_y < line+8; img_y++)
133       for (let img_x = 0; img_x < canvas.width; img_x++) {
134         let C = new complex(Cr_min + (img_x / canvas.width) * Cr_scale,
135                             Ci_min + (img_y / canvas.height) * Ci_scale);
136         pixels.push.apply(pixels, drawPoint(context, img_x, img_y, C, iterMax, algorithm));
137       }
138     context.putImageData({width: canvas.width, height: pixels.length/4/canvas.width, data: pixels}, 0, line);
139
140     if (img_y < canvas.height)
141       setTimeout(drawLine, 0, img_y, dimensions, canvas, context, iterMax, algorithm);
142     else if (gStartTime)
143       EndCalc();
144 }
145
146 function EndCalc() {
147   let endTime = new Date();
148   let timeUsed = (endTime.getTime() - gStartTime.getTime()) / 1000;
149   document.getElementById("statusLabel").value =
150       document.getElementById("mbrotBundle").getFormattedString("statusTime", [timeUsed.toFixed(3)]);
151 }
152
153 function complex(aReal, aImag) {
154   this.r = aReal;
155   this.i = aImag;
156 }
157 complex.prototype = {
158   square: function() {
159     return new complex(this.r * this.r - this.i * this.i,
160                        2 * this.r * this.i);
161   },
162   dist: function() {
163     return Math.sqrt(this.r * this.r + this.i * this.i);
164   },
165   add: function(aComplex) {
166     return new complex(this.r + aComplex.r, this.i + aComplex.i);
167   }
168 }
169
170 function mandelbrotValueOO (aC, aIterMax) {
171   // this would be nice code in general but it looks like JS objects are too heavy for normal use.
172   let Z = new complex(0.0, 0.0);
173   for (var iter = 0; iter < aIterMax; iter++) {
174     Z = Z.square().add(aC);
175     if (Z.r * Z.r + Z.i * Z.i > 256) { break; }
176   }
177   return iter;
178 }
179
180 function mandelbrotValueNumeric (aC, aIterMax) {
181   // optimized numeric code for fast calculation
182   let Cr = aC.r, Ci = aC.i;
183   let Zr = 0.0, Zi = 0.0;
184   let Zr2 = Zr * Zr, Zi2 = Zi * Zi;
185   for (var iter = 0; iter < aIterMax; iter++) {
186     Zi = 2 * Zr * Zi + Ci;
187     Zr = Zr2 - Zi2 + Cr;
188
189     Zr2 = Zr * Zr; Zi2 = Zi * Zi;
190     if (Zr2 + Zi2 > 256) { break; }
191   }
192   return iter;
193 }
194
195 function getColor(aIterValue, aIterMax) {
196   let standardizedValue = Math.round(aIterValue * 1024 / aIterMax);
197   if (gColorPalette && gColorPalette.length)
198     return gColorPalette[standardizedValue];
199
200   // fallback to simple b/w if for some reason we don't have a palette
201   if (aIterValue == aIterMax)
202     return [0, 0, 0, 255];
203   else
204     return [255, 255, 255, 255];
205 }
206
207 function getColorPalette(palName) {
208   var palette = [];
209   switch (palName) {
210     case 'bw':
211       for (let i = 0; i < 1024; i++) {
212         palette[i] = [255, 255, 255, 255];
213       }
214       palette[1024] = [0, 0, 0, 255];
215       break;
216     case 'kairo':
217       // outer areas
218       for (let i = 0; i < 32; i++) {
219         let cc1 = Math.floor(i * 127 / 31);
220         let cc2 = 170 - Math.floor(i * 43 / 31);
221         palette[i] = [cc1, cc2, cc1, 255];
222       }
223       // inner areas
224       for (let i = 0; i < 51; i++) {
225         let cc = Math.floor(i * 170 / 50);
226         palette[32 + i] = [cc, 0, (170-cc), 255];
227       }
228       // corona
229       for (let i = 0; i < 101; i++) {
230         let cc = Math.floor(i * 200 / 100);
231         palette[83 + i] = [255, cc, 0, 255];
232       }
233       // inner corona
234       for (let i = 0; i < 201; i++) {
235         let cc1 = 255 - Math.floor(i * 85 / 200);
236         let cc2 = 200 - Math.floor(i * 30 / 200);
237         let cc3 = Math.floor(i * 170 / 200);
238         palette[184 + i] = [cc1, cc2, cc3, 255];
239       }
240       for (let i = 0; i < 301; i++) {
241         let cc1 = 170 - Math.floor(i * 43 / 300);
242         let cc2 = 170 + Math.floor(i * 85 / 300);
243         palette[385 + i] = [cc1, cc1, cc2, 255];
244       }
245       for (let i = 0; i < 338; i++) {
246         let cc = 127 + Math.floor(i * 128 / 337);
247         palette[686 + i] = [cc, cc, 255, 255];
248       }
249       palette[1024] = [0, 0, 0, 255];
250       break;
251     case 'rainbow-linear1':
252       for (let i = 0; i < 256; i++) {
253         palette[i] = [i, 0, 0, 255];
254         palette[256 + i] = [255, i, 0, 255];
255         palette[512 + i] = [255 - i, 255, i, 255];
256         palette[768 + i] = [i, 255-i, 255, 255];
257       }
258       palette[1024] = [0, 0, 0, 255];
259       break;
260   }
261 /*
262 Select Case palnr
263 Case 1  'Standard-Palette (QB-Colors)
264      For i = 0 To 1024
265          xx = CInt(i * 500 / 1024 + 2)
266          If xx <= 15 Then clr = xx
267          If xx > 15 Then clr = CInt(Sqr((xx - 15 + 1) * 15 ^ 2 / 485))
268          If xx >= 500 Then clr = 0
269          palette(i) = QBColor(clr)
270      Next
271 Case 3  'Regenbogen-Palette 1 (qu.)
272      For i = 0 To 33
273          clr = CInt(i * 255 / 33)
274          palette(i) = RGB(clr, 0, 0)
275      Next
276      For i = 0 To 136
277          clr = CInt(i * 255 / 136)
278          palette(34 + i) = RGB(255, clr, 0)
279      Next
280      For i = 0 To 306
281          clr = CInt(i * 255 / 306)
282          palette(171 + i) = RGB(255 - clr, 255, clr)
283      Next
284      For i = 0 To 545
285          clr = CInt(i * 255 / 545)
286          palette(478 + i) = RGB(clr, 255 - clr, 255)
287      Next
288 Case 4  'Regenbogen-Palette 2 (linear)
289      For i = 0 To 204
290          clr = CInt(i * 255 / 204)
291          palette(i) = RGB(255, clr, 0)
292          palette(204 + i) = RGB(255 - clr, 255, 0)
293          palette(409 + i) = RGB(0, 255, clr)
294          palette(614 + i) = RGB(0, 255 - clr, 255)
295          palette(819 + i) = RGB(clr, 0, 255)
296      Next
297 Case 5  'Regenbogen-Palette 2 (qu.)
298      For i = 0 To 18
299          clr = CInt(i * 255 / 18)
300          palette(i) = RGB(255, clr, 0)
301      Next
302      For i = 0 To 73
303          clr = CInt(i * 255 / 73)
304          palette(20 + i) = RGB(255 - clr, 255, 0)
305      Next
306      For i = 0 To 167
307          clr = CInt(i * 255 / 167)
308          palette(93 + i) = RGB(0, 255, clr)
309      Next
310      For i = 0 To 297
311          clr = CInt(i * 255 / 297)
312          palette(261 + i) = RGB(0, 255 - clr, 255)
313      Next
314      For i = 0 To 464
315          clr = CInt(i * 255 / 464)
316          palette(559 + i) = RGB(clr, 0, 255)
317      Next
318 */
319   return palette;
320 }
321
322 function drawPoint(context, img_x, img_y, C, iterMax, algorithm) {
323   var itVal;
324   switch (algorithm) {
325     case 'oo':
326       itVal = mandelbrotValueOO(C, iterMax);
327       break;
328     case 'numeric':
329     default:
330       itVal = mandelbrotValueNumeric(C, iterMax);
331       break;
332   }
333   return getColor(itVal, iterMax);
334 }
335
336 /***** pure UI functions *****/
337
338 var zoomstart;
339
340 function mouseevent(etype, event) {
341   let canvas = document.getElementById("mbrotImage");
342   switch (etype) {
343     case 'down':
344       if (event.button == 0)
345         // left button - start dragzoom
346         zoomstart = {x: event.clientX - canvas.offsetLeft,
347                      y: event.clientY - canvas.offsetTop};
348       break;
349     case 'up':
350       if (event.button == 0)
351         alert(zoomstart.x + ',' + zoomstart.y + '-' +
352               (event.clientX - canvas.offsetLeft) + ',' +
353               (event.clientY - canvas.offsetTop)); 
354       zoomstart = undefined;
355     break;
356   }
357 }
358
359 function saveImage() {
360   const bundle = document.getElementById("mbrotBundle");
361   const nsIFilePicker = Components.interfaces.nsIFilePicker;
362   var fp = null;
363   try {
364     fp = Components.classes["@mozilla.org/filepicker;1"]
365                    .createInstance(nsIFilePicker);
366   } catch (e) {}
367   if (!fp) return;
368   var promptString = bundle.getString("savePrompt");
369   fp.init(window, promptString, nsIFilePicker.modeSave);
370   fp.appendFilter(bundle.getString("pngFilterName"), "*.png");
371   fp.defaultString = "mandelbrot.png";
372
373   var fpResult = fp.show();
374   if (fpResult != nsIFilePicker.returnCancel) {
375     saveCanvas(document.getElementById("mbrotImage"), fp.file);
376   }
377 }
378
379 function updateBookmarksMenu(aParent) {
380   /* from SM UBhistory, needs to be adapted
381     while (aParent.hasChildNodes())
382       aParent.removeChild(aParent.lastChild);
383
384     var file = Components.classes["@mozilla.org/file/directory_service;1"]
385                          .getService(Components.interfaces.nsIProperties)
386                          .get("ProfD", Components.interfaces.nsIFile);
387     file.append("urlbarhistory.sqlite");
388     if (file.exists()) {
389       var connection = Components.classes["@mozilla.org/storage/service;1"]
390                                  .getService(Components.interfaces.mozIStorageService)
391                                  .openDatabase(file);
392       try {
393         if (connection.tableExists("urlbarhistory")) {
394           var statement = connection.createStatement(
395               "SELECT url FROM urlbarhistory ORDER BY ROWID DESC");
396           while (statement.executeStep())
397             aParent.appendChild(document.createElement("menuitem"))
398                    .setAttribute("label", statement.getString(0));
399           statement.reset();
400           statement.finalize();
401           return;
402         }
403       } finally {
404         connection.close();
405       }
406     }
407     //Create the "Nothing Available" Menu item and disable it.
408     var na = aParent.appendChild(document.createElement("menuitem"));
409     na.setAttribute("label", gNavigatorBundle.getString("nothingAvailable"));
410     na.setAttribute("disabled", "true");
411   */
412 }
413
414 function callBookmark(evtarget) {
415 }
416
417 function saveBookmark() {
418   /* from SM UBhistory, needs to be adapted
419      // Open or create the urlbar history database.
420      var file = Components.classes["@mozilla.org/file/directory_service;1"]
421                           .getService(Components.interfaces.nsIProperties)
422                           .get("ProfD", Components.interfaces.nsIFile);
423      file.append("urlbarhistory.sqlite");
424      var connection = Components.classes["@mozilla.org/storage/service;1"]
425                                 .getService(Components.interfaces.mozIStorageService)
426                                 .openDatabase(file);
427      connection.beginTransaction();
428      if (!connection.tableExists("urlbarhistory"))
429        connection.createTable("urlbarhistory", "url TEXT, foo INTEGER, bar REAL");
430        // NULL. The value is a NULL value.
431        // INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
432        // REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.
433        // TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).
434
435      // Put the value as it was typed by the user in to urlbar history
436      statement = connection.createStatement(
437          "INSERT INTO urlbarhistory (url) VALUES (?1)");
438      statement.bindStringParameter(0, aUrlToAdd);
439      statement.execute();
440      statement.finalize();
441   */
442 }
443
444 function updateIterMenu() {
445   try {
446     var currentIter = gPref.getIntPref("mandelbrot.iteration_max");
447   }
448   catch(e) {
449     var currentIter = 0;
450   }
451   if (currentIter < 10) {
452     currentIter = 500;
453     setIter(currentIter);
454   }
455
456   var popup = document.getElementById("menu_iterPopup");
457   var item = popup.firstChild;
458   while (item) {
459     if (item.getAttribute("name") == "iter") {
460       if (item.getAttribute("value") == currentIter)
461         item.setAttribute("checked","true");
462       else
463         item.removeAttribute("checked");
464     }
465     item = item.nextSibling;
466   }
467 }
468
469 function setIter(aIter) {
470   gPref.setIntPref("mandelbrot.iteration_max", aIter);
471 }
472
473 function updatePaletteMenu() {
474   try {
475     var currentPalette = gPref.getCharPref("mandelbrot.color_palette");
476   }
477   catch(e) {
478     var currentPalette = '';
479   }
480   if (!currentPalette.length) {
481     currentPalette = 'kairo';
482     setPalette(currentPalette);
483   }
484   if (!gColorPalette || !gColorPalette.length)
485     gColorPalette = getColorPalette(currentPalette);
486
487   var popup = document.getElementById("menu_palettePopup");
488   var item = popup.firstChild;
489   while (item) {
490     if (item.getAttribute("name") == "palette") {
491       if (item.getAttribute("value") == currentPalette)
492         item.setAttribute("checked", "true");
493       else
494         item.removeAttribute("checked");
495     }
496     item = item.nextSibling;
497   }
498 }
499
500 function setPalette(aPaletteID) {
501   gPref.setCharPref("mandelbrot.color_palette", aPaletteID);
502   gColorPalette = getColorPalette(aPaletteID);
503 }
504
505 function imgSettings() {
506   window.openDialog("chrome://mandelbrot/content/image-settings.xul");
507 }
508
509 function updateDebugMenu() {
510   var jitMenuItem = document.getElementById("jitEnabled");
511   jitMenuItem.setAttribute("checked", gPref.getBoolPref("javascript.options.jit.chrome"));
512 }
513
514 function toggleJITState(jitMenuItem) {
515   var jitEnabled = !gPref.getBoolPref("javascript.options.jit.chrome");
516   gPref.setBoolPref("javascript.options.jit.chrome", jitEnabled)
517   jitMenuItem.setAttribute("checked", jitEnabled? "true" : "false");
518 }
519
520 function updateAlgoMenu() {
521   try {
522     var currentAlgo = gPref.getCharPref("mandelbrot.use_algorithm");
523   }
524   catch(e) {
525     var currentAlgo = '';
526   }
527   if (!currentAlgo.length) {
528     currentAlgo = 'numeric';
529     setAlgorithm(currentAlgo);
530   }
531
532   var popup = document.getElementById("menu_algoPopup");
533   var item = popup.firstChild;
534   while (item) {
535     if (item.getAttribute("name") == "algorithm") {
536       if (item.getAttribute("value") == currentAlgo)
537         item.setAttribute("checked", "true");
538       else
539         item.removeAttribute("checked");
540     }
541     item = item.nextSibling;
542   }
543 }
544
545 function setAlgorithm(algoID) {
546   gPref.setCharPref("mandelbrot.use_algorithm", algoID);
547 }
548
549 function addonsManager(aPane) {
550   var theEM = Components.classes["@mozilla.org/appshell/window-mediator;1"]
551                         .getService(Components.interfaces.nsIWindowMediator)
552                         .getMostRecentWindow("Extension:Manager");
553   if (theEM) {
554     theEM.focus();
555     if (aPane)
556       theEM.showView(aPane);
557     return;
558   }
559
560   const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
561   const EMFEATURES = "all,dialog=no";
562   if (aPane)
563     window.openDialog(EMURL, "", EMFEATURES, aPane);
564   else
565     window.openDialog(EMURL, "", EMFEATURES);
566 }
567
568 function errorConsole() {
569   toOpenWindowByType("global:console", "chrome://global/content/console.xul");
570 }
571
572 /***** helper functions from external sources *****/
573
574 // function below is based on http://developer.mozilla.org/en/docs/Code_snippets:Canvas
575 // custom modifications:
576 //   - use "a"-prefix on function arguments
577 //   - take an nsILocalFile as aDestFile argument
578 //   - always do silent download
579 function saveCanvas(aCanvas, aDestFile) {
580   // create a data url from the canvas and then create URIs of the source and targets  
581   var io = Components.classes["@mozilla.org/network/io-service;1"]
582                      .getService(Components.interfaces.nsIIOService);
583   var source = io.newURI(aCanvas.toDataURL("image/png", ""), "UTF8", null);
584
585   // prepare to save the canvas data
586   var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
587                           .createInstance(Components.interfaces.nsIWebBrowserPersist);
588
589   persist.persistFlags = Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
590   persist.persistFlags |= Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
591
592   // save the canvas data to the file
593   persist.saveURI(source, null, null, null, null, aDestFile);
594 }
595
596 // function below is from http://developer.mozilla.org/en/docs/How_to_Quit_a_XUL_Application
597 function quitApp(aForceQuit) {
598   var appStartup = Components.classes['@mozilla.org/toolkit/app-startup;1']
599                              .getService(Components.interfaces.nsIAppStartup);
600
601   // eAttemptQuit will try to close each XUL window, but the XUL window can cancel the quit
602   // process if there is unsaved data. eForceQuit will quit no matter what.
603   var quitSeverity = aForceQuit ? Components.interfaces.nsIAppStartup.eForceQuit :
604                                   Components.interfaces.nsIAppStartup.eAttemptQuit;
605   appStartup.quit(quitSeverity);
606 }
607
608 // functions below are from comm-central/suite/common/tasksOverlay.js
609 function toOpenWindow(aWindow) {
610   try {
611     // Try to focus the previously focused window e.g. message compose body
612     aWindow.document.commandDispatcher.focusedWindow.focus();
613   } catch (e) {
614     // e.g. full-page plugin or non-XUL document; just raise the top window
615     aWindow.focus();
616   }
617 }
618
619 function toOpenWindowByType(inType, uri, features) {
620   // don't do several loads in parallel
621   if (uri in window)
622     return;
623
624   var topWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"]
625                             .getService(Components.interfaces.nsIWindowMediator)
626                             .getMostRecentWindow(inType);
627   if ( topWindow )
628     toOpenWindow( topWindow );
629   else {
630     // open the requested window, but block it until it's fully loaded
631     function newWindowLoaded(event) {
632       // make sure that this handler is called only once
633       window.removeEventListener("unload", newWindowLoaded, false);
634       window[uri].removeEventListener("load", newWindowLoaded, false);
635       delete window[uri];
636     }
637     // remember the newly loading window until it's fully loaded
638     // or until the current window passes away
639     window[uri] = window.openDialog(uri, "", features || "all,dialog=no");
640     window[uri].addEventListener("load", newWindowLoaded, false);
641     window.addEventListener("unload", newWindowLoaded, false);
642   }
643 }