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