bind "C-x left" and "C-x right" to buffer-previous and buffer-next
[conkeror/arlinius.git] / modules / download-manager.js
blob63eba4b187ad9e6925a92edfb9dee3752d27f121
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                             } catch (e) {
322                                 handle_interactive_error(info.source_buffer.window, e);
323                             } finally  {
324                                 if (info.temporary_status == DOWNLOAD_TEMPORARY_FOR_COMMAND)
325                                     if(delete_temporary_files_for_command) {
326                                         info.target_file.remove(false /* not recursive */);
327                                     }
328                                 info.running_shell_command = false;
329                                 download_shell_command_change_hook.run(info);
330                             }
331                         }());
332                         download_shell_command_change_hook.run(info);
333                     }
334                 }
335             }
336         }
337     },
339     onProgressChange : function (progress, request, cur_self_progress, max_self_progress,
340                                  cur_total_progress, max_total_progress,
341                                  download) {
342         var info = id_to_download_info[download.id];
343         if (info == null) {
344             dumpln("error: encountered unknown download in progress change");
345             return;
346         }
347         info.mozilla_info = download;
348         download_progress_change_hook.run(info);
349         //dumpln("download progress change: " + download.source.spec + ": " + cur_self_progress + "/" + max_self_progress + " "
350         // + cur_total_progress + "/" + max_total_progress + ", " + download.state + ", " + download.id);
351     },
353     onSecurityChange : function (progress, request, state, download) {
354     },
356     onStateChange : function (progress, request, state_flags, status, download) {
357     }
360 var download_observer = {
361     observe : function (subject, topic, data) {
362         switch(topic) {
363         case "download-manager-remove-download":
364             var ids = [];
365             if (!subject) {
366                 // Remove all downloads
367                 for (let i in id_to_download_info)
368                     ids.push(i);
369             } else {
370                 let id = subject.QueryInterface(Ci.nsISupportsPRUint32);
371                 /* FIXME: determine if this should really be an error */
372                 if (!(id in id_to_download_info)) {
373                     dumpln("Error: download-manager-remove-download event received for unknown download: " + id);
374                 } else
375                     ids.push(id);
376             }
377             for each (let i in ids) {
378                 dumpln("deleting download: " + i);
379                 let d = id_to_download_info[i];
380                 d.removed = true;
381                 download_removed_hook.run(d);
382                 delete id_to_download_info[i];
383             }
384             break;
385         }
386     }
388 observer_service.addObserver(download_observer, "download-manager-remove-download", false);
390 download_manager_service.addListener(download_progress_listener);
392 define_variable("download_buffer_min_update_interval", 2000,
393     "Minimum interval (in milliseconds) between updates in download progress buffers.\n" +
394     "Lowering this interval will increase the promptness of the progress display at " +
395     "the cost of using additional processor time.");
397 function download_buffer_modality (buffer, element) {
398     buffer.keymaps.push(download_buffer_keymap);
401 define_keywords("$info");
402 function download_buffer (window, element) {
403     this.constructor_begin();
404     keywords(arguments);
405     special_buffer.call(this, window, element, forward_keywords(arguments));
406     this.info = arguments.$info;
407     this.local.cwd = this.info.mozilla_info.targetFile.parent;
408     this.description = this.info.mozilla_info.source.spec;
409     this.update_title();
411     this.progress_change_handler_fn = method_caller(this, this.handle_progress_change);
412     add_hook.call(this.info, "download_progress_change_hook", this.progress_change_handler_fn);
413     add_hook.call(this.info, "download_state_change_hook", this.progress_change_handler_fn);
414     this.command_change_handler_fn = method_caller(this, this.update_command_field);
415     add_hook.call(this.info, "download_shell_command_change_hook", this.command_change_handler_fn);
416     this.modalities.push(download_buffer_modality);
417     this.constructor_end();
419 download_buffer.prototype = {
420     __proto__: special_buffer.prototype,
422     handle_kill : function () {
423         special_buffer.prototype.handle_kill.call(this);
424         remove_hook.call(this.info, "download_progress_change_hook", this.progress_change_handler_fn);
425         remove_hook.call(this.info, "download_state_change_hook", this.progress_change_handler_fn);
426         remove_hook.call(this.info, "download_shell_command_change_hook", this.command_change_handler_fn);
428         // Remove all node references
429         delete this.status_textnode;
430         delete this.target_file_node;
431         delete this.transferred_div_node;
432         delete this.transferred_textnode;
433         delete this.progress_container_node;
434         delete this.progress_bar_node;
435         delete this.percent_textnode;
436         delete this.time_textnode;
437         delete this.command_div_node;
438         delete this.command_label_textnode;
439         delete this.command_textnode;
440     },
442     update_title : function () {
443         // FIXME: do this properly
444         var new_title;
445         var info = this.info;
446         var append_transfer_info = false;
447         var append_speed_info = true;
448         var label = null;
449         switch(info.state) {
450         case DOWNLOAD_DOWNLOADING:
451             label = "Downloading";
452             append_transfer_info = true;
453             break;
454         case DOWNLOAD_FINISHED:
455             label = "Download complete";
456             break;
457         case DOWNLOAD_FAILED:
458             label = "Download failed";
459             append_transfer_info = true;
460             append_speed_info = false;
461             break;
462         case DOWNLOAD_CANCELED:
463             label = "Download canceled";
464             append_transfer_info = true;
465             append_speed_info = false;
466             break;
467         case DOWNLOAD_PAUSED:
468             label = "Download paused";
469             append_transfer_info = true;
470             append_speed_info = false;
471             break;
472         case DOWNLOAD_QUEUED:
473         default:
474             label = "Download queued";
475             break;
476         }
478         if (append_transfer_info) {
479             if (append_speed_info)
480                 new_title = label + " at " + pretty_print_file_size(info.speed).join(" ") + "/s: ";
481             else
482                 new_title = label + ": ";
483             var trans = pretty_print_file_size(info.amount_transferred);
484             if (info.size >= 0) {
485                 var total = pretty_print_file_size(info.size);
486                 if (trans[1] == total[1])
487                     new_title += trans[0] + "/" + total[0] + " " + total[1];
488                 else
489                     new_title += trans.join(" ") + "/" + total.join(" ");
490             } else
491                 new_title += trans.join(" ");
492             if (info.percent_complete >= 0)
493                 new_title += " (" + info.percent_complete + "%)";
494         } else
495             new_title = label;
496         if (new_title != this.title) {
497             this.title = new_title;
498             return true;
499         }
500         return false;
501     },
503     handle_progress_change : function () {
504         var cur_time = Date.now();
505         if (this.last_update == null ||
506             (cur_time - this.last_update) > download_buffer_min_update_interval ||
507             this.info.state != this.previous_state) {
509             if (this.update_title())
510                 buffer_title_change_hook.run(this);
512             if (this.generated) {
513                 this.update_fields();
514             }
515             this.previous_status = this.info.status;
516             this.last_update = cur_time;
517         }
518     },
520     generate : function () {
521         var d = this.document;
522         var g = new dom_generator(d, XHTML_NS);
524         /* Warning: If any additional node references are saved in
525          * this function, appropriate code to delete the saved
526          * properties must be added to handle_kill. */
528         var info = this.info;
530         d.body.setAttribute("class", "download-buffer");
532         g.add_stylesheet("chrome://conkeror-gui/content/downloads.css");
534         var row, cell;
535         var table = g.element("table", d.body);
537         row = g.element("tr", table, "class", "download-info", "id", "download-source");
538         cell = g.element("td", row, "class", "download-label");
539         this.status_textnode = g.text("", cell);
540         cell = g.element("td", row, "class", "download-value");
541         g.text(info.source.spec, cell);
543         row = g.element("tr", table, "class", "download-info", "id", "download-target");
544         cell = g.element("td", row, "class", "download-label");
545         var target_label;
546         if (info.temporary_status != DOWNLOAD_NOT_TEMPORARY)
547             target_label = "Temp. file:";
548         else
549             target_label = "Target:";
550         g.text(target_label, cell);
551         cell = g.element("td", row, "class", "download-value");
552         this.target_file_node = g.text("", cell);
554         row = g.element("tr", table, "class", "download-info", "id", "download-mime-type");
555         cell = g.element("td", row, "class", "download-label");
556         g.text("MIME type:", cell);
557         cell = g.element("td", row, "class", "download-value");
558         g.text(info.MIME_type || "unknown", cell);
560         this.transferred_div_node = row =
561             g.element("tr", table, "class", "download-info", "id", "download-transferred");
562         cell = g.element("td", row, "class", "download-label");
563         g.text("Transferred:", cell);
564         cell = g.element("td", row, "class", "download-value");
565         var sub_item = g.element("div", cell);
566         this.transferred_textnode = g.text("", sub_item);
567         sub_item = g.element("div", cell, "id", "download-percent");
568         this.percent_textnode = g.text("", sub_item);
569         this.progress_container_node = sub_item = g.element("div", cell, "id", "download-progress-container");
570         this.progress_bar_node = g.element("div", sub_item, "id", "download-progress-bar");
572         row = g.element("tr", table, "class", "download-info", "id", "download-time");
573         cell = g.element("td", row, "class", "download-label");
574         g.text("Time:", cell);
575         cell = g.element("td", row, "class", "download-value");
576         this.time_textnode = g.text("", cell);
578         if (info.action_description != null) {
579             row = g.element("tr", table, "class", "download-info", "id", "download-action");
580             cell = g.element("div", row, "class", "download-label");
581             g.text("Action:", cell);
582             cell = g.element("div", row, "class", "download-value");
583             g.text(info.action_description, cell);
584        }
586         this.command_div_node = row = g.element("tr", table, "class", "download-info", "id", "download-command");
587         cell = g.element("td", row, "class", "download-label");
588         this.command_label_textnode = g.text("Run command:", cell);
589         cell = g.element("td", row, "class", "download-value");
590         this.command_textnode = g.text("", cell);
593         this.update_fields();
594         this.update_command_field();
595     },
597     update_fields : function () {
598         if (!this.generated)
599             return;
600         var info = this.info;
601         var label = null;
602         switch(info.state) {
603         case DOWNLOAD_DOWNLOADING:
604             label = "Downloading";
605             break;
606         case DOWNLOAD_FINISHED:
607             label = "Completed";
608             break;
609         case DOWNLOAD_FAILED:
610             label = "Failed";
611             break;
612         case DOWNLOAD_CANCELED:
613             label = "Canceled";
614             break;
615         case DOWNLOAD_PAUSED:
616             label = "Paused";
617             break;
618         case DOWNLOAD_QUEUED:
619         default:
620             label = "Queued";
621             break;
622         }
623         this.status_textnode.nodeValue = label + ":";
624         this.target_file_node.nodeValue = info.target_file_text();
625         this.update_time_field();
627         var tran_text = "";
628         if (info.state == DOWNLOAD_FINISHED)
629             tran_text = pretty_print_file_size(info.size).join(" ");
630         else {
631             var trans = pretty_print_file_size(info.amount_transferred);
632             if (info.size >= 0) {
633                 var total = pretty_print_file_size(info.size);
634                 if (trans[1] == total[1])
635                     tran_text += trans[0] + "/" + total[0] + " " + total[1];
636                 else
637                     tran_text += trans.join(" ") + "/" + total.join(" ");
638             } else
639                 tran_text += trans.join(" ");
640         }
641         this.transferred_textnode.nodeValue = tran_text;
642         if (info.percent_complete >= 0) {
643             this.progress_container_node.style.display = "";
644             this.percent_textnode.nodeValue = info.percent_complete + "%";
645             this.progress_bar_node.style.width = info.percent_complete + "%";
646         } else {
647             this.percent_textnode.nodeValue = "";
648             this.progress_container_node.style.display = "none";
649         }
651         this.update_command_field();
652     },
654     update_time_field : function () {
655         var info = this.info;
656         var elapsed_text = pretty_print_time((Date.now() - info.start_time / 1000) / 1000) + " elapsed";
657         var text = "";
658         if (info.state == DOWNLOAD_DOWNLOADING) {
659             text = pretty_print_file_size(info.speed).join(" ") + "/s, ";
660         }
661         if (info.state == DOWNLOAD_DOWNLOADING &&
662             info.size >= 0 &&
663             info.speed > 0) {
664             let remaining = (info.size - info.amount_transferred) / info.speed;
665             text += pretty_print_time(remaining) + " left (" + elapsed_text + ")";
666         } else {
667             text = elapsed_text;
668         }
669         this.time_textnode.nodeValue = text;
670     },
672     update_command_field : function () {
673         if (!this.generated)
674             return;
675         if (this.info.shell_command != null) {
676             this.command_div_node.style.display = "";
677             var label;
678             if (this.info.running_shell_command)
679                 label = "Running:";
680             else if (this.info.state == DOWNLOAD_FINISHED)
681                 label = "Ran command:";
682             else
683                 label = "Run command:";
684             this.command_label_textnode.nodeValue = label;
685             this.command_textnode.nodeValue = this.info.shell_command;
686         } else {
687             this.command_div_node.style.display = "none";
688         }
689     }
692 function download_cancel (buffer) {
693     check_buffer(buffer, download_buffer);
694     var info = buffer.info;
695     info.cancel();
696     buffer.window.minibuffer.message("Download canceled");
698 interactive("download-cancel",
699             "Cancel the current download.\n" +
700             "The download can later be retried using the `download-retry' command, but any " +
701             "data already transferred will be lost.",
702             function (I) {
703                 let result = yield I.window.minibuffer.read_single_character_option(
704                     $prompt = "Cancel this download? (y/n)",
705                     $options = ["y", "n"]);
706                 if (result == "y")
707                     download_cancel(I.buffer);
708             });
710 function download_retry (buffer) {
711     check_buffer(buffer, download_buffer);
712     var info = buffer.info;
713     info.retry();
714     buffer.window.minibuffer.message("Download retried");
716 interactive("download-retry",
717             "Retry a failed or canceled download.\n" +
718             "This command can be used to retry a download that failed or was canceled using " +
719             "the `download-cancel' command.  The download will begin from the start again.",
720             function (I) {download_retry(I.buffer);});
722 function download_pause (buffer) {
723     check_buffer(buffer, download_buffer);
724     buffer.info.pause();
725     buffer.window.minibuffer.message("Download paused");
727 interactive("download-pause",
728             "Pause the current download.\n" +
729             "The download can later be resumed using the `download-resume' command.  The " +
730             "data already transferred will not be lost.",
731             function (I) {download_pause(I.buffer);});
733 function download_resume (buffer) {
734     check_buffer(buffer, download_buffer);
735     buffer.info.resume();
736     buffer.window.minibuffer.message("Download resumed");
738 interactive("download-resume",
739             "Resume the current download.\n" +
740             "This command can be used to resume a download paused using the `download-pause' command.",
741             function (I) { download_resume(I.buffer); });
743 function download_remove (buffer) {
744     check_buffer(buffer, download_buffer);
745     buffer.info.remove();
746     buffer.window.minibuffer.message("Download removed");
748 interactive("download-remove",
749             "Remove the current download from the download manager.\n" +
750             "This command can only be used on inactive (paused, canceled, "+
751             "completed, or failed) downloads.",
752             function (I) {download_remove(I.buffer);});
754 function download_retry_or_resume (buffer) {
755     check_buffer(buffer, download_buffer);
756     var info = buffer.info;
757     if (info.state == DOWNLOAD_PAUSED)
758         download_resume(buffer);
759     else
760         download_retry(buffer);
762 interactive("download-retry-or-resume",
763             "Retry or resume the current download.\n" +
764             "This command can be used to resume a download paused using the `download-pause' " +
765             "command or canceled using the `download-cancel' command.",
766             function (I) {download_retry_or_resume(I.buffer);});
768 function download_pause_or_resume (buffer) {
769     check_buffer(buffer, download_buffer);
770     var info = buffer.info;
771     if (info.state == DOWNLOAD_PAUSED)
772         download_resume(buffer);
773     else
774         download_pause(buffer);
776 interactive("download-pause-or-resume",
777             "Pause or resume the current download.\n" +
778             "This command toggles the paused state of the current download.",
779             function (I) {download_pause_or_resume(I.buffer);});
781 function download_delete_target (buffer) {
782     check_buffer(buffer, download_buffer);
783     var info = buffer.info;
784     info.delete_target();
785     buffer.window.minibuffer.message("Deleted file: " + info.target_file.path);
787 interactive("download-delete-target",
788             "Delete the target file of the current download.\n"  +
789             "This command can only be used if the download has finished successfully.",
790             function (I) {download_delete_target(I.buffer);});
792 function download_shell_command (buffer, cwd, cmd) {
793     check_buffer(buffer, download_buffer);
794     var info = buffer.info;
795     if (info.state == DOWNLOAD_FINISHED) {
796         shell_command_with_argument_blind(cmd, info.target_file.path, $cwd = cwd);
797         return;
798     }
799     if (info.state != DOWNLOAD_DOWNLOADING && info.state != DOWNLOAD_PAUSED && info.state != DOWNLOAD_QUEUED)
800         info.throw_state_error();
801     if (cmd == null || cmd.length == 0)
802         info.set_shell_command(null, cwd);
803     else
804         info.set_shell_command(cmd, cwd);
805     buffer.window.minibuffer.message("Queued shell command: " + cmd);
807 interactive("download-shell-command",
808             "Run a shell command on the target file of the current download.\n" +
809             "If the download is still in progress, the shell command will be queued " +
810             "to run when the download finishes.",
811             function (I) {
812                 var buffer = check_buffer(I.buffer, download_buffer);
813                 var cwd = buffer.info.shell_command_cwd || I.local.cwd;
814                 var cmd = yield I.minibuffer.read_shell_command(
815                     $cwd = cwd,
816                     $initial_value = buffer.info.shell_command ||
817                         external_content_handlers.get(buffer.info.MIME_type));
818                 download_shell_command(buffer, cwd, cmd);
819             });
821 function download_manager_ui () {}
822 download_manager_ui.prototype = {
823     QueryInterface : XPCOMUtils.generateQI([Ci.nsIDownloadManagerUI]),
825     getAttention : function () {},
826     show : function () {},
827     visible : false
831 function download_manager_show_builtin_ui (window) {
832     download_manager_builtin_ui.show(window);
834 interactive("download-manager-show-builtin-ui",
835             "Show the built-in (Firefox-style) download manager user interface.",
836             function (I) {download_manager_show_builtin_ui(I.window);});
839 define_variable("download_temporary_file_open_buffer_delay", 500,
840     "Delay (in milliseconds) before a download buffer is opened for "+
841     "temporary downloads.  If the download completes before this amount "+
842     "of time, no download buffer will be opened.  This variable takes "+
843     "effect only if `open_download_buffer_automatically' is in "+
844     "`download_added_hook', which is the case by default.");
847 define_variable("download_buffer_automatic_open_target",
848                 [OPEN_NEW_WINDOW, OPEN_NEW_BUFFER_BACKGROUND],
849     "Target(s) for download buffers created by "+
850     "`open_download_buffer_automatically' and `download-show'.\n"+
851     "It can be a single target or an array of two targets.  When it is an "+
852     "array, the `download-show' command will use the second target when "+
853     "called with universal-argument.");
856 function open_download_buffer_automatically (info, target) {
857     var buf = info.source_buffer;
858     if (target == null) {
859         if (typeof(download_buffer_automatic_open_target) == "object")
860             target = download_buffer_automatic_open_target[0];
861         else
862             target = download_buffer_automatic_open_target;
863     }
864     if (buf == null)
865         target = OPEN_NEW_WINDOW;
866     if (info.temporary_status == DOWNLOAD_NOT_TEMPORARY ||
867         download_temporary_file_open_buffer_delay == 0)
868     {
869         create_buffer(buf.window, buffer_creator(download_buffer, $info = info), target);
870     } else {
871         var timer = null;
872         function finish () {
873             timer.cancel();
874         }
875         add_hook.call(info, "download_finished_hook", finish);
876         timer = call_after_timeout(function () {
877                 remove_hook.call(info, "download_finished_hook", finish);
878                 create_buffer(buf.window, buffer_creator(download_buffer, $info = info), target);
879             }, download_temporary_file_open_buffer_delay);
880     }
882 add_hook("download_added_hook", open_download_buffer_automatically);
886  * Download-show
887  */ 
889 minibuffer_auto_complete_preferences.download = true;
891 minibuffer.prototype.read_download = function () {
892     keywords(arguments,
893              $prompt = "Download",
894              $completer = all_word_completer(
895                  $completions = function (visitor) {
896                      var dls = download_manager_service.activeDownloads;
897                      while (dls.hasMoreElements()) {
898                          let dl = dls.getNext();
899                          visitor(id_to_download_info[dl.id]);
900                      }
901                  },
902                  $get_string = function (x) x.display_name,
903                  $get_description = function (x) x.source.spec,
904                  $get_value = function (x) x),
905              $auto_complete = "download",
906              $auto_complete_initial = true,
907              $match_required = true);
908     var result = yield this.read(forward_keywords(arguments));
909     yield co_return(result);
912 interactive("download-show",
913     "Prompt for an ongoing download and open a download buffer showing "+
914     "its progress.  When called with universal argument, the second "+
915     "target from `download_buffer_automatic_open_target' will be used.",
916     function (I) {
917         var target = null;
918         if (I.P && typeof(download_buffer_automatic_open_target) == "object")
919             target = download_buffer_automatic_open_target[1];
920         open_download_buffer_automatically(
921             (yield I.minibuffer.read_download($prompt = "Show download:")),
922             target);
923     });