Debian package: Update debian patches to fit new module API
[conkeror.git] / modules / download-manager.js
blob1ff50d5dbede5ee3ad8248cc96ce4cdc36e2b260
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 unmanaged_download_info_list = [];
17 var id_to_download_info = {};
19 // Import these constants for convenience
20 const DOWNLOAD_NOTSTARTED = Ci.nsIDownloadManager.DOWNLOAD_NOTSTARTED;
21 const DOWNLOAD_DOWNLOADING = Ci.nsIDownloadManager.DOWNLOAD_DOWNLOADING;
22 const DOWNLOAD_FINISHED = Ci.nsIDownloadManager.DOWNLOAD_FINISHED;
23 const DOWNLOAD_FAILED = Ci.nsIDownloadManager.DOWNLOAD_FAILED;
24 const DOWNLOAD_CANCELED = Ci.nsIDownloadManager.DOWNLOAD_CANCELED;
25 const DOWNLOAD_PAUSED = Ci.nsIDownloadManager.DOWNLOAD_PAUSED;
26 const DOWNLOAD_QUEUED = Ci.nsIDownloadManager.DOWNLOAD_QUEUED;
27 const DOWNLOAD_BLOCKED = Ci.nsIDownloadManager.DOWNLOAD_BLOCKED;
28 const DOWNLOAD_SCANNING = Ci.nsIDownloadManager.DOWNLOAD_SCANNING;
31 const DOWNLOAD_NOT_TEMPORARY = 0;
32 const DOWNLOAD_TEMPORARY_FOR_ACTION = 1;
33 const DOWNLOAD_TEMPORARY_FOR_COMMAND = 2;
35 function download_info (source_buffer, mozilla_info, target_file) {
36     this.source_buffer = source_buffer;
37     this.target_file = target_file;
38     if (mozilla_info != null)
39         this.attach(mozilla_info);
41 download_info.prototype = {
42     constructor: download_info,
43     attach: function (mozilla_info) {
44         if (!this.target_file)
45             this.__defineGetter__("target_file", function () {
46                     return this.mozilla_info.targetFile;
47                 });
48         else if (this.target_file.path != mozilla_info.targetFile.path)
49             throw interactive_error("Download target file unexpected.");
50         this.mozilla_info = mozilla_info;
51         id_to_download_info[mozilla_info.id] = this;
52         download_added_hook.run(this);
53     },
54     target_file: null,
55     shell_command: null,
56     shell_command_cwd: null,
57     temporary_status: DOWNLOAD_NOT_TEMPORARY,
58     action_description: null,
59     set_shell_command: function (str, cwd) {
60         this.shell_command = str;
61         this.shell_command_cwd = cwd;
62         if (this.mozilla_info)
63             download_shell_command_change_hook.run(this);
64     },
66     /**
67      * None of the following members may be used until attach is called
68      */
70     // Reflectors to properties of nsIDownload
71     get state () { return this.mozilla_info.state; },
72     get display_name () { return this.mozilla_info.displayName; },
73     get amount_transferred () { return this.mozilla_info.amountTransferred; },
74     get percent_complete () { return this.mozilla_info.percentComplete; },
75     get size () {
76         var s = this.mozilla_info.size;
77         /* nsIDownload.size is a PRUint64, and will have value
78          * LL_MAXUINT (2^64 - 1) to indicate an unknown size.  Because
79          * JavaScript only has a double numerical type, this value
80          * cannot be represented exactly, so 2^36 is used instead as the cutoff. */
81         if (s < 68719476736 /* 2^36 */)
82             return s;
83         return -1;
84     },
85     get source () { return this.mozilla_info.source; },
86     get start_time () { return this.mozilla_info.startTime; },
87     get speed () { return this.mozilla_info.speed; },
88     get MIME_info () { return this.mozilla_info.MIMEInfo; },
89     get MIME_type () {
90         if (this.MIME_info)
91             return this.MIME_info.MIMEType;
92         return null;
93     },
94     get id () { return this.mozilla_info.id; },
95     get referrer () { return this.mozilla_info.referrer; },
97     target_file_text: function () {
98         let target = this.target_file.path;
99         let display = this.display_name;
100         if (target.indexOf(display, target.length - display.length) == -1)
101             target += " (" + display + ")";
102         return target;
103     },
105     throw_if_removed: function () {
106         if (this.removed)
107             throw interactive_error("Download has already been removed from the download manager.");
108     },
110     throw_state_error: function () {
111         switch (this.state) {
112         case DOWNLOAD_DOWNLOADING:
113             throw interactive_error("Download is already in progress.");
114         case DOWNLOAD_FINISHED:
115             throw interactive_error("Download has already completed.");
116         case DOWNLOAD_FAILED:
117             throw interactive_error("Download has already failed.");
118         case DOWNLOAD_CANCELED:
119             throw interactive_error("Download has already been canceled.");
120         case DOWNLOAD_PAUSED:
121             throw interactive_error("Download has already been paused.");
122         case DOWNLOAD_QUEUED:
123             throw interactive_error("Download is queued.");
124         default:
125             throw new Error("Download has unexpected state: " + this.state);
126         }
127     },
129     // Download manager operations
130     cancel: function ()  {
131         this.throw_if_removed();
132         switch (this.state) {
133         case DOWNLOAD_DOWNLOADING:
134         case DOWNLOAD_PAUSED:
135         case DOWNLOAD_QUEUED:
136             try {
137                 download_manager_service.cancelDownload(this.id);
138             } catch (e) {
139                 throw interactive_error("Download cannot be canceled.");
140             }
141             break;
142         default:
143             this.throw_state_error();
144         }
145     },
147     retry: function () {
148         this.throw_if_removed();
149         switch (this.state) {
150         case DOWNLOAD_CANCELED:
151         case DOWNLOAD_FAILED:
152             try {
153                 download_manager_service.retryDownload(this.id);
154             } catch (e) {
155                 throw interactive_error("Download cannot be retried.");
156             }
157             break;
158         default:
159             this.throw_state_error();
160         }
161     },
163     resume: function () {
164         this.throw_if_removed();
165         switch (this.state) {
166         case DOWNLOAD_PAUSED:
167             try {
168                 download_manager_service.resumeDownload(this.id);
169             } catch (e) {
170                 throw interactive_error("Download cannot be resumed.");
171             }
172             break;
173         default:
174             this.throw_state_error();
175         }
176     },
178     pause: function () {
179         this.throw_if_removed();
180         switch (this.state) {
181         case DOWNLOAD_DOWNLOADING:
182         case DOWNLOAD_QUEUED:
183             try {
184                 download_manager_service.pauseDownload(this.id);
185             } catch (e) {
186                 throw interactive_error("Download cannot be paused.");
187             }
188             break;
189         default:
190             this.throw_state_error();
191         }
192     },
194     remove: function () {
195         this.throw_if_removed();
196         switch (this.state) {
197         case DOWNLOAD_FAILED:
198         case DOWNLOAD_CANCELED:
199         case DOWNLOAD_FINISHED:
200             try {
201                 download_manager_service.removeDownload(this.id);
202             } catch (e) {
203                 throw interactive_error("Download cannot be removed.");
204             }
205             break;
206         default:
207             throw interactive_error("Download is still in progress.");
208         }
209     },
211     delete_target: function () {
212         if (this.state != DOWNLOAD_FINISHED)
213             throw interactive_error("Download has not finished.");
214         try {
215             this.target_file.remove(false);
216         } catch (e) {
217             if ("result" in e) {
218                 switch (e.result) {
219                 case Cr.NS_ERROR_FILE_TARGET_DOES_NOT_EXIST:
220                     throw interactive_error("File has already been deleted.");
221                 case Cr.NS_ERROR_FILE_ACCESS_DENIED:
222                     throw interactive_error("Access denied");
223                 case Cr.NS_ERROR_FILE_DIR_NOT_EMPTY:
224                     throw interactive_error("Failed to delete file.");
225                 }
226             }
227             throw e;
228         }
229     }
232 var define_download_local_hook = simple_local_hook_definer();
234 function register_download (buffer, source_uri, target_file) {
235     var info = new download_info(buffer, null, target_file);
236     info.registered_time_stamp = Date.now();
237     info.registered_source_uri = source_uri;
238     unmanaged_download_info_list.push(info);
239     return info;
242 function match_registered_download (mozilla_info) {
243     let list = unmanaged_download_info_list;
244     let t = Date.now();
245     for (let i = 0; i < list.length; ++i) {
246         let x = list[i];
247         if (x.registered_source_uri == mozilla_info.source) {
248             list.splice(i, 1);
249             return x;
250         }
251         if (t - x.registered_time_stamp > download_info_max_queue_delay) {
252             list.splice(i, 1);
253             --i;
254             continue;
255         }
256     }
257     return null;
260 define_download_local_hook("download_added_hook");
261 define_download_local_hook("download_removed_hook");
262 define_download_local_hook("download_finished_hook");
263 define_download_local_hook("download_progress_change_hook");
264 define_download_local_hook("download_state_change_hook");
265 define_download_local_hook("download_shell_command_change_hook");
267 define_variable('delete_temporary_files_for_command', true,
268     'If this is set to true, temporary files downloaded to run a command '+
269     'on them will be deleted once the command completes. If not, the file '+
270     'will stay around forever unless deleted outside the browser.');
272 var download_info_max_queue_delay = 100;
274 var download_progress_listener = {
275     QueryInterface: generate_QI(Ci.nsIDownloadProgressListener),
277     onDownloadStateChange: function (state, download) {
278         var info = null;
279         /* FIXME: Determine if only new downloads will have this state
280          * as their previous state. */
282         dumpln("download state change: " + download.source.spec + ": " + state + ", " + download.state + ", " + download.id);
284         if (state == DOWNLOAD_NOTSTARTED) {
285             info = match_registered_download(download);
286             if (info == null) {
287                 info = new download_info(null, download);
288                 dumpln("error: encountered unknown new download");
289             } else {
290                 info.attach(download);
291             }
292         } else {
293             info = id_to_download_info[download.id];
294             if (info == null) {
295                 dumpln("Error: encountered unknown download");
297             } else {
298                 info.mozilla_info = download;
299                 download_state_change_hook.run(info);
300                 if (info.state == DOWNLOAD_FINISHED) {
301                     download_finished_hook.run(info);
303                     if (info.shell_command != null) {
304                         info.running_shell_command = true;
305                         co_call(function () {
306                             try {
307                                 yield shell_command_with_argument(info.shell_command,
308                                                                   info.target_file.path,
309                                                                   $cwd = info.shell_command_cwd);
310                             } catch (e) {
311                                 handle_interactive_error(info.source_buffer.window, e);
312                             } finally  {
313                                 if (info.temporary_status == DOWNLOAD_TEMPORARY_FOR_COMMAND)
314                                     if(delete_temporary_files_for_command) {
315                                         info.target_file.remove(false /* not recursive */);
316                                     }
317                                 info.running_shell_command = false;
318                                 download_shell_command_change_hook.run(info);
319                             }
320                         }());
321                         download_shell_command_change_hook.run(info);
322                     }
323                 }
324             }
325         }
326     },
328     onProgressChange: function (progress, request, cur_self_progress, max_self_progress,
329                                 cur_total_progress, max_total_progress,
330                                 download) {
331         var info = id_to_download_info[download.id];
332         if (info == null) {
333             dumpln("error: encountered unknown download in progress change");
334             return;
335         }
336         info.mozilla_info = download;
337         download_progress_change_hook.run(info);
338         //dumpln("download progress change: " + download.source.spec + ": " + cur_self_progress + "/" + max_self_progress + " "
339         // + cur_total_progress + "/" + max_total_progress + ", " + download.state + ", " + download.id);
340     },
342     onSecurityChange: function (progress, request, state, download) {
343     },
345     onStateChange: function (progress, request, state_flags, status, download) {
346     }
349 var download_observer = {
350     observe: function (subject, topic, data) {
351         switch(topic) {
352         case "download-manager-remove-download":
353             var ids = [];
354             if (!subject) {
355                 // Remove all downloads
356                 for (let i in id_to_download_info)
357                     ids.push(i);
358             } else {
359                 let id = subject.QueryInterface(Ci.nsISupportsPRUint32);
360                 /* FIXME: determine if this should really be an error */
361                 if (!(id in id_to_download_info)) {
362                     dumpln("Error: download-manager-remove-download event received for unknown download: " + id);
363                 } else
364                     ids.push(id);
365             }
366             for each (let i in ids) {
367                 dumpln("deleting download: " + i);
368                 let d = id_to_download_info[i];
369                 d.removed = true;
370                 download_removed_hook.run(d);
371                 delete id_to_download_info[i];
372             }
373             break;
374         }
375     }
377 observer_service.addObserver(download_observer, "download-manager-remove-download", false);
379 download_manager_service.addListener(download_progress_listener);
381 define_variable("download_buffer_min_update_interval", 2000,
382     "Minimum interval (in milliseconds) between updates in download progress buffers.\n" +
383     "Lowering this interval will increase the promptness of the progress display at " +
384     "the cost of using additional processor time.");
386 function download_buffer_modality (buffer, element) {
387     buffer.keymaps.push(download_buffer_keymap);
390 define_keywords("$info");
391 function download_buffer (window) {
392     this.constructor_begin();
393     keywords(arguments);
394     special_buffer.call(this, window, forward_keywords(arguments));
395     this.info = arguments.$info;
396     this.local.cwd = this.info.mozilla_info.targetFile.parent;
397     this.description = this.info.mozilla_info.source.spec;
398     this.update_title();
400     this.progress_change_handler_fn = method_caller(this, this.handle_progress_change);
401     add_hook.call(this.info, "download_progress_change_hook", this.progress_change_handler_fn);
402     add_hook.call(this.info, "download_state_change_hook", this.progress_change_handler_fn);
403     this.command_change_handler_fn = method_caller(this, this.update_command_field);
404     add_hook.call(this.info, "download_shell_command_change_hook", this.command_change_handler_fn);
405     this.modalities.push(download_buffer_modality);
406     this.constructor_end();
408 download_buffer.prototype = {
409     constructor: download_buffer,
410     __proto__: special_buffer.prototype,
412     destroy: function () {
413         remove_hook.call(this.info, "download_progress_change_hook", this.progress_change_handler_fn);
414         remove_hook.call(this.info, "download_state_change_hook", this.progress_change_handler_fn);
415         remove_hook.call(this.info, "download_shell_command_change_hook", this.command_change_handler_fn);
417         // Remove all node references
418         delete this.status_textnode;
419         delete this.target_file_node;
420         delete this.transferred_div_node;
421         delete this.transferred_textnode;
422         delete this.progress_container_node;
423         delete this.progress_bar_node;
424         delete this.percent_textnode;
425         delete this.time_textnode;
426         delete this.command_div_node;
427         delete this.command_label_textnode;
428         delete this.command_textnode;
430         special_buffer.prototype.destroy.call(this);
431     },
433     update_title: function () {
434         // FIXME: do this properly
435         var new_title;
436         var info = this.info;
437         var append_transfer_info = false;
438         var append_speed_info = true;
439         var label = null;
440         switch(info.state) {
441         case DOWNLOAD_DOWNLOADING:
442             label = "Downloading";
443             append_transfer_info = true;
444             break;
445         case DOWNLOAD_FINISHED:
446             label = "Download complete";
447             break;
448         case DOWNLOAD_FAILED:
449             label = "Download failed";
450             append_transfer_info = true;
451             append_speed_info = false;
452             break;
453         case DOWNLOAD_CANCELED:
454             label = "Download canceled";
455             append_transfer_info = true;
456             append_speed_info = false;
457             break;
458         case DOWNLOAD_PAUSED:
459             label = "Download paused";
460             append_transfer_info = true;
461             append_speed_info = false;
462             break;
463         case DOWNLOAD_QUEUED:
464         default:
465             label = "Download queued";
466             break;
467         }
469         if (append_transfer_info) {
470             if (append_speed_info)
471                 new_title = label + " at " + pretty_print_file_size(info.speed).join(" ") + "/s: ";
472             else
473                 new_title = label + ": ";
474             var trans = pretty_print_file_size(info.amount_transferred);
475             if (info.size >= 0) {
476                 var total = pretty_print_file_size(info.size);
477                 if (trans[1] == total[1])
478                     new_title += trans[0] + "/" + total[0] + " " + total[1];
479                 else
480                     new_title += trans.join(" ") + "/" + total.join(" ");
481             } else
482                 new_title += trans.join(" ");
483             if (info.percent_complete >= 0)
484                 new_title += " (" + info.percent_complete + "%)";
485         } else
486             new_title = label;
487         if (new_title != this.title) {
488             this.title = new_title;
489             return true;
490         }
491         return false;
492     },
494     handle_progress_change: function () {
495         var cur_time = Date.now();
496         if (this.last_update == null ||
497             (cur_time - this.last_update) > download_buffer_min_update_interval ||
498             this.info.state != this.previous_state) {
500             if (this.update_title())
501                 buffer_title_change_hook.run(this);
503             if (this.generated) {
504                 this.update_fields();
505             }
506             this.previous_status = this.info.status;
507             this.last_update = cur_time;
508         }
509     },
511     generate: function () {
512         var d = this.document;
513         var g = new dom_generator(d, XHTML_NS);
515         /* Warning: If any additional node references are saved in
516          * this function, appropriate code to delete the saved
517          * properties must be added to destroy method. */
519         var info = this.info;
521         d.body.setAttribute("class", "download-buffer");
523         g.add_stylesheet("chrome://conkeror-gui/content/downloads.css");
525         var row, cell;
526         var table = g.element("table", d.body);
528         row = g.element("tr", table, "class", "download-info", "id", "download-source");
529         cell = g.element("td", row, "class", "download-label");
530         this.status_textnode = g.text("", cell);
531         cell = g.element("td", row, "class", "download-value");
532         g.text(info.source.spec, cell);
534         row = g.element("tr", table, "class", "download-info", "id", "download-target");
535         cell = g.element("td", row, "class", "download-label");
536         var target_label;
537         if (info.temporary_status != DOWNLOAD_NOT_TEMPORARY)
538             target_label = "Temp. file:";
539         else
540             target_label = "Target:";
541         g.text(target_label, cell);
542         cell = g.element("td", row, "class", "download-value");
543         this.target_file_node = g.text("", cell);
545         row = g.element("tr", table, "class", "download-info", "id", "download-mime-type");
546         cell = g.element("td", row, "class", "download-label");
547         g.text("MIME type:", cell);
548         cell = g.element("td", row, "class", "download-value");
549         g.text(info.MIME_type || "unknown", cell);
551         this.transferred_div_node = row =
552             g.element("tr", table, "class", "download-info", "id", "download-transferred");
553         cell = g.element("td", row, "class", "download-label");
554         g.text("Transferred:", cell);
555         cell = g.element("td", row, "class", "download-value");
556         var sub_item = g.element("div", cell);
557         this.transferred_textnode = g.text("", sub_item);
558         sub_item = g.element("div", cell, "id", "download-percent");
559         this.percent_textnode = g.text("", sub_item);
560         this.progress_container_node = sub_item = g.element("div", cell, "id", "download-progress-container");
561         this.progress_bar_node = g.element("div", sub_item, "id", "download-progress-bar");
563         row = g.element("tr", table, "class", "download-info", "id", "download-time");
564         cell = g.element("td", row, "class", "download-label");
565         g.text("Time:", cell);
566         cell = g.element("td", row, "class", "download-value");
567         this.time_textnode = g.text("", cell);
569         if (info.action_description != null) {
570             row = g.element("tr", table, "class", "download-info", "id", "download-action");
571             cell = g.element("div", row, "class", "download-label");
572             g.text("Action:", cell);
573             cell = g.element("div", row, "class", "download-value");
574             g.text(info.action_description, cell);
575         }
577         this.command_div_node = row = g.element("tr", table, "class", "download-info", "id", "download-command");
578         cell = g.element("td", row, "class", "download-label");
579         this.command_label_textnode = g.text("Run command:", cell);
580         cell = g.element("td", row, "class", "download-value");
581         this.command_textnode = g.text("", cell);
583         this.update_fields();
584         this.update_command_field();
585     },
587     update_fields: function () {
588         if (!this.generated)
589             return;
590         var info = this.info;
591         var label = null;
592         switch (info.state) {
593         case DOWNLOAD_DOWNLOADING:
594             label = "Downloading";
595             break;
596         case DOWNLOAD_FINISHED:
597             label = "Completed";
598             break;
599         case DOWNLOAD_FAILED:
600             label = "Failed";
601             break;
602         case DOWNLOAD_CANCELED:
603             label = "Canceled";
604             break;
605         case DOWNLOAD_PAUSED:
606             label = "Paused";
607             break;
608         case DOWNLOAD_QUEUED:
609         default:
610             label = "Queued";
611             break;
612         }
613         this.status_textnode.nodeValue = label + ":";
614         this.target_file_node.nodeValue = info.target_file_text();
615         this.update_time_field();
617         var tran_text = "";
618         if (info.state == DOWNLOAD_FINISHED)
619             tran_text = pretty_print_file_size(info.size).join(" ");
620         else {
621             var trans = pretty_print_file_size(info.amount_transferred);
622             if (info.size >= 0) {
623                 var total = pretty_print_file_size(info.size);
624                 if (trans[1] == total[1])
625                     tran_text += trans[0] + "/" + total[0] + " " + total[1];
626                 else
627                     tran_text += trans.join(" ") + "/" + total.join(" ");
628             } else
629                 tran_text += trans.join(" ");
630         }
631         this.transferred_textnode.nodeValue = tran_text;
632         if (info.percent_complete >= 0) {
633             this.progress_container_node.style.display = "";
634             this.percent_textnode.nodeValue = info.percent_complete + "%";
635             this.progress_bar_node.style.width = info.percent_complete + "%";
636         } else {
637             this.percent_textnode.nodeValue = "";
638             this.progress_container_node.style.display = "none";
639         }
641         this.update_command_field();
642     },
644     update_time_field: function () {
645         var info = this.info;
646         var elapsed_text = pretty_print_time((Date.now() - info.start_time / 1000) / 1000) + " elapsed";
647         var text = "";
648         if (info.state == DOWNLOAD_DOWNLOADING)
649             text = pretty_print_file_size(info.speed).join(" ") + "/s, ";
650         if (info.state == DOWNLOAD_DOWNLOADING &&
651             info.size >= 0 &&
652             info.speed > 0)
653         {
654             let remaining = (info.size - info.amount_transferred) / info.speed;
655             text += pretty_print_time(remaining) + " left (" + elapsed_text + ")";
656         } else
657             text = elapsed_text;
658         this.time_textnode.nodeValue = text;
659     },
661     update_command_field: function () {
662         if (!this.generated)
663             return;
664         if (this.info.shell_command != null) {
665             this.command_div_node.style.display = "";
666             var label;
667             if (this.info.running_shell_command)
668                 label = "Running:";
669             else if (this.info.state == DOWNLOAD_FINISHED)
670                 label = "Ran command:";
671             else
672                 label = "Run command:";
673             this.command_label_textnode.nodeValue = label;
674             this.command_textnode.nodeValue = this.info.shell_command;
675         } else
676             this.command_div_node.style.display = "none";
677     }
680 function download_cancel (buffer) {
681     check_buffer(buffer, download_buffer);
682     var info = buffer.info;
683     info.cancel();
684     buffer.window.minibuffer.message("Download canceled");
686 interactive("download-cancel",
687     "Cancel the current download.\n" +
688     "The download can later be retried using the `download-retry' "+
689     "command, but any data already transferred will be lost.",
690     function (I) {
691         let result = yield I.window.minibuffer.read_single_character_option(
692             $prompt = "Cancel this download? (y/n)",
693             $options = ["y", "n"]);
694         if (result == "y")
695             download_cancel(I.buffer);
696     });
698 function download_retry (buffer) {
699     check_buffer(buffer, download_buffer);
700     var info = buffer.info;
701     info.retry();
702     buffer.window.minibuffer.message("Download retried");
704 interactive("download-retry",
705     "Retry a failed or canceled download.\n" +
706     "This command can be used to retry a download that failed or "+
707     "was canceled using the `download-cancel' command.  The download "+
708     "will begin from the start again.",
709     function (I) { download_retry(I.buffer); });
711 function download_pause (buffer) {
712     check_buffer(buffer, download_buffer);
713     buffer.info.pause();
714     buffer.window.minibuffer.message("Download paused");
716 interactive("download-pause",
717     "Pause the current download.\n" +
718     "The download can later be resumed using the `download-resume' command. "+
719     "The data already transferred will not be lost.",
720     function (I) { download_pause(I.buffer); });
722 function download_resume (buffer) {
723     check_buffer(buffer, download_buffer);
724     buffer.info.resume();
725     buffer.window.minibuffer.message("Download resumed");
727 interactive("download-resume",
728     "Resume the current download.\n" +
729     "This command can be used to resume a download paused using the "+
730     "`download-pause' command.",
731     function (I) { download_resume(I.buffer); });
733 function download_remove (buffer) {
734     check_buffer(buffer, download_buffer);
735     buffer.info.remove();
736     buffer.window.minibuffer.message("Download removed");
738 interactive("download-remove",
739     "Remove the current download from the download manager.\n" +
740     "This command can only be used on inactive (paused, canceled, "+
741     "completed, or failed) downloads.",
742     function (I) { download_remove(I.buffer); });
744 function download_retry_or_resume (buffer) {
745     check_buffer(buffer, download_buffer);
746     var info = buffer.info;
747     if (info.state == DOWNLOAD_PAUSED)
748         download_resume(buffer);
749     else
750         download_retry(buffer);
752 interactive("download-retry-or-resume",
753     "Retry or resume the current download.\n" +
754     "This command can be used to resume a download paused using the " +
755     "`download-pause' command or canceled using the `download-cancel' "+
756     "command.",
757     function (I) { download_retry_or_resume(I.buffer); });
759 function download_pause_or_resume (buffer) {
760     check_buffer(buffer, download_buffer);
761     var info = buffer.info;
762     if (info.state == DOWNLOAD_PAUSED)
763         download_resume(buffer);
764     else
765         download_pause(buffer);
767 interactive("download-pause-or-resume",
768     "Pause or resume the current download.\n" +
769     "This command toggles the paused state of the current download.",
770     function (I) { download_pause_or_resume(I.buffer); });
772 function download_delete_target (buffer) {
773     check_buffer(buffer, download_buffer);
774     var info = buffer.info;
775     info.delete_target();
776     buffer.window.minibuffer.message("Deleted file: " + info.target_file.path);
778 interactive("download-delete-target",
779     "Delete the target file of the current download.\n" +
780     "This command can only be used if the download has finished successfully.",
781     function (I) { download_delete_target(I.buffer); });
783 function download_shell_command (buffer, cwd, cmd) {
784     check_buffer(buffer, download_buffer);
785     var info = buffer.info;
786     if (info.state == DOWNLOAD_FINISHED) {
787         shell_command_with_argument_blind(cmd, info.target_file.path, $cwd = cwd);
788         return;
789     }
790     if (info.state != DOWNLOAD_DOWNLOADING && info.state != DOWNLOAD_PAUSED && info.state != DOWNLOAD_QUEUED)
791         info.throw_state_error();
792     if (cmd == null || cmd.length == 0)
793         info.set_shell_command(null, cwd);
794     else
795         info.set_shell_command(cmd, cwd);
796     buffer.window.minibuffer.message("Queued shell command: " + cmd);
798 interactive("download-shell-command",
799     "Run a shell command on the target file of the current download.\n"+
800     "If the download is still in progress, the shell command will be queued "+
801     "to run when the download finishes.",
802     function (I) {
803         var buffer = check_buffer(I.buffer, download_buffer);
804         var cwd = buffer.info.shell_command_cwd || I.local.cwd;
805         var cmd = yield I.minibuffer.read_shell_command(
806             $cwd = cwd,
807             $initial_value = buffer.info.shell_command ||
808                 external_content_handlers.get(buffer.info.MIME_type));
809         download_shell_command(buffer, cwd, cmd);
810     });
812 function download_manager_ui () {}
813 download_manager_ui.prototype = {
814     constructor: download_manager_ui,
815     QueryInterface: XPCOMUtils.generateQI([Ci.nsIDownloadManagerUI]),
817     getAttention: function () {},
818     show: function () {},
819     visible: false
823 interactive("download-manager-show-builtin-ui",
824     "Show the built-in (Firefox-style) download manager window.",
825     function (I) {
826         Components.classesByID["{7dfdf0d1-aff6-4a34-bad1-d0fe74601642}"]
827             .getService(Ci.nsIDownloadManagerUI)
828             .show(I.window);
829     });
833  * Download-show
834  */ 
836 define_variable("download_temporary_file_open_buffer_delay", 500,
837     "Delay (in milliseconds) before a download buffer is opened for "+
838     "temporary downloads.  If the download completes before this amount "+
839     "of time, no download buffer will be opened.  This variable takes "+
840     "effect only if `open_download_buffer_automatically' is in "+
841     "`download_added_hook', which is the case by default.");
843 define_variable("download_buffer_automatic_open_target", OPEN_NEW_WINDOW,
844     "Target(s) for download buffers created by "+
845     "`open_download_buffer_automatically'.");
847 minibuffer_auto_complete_preferences.download = true;
848 minibuffer.prototype.read_download = function () {
849     keywords(arguments,
850              $prompt = "Download",
851              $completer = all_word_completer(
852                  $completions = function (visitor) {
853                      var dls = download_manager_service.activeDownloads;
854                      while (dls.hasMoreElements()) {
855                          let dl = dls.getNext();
856                          visitor(id_to_download_info[dl.id]);
857                      }
858                  },
859                  $get_string = function (x) x.display_name,
860                  $get_description = function (x) x.source.spec,
861                  $get_value = function (x) x),
862              $auto_complete = "download",
863              $auto_complete_initial = true,
864              $match_required = true);
865     var result = yield this.read(forward_keywords(arguments));
866     yield co_return(result);
869 function download_show (window, target, info) {
870     if (! window)
871         target = OPEN_NEW_WINDOW;
872     create_buffer(window, buffer_creator(download_buffer, $info = info), target);
875 function download_show_new_window (I) {
876     var info = yield I.minibuffer.read_download($prompt = "Show download:");
877     download_show(I.window, OPEN_NEW_WINDOW, info);
880 function download_show_new_buffer (I) {
881     var info = yield I.minibuffer.read_download($prompt = "Show download:");
882     download_show(I.window, OPEN_NEW_BUFFER, info);
885 function download_show_new_buffer_background (I) {
886     var info = yield I.minibuffer.read_download($prompt = "Show download:");
887     download_show(I.window, OPEN_NEW_BUFFER_BACKGROUND, info);
890 function open_download_buffer_automatically (info) {
891     var buf = info.source_buffer;
892     var target = download_buffer_automatic_open_target;
893     if (info.temporary_status == DOWNLOAD_NOT_TEMPORARY ||
894         download_temporary_file_open_buffer_delay == 0)
895     {
896         download_show(buf.window, target, info);
897     } else {
898         var timer = null;
899         function finish () {
900             timer.cancel();
901         }
902         add_hook.call(info, "download_finished_hook", finish);
903         timer = call_after_timeout(function () {
904                 remove_hook.call(info, "download_finished_hook", finish);
905                 download_show(buf.window, target, info);
906             }, download_temporary_file_open_buffer_delay);
907     }
909 add_hook("download_added_hook", open_download_buffer_automatically);
911 interactive("download-show",
912     "Prompt for an ongoing download and open a download buffer showing "+
913     "its progress.",
914     alternates(download_show_new_buffer,
915                download_show_new_window));
917 provide("download-manager");