download-manager.js: fix bug resulting in un-killable special buffers
[conkeror.git] / modules / download-manager.js
blob7957a65a39cee3396b3d8c85f028a8a13cd378b7
1 /**
2  * (C) Copyright 2008 Jeremy Maitin-Shepard
3  *
4  * Use, modification, and distribution are subject to the terms specified in the
5  * COPYING file.
6 **/
8 require("special-buffer.js");
9 require("mime-type-override.js");
10 require("minibuffer-read-mime-type.js");
12 var download_manager_service = Cc["@mozilla.org/download-manager;1"].getService(Ci.nsIDownloadManager);
13 //var download_manager_ui = Cc["@mozilla.org/download-manager-ui;1"].getService(Ci.nsIDownloadManagerUI);
14 var download_manager_builtin_ui = Components.classesByID["{7dfdf0d1-aff6-4a34-bad1-d0fe74601642}"]
15     .getService(Ci.nsIDownloadManagerUI);
17 /* This implements nsIHelperAppLauncherDialog interface. */
18 function download_helper()
20 download_helper.prototype = {
21     QueryInterface: generate_QI(Ci.nsIHelperAppLauncherDialog, Ci.nsIWebProgressListener2),
23     handle_show: function () {
24         var action_chosen = false;
26         var can_view_internally = this.frame != null &&
27                 can_override_mime_type_for_uri(this.launcher.source);
28         try {
29             this.panel = create_info_panel(this.window, "download-panel",
30                                            [["downloading", "Downloading:", this.launcher.source.spec],
31                                             ["mime-type", "Mime type:", this.launcher.MIMEInfo.MIMEType]]);
32             var action = yield this.window.minibuffer.read_single_character_option(
33                 $prompt = "Action to perform: (s: save; o: open; O: open URL; c: copy URL; " +
34                     (can_view_internally ? "i: view internally; t: view as text)" : ")"),
35                 $options = (can_view_internally ? ["s", "o", "O", "c", "i", "t"] : ["s", "o", "O", "c"]));
37             if (action == "s") {
38                 var suggested_path = suggest_save_path_from_file_name(this.launcher.suggestedFileName, this.buffer);
39                 var file = yield this.window.minibuffer.read_file_check_overwrite(
40                     $prompt = "Save to file:",
41                     $initial_value = suggested_path,
42                     $select);
43                 register_download(this.buffer, this.launcher.source);
44                 this.launcher.saveToDisk(file, false);
45                 action_chosen = true;
47             } else if (action == "o") {
48                 var cwd = this.buffer ? this.buffer.cwd : default_directory.path;
49                 var mime_type = this.launcher.MIMEInfo.MIMEType;
50                 var suggested_action = get_external_handler_for_mime_type(mime_type);
51                 var command = yield this.window.minibuffer.read_shell_command(
52                     $initial_value = suggested_action,
53                     $cwd = cwd);
54                 var file = get_temporary_file(this.launcher.suggestedFileName);
55                 var info = register_download(this.buffer, this.launcher.source);
56                 info.temporary_status = DOWNLOAD_TEMPORARY_FOR_COMMAND;
57                 info.set_shell_command(command, cwd);
58                 this.launcher.saveToDisk(file, false);
59                 action_chosen = true;
60             } else if (action == "O") {
61                 action_chosen = true;
62                 this.abort(); // abort download
63                 let mime_type = this.launcher.MIMEInfo.MIMEType;
64                 let cwd = this.buffer ? this.buffer.cwd : this.window.buffers.current.cwd;
65                 let cmd = yield this.window.minibuffer.read_shell_command(
66                     $cwd = cwd,
67                     $initial_value = get_external_handler_for_mime_type(mime_type));
68                 shell_command_with_argument_blind(cmd, this.launcher.source.spec, $cwd = cwd);
69             } else if (action == "c") {
70                 action_chosen = true;
71                 this.abort(); // abort download
72                 let uri = this.launcher.source.spec;
73                 writeToClipboard(uri);
74                 this.window.minibuffer.message("Copied: " + uri);
75             } else /* if (action == "i" || action == "t") */ {
76                 let mime_type;
77                 if (action == "t")
78                     mime_type = "text/plain";
79                 else {
80                     let suggested_type = this.launcher.MIMEInfo.MIMEType;
81                     if (gecko_viewable_mime_type_list.indexOf(suggested_type) == -1)
82                         suggested_type = "text/plain";
83                     mime_type = yield this.window.minibuffer.read_gecko_viewable_mime_type(
84                         $prompt = "View internally as",
85                         $initial_value = suggested_type,
86                         $select);
87                 }
88                 action_chosen = true;
89                 this.abort(); // abort before reloading
91                 override_mime_type_for_next_load(this.launcher.source, mime_type);
92                 this.frame.location = this.launcher.source.spec; // reload
93             }
94         } catch (e) {
95             handle_interactive_error(this.window, e);
96         } finally {
97             if (!action_chosen)
98                 this.abort();
99             this.cleanup();
100         }
101     },
103     show : function (launcher, context, reason) {
104         this.launcher = launcher;
106         // Get associated buffer; if that fails (hopefully not), just get any window
107         var buffer = null;
108         var window = null;
109         var frame = null;
110         try {
111             frame = context.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal);
112             window = get_window_from_frame(frame.top);
113             if (window)
114                 buffer = get_buffer_from_frame(window, frame);
115         } catch (e) {
116             window = get_recent_conkeror_window();
118             if (window == null) {
119                 // FIXME: need to handle this case perhaps where no windows exist
120                 this.abort(); // for now, just cancel the download
121                 return;
122             }
123         }
125         this.frame = frame;
126         this.window = window;
127         this.buffer = buffer;
129         co_call(this.handle_show());
130     },
132     abort : function () {
133         const NS_BINDING_ABORTED = 0x804b0002;
134         this.launcher.cancel(NS_BINDING_ABORTED);
135     },
137     cleanup : function () {
138         if (this.panel)
139             this.panel.destroy();
140         this.panel = null;
141         this.launcher = null;
142         this.window = null;
143         this.buffer = null;
144         this.frame = null;
145     },
147     promptForSaveToFile : function(launcher, context, default_file, suggested_file_extension) {
148         return null;
149     }
153 var unmanaged_download_info_list = [];
154 var id_to_download_info = {};
156 // Import these constants for convenience
157 const DOWNLOAD_NOTSTARTED = Ci.nsIDownloadManager.DOWNLOAD_NOTSTARTED;
158 const DOWNLOAD_DOWNLOADING = Ci.nsIDownloadManager.DOWNLOAD_DOWNLOADING;
159 const DOWNLOAD_FINISHED = Ci.nsIDownloadManager.DOWNLOAD_FINISHED;
160 const DOWNLOAD_FAILED = Ci.nsIDownloadManager.DOWNLOAD_FAILED;
161 const DOWNLOAD_CANCELED = Ci.nsIDownloadManager.DOWNLOAD_CANCELED;
162 const DOWNLOAD_PAUSED = Ci.nsIDownloadManager.DOWNLOAD_PAUSED;
163 const DOWNLOAD_QUEUED = Ci.nsIDownloadManager.DOWNLOAD_QUEUED;
164 const DOWNLOAD_BLOCKED = Ci.nsIDownloadManager.DOWNLOAD_BLOCKED;
165 const DOWNLOAD_SCANNING = Ci.nsIDownloadManager.DOWNLOAD_SCANNING;
168 const DOWNLOAD_NOT_TEMPORARY = 0;
169 const DOWNLOAD_TEMPORARY_FOR_ACTION = 1;
170 const DOWNLOAD_TEMPORARY_FOR_COMMAND = 2;
172 function download_info(source_buffer, mozilla_info) {
173     this.source_buffer = source_buffer;
174     if (mozilla_info != null)
175         this.attach(mozilla_info);
177 download_info.prototype = {
178     attach : function (mozilla_info) {
179         this.mozilla_info = mozilla_info;
180         id_to_download_info[mozilla_info.id] = this;
181         download_added_hook.run(this);
182     },
184     shell_command : null,
186     shell_command_cwd : null,
188     temporary_status : DOWNLOAD_NOT_TEMPORARY,
190     action_description : null,
192     set_shell_command : function (str, cwd) {
193         this.shell_command = str;
194         this.shell_command_cwd = cwd;
195         if (this.mozilla_info)
196             download_shell_command_change_hook.run(this);
197     },
199     /**
200      * None of the following members may be used until attach is called
201      */
203     // Reflectors to properties of nsIDownload
204     get state () { return this.mozilla_info.state; },
205     get target_file () { return this.mozilla_info.targetFile; },
206     get amount_transferred () { return this.mozilla_info.amountTransferred; },
207     get percent_complete () { return this.mozilla_info.percentComplete; },
208     get size () {
209         var s = this.mozilla_info.size;
210         /* nsIDownload.size is a PRUint64, and will have value
211          * LL_MAXUINT (2^64 - 1) to indicate an unknown size.  Because
212          * JavaScript only has a double numerical type, this value
213          * cannot be represented exactly, so 2^36 is used instead as the cutoff. */
214         if (s < 68719476736 /* 2^36 */)
215             return s;
216         return -1;
217     },
218     get source () { return this.mozilla_info.source; },
219     get start_time () { return this.mozilla_info.startTime; },
220     get speed () { return this.mozilla_info.speed; },
221     get MIME_info () { return this.mozilla_info.MIMEInfo; },
222     get MIME_type () {
223         if (this.MIME_info)
224             return this.MIME_info.MIMEType;
225         return null;
226     },
227     get id () { return this.mozilla_info.id; },
228     get referrer () { return this.mozilla_info.referrer; },
230     throw_if_removed : function () {
231         if (this.removed)
232             throw interactive_error("Download has already been removed from the download manager.");
233     },
235     throw_state_error : function () {
236         switch (this.state) {
237         case DOWNLOAD_DOWNLOADING:
238             throw interactive_error("Download is already in progress.");
239         case DOWNLOAD_FINISHED:
240             throw interactive_error("Download has already completed.");
241         case DOWNLOAD_FAILED:
242             throw interactive_error("Download has already failed.");
243         case DOWNLOAD_CANCELED:
244             throw interactive_error("Download has already been canceled.");
245         case DOWNLOAD_PAUSED:
246             throw interactive_error("Download has already been paused.");
247         case DOWNLOAD_QUEUED:
248             throw interactive_error("Download is queued.");
249         default:
250             throw new Error("Download has unexpected state: " + this.state);
251         }
252     },
254     // Download manager operations
255     cancel : function ()  {
256         this.throw_if_removed();
257         switch (this.state) {
258         case DOWNLOAD_DOWNLOADING:
259         case DOWNLOAD_PAUSED:
260         case DOWNLOAD_QUEUED:
261             try {
262                 download_manager_service.cancelDownload(this.id);
263             } catch (e) {
264                 throw interactive_error("Download cannot be canceled.");
265             }
266             break;
267         default:
268             this.throw_state_error();
269         }
270     },
272     retry : function () {
273         this.throw_if_removed();
274         switch (this.state) {
275         case DOWNLOAD_CANCELED:
276         case DOWNLOAD_FAILED:
277             try {
278                 download_manager_service.retryDownload(this.id);
279             } catch (e) {
280                 throw interactive_error("Download cannot be retried.");
281             }
282             break;
283         default:
284             this.throw_state_error();
285         }
286     },
288     resume : function () {
289         this.throw_if_removed();
290         switch (this.state) {
291         case DOWNLOAD_PAUSED:
292             try {
293                 download_manager_service.resumeDownload(this.id);
294             } catch (e) {
295                 throw interactive_error("Download cannot be resumed.");
296             }
297             break;
298         default:
299             this.throw_state_error();
300         }
301     },
303     pause : function () {
304         this.throw_if_removed();
305         switch (this.state) {
306         case DOWNLOAD_DOWNLOADING:
307         case DOWNLOAD_QUEUED:
308             try {
309                 download_manager_service.pauseDownload(this.id);
310             } catch (e) {
311                 throw interactive_error("Download cannot be paused.");
312             }
313             break;
314         default:
315             this.throw_state_error();
316         }
317     },
319     remove : function () {
320         this.throw_if_removed();
321         switch (this.state) {
322         case DOWNLOAD_FAILED:
323         case DOWNLOAD_CANCELED:
324         case DOWNLOAD_FINISHED:
325             try {
326                 download_manager_service.removeDownload(this.id);
327             } catch (e) {
328                 throw interactive_error("Download cannot be removed.");
329             }
330             break;
331         default:
332             throw interactive_error("Download is still in progress.");
333         }
334     },
336     delete_target : function () {
337         if (this.state != DOWNLOAD_FINISHED)
338             throw interactive_error("Download has not finished.");
339         try {
340             this.target_file.remove(false);
341         } catch (e) {
342             if (result in e) {
343                 switch (e) {
344                 case Cr.NS_ERROR_FILE_TARGET_DOES_NOT_EXIST:
345                     throw interactive_error("File has already been deleted.");
346                 case Cr.NS_ERROR_FILE_ACCESS_DENIED:
347                     throw interactive_error("Access denied");
348                 case Cr.NS_ERROR_FILE_DIR_NOT_EMPTY:
349                     throw interactive_error("Failed to delete file.");
350                 }
351             }
352             throw e;
353         }
354     }
357 var define_download_local_hook = simple_local_hook_definer();
359 // FIXME: add more parameters
360 function register_download(buffer, source_uri) {
361     var info = new download_info(buffer);
362     info.registered_time_stamp = Date.now();
363     info.registered_source_uri = source_uri;
364     unmanaged_download_info_list.push(info);
365     return info;
368 function match_registered_download(mozilla_info) {
369     let list = unmanaged_download_info_list;
370     let t = Date.now();
371     for (let i = 0; i < list.length; ++i) {
372         let x = list[i];
373         if (x.registered_source_uri == mozilla_info.source) {
374             list.splice(i, 1);
375             return x;
376         }
377         if (t - x.registered_time_stamp > download_info_max_queue_delay) {
378             list.splice(i, 1);
379             --i;
380             continue;
381         }
382     }
383     return null;
386 define_download_local_hook("download_added_hook");
387 define_download_local_hook("download_removed_hook");
388 define_download_local_hook("download_finished_hook");
389 define_download_local_hook("download_progress_change_hook");
390 define_download_local_hook("download_state_change_hook");
391 define_download_local_hook("download_shell_command_change_hook");
393 var download_info_max_queue_delay = 100;
395 var download_progress_listener = {
396     QueryInterface: generate_QI(Ci.nsIDownloadProgressListener),
398     onDownloadStateChange : function (state, download) {
399         var info = null;
400         /* FIXME: Determine if only new downloads will have this state
401          * as their previous state. */
403         dumpln("download state change: " + download.source.spec + ": " + state + ", " + download.state + ", " + download.id);
405         if (state == DOWNLOAD_NOTSTARTED) {
406             info = match_registered_download(download);
407             if (info == null) {
408                 info = new download_info(null, download);
409                 dumpln("error: encountered unknown new download");
410             } else {
411                 info.attach(download);
412             }
413         } else {
414             info = id_to_download_info[download.id];
415             if (info == null) {
416                 dumpln("Error: encountered unknown download");
418             } else {
419                 info.mozilla_info = download;
420                 download_state_change_hook.run(info);
421                 if (info.state == DOWNLOAD_FINISHED) {
422                     download_finished_hook.run(info);
424                     if (info.shell_command != null) {
425                         info.running_shell_command = true;
426                         co_call(function () {
427                             try {
428                                 yield shell_command_with_argument(info.shell_command,
429                                                                   info.target_file.path,
430                                                                   $cwd = info.shell_command_cwd);
431                             } finally  {
432                                 if (info.temporary_status == DOWNLOAD_TEMPORARY_FOR_COMMAND)
433                                     info.target_file.remove(false /* not recursive */);
434                                 info.running_shell_command = false;
435                                 download_shell_command_change_hook.run(info);
436                             }
437                         }());
438                         download_shell_command_change_hook.run(info);
439                     }
440                 }
441             }
442         }
443     },
445     onProgressChange : function (progress, request, cur_self_progress, max_self_progress,
446                                  cur_total_progress, max_total_progress,
447                                  download) {
448         var info = id_to_download_info[download.id];
449         if (info == null) {
450             dumpln("error: encountered unknown download in progress change");
451             return;
452         }
453         info.mozilla_info = download;
454         download_progress_change_hook.run(info);
455         //dumpln("download progress change: " + download.source.spec + ": " + cur_self_progress + "/" + max_self_progress + " "
456         // + cur_total_progress + "/" + max_total_progress + ", " + download.state + ", " + download.id);
457     },
459     onSecurityChange : function (progress, request, state, download) {
460     },
462     onStateChange : function (progress, request, state_flags, status, download) {
463     }
466 var download_observer = {
467     observe : function(subject, topic, data) {
468         switch(topic) {
469         case "download-manager-remove-download":
470             var ids = [];
471             if (!subject) {
472                 // Remove all downloads
473                 for (let i in id_to_download_info)
474                     ids.push(i);
475             } else {
476                 let id = subject.QueryInterface(Ci.nsISupportsPRUint32);
477                 /* FIXME: determine if this should really be an error */
478                 if (!(id in id_to_download_info)) {
479                     dumpln("Error: download-manager-remove-download event received for unknown download: " + id);
480                 } else
481                     ids.push(id);
482             }
483             for each (let i in ids) {
484                 dumpln("deleting download: " + i);
485                 let d = id_to_download_info[i];
486                 d.removed = true;
487                 download_removed_hook.run(d);
488                 delete id_to_download_info[i];
489             }
490             break;
491         }
492     }
494 observer_service.addObserver(download_observer, "download-manager-remove-download", false);
496 download_manager_service.addListener(download_progress_listener);
498 function pretty_print_file_size(val) {
499     const GIBI = 1073741824; /* 2^30 */
500     const MEBI = 1048576; /* 2^20 */
501     const KIBI = 1024; /* 2^10 */
502     var suffix, div;
503     if (val < KIBI) {
504         div = 1;
505         suffix = "B";
506     }
507     else if (val < MEBI) {
508         suffix = "KiB";
509         div = KIBI;
510     } else if (val < GIBI) {
511         suffix = "MiB";
512         div = MEBI;
513     } else {
514         suffix = "GiB";
515         div = GIBI;
516     }
517     val = val / div;
518     var precision = 2;
519     if (val > 10)
520         precision = 1;
521     if (val > 100)
522         precision = 0;
523     return [val.toFixed(precision), suffix];
526 function pretty_print_time(val) {
527     val = Math.round(val);
528     var seconds = val % 60;
530     val = Math.floor(val / 60);
532     var minutes = val % 60;
534     var hours = Math.floor(val / 60);
536     var parts = [];
538     if (hours > 1)
539         parts.push(hours + " hours");
540     else if (hours == 1)
541         parts.push("1 hour");
543     if (minutes > 1)
544         parts.push(minutes + " minutes");
545     else if (minutes == 1)
546         parts.push("1 minute");
548     if (minutes <= 1 && hours == 0) {
549         if (seconds != 1)
550             parts.push(seconds + " seconds");
551         else
552             parts.push("1 second");
553     }
555     return parts.join(", ");
558 define_variable(
559     "download_buffer_min_update_interval", 2000,
560     "Minimum interval (in milliseconds) between updates in download progress buffers.\n" +
561         "Lowering this interval will increase the promptness of the progress display at " +
562         "the cost of using additional processor time.");
564 define_keywords("$info");
565 function download_buffer(window, element) {
566     this.constructor_begin();
567     keywords(arguments);
568     special_buffer.call(this, window, element, forward_keywords(arguments));
569     this.info = arguments.$info;
570     this.configuration.cwd = this.info.mozilla_info.targetFile.parent.path;
571     this.description = this.info.mozilla_info.source.spec;
572     this.keymap = download_buffer_keymap;
573     this.update_title();
575     this.progress_change_handler_fn = method_caller(this, this.handle_progress_change);
576     add_hook.call(this.info, "download_progress_change_hook", this.progress_change_handler_fn);
577     add_hook.call(this.info, "download_state_change_hook", this.progress_change_handler_fn);
578     this.command_change_handler_fn = method_caller(this, this.update_command_field);
579     add_hook.call(this.info, "download_shell_command_change_hook", this.command_change_handler_fn);
580     this.constructor_end();
582 download_buffer.prototype = {
583     __proto__: special_buffer.prototype,
585     handle_kill : function () {
586         this.__proto__.handle_kill.call(this);
587         remove_hook.call(this.info, "download_progress_change_hook", this.progress_change_handler_fn);
588         remove_hook.call(this.info, "download_state_change_hook", this.progress_change_handler_fn);
589         remove_hook.call(this.info, "download_shell_command_change_hook", this.command_change_handler_fn);
591         // Remove all node references
592         delete this.status_textnode;
593         delete this.transferred_div_node;
594         delete this.transferred_textnode;
595         delete this.progress_container_node;
596         delete this.progress_bar_node;
597         delete this.time_textnode;
598         delete this.command_div_node;
599         delete this.command_label_textnode;
600         delete this.command_textnode;
601     },
603     update_title : function () {
604         // FIXME: do this properly
605         var new_title;
606         var info = this.info;
607         var append_transfer_info = false;
608         var append_speed_info = true;
609         var label = null;
610         switch(info.state) {
611         case DOWNLOAD_DOWNLOADING:
612             label = "Downloading";
613             append_transfer_info = true;
614             break;
615         case DOWNLOAD_FINISHED:
616             label = "Download complete";
617             break;
618         case DOWNLOAD_FAILED:
619             label = "Download failed";
620             append_transfer_info = true;
621             append_speed_info = false;
622             break;
623         case DOWNLOAD_CANCELED:
624             label = "Download canceled";
625             append_transfer_info = true;
626             append_speed_info = false;
627             break;
628         case DOWNLOAD_PAUSED:
629             label = "Download paused";
630             append_transfer_info = true;
631             append_speed_info = false;
632             break;
633         case DOWNLOAD_QUEUED:
634         default:
635             label = "Download queued";
636             break;
637         }
639         if (append_transfer_info) {
640             if (append_speed_info)
641                 new_title = label + " at " + pretty_print_file_size(info.speed).join(" ") + "/s: ";
642             else
643                 new_title = label + ": ";
644             var trans = pretty_print_file_size(info.amount_transferred);
645             if (info.size >= 0) {
646                 var total = pretty_print_file_size(info.size);
647                 if (trans[1] == total[1])
648                     new_title += trans[0] + "/" + total[0] + " " + total[1];
649                 else
650                     new_title += trans.join(" ") + "/" + total.join(" ");
651             } else
652                 new_title += trans.join(" ");
653             if (info.percent_complete >= 0)
654                 new_title += " (" + info.percent_complete + "%)";
655         } else
656             new_title = label;
657         if (new_title != this.title) {
658             this.title = new_title;
659             return true;
660         }
661         return false;
662     },
664     handle_progress_change : function () {
665         var cur_time = Date.now();
666         if (this.last_update == null ||
667             (cur_time - this.last_update) > download_buffer_min_update_interval ||
668             this.info.state != this.previous_state) {
670             if (this.update_title())
671                 buffer_title_change_hook.run(this);
673             if (this.generated) {
674                 this.update_fields();
675             }
676             this.previous_status = this.info.status;
677             this.last_update = cur_time;
678         }
679     },
681     generate: function() {
682         var d = this.document;
683         var g = new dom_generator(d, XHTML_NS);
685         /* Warning: If any additional node references are saved in
686          * this function, appropriate code to delete the saved
687          * properties must be added to handle_kill. */
689         var info = this.info;
691         d.body.setAttribute("class", "download-buffer");
693         g.add_stylesheet("chrome://conkeror/content/downloads.css");
695         var div;
696         var label, value;
698         div = g.element("div", d.body, "class", "download-info", "id", "download-source");
699         label = g.element("div", div, "class", "download-label");
700         this.status_textnode = g.text("", label);
701         value = g.element("div", div, "class", "download-value");
702         g.text(info.source.spec, value);
704         div = g.element("div", d.body, "class", "download-info", "id", "download-target");
705         label = g.element("div", div, "class", "download-label");
706         var target_label;
707         if (info.temporary_status != DOWNLOAD_NOT_TEMPORARY)
708             target_label = "Temp. file:";
709         else
710             target_label = "Target:";
711         g.text(target_label, label);
712         value = g.element("div", div, "class", "download-value");
713         g.text(info.target_file.path, value);
715         div = g.element("div", d.body, "class", "download-info", "id", "download-mime-type");
716         label = g.element("div", div, "class", "download-label");
717         g.text("MIME type:", label);
718         value = g.element("div", div, "class", "download-value");
719         g.text(info.MIME_type || "unknown", value);
721         this.transferred_div_node = div = g.element("div", d.body,
722                                                     "class", "download-info",
723                                                     "id", "download-transferred");
724         label = g.element("div", div, "class", "download-label");
725         g.text("Transferred:", label);
726         value = g.element("div", div, "class", "download-value");
727         this.transferred_textnode = g.text("", value);
728         this.progress_container_node = value = g.element("div", div, "id", "download-progress-container");
729         this.progress_bar_node = g.element("div", value, "id", "download-progress-bar");
730         value = g.element("div", div, "class", "download-value", "id", "download-percent");
731         this.percent_textnode = g.text("", value);
733         div = g.element("div", d.body, "class", "download-info", "id", "download-time");
734         label = g.element("div", div, "class", "download-label");
735         g.text("Time:", label);
736         value = g.element("div", div, "class", "download-value");
737         this.time_textnode = g.text("", value);
739         if (info.action_description != null) {
740             div = g.element("div", d.body, "class", "download-info", "id", "download-action");
741             label = g.element("div", div, "class", "download-label");
742             g.text("Action:", label);
743             value = g.element("div", div, "class", "download-value");
744             g.text(info.action_description, value);
745         }
747         this.command_div_node = div = g.element("div", d.body, "class", "download-info", "id", "download-command");
748         label = g.element("div", div, "class", "download-label");
749         this.command_label_textnode = g.text("Run command:", label);
750         value = g.element("div", div, "class", "download-value");
751         this.command_textnode = g.text("", value);
753         this.update_fields();
755         this.update_command_field();
756     },
758     update_fields : function () {
759         if (!this.generated)
760             return;
761         var info = this.info;
762         var label = null;
763         switch(info.state) {
764         case DOWNLOAD_DOWNLOADING:
765             label = "Downloading";
766             break;
767         case DOWNLOAD_FINISHED:
768             label = "Completed";
769             break;
770         case DOWNLOAD_FAILED:
771             label = "Failed";
772             break;
773         case DOWNLOAD_CANCELED:
774             label = "Canceled";
775             break;
776         case DOWNLOAD_PAUSED:
777             label = "Paused";
778             break;
779         case DOWNLOAD_QUEUED:
780         default:
781             label = "Queued";
782             break;
783         }
784         this.status_textnode.nodeValue = label + ":";
785         this.update_time_field();
787         var tran_text = "";
788         if (info.state == DOWNLOAD_FINISHED)
789             tran_text = pretty_print_file_size(info.size).join(" ");
790         else {
791             var trans = pretty_print_file_size(info.amount_transferred);
792             if (info.size >= 0) {
793                 var total = pretty_print_file_size(info.size);
794                 if (trans[1] == total[1])
795                     tran_text += trans[0] + "/" + total[0] + " " + total[1];
796                 else
797                     tran_text += trans.join(" ") + "/" + total.join(" ");
798             } else
799                 tran_text += trans.join(" ");
800         }
801         this.transferred_textnode.nodeValue = tran_text;
802         if (info.percent_complete >= 0) {
803             this.progress_container_node.style.display = "";
804             this.percent_textnode.nodeValue = info.percent_complete + "%";
805             this.progress_bar_node.style.width = info.percent_complete + "%";
806         } else {
807             this.percent_textnode.nodeValue = "";
808             this.progress_container_node.style.display = "none";
809         }
811         this.update_command_field();
812     },
814     update_time_field : function () {
815         var info = this.info;
816         var elapsed_text = pretty_print_time((Date.now() - info.start_time / 1000) / 1000) + " elapsed";
817         var text = "";
818         if (info.state == DOWNLOAD_DOWNLOADING) {
819             text = pretty_print_file_size(info.speed).join(" ") + "/s, ";
820         }
821         if (info.state == DOWNLOAD_DOWNLOADING &&
822             info.size >= 0 &&
823             info.speed > 0) {
824             let remaining = (info.size - info.amount_transferred) / info.speed;
825             text += pretty_print_time(remaining) + " left (" + elapsed_text + ")";
826         } else {
827             text = elapsed_text;
828         }
829         this.time_textnode.nodeValue = text;
830     },
832     update_command_field : function () {
833         if (!this.generated)
834             return;
835         if (this.info.shell_command != null) {
836             this.command_div_node.style.display = "";
837             var label;
838             if (this.info.running_shell_command)
839                 label = "Running:";
840             else if (this.info.state == DOWNLOAD_FINISHED)
841                 label = "Ran command:";
842             else
843                 label = "Run command:";
844             this.command_label_textnode.nodeValue = label;
845             this.command_textnode.nodeValue = this.info.shell_command;
846         } else {
847             this.command_div_node.style.display = "none";
848         }
849     }
852 function download_cancel(buffer) {
853     check_buffer(buffer, download_buffer);
854     var info = buffer.info;
855     info.cancel();
856     buffer.window.minibuffer.message("Download canceled");
858 interactive("download-cancel",
859             "Cancel the current download.\n" +
860             "The download can later be retried using the `download-retry' command, but any " +
861             "data already transferred will be lost.",
862             function (I) {download_cancel(I.buffer);});
864 function download_retry(buffer) {
865     check_buffer(buffer, download_buffer);
866     var info = buffer.info;
867     info.retry();
868     buffer.window.minibuffer.message("Download retried");
870 interactive("download-retry",
871             "Retry a failed or canceled download.\n" +
872             "This command can be used to retry a download that failed or was cancled using " +
873             "the `download-cancel' command.  The download will begin from the start again.",
874             function (I) {download_retry(I.buffer);});
876 function download_pause(buffer) {
877     check_buffer(buffer, download_buffer);
878     buffer.info.pause();
879     buffer.window.minibuffer.message("Download paused");
881 interactive("download-pause",
882             "Pause the current download.\n" +
883             "The download can later be resumed using the `download-resume' command.  The " +
884             "data already transferred will not be lost.",
885             function (I) {download_pause(I.buffer);});
887 function download_resume(buffer) {
888     check_buffer(buffer, download_buffer);
889     buffer.info.resume();
890     buffer.window.minibuffer.message("Download resumed");
892 interactive("download-resume",
893             "Resume the current download.\n" +
894             "This command can be used to resume a download paused using the `download-pause' command.",
895             function (I) {download_resume(I.buffer);});
897 function download_remove(buffer) {
898     check_buffer(buffer, download_buffer);
899     buffer.info.remove();
900     buffer.window.minibuffer.message("Download removed");
902 interactive("download-remove",
903             "Remove the current download from the download manager.\n" +
904             "This command can only be used on inactive (paused, canceled, completed, or failed) downloads.",
905             function (I) {download_remove(I.buffer);});
907 function download_retry_or_resume(buffer) {
908     check_buffer(buffer, download_buffer);
909     var info = buffer.info;
910     if (info.state == DOWNLOAD_PAUSED)
911         download_resume(buffer);
912     else
913         download_retry(buffer);
915 interactive("download-retry-or-resume",
916             "Retry or resume the current download.\n" +
917             "This command can be used to resume a download paused using the `download-pause' " +
918             "command or canceled using the `download-cancel' command.",
919             function (I) {download_retry_or_resume(I.buffer);});
921 function download_pause_or_resume(buffer) {
922     check_buffer(buffer, download_buffer);
923     var info = buffer.info;
924     if (info.state == DOWNLOAD_PAUSED)
925         download_resume(buffer);
926     else
927         download_pause(buffer);
929 interactive("download-pause-or-resume",
930             "Pause or resume the current download.\n" +
931             "This command toggles the paused state of the current download.",
932             function (I) {download_pause_or_resume(I.buffer);});
934 function download_delete_target(buffer) {
935     check_buffer(buffer, download_buffer);
936     var info = buffer.info;
937     info.delete_target();
938     buffer.window.minibuffer.message("Deleted file: " + info.target_file.path);
940 interactive("download-delete-target",
941             "Delete the target file of the current download.\n"  +
942             "This command can only be used if the download has finished successfully.",
943             function (I) {download_delete_target(I.buffer);});
945 function download_shell_command(buffer, cwd, cmd) {
946     check_buffer(buffer, download_buffer);
947     var info = buffer.info;
948     if (info.state == DOWNLOAD_FINISHED) {
949         shell_command_with_argument_blind(cmd, info.target_file.path, $cwd = cwd);
950         return;
951     }
952     if (info.state != DOWNLOAD_DOWNLOADING && info.state != DOWNLOAD_PAUSED && info.state != DOWNLOAD_QUEUED)
953         info.throw_state_error();
954     if (cmd == null || cmd.length == 0)
955         info.set_shell_command(null, cwd);
956     else
957         info.set_shell_command(cmd, cwd);
958     buffer.window.minibuffer.message("Queued shell command: " + cmd);
960 interactive("download-shell-command",
961             "Run a shell command on the target file of the current download.\n" +
962             "If the download is still in progress, the shell command will be queued " +
963             "to run when the download finishes.",
964             function (I) {
965                 var buffer = check_buffer(I.buffer, download_buffer);
966                 var cwd = buffer.info.shell_command_cwd || buffer.cwd;
967                 var cmd = yield I.minibuffer.read_shell_command(
968                     $cwd = cwd,
969                     $initial_value = buffer.info.shell_command ||
970                         get_external_handler_for_mime_type(buffer.info.MIME_type));
971                 download_shell_command(buffer, cwd, cmd);
972             });
974 function download_manager_ui()
976 download_manager_ui.prototype = {
977     QueryInterface : XPCOMUtils.generateQI([Ci.nsIDownloadManagerUI]),
979     getAttention : function () {},
980     show : function () {},
981     visible : false
985 function download_manager_show_builtin_ui(window) {
986     download_manager_builtin_ui.show(window);
988 interactive("download-manager-show-builtin-ui",
989             "Show the built-in (Firefox-style) download manager user interface.",
990             function (I) {download_manager_show_builtin_ui(I.window);});
994 define_variable("download_temporary_file_open_buffer_delay", 500,
995                      "Delay (in milliseconds) before a download buffer is opened for temporary downloads.\n" +
996                      "This variable takes effect only if `open_download_buffer_automatically' is in " +
997                      "`download_added_hook', as it is by default.");
1000 define_variable("download_buffer_automatic_open_target", OPEN_NEW_WINDOW,
1001                      "Target for download buffers created by the `open_download_buffer_automatically' function.\n" +
1002                      "This variable takes effect only if `open_download_buffer_auotmatically' is in " +
1003                      "`download_added_hook', as it is by default.");
1005 function open_download_buffer_automatically(info) {
1006     var buf = info.source_buffer;
1007     var target = download_buffer_automatic_open_target;
1008     if (buf == null)
1009         target = OPEN_NEW_WINDOW;
1010     if (info.temporary_status == DOWNLOAD_NOT_TEMPORARY ||
1011         !(download_temporary_file_open_buffer_delay > 0))
1012         create_buffer(buf, buffer_creator(download_buffer, $info = info), target);
1013     else {
1014         var timer = null;
1015         function finish() {
1016             timer.cancel();
1017         }
1018         add_hook.call(info, "download_finished_hook", finish);
1019         timer = call_after_timeout(function () {
1020                 remove_hook.call(info, "download_finished_hook", finish);
1021                 create_buffer(buf, buffer_creator(download_buffer, $info = info), target);
1022             }, download_temporary_file_open_buffer_delay);
1023     }
1025 add_hook("download_added_hook", open_download_buffer_automatically);