for loop efficiency
[conkeror.git] / modules / download-manager.js
blob367277feac37cf9d8a3ba95d965177712454edbb
1 /**
2  * (C) Copyright 2008 Jeremy Maitin-Shepard
3  * (C) Copyright 2009 John Foerch
4  *
5  * Use, modification, and distribution are subject to the terms specified in the
6  * COPYING file.
7 **/
9 require("special-buffer.js");
10 require("mime-type-override.js");
11 require("minibuffer-read-mime-type.js");
13 var download_manager_service = Cc["@mozilla.org/download-manager;1"]
14     .getService(Ci.nsIDownloadManager);
16 var download_manager_builtin_ui = Components
17     .classesByID["{7dfdf0d1-aff6-4a34-bad1-d0fe74601642}"]
18     .getService(Ci.nsIDownloadManagerUI);
21 var unmanaged_download_info_list = [];
22 var id_to_download_info = {};
24 // Import these constants for convenience
25 const DOWNLOAD_NOTSTARTED = Ci.nsIDownloadManager.DOWNLOAD_NOTSTARTED;
26 const DOWNLOAD_DOWNLOADING = Ci.nsIDownloadManager.DOWNLOAD_DOWNLOADING;
27 const DOWNLOAD_FINISHED = Ci.nsIDownloadManager.DOWNLOAD_FINISHED;
28 const DOWNLOAD_FAILED = Ci.nsIDownloadManager.DOWNLOAD_FAILED;
29 const DOWNLOAD_CANCELED = Ci.nsIDownloadManager.DOWNLOAD_CANCELED;
30 const DOWNLOAD_PAUSED = Ci.nsIDownloadManager.DOWNLOAD_PAUSED;
31 const DOWNLOAD_QUEUED = Ci.nsIDownloadManager.DOWNLOAD_QUEUED;
32 const DOWNLOAD_BLOCKED = Ci.nsIDownloadManager.DOWNLOAD_BLOCKED;
33 const DOWNLOAD_SCANNING = Ci.nsIDownloadManager.DOWNLOAD_SCANNING;
36 const DOWNLOAD_NOT_TEMPORARY = 0;
37 const DOWNLOAD_TEMPORARY_FOR_ACTION = 1;
38 const DOWNLOAD_TEMPORARY_FOR_COMMAND = 2;
40 function download_info (source_buffer, mozilla_info, target_file) {
41     this.source_buffer = source_buffer;
42     this.target_file = target_file;
43     if (mozilla_info != null)
44         this.attach(mozilla_info);
46 download_info.prototype = {
47     attach : function (mozilla_info) {
48         if (!this.target_file)
49             this.__defineGetter__("target_file", function(){
50                     return this.mozilla_info.targetFile;
51                 });
52         else if (this.target_file.path != mozilla_info.targetFile.path)
53             throw interactive_error("Download target file unexpected.");
54         this.mozilla_info = mozilla_info;
55         id_to_download_info[mozilla_info.id] = this;
56         download_added_hook.run(this);
57     },
59     target_file : null,
61     shell_command : null,
63     shell_command_cwd : null,
65     temporary_status : DOWNLOAD_NOT_TEMPORARY,
67     action_description : null,
69     set_shell_command : function (str, cwd) {
70         this.shell_command = str;
71         this.shell_command_cwd = cwd;
72         if (this.mozilla_info)
73             download_shell_command_change_hook.run(this);
74     },
76     /**
77      * None of the following members may be used until attach is called
78      */
80     // Reflectors to properties of nsIDownload
81     get state () { return this.mozilla_info.state; },
82     get display_name () { return this.mozilla_info.displayName; },
83     get amount_transferred () { return this.mozilla_info.amountTransferred; },
84     get percent_complete () { return this.mozilla_info.percentComplete; },
85     get size () {
86         var s = this.mozilla_info.size;
87         /* nsIDownload.size is a PRUint64, and will have value
88          * LL_MAXUINT (2^64 - 1) to indicate an unknown size.  Because
89          * JavaScript only has a double numerical type, this value
90          * cannot be represented exactly, so 2^36 is used instead as the cutoff. */
91         if (s < 68719476736 /* 2^36 */)
92             return s;
93         return -1;
94     },
95     get source () { return this.mozilla_info.source; },
96     get start_time () { return this.mozilla_info.startTime; },
97     get speed () { return this.mozilla_info.speed; },
98     get MIME_info () { return this.mozilla_info.MIMEInfo; },
99     get MIME_type () {
100         if (this.MIME_info)
101             return this.MIME_info.MIMEType;
102         return null;
103     },
104     get id () { return this.mozilla_info.id; },
105     get referrer () { return this.mozilla_info.referrer; },
107     target_file_text : function () {
108         let target = this.target_file.path;
109         let display = this.display_name;
110         if (target.indexOf(display, target.length - display.length) == -1)
111             target += " (" + display + ")";
112         return target;
113     },
115     throw_if_removed : function () {
116         if (this.removed)
117             throw interactive_error("Download has already been removed from the download manager.");
118     },
120     throw_state_error : function () {
121         switch (this.state) {
122         case DOWNLOAD_DOWNLOADING:
123             throw interactive_error("Download is already in progress.");
124         case DOWNLOAD_FINISHED:
125             throw interactive_error("Download has already completed.");
126         case DOWNLOAD_FAILED:
127             throw interactive_error("Download has already failed.");
128         case DOWNLOAD_CANCELED:
129             throw interactive_error("Download has already been canceled.");
130         case DOWNLOAD_PAUSED:
131             throw interactive_error("Download has already been paused.");
132         case DOWNLOAD_QUEUED:
133             throw interactive_error("Download is queued.");
134         default:
135             throw new Error("Download has unexpected state: " + this.state);
136         }
137     },
139     // Download manager operations
140     cancel : function ()  {
141         this.throw_if_removed();
142         switch (this.state) {
143         case DOWNLOAD_DOWNLOADING:
144         case DOWNLOAD_PAUSED:
145         case DOWNLOAD_QUEUED:
146             try {
147                 download_manager_service.cancelDownload(this.id);
148             } catch (e) {
149                 throw interactive_error("Download cannot be canceled.");
150             }
151             break;
152         default:
153             this.throw_state_error();
154         }
155     },
157     retry : function () {
158         this.throw_if_removed();
159         switch (this.state) {
160         case DOWNLOAD_CANCELED:
161         case DOWNLOAD_FAILED:
162             try {
163                 download_manager_service.retryDownload(this.id);
164             } catch (e) {
165                 throw interactive_error("Download cannot be retried.");
166             }
167             break;
168         default:
169             this.throw_state_error();
170         }
171     },
173     resume : function () {
174         this.throw_if_removed();
175         switch (this.state) {
176         case DOWNLOAD_PAUSED:
177             try {
178                 download_manager_service.resumeDownload(this.id);
179             } catch (e) {
180                 throw interactive_error("Download cannot be resumed.");
181             }
182             break;
183         default:
184             this.throw_state_error();
185         }
186     },
188     pause : function () {
189         this.throw_if_removed();
190         switch (this.state) {
191         case DOWNLOAD_DOWNLOADING:
192         case DOWNLOAD_QUEUED:
193             try {
194                 download_manager_service.pauseDownload(this.id);
195             } catch (e) {
196                 throw interactive_error("Download cannot be paused.");
197             }
198             break;
199         default:
200             this.throw_state_error();
201         }
202     },
204     remove : function () {
205         this.throw_if_removed();
206         switch (this.state) {
207         case DOWNLOAD_FAILED:
208         case DOWNLOAD_CANCELED:
209         case DOWNLOAD_FINISHED:
210             try {
211                 download_manager_service.removeDownload(this.id);
212             } catch (e) {
213                 throw interactive_error("Download cannot be removed.");
214             }
215             break;
216         default:
217             throw interactive_error("Download is still in progress.");
218         }
219     },
221     delete_target : function () {
222         if (this.state != DOWNLOAD_FINISHED)
223             throw interactive_error("Download has not finished.");
224         try {
225             this.target_file.remove(false);
226         } catch (e) {
227             if ("result" in e) {
228                 switch (e.result) {
229                 case Cr.NS_ERROR_FILE_TARGET_DOES_NOT_EXIST:
230                     throw interactive_error("File has already been deleted.");
231                 case Cr.NS_ERROR_FILE_ACCESS_DENIED:
232                     throw interactive_error("Access denied");
233                 case Cr.NS_ERROR_FILE_DIR_NOT_EMPTY:
234                     throw interactive_error("Failed to delete file.");
235                 }
236             }
237             throw e;
238         }
239     }
242 var define_download_local_hook = simple_local_hook_definer();
244 // FIXME: add more parameters
245 function register_download (buffer, source_uri, target_file) {
246     var info = new download_info(buffer, null, target_file);
247     info.registered_time_stamp = Date.now();
248     info.registered_source_uri = source_uri;
249     unmanaged_download_info_list.push(info);
250     return info;
253 function match_registered_download (mozilla_info) {
254     let list = unmanaged_download_info_list;
255     let t = Date.now();
256     for (let i = 0; i < list.length; ++i) {
257         let x = list[i];
258         if (x.registered_source_uri == mozilla_info.source) {
259             list.splice(i, 1);
260             return x;
261         }
262         if (t - x.registered_time_stamp > download_info_max_queue_delay) {
263             list.splice(i, 1);
264             --i;
265             continue;
266         }
267     }
268     return null;
271 define_download_local_hook("download_added_hook");
272 define_download_local_hook("download_removed_hook");
273 define_download_local_hook("download_finished_hook");
274 define_download_local_hook("download_progress_change_hook");
275 define_download_local_hook("download_state_change_hook");
276 define_download_local_hook("download_shell_command_change_hook");
278 define_variable('delete_temporary_files_for_command', true,
279     'If this is set to true, temporary files downloaded to run a command '+
280     'on them will be deleted once the command completes. If not, the file '+
281     'will stay around forever unless deleted outside the browser.');
283 var download_info_max_queue_delay = 100;
285 var download_progress_listener = {
286     QueryInterface: generate_QI(Ci.nsIDownloadProgressListener),
288     onDownloadStateChange : function (state, download) {
289         var info = null;
290         /* FIXME: Determine if only new downloads will have this state
291          * as their previous state. */
293         dumpln("download state change: " + download.source.spec + ": " + state + ", " + download.state + ", " + download.id);
295         if (state == DOWNLOAD_NOTSTARTED) {
296             info = match_registered_download(download);
297             if (info == null) {
298                 info = new download_info(null, download);
299                 dumpln("error: encountered unknown new download");
300             } else {
301                 info.attach(download);
302             }
303         } else {
304             info = id_to_download_info[download.id];
305             if (info == null) {
306                 dumpln("Error: encountered unknown download");
308             } else {
309                 info.mozilla_info = download;
310                 download_state_change_hook.run(info);
311                 if (info.state == DOWNLOAD_FINISHED) {
312                     download_finished_hook.run(info);
314                     if (info.shell_command != null) {
315                         info.running_shell_command = true;
316                         co_call(function () {
317                             try {
318                                 yield shell_command_with_argument(info.shell_command,
319                                                                   info.target_file.path,
320                                                                   $cwd = info.shell_command_cwd);
321                             } finally  {
322                                 if (info.temporary_status == DOWNLOAD_TEMPORARY_FOR_COMMAND)
323                                     if(delete_temporary_files_for_command) {
324                                         info.target_file.remove(false /* not recursive */);
325                                     }
326                                 info.running_shell_command = false;
327                                 download_shell_command_change_hook.run(info);
328                             }
329                         }());
330                         download_shell_command_change_hook.run(info);
331                     }
332                 }
333             }
334         }
335     },
337     onProgressChange : function (progress, request, cur_self_progress, max_self_progress,
338                                  cur_total_progress, max_total_progress,
339                                  download) {
340         var info = id_to_download_info[download.id];
341         if (info == null) {
342             dumpln("error: encountered unknown download in progress change");
343             return;
344         }
345         info.mozilla_info = download;
346         download_progress_change_hook.run(info);
347         //dumpln("download progress change: " + download.source.spec + ": " + cur_self_progress + "/" + max_self_progress + " "
348         // + cur_total_progress + "/" + max_total_progress + ", " + download.state + ", " + download.id);
349     },
351     onSecurityChange : function (progress, request, state, download) {
352     },
354     onStateChange : function (progress, request, state_flags, status, download) {
355     }
358 var download_observer = {
359     observe : function (subject, topic, data) {
360         switch(topic) {
361         case "download-manager-remove-download":
362             var ids = [];
363             if (!subject) {
364                 // Remove all downloads
365                 for (let i in id_to_download_info)
366                     ids.push(i);
367             } else {
368                 let id = subject.QueryInterface(Ci.nsISupportsPRUint32);
369                 /* FIXME: determine if this should really be an error */
370                 if (!(id in id_to_download_info)) {
371                     dumpln("Error: download-manager-remove-download event received for unknown download: " + id);
372                 } else
373                     ids.push(id);
374             }
375             for each (let i in ids) {
376                 dumpln("deleting download: " + i);
377                 let d = id_to_download_info[i];
378                 d.removed = true;
379                 download_removed_hook.run(d);
380                 delete id_to_download_info[i];
381             }
382             break;
383         }
384     }
386 observer_service.addObserver(download_observer, "download-manager-remove-download", false);
388 download_manager_service.addListener(download_progress_listener);
390 function pretty_print_file_size (val) {
391     const GIBI = 1073741824; /* 2^30 */
392     const MEBI = 1048576; /* 2^20 */
393     const KIBI = 1024; /* 2^10 */
394     var suffix, div;
395     if (val < KIBI) {
396         div = 1;
397         suffix = "B";
398     }
399     else if (val < MEBI) {
400         suffix = "KiB";
401         div = KIBI;
402     } else if (val < GIBI) {
403         suffix = "MiB";
404         div = MEBI;
405     } else {
406         suffix = "GiB";
407         div = GIBI;
408     }
409     val = val / div;
410     var precision = 2;
411     if (val > 10)
412         precision = 1;
413     if (val > 100)
414         precision = 0;
415     return [val.toFixed(precision), suffix];
418 function pretty_print_time (val) {
419     val = Math.round(val);
420     var seconds = val % 60;
422     val = Math.floor(val / 60);
424     var minutes = val % 60;
426     var hours = Math.floor(val / 60);
428     var parts = [];
430     if (hours > 1)
431         parts.push(hours + " hours");
432     else if (hours == 1)
433         parts.push("1 hour");
435     if (minutes > 1)
436         parts.push(minutes + " minutes");
437     else if (minutes == 1)
438         parts.push("1 minute");
440     if (minutes <= 1 && hours == 0) {
441         if (seconds != 1)
442             parts.push(seconds + " seconds");
443         else
444             parts.push("1 second");
445     }
447     return parts.join(", ");
450 define_variable("download_buffer_min_update_interval", 2000,
451     "Minimum interval (in milliseconds) between updates in download progress buffers.\n" +
452     "Lowering this interval will increase the promptness of the progress display at " +
453     "the cost of using additional processor time.");
455 function download_buffer_modality (buffer, element) {
456     buffer.keymaps.push(download_buffer_keymap);
459 define_keywords("$info");
460 function download_buffer (window, element) {
461     this.constructor_begin();
462     keywords(arguments);
463     special_buffer.call(this, window, element, forward_keywords(arguments));
464     this.info = arguments.$info;
465     this.local.cwd = this.info.mozilla_info.targetFile.parent;
466     this.description = this.info.mozilla_info.source.spec;
467     this.update_title();
469     this.progress_change_handler_fn = method_caller(this, this.handle_progress_change);
470     add_hook.call(this.info, "download_progress_change_hook", this.progress_change_handler_fn);
471     add_hook.call(this.info, "download_state_change_hook", this.progress_change_handler_fn);
472     this.command_change_handler_fn = method_caller(this, this.update_command_field);
473     add_hook.call(this.info, "download_shell_command_change_hook", this.command_change_handler_fn);
474     this.modalities.push(download_buffer_modality);
475     this.constructor_end();
477 download_buffer.prototype = {
478     __proto__: special_buffer.prototype,
480     handle_kill : function () {
481         special_buffer.prototype.handle_kill.call(this);
482         remove_hook.call(this.info, "download_progress_change_hook", this.progress_change_handler_fn);
483         remove_hook.call(this.info, "download_state_change_hook", this.progress_change_handler_fn);
484         remove_hook.call(this.info, "download_shell_command_change_hook", this.command_change_handler_fn);
486         // Remove all node references
487         delete this.status_textnode;
488         delete this.target_file_node;
489         delete this.transferred_div_node;
490         delete this.transferred_textnode;
491         delete this.progress_container_node;
492         delete this.progress_bar_node;
493         delete this.percent_textnode;
494         delete this.time_textnode;
495         delete this.command_div_node;
496         delete this.command_label_textnode;
497         delete this.command_textnode;
498     },
500     update_title : function () {
501         // FIXME: do this properly
502         var new_title;
503         var info = this.info;
504         var append_transfer_info = false;
505         var append_speed_info = true;
506         var label = null;
507         switch(info.state) {
508         case DOWNLOAD_DOWNLOADING:
509             label = "Downloading";
510             append_transfer_info = true;
511             break;
512         case DOWNLOAD_FINISHED:
513             label = "Download complete";
514             break;
515         case DOWNLOAD_FAILED:
516             label = "Download failed";
517             append_transfer_info = true;
518             append_speed_info = false;
519             break;
520         case DOWNLOAD_CANCELED:
521             label = "Download canceled";
522             append_transfer_info = true;
523             append_speed_info = false;
524             break;
525         case DOWNLOAD_PAUSED:
526             label = "Download paused";
527             append_transfer_info = true;
528             append_speed_info = false;
529             break;
530         case DOWNLOAD_QUEUED:
531         default:
532             label = "Download queued";
533             break;
534         }
536         if (append_transfer_info) {
537             if (append_speed_info)
538                 new_title = label + " at " + pretty_print_file_size(info.speed).join(" ") + "/s: ";
539             else
540                 new_title = label + ": ";
541             var trans = pretty_print_file_size(info.amount_transferred);
542             if (info.size >= 0) {
543                 var total = pretty_print_file_size(info.size);
544                 if (trans[1] == total[1])
545                     new_title += trans[0] + "/" + total[0] + " " + total[1];
546                 else
547                     new_title += trans.join(" ") + "/" + total.join(" ");
548             } else
549                 new_title += trans.join(" ");
550             if (info.percent_complete >= 0)
551                 new_title += " (" + info.percent_complete + "%)";
552         } else
553             new_title = label;
554         if (new_title != this.title) {
555             this.title = new_title;
556             return true;
557         }
558         return false;
559     },
561     handle_progress_change : function () {
562         var cur_time = Date.now();
563         if (this.last_update == null ||
564             (cur_time - this.last_update) > download_buffer_min_update_interval ||
565             this.info.state != this.previous_state) {
567             if (this.update_title())
568                 buffer_title_change_hook.run(this);
570             if (this.generated) {
571                 this.update_fields();
572             }
573             this.previous_status = this.info.status;
574             this.last_update = cur_time;
575         }
576     },
578     generate : function () {
579         var d = this.document;
580         var g = new dom_generator(d, XHTML_NS);
582         /* Warning: If any additional node references are saved in
583          * this function, appropriate code to delete the saved
584          * properties must be added to handle_kill. */
586         var info = this.info;
588         d.body.setAttribute("class", "download-buffer");
590         g.add_stylesheet("chrome://conkeror-gui/content/downloads.css");
592         var row, cell;
593         var table = g.element("table", d.body);
595         row = g.element("tr", table, "class", "download-info", "id", "download-source");
596         cell = g.element("td", row, "class", "download-label");
597         this.status_textnode = g.text("", cell);
598         cell = g.element("td", row, "class", "download-value");
599         g.text(info.source.spec, cell);
601         row = g.element("tr", table, "class", "download-info", "id", "download-target");
602         cell = g.element("td", row, "class", "download-label");
603         var target_label;
604         if (info.temporary_status != DOWNLOAD_NOT_TEMPORARY)
605             target_label = "Temp. file:";
606         else
607             target_label = "Target:";
608         g.text(target_label, cell);
609         cell = g.element("td", row, "class", "download-value");
610         this.target_file_node = g.text("", cell);
612         row = g.element("tr", table, "class", "download-info", "id", "download-mime-type");
613         cell = g.element("td", row, "class", "download-label");
614         g.text("MIME type:", cell);
615         cell = g.element("td", row, "class", "download-value");
616         g.text(info.MIME_type || "unknown", cell);
618         this.transferred_div_node = row =
619             g.element("tr", table, "class", "download-info", "id", "download-transferred");
620         cell = g.element("td", row, "class", "download-label");
621         g.text("Transferred:", cell);
622         cell = g.element("td", row, "class", "download-value");
623         var sub_item = g.element("div", cell);
624         this.transferred_textnode = g.text("", sub_item);
625         sub_item = g.element("div", cell, "id", "download-percent");
626         this.percent_textnode = g.text("", sub_item);
627         this.progress_container_node = sub_item = g.element("div", cell, "id", "download-progress-container");
628         this.progress_bar_node = g.element("div", sub_item, "id", "download-progress-bar");
630         row = g.element("tr", table, "class", "download-info", "id", "download-time");
631         cell = g.element("td", row, "class", "download-label");
632         g.text("Time:", cell);
633         cell = g.element("td", row, "class", "download-value");
634         this.time_textnode = g.text("", cell);
636         if (info.action_description != null) {
637             row = g.element("tr", table, "class", "download-info", "id", "download-action");
638             cell = g.element("div", row, "class", "download-label");
639             g.text("Action:", cell);
640             cell = g.element("div", row, "class", "download-value");
641             g.text(info.action_description, cell);
642        }
644         this.command_div_node = row = g.element("tr", table, "class", "download-info", "id", "download-command");
645         cell = g.element("td", row, "class", "download-label");
646         this.command_label_textnode = g.text("Run command:", cell);
647         cell = g.element("td", row, "class", "download-value");
648         this.command_textnode = g.text("", cell);
651         this.update_fields();
652         this.update_command_field();
653     },
655     update_fields : function () {
656         if (!this.generated)
657             return;
658         var info = this.info;
659         var label = null;
660         switch(info.state) {
661         case DOWNLOAD_DOWNLOADING:
662             label = "Downloading";
663             break;
664         case DOWNLOAD_FINISHED:
665             label = "Completed";
666             break;
667         case DOWNLOAD_FAILED:
668             label = "Failed";
669             break;
670         case DOWNLOAD_CANCELED:
671             label = "Canceled";
672             break;
673         case DOWNLOAD_PAUSED:
674             label = "Paused";
675             break;
676         case DOWNLOAD_QUEUED:
677         default:
678             label = "Queued";
679             break;
680         }
681         this.status_textnode.nodeValue = label + ":";
682         this.target_file_node.nodeValue = info.target_file_text();
683         this.update_time_field();
685         var tran_text = "";
686         if (info.state == DOWNLOAD_FINISHED)
687             tran_text = pretty_print_file_size(info.size).join(" ");
688         else {
689             var trans = pretty_print_file_size(info.amount_transferred);
690             if (info.size >= 0) {
691                 var total = pretty_print_file_size(info.size);
692                 if (trans[1] == total[1])
693                     tran_text += trans[0] + "/" + total[0] + " " + total[1];
694                 else
695                     tran_text += trans.join(" ") + "/" + total.join(" ");
696             } else
697                 tran_text += trans.join(" ");
698         }
699         this.transferred_textnode.nodeValue = tran_text;
700         if (info.percent_complete >= 0) {
701             this.progress_container_node.style.display = "";
702             this.percent_textnode.nodeValue = info.percent_complete + "%";
703             this.progress_bar_node.style.width = info.percent_complete + "%";
704         } else {
705             this.percent_textnode.nodeValue = "";
706             this.progress_container_node.style.display = "none";
707         }
709         this.update_command_field();
710     },
712     update_time_field : function () {
713         var info = this.info;
714         var elapsed_text = pretty_print_time((Date.now() - info.start_time / 1000) / 1000) + " elapsed";
715         var text = "";
716         if (info.state == DOWNLOAD_DOWNLOADING) {
717             text = pretty_print_file_size(info.speed).join(" ") + "/s, ";
718         }
719         if (info.state == DOWNLOAD_DOWNLOADING &&
720             info.size >= 0 &&
721             info.speed > 0) {
722             let remaining = (info.size - info.amount_transferred) / info.speed;
723             text += pretty_print_time(remaining) + " left (" + elapsed_text + ")";
724         } else {
725             text = elapsed_text;
726         }
727         this.time_textnode.nodeValue = text;
728     },
730     update_command_field : function () {
731         if (!this.generated)
732             return;
733         if (this.info.shell_command != null) {
734             this.command_div_node.style.display = "";
735             var label;
736             if (this.info.running_shell_command)
737                 label = "Running:";
738             else if (this.info.state == DOWNLOAD_FINISHED)
739                 label = "Ran command:";
740             else
741                 label = "Run command:";
742             this.command_label_textnode.nodeValue = label;
743             this.command_textnode.nodeValue = this.info.shell_command;
744         } else {
745             this.command_div_node.style.display = "none";
746         }
747     }
750 function download_cancel (buffer) {
751     check_buffer(buffer, download_buffer);
752     var info = buffer.info;
753     info.cancel();
754     buffer.window.minibuffer.message("Download canceled");
756 interactive("download-cancel",
757             "Cancel the current download.\n" +
758             "The download can later be retried using the `download-retry' command, but any " +
759             "data already transferred will be lost.",
760             function (I) {
761                 let result = yield I.window.minibuffer.read_single_character_option(
762                     $prompt = "Cancel this download? (y/n)",
763                     $options = ["y", "n"]);
764                 if (result == "y")
765                     download_cancel(I.buffer);
766             });
768 function download_retry (buffer) {
769     check_buffer(buffer, download_buffer);
770     var info = buffer.info;
771     info.retry();
772     buffer.window.minibuffer.message("Download retried");
774 interactive("download-retry",
775             "Retry a failed or canceled download.\n" +
776             "This command can be used to retry a download that failed or was canceled using " +
777             "the `download-cancel' command.  The download will begin from the start again.",
778             function (I) {download_retry(I.buffer);});
780 function download_pause (buffer) {
781     check_buffer(buffer, download_buffer);
782     buffer.info.pause();
783     buffer.window.minibuffer.message("Download paused");
785 interactive("download-pause",
786             "Pause the current download.\n" +
787             "The download can later be resumed using the `download-resume' command.  The " +
788             "data already transferred will not be lost.",
789             function (I) {download_pause(I.buffer);});
791 function download_resume (buffer) {
792     check_buffer(buffer, download_buffer);
793     buffer.info.resume();
794     buffer.window.minibuffer.message("Download resumed");
796 interactive("download-resume",
797             "Resume the current download.\n" +
798             "This command can be used to resume a download paused using the `download-pause' command.",
799             function (I) { download_resume(I.buffer); });
801 function download_remove (buffer) {
802     check_buffer(buffer, download_buffer);
803     buffer.info.remove();
804     buffer.window.minibuffer.message("Download removed");
806 interactive("download-remove",
807             "Remove the current download from the download manager.\n" +
808             "This command can only be used on inactive (paused, canceled, "+
809             "completed, or failed) downloads.",
810             function (I) {download_remove(I.buffer);});
812 function download_retry_or_resume (buffer) {
813     check_buffer(buffer, download_buffer);
814     var info = buffer.info;
815     if (info.state == DOWNLOAD_PAUSED)
816         download_resume(buffer);
817     else
818         download_retry(buffer);
820 interactive("download-retry-or-resume",
821             "Retry or resume the current download.\n" +
822             "This command can be used to resume a download paused using the `download-pause' " +
823             "command or canceled using the `download-cancel' command.",
824             function (I) {download_retry_or_resume(I.buffer);});
826 function download_pause_or_resume (buffer) {
827     check_buffer(buffer, download_buffer);
828     var info = buffer.info;
829     if (info.state == DOWNLOAD_PAUSED)
830         download_resume(buffer);
831     else
832         download_pause(buffer);
834 interactive("download-pause-or-resume",
835             "Pause or resume the current download.\n" +
836             "This command toggles the paused state of the current download.",
837             function (I) {download_pause_or_resume(I.buffer);});
839 function download_delete_target (buffer) {
840     check_buffer(buffer, download_buffer);
841     var info = buffer.info;
842     info.delete_target();
843     buffer.window.minibuffer.message("Deleted file: " + info.target_file.path);
845 interactive("download-delete-target",
846             "Delete the target file of the current download.\n"  +
847             "This command can only be used if the download has finished successfully.",
848             function (I) {download_delete_target(I.buffer);});
850 function download_shell_command (buffer, cwd, cmd) {
851     check_buffer(buffer, download_buffer);
852     var info = buffer.info;
853     if (info.state == DOWNLOAD_FINISHED) {
854         shell_command_with_argument_blind(cmd, info.target_file.path, $cwd = cwd);
855         return;
856     }
857     if (info.state != DOWNLOAD_DOWNLOADING && info.state != DOWNLOAD_PAUSED && info.state != DOWNLOAD_QUEUED)
858         info.throw_state_error();
859     if (cmd == null || cmd.length == 0)
860         info.set_shell_command(null, cwd);
861     else
862         info.set_shell_command(cmd, cwd);
863     buffer.window.minibuffer.message("Queued shell command: " + cmd);
865 interactive("download-shell-command",
866             "Run a shell command on the target file of the current download.\n" +
867             "If the download is still in progress, the shell command will be queued " +
868             "to run when the download finishes.",
869             function (I) {
870                 var buffer = check_buffer(I.buffer, download_buffer);
871                 var cwd = buffer.info.shell_command_cwd || I.local.cwd;
872                 var cmd = yield I.minibuffer.read_shell_command(
873                     $cwd = cwd,
874                     $initial_value = buffer.info.shell_command ||
875                         external_content_handlers.get(buffer.info.MIME_type));
876                 download_shell_command(buffer, cwd, cmd);
877             });
879 function download_manager_ui () {}
880 download_manager_ui.prototype = {
881     QueryInterface : XPCOMUtils.generateQI([Ci.nsIDownloadManagerUI]),
883     getAttention : function () {},
884     show : function () {},
885     visible : false
889 function download_manager_show_builtin_ui (window) {
890     download_manager_builtin_ui.show(window);
892 interactive("download-manager-show-builtin-ui",
893             "Show the built-in (Firefox-style) download manager user interface.",
894             function (I) {download_manager_show_builtin_ui(I.window);});
897 define_variable("download_temporary_file_open_buffer_delay", 500,
898     "Delay (in milliseconds) before a download buffer is opened for "+
899     "temporary downloads.  If the download completes before this amount "+
900     "of time, no download buffer will be opened.  This variable takes "+
901     "effect only if `open_download_buffer_automatically' is in "+
902     "`download_added_hook', which is the case by default.");
905 define_variable("download_buffer_automatic_open_target",
906                 [OPEN_NEW_WINDOW, OPEN_NEW_BUFFER_BACKGROUND],
907     "Target(s) for download buffers created by "+
908     "`open_download_buffer_automatically' and `download-show'.\n"+
909     "It can be a single target or an array of two targets.  When it is an "+
910     "array, the `download-show' command will use the second target when "+
911     "called with universal-argument.");
914 function open_download_buffer_automatically (info, target) {
915     var buf = info.source_buffer;
916     if (target == null) {
917         if (typeof(download_buffer_automatic_open_target) == "object")
918             target = download_buffer_automatic_open_target[0];
919         else
920             target = download_buffer_automatic_open_target;
921     }
922     if (buf == null)
923         target = OPEN_NEW_WINDOW;
924     if (info.temporary_status == DOWNLOAD_NOT_TEMPORARY ||
925         download_temporary_file_open_buffer_delay == 0)
926     {
927         create_buffer(buf.window, buffer_creator(download_buffer, $info = info), target);
928     } else {
929         var timer = null;
930         function finish () {
931             timer.cancel();
932         }
933         add_hook.call(info, "download_finished_hook", finish);
934         timer = call_after_timeout(function () {
935                 remove_hook.call(info, "download_finished_hook", finish);
936                 create_buffer(buf.window, buffer_creator(download_buffer, $info = info), target);
937             }, download_temporary_file_open_buffer_delay);
938     }
940 add_hook("download_added_hook", open_download_buffer_automatically);
944  * Download-show
945  */ 
947 minibuffer_auto_complete_preferences.download = true;
949 minibuffer.prototype.read_download = function () {
950     keywords(arguments,
951              $prompt = "Download",
952              $completer = all_word_completer(
953                  $completions = function (visitor) {
954                      var dls = download_manager_service.activeDownloads;
955                      while (dls.hasMoreElements()) {
956                          let dl = dls.getNext();
957                          visitor(id_to_download_info[dl.id]);
958                      }
959                  },
960                  $get_string = function (x) x.display_name,
961                  $get_description = function (x) x.source.spec,
962                  $get_value = function (x) x),
963              $auto_complete = "download",
964              $auto_complete_initial = true,
965              $match_required = true);
966     var result = yield this.read(forward_keywords(arguments));
967     yield co_return(result);
970 interactive("download-show",
971     "Prompt for an ongoing download and open a download buffer showing "+
972     "its progress.  When called with universal argument, the second "+
973     "target from `download_buffer_automatic_open_target' will be used.",
974     function (I) {
975         var target = null;
976         if (I.P && typeof(download_buffer_automatic_open_target) == "object")
977             target = download_buffer_automatic_open_target[1];
978         open_download_buffer_automatically(
979             (yield I.minibuffer.read_download($prompt = "Show download:")),
980             target);
981     });