gmane page-mode: binding for browser-object-links
[conkeror.git] / modules / download-manager.js
blob1426acff55a431c522bcea29b48e2e123178c5d2
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, target_file) {
173     this.source_buffer = source_buffer;
174     this.target_file = target_file;
175     if (mozilla_info != null)
176         this.attach(mozilla_info);
178 download_info.prototype = {
179     attach : function (mozilla_info) {
180         if (!this.target_file)
181             this.__defineGetter__("target_file", function(){
182                     return this.mozilla_info.targetFile;
183                 });
184         else if (this.target_file.path != mozilla_info.targetFile.path)
185             throw interactive_error("Download target file unexpected.");
186         this.mozilla_info = mozilla_info;
187         id_to_download_info[mozilla_info.id] = this;
188         download_added_hook.run(this);
189     },
191     target_file : null,
193     shell_command : null,
195     shell_command_cwd : null,
197     temporary_status : DOWNLOAD_NOT_TEMPORARY,
199     action_description : null,
201     set_shell_command : function (str, cwd) {
202         this.shell_command = str;
203         this.shell_command_cwd = cwd;
204         if (this.mozilla_info)
205             download_shell_command_change_hook.run(this);
206     },
208     /**
209      * None of the following members may be used until attach is called
210      */
212     // Reflectors to properties of nsIDownload
213     get state () { return this.mozilla_info.state; },
214     get display_name () { return this.mozilla_info.displayName; },
215     get amount_transferred () { return this.mozilla_info.amountTransferred; },
216     get percent_complete () { return this.mozilla_info.percentComplete; },
217     get size () {
218         var s = this.mozilla_info.size;
219         /* nsIDownload.size is a PRUint64, and will have value
220          * LL_MAXUINT (2^64 - 1) to indicate an unknown size.  Because
221          * JavaScript only has a double numerical type, this value
222          * cannot be represented exactly, so 2^36 is used instead as the cutoff. */
223         if (s < 68719476736 /* 2^36 */)
224             return s;
225         return -1;
226     },
227     get source () { return this.mozilla_info.source; },
228     get start_time () { return this.mozilla_info.startTime; },
229     get speed () { return this.mozilla_info.speed; },
230     get MIME_info () { return this.mozilla_info.MIMEInfo; },
231     get MIME_type () {
232         if (this.MIME_info)
233             return this.MIME_info.MIMEType;
234         return null;
235     },
236     get id () { return this.mozilla_info.id; },
237     get referrer () { return this.mozilla_info.referrer; },
239     target_file_text : function() {
240         let target = this.target_file.path;
241         let display = this.display_name;
242         if (target.indexOf(display, target.length - display.length) == -1)
243             target += " (" + display + ")";
244         return target;
245     },
247     throw_if_removed : function () {
248         if (this.removed)
249             throw interactive_error("Download has already been removed from the download manager.");
250     },
252     throw_state_error : function () {
253         switch (this.state) {
254         case DOWNLOAD_DOWNLOADING:
255             throw interactive_error("Download is already in progress.");
256         case DOWNLOAD_FINISHED:
257             throw interactive_error("Download has already completed.");
258         case DOWNLOAD_FAILED:
259             throw interactive_error("Download has already failed.");
260         case DOWNLOAD_CANCELED:
261             throw interactive_error("Download has already been canceled.");
262         case DOWNLOAD_PAUSED:
263             throw interactive_error("Download has already been paused.");
264         case DOWNLOAD_QUEUED:
265             throw interactive_error("Download is queued.");
266         default:
267             throw new Error("Download has unexpected state: " + this.state);
268         }
269     },
271     // Download manager operations
272     cancel : function ()  {
273         this.throw_if_removed();
274         switch (this.state) {
275         case DOWNLOAD_DOWNLOADING:
276         case DOWNLOAD_PAUSED:
277         case DOWNLOAD_QUEUED:
278             try {
279                 download_manager_service.cancelDownload(this.id);
280             } catch (e) {
281                 throw interactive_error("Download cannot be canceled.");
282             }
283             break;
284         default:
285             this.throw_state_error();
286         }
287     },
289     retry : function () {
290         this.throw_if_removed();
291         switch (this.state) {
292         case DOWNLOAD_CANCELED:
293         case DOWNLOAD_FAILED:
294             try {
295                 download_manager_service.retryDownload(this.id);
296             } catch (e) {
297                 throw interactive_error("Download cannot be retried.");
298             }
299             break;
300         default:
301             this.throw_state_error();
302         }
303     },
305     resume : function () {
306         this.throw_if_removed();
307         switch (this.state) {
308         case DOWNLOAD_PAUSED:
309             try {
310                 download_manager_service.resumeDownload(this.id);
311             } catch (e) {
312                 throw interactive_error("Download cannot be resumed.");
313             }
314             break;
315         default:
316             this.throw_state_error();
317         }
318     },
320     pause : function () {
321         this.throw_if_removed();
322         switch (this.state) {
323         case DOWNLOAD_DOWNLOADING:
324         case DOWNLOAD_QUEUED:
325             try {
326                 download_manager_service.pauseDownload(this.id);
327             } catch (e) {
328                 throw interactive_error("Download cannot be paused.");
329             }
330             break;
331         default:
332             this.throw_state_error();
333         }
334     },
336     remove : function () {
337         this.throw_if_removed();
338         switch (this.state) {
339         case DOWNLOAD_FAILED:
340         case DOWNLOAD_CANCELED:
341         case DOWNLOAD_FINISHED:
342             try {
343                 download_manager_service.removeDownload(this.id);
344             } catch (e) {
345                 throw interactive_error("Download cannot be removed.");
346             }
347             break;
348         default:
349             throw interactive_error("Download is still in progress.");
350         }
351     },
353     delete_target : function () {
354         if (this.state != DOWNLOAD_FINISHED)
355             throw interactive_error("Download has not finished.");
356         try {
357             this.target_file.remove(false);
358         } catch (e) {
359             if ("result" in e) {
360                 switch (e.result) {
361                 case Cr.NS_ERROR_FILE_TARGET_DOES_NOT_EXIST:
362                     throw interactive_error("File has already been deleted.");
363                 case Cr.NS_ERROR_FILE_ACCESS_DENIED:
364                     throw interactive_error("Access denied");
365                 case Cr.NS_ERROR_FILE_DIR_NOT_EMPTY:
366                     throw interactive_error("Failed to delete file.");
367                 }
368             }
369             throw e;
370         }
371     }
374 var define_download_local_hook = simple_local_hook_definer();
376 // FIXME: add more parameters
377 function register_download(buffer, source_uri, target_file) {
378     var info = new download_info(buffer, null, target_file);
379     info.registered_time_stamp = Date.now();
380     info.registered_source_uri = source_uri;
381     unmanaged_download_info_list.push(info);
382     return info;
385 function match_registered_download(mozilla_info) {
386     let list = unmanaged_download_info_list;
387     let t = Date.now();
388     for (let i = 0; i < list.length; ++i) {
389         let x = list[i];
390         if (x.registered_source_uri == mozilla_info.source) {
391             list.splice(i, 1);
392             return x;
393         }
394         if (t - x.registered_time_stamp > download_info_max_queue_delay) {
395             list.splice(i, 1);
396             --i;
397             continue;
398         }
399     }
400     return null;
403 define_download_local_hook("download_added_hook");
404 define_download_local_hook("download_removed_hook");
405 define_download_local_hook("download_finished_hook");
406 define_download_local_hook("download_progress_change_hook");
407 define_download_local_hook("download_state_change_hook");
408 define_download_local_hook("download_shell_command_change_hook");
410 define_variable('delete_temporary_files_for_command', true,
411                 'If this is set to true, temporary files '
412                 + 'downloaded to run a command on them will be '
413                 + 'deleted once the command completes. If not, the '
414                 + 'file will stay around forever unless deleted '
415                 + 'outside the browser.');
417 var download_info_max_queue_delay = 100;
419 var download_progress_listener = {
420     QueryInterface: generate_QI(Ci.nsIDownloadProgressListener),
422     onDownloadStateChange : function (state, download) {
423         var info = null;
424         /* FIXME: Determine if only new downloads will have this state
425          * as their previous state. */
427         dumpln("download state change: " + download.source.spec + ": " + state + ", " + download.state + ", " + download.id);
429         if (state == DOWNLOAD_NOTSTARTED) {
430             info = match_registered_download(download);
431             if (info == null) {
432                 info = new download_info(null, download);
433                 dumpln("error: encountered unknown new download");
434             } else {
435                 info.attach(download);
436             }
437         } else {
438             info = id_to_download_info[download.id];
439             if (info == null) {
440                 dumpln("Error: encountered unknown download");
442             } else {
443                 info.mozilla_info = download;
444                 download_state_change_hook.run(info);
445                 if (info.state == DOWNLOAD_FINISHED) {
446                     download_finished_hook.run(info);
448                     if (info.shell_command != null) {
449                         info.running_shell_command = true;
450                         co_call(function () {
451                             try {
452                                 yield shell_command_with_argument(info.shell_command,
453                                                                   info.target_file.path,
454                                                                   $cwd = info.shell_command_cwd);
455                             } finally  {
456                                 if (info.temporary_status == DOWNLOAD_TEMPORARY_FOR_COMMAND)
457                                     if(delete_temporary_files_for_command) {
458                                         info.target_file.remove(false /* not recursive */);
459                                     }
460                                 info.running_shell_command = false;
461                                 download_shell_command_change_hook.run(info);
462                             }
463                         }());
464                         download_shell_command_change_hook.run(info);
465                     }
466                 }
467             }
468         }
469     },
471     onProgressChange : function (progress, request, cur_self_progress, max_self_progress,
472                                  cur_total_progress, max_total_progress,
473                                  download) {
474         var info = id_to_download_info[download.id];
475         if (info == null) {
476             dumpln("error: encountered unknown download in progress change");
477             return;
478         }
479         info.mozilla_info = download;
480         download_progress_change_hook.run(info);
481         //dumpln("download progress change: " + download.source.spec + ": " + cur_self_progress + "/" + max_self_progress + " "
482         // + cur_total_progress + "/" + max_total_progress + ", " + download.state + ", " + download.id);
483     },
485     onSecurityChange : function (progress, request, state, download) {
486     },
488     onStateChange : function (progress, request, state_flags, status, download) {
489     }
492 var download_observer = {
493     observe : function(subject, topic, data) {
494         switch(topic) {
495         case "download-manager-remove-download":
496             var ids = [];
497             if (!subject) {
498                 // Remove all downloads
499                 for (let i in id_to_download_info)
500                     ids.push(i);
501             } else {
502                 let id = subject.QueryInterface(Ci.nsISupportsPRUint32);
503                 /* FIXME: determine if this should really be an error */
504                 if (!(id in id_to_download_info)) {
505                     dumpln("Error: download-manager-remove-download event received for unknown download: " + id);
506                 } else
507                     ids.push(id);
508             }
509             for each (let i in ids) {
510                 dumpln("deleting download: " + i);
511                 let d = id_to_download_info[i];
512                 d.removed = true;
513                 download_removed_hook.run(d);
514                 delete id_to_download_info[i];
515             }
516             break;
517         }
518     }
520 observer_service.addObserver(download_observer, "download-manager-remove-download", false);
522 download_manager_service.addListener(download_progress_listener);
524 function pretty_print_file_size(val) {
525     const GIBI = 1073741824; /* 2^30 */
526     const MEBI = 1048576; /* 2^20 */
527     const KIBI = 1024; /* 2^10 */
528     var suffix, div;
529     if (val < KIBI) {
530         div = 1;
531         suffix = "B";
532     }
533     else if (val < MEBI) {
534         suffix = "KiB";
535         div = KIBI;
536     } else if (val < GIBI) {
537         suffix = "MiB";
538         div = MEBI;
539     } else {
540         suffix = "GiB";
541         div = GIBI;
542     }
543     val = val / div;
544     var precision = 2;
545     if (val > 10)
546         precision = 1;
547     if (val > 100)
548         precision = 0;
549     return [val.toFixed(precision), suffix];
552 function pretty_print_time(val) {
553     val = Math.round(val);
554     var seconds = val % 60;
556     val = Math.floor(val / 60);
558     var minutes = val % 60;
560     var hours = Math.floor(val / 60);
562     var parts = [];
564     if (hours > 1)
565         parts.push(hours + " hours");
566     else if (hours == 1)
567         parts.push("1 hour");
569     if (minutes > 1)
570         parts.push(minutes + " minutes");
571     else if (minutes == 1)
572         parts.push("1 minute");
574     if (minutes <= 1 && hours == 0) {
575         if (seconds != 1)
576             parts.push(seconds + " seconds");
577         else
578             parts.push("1 second");
579     }
581     return parts.join(", ");
584 define_variable(
585     "download_buffer_min_update_interval", 2000,
586     "Minimum interval (in milliseconds) between updates in download progress buffers.\n" +
587         "Lowering this interval will increase the promptness of the progress display at " +
588         "the cost of using additional processor time.");
590 define_keywords("$info");
591 function download_buffer(window, element) {
592     this.constructor_begin();
593     keywords(arguments);
594     special_buffer.call(this, window, element, forward_keywords(arguments));
595     this.info = arguments.$info;
596     this.configuration.cwd = this.info.mozilla_info.targetFile.parent.path;
597     this.description = this.info.mozilla_info.source.spec;
598     this.keymap = download_buffer_keymap;
599     this.update_title();
601     this.progress_change_handler_fn = method_caller(this, this.handle_progress_change);
602     add_hook.call(this.info, "download_progress_change_hook", this.progress_change_handler_fn);
603     add_hook.call(this.info, "download_state_change_hook", this.progress_change_handler_fn);
604     this.command_change_handler_fn = method_caller(this, this.update_command_field);
605     add_hook.call(this.info, "download_shell_command_change_hook", this.command_change_handler_fn);
606     this.constructor_end();
608 download_buffer.prototype = {
609     __proto__: special_buffer.prototype,
611     handle_kill : function () {
612         this.__proto__.__proto__.handle_kill.call(this);
613         remove_hook.call(this.info, "download_progress_change_hook", this.progress_change_handler_fn);
614         remove_hook.call(this.info, "download_state_change_hook", this.progress_change_handler_fn);
615         remove_hook.call(this.info, "download_shell_command_change_hook", this.command_change_handler_fn);
617         // Remove all node references
618         delete this.status_textnode;
619         delete this.target_file_node;
620         delete this.transferred_div_node;
621         delete this.transferred_textnode;
622         delete this.progress_container_node;
623         delete this.progress_bar_node;
624         delete this.time_textnode;
625         delete this.command_div_node;
626         delete this.command_label_textnode;
627         delete this.command_textnode;
628     },
630     update_title : function () {
631         // FIXME: do this properly
632         var new_title;
633         var info = this.info;
634         var append_transfer_info = false;
635         var append_speed_info = true;
636         var label = null;
637         switch(info.state) {
638         case DOWNLOAD_DOWNLOADING:
639             label = "Downloading";
640             append_transfer_info = true;
641             break;
642         case DOWNLOAD_FINISHED:
643             label = "Download complete";
644             break;
645         case DOWNLOAD_FAILED:
646             label = "Download failed";
647             append_transfer_info = true;
648             append_speed_info = false;
649             break;
650         case DOWNLOAD_CANCELED:
651             label = "Download canceled";
652             append_transfer_info = true;
653             append_speed_info = false;
654             break;
655         case DOWNLOAD_PAUSED:
656             label = "Download paused";
657             append_transfer_info = true;
658             append_speed_info = false;
659             break;
660         case DOWNLOAD_QUEUED:
661         default:
662             label = "Download queued";
663             break;
664         }
666         if (append_transfer_info) {
667             if (append_speed_info)
668                 new_title = label + " at " + pretty_print_file_size(info.speed).join(" ") + "/s: ";
669             else
670                 new_title = label + ": ";
671             var trans = pretty_print_file_size(info.amount_transferred);
672             if (info.size >= 0) {
673                 var total = pretty_print_file_size(info.size);
674                 if (trans[1] == total[1])
675                     new_title += trans[0] + "/" + total[0] + " " + total[1];
676                 else
677                     new_title += trans.join(" ") + "/" + total.join(" ");
678             } else
679                 new_title += trans.join(" ");
680             if (info.percent_complete >= 0)
681                 new_title += " (" + info.percent_complete + "%)";
682         } else
683             new_title = label;
684         if (new_title != this.title) {
685             this.title = new_title;
686             return true;
687         }
688         return false;
689     },
691     handle_progress_change : function () {
692         var cur_time = Date.now();
693         if (this.last_update == null ||
694             (cur_time - this.last_update) > download_buffer_min_update_interval ||
695             this.info.state != this.previous_state) {
697             if (this.update_title())
698                 buffer_title_change_hook.run(this);
700             if (this.generated) {
701                 this.update_fields();
702             }
703             this.previous_status = this.info.status;
704             this.last_update = cur_time;
705         }
706     },
708     generate: function() {
709         var d = this.document;
710         var g = new dom_generator(d, XHTML_NS);
712         /* Warning: If any additional node references are saved in
713          * this function, appropriate code to delete the saved
714          * properties must be added to handle_kill. */
716         var info = this.info;
718         d.body.setAttribute("class", "download-buffer");
720         g.add_stylesheet("chrome://conkeror-gui/content/downloads.css");
722         var div;
723         var label, value;
725         div = g.element("div", d.body, "class", "download-info", "id", "download-source");
726         label = g.element("div", div, "class", "download-label");
727         this.status_textnode = g.text("", label);
728         value = g.element("div", div, "class", "download-value");
729         g.text(info.source.spec, value);
731         div = g.element("div", d.body, "class", "download-info", "id", "download-target");
732         label = g.element("div", div, "class", "download-label");
733         var target_label;
734         if (info.temporary_status != DOWNLOAD_NOT_TEMPORARY)
735             target_label = "Temp. file:";
736         else
737             target_label = "Target:";
738         g.text(target_label, label);
739         value = g.element("div", div, "class", "download-value");
740         this.target_file_node = g.text("", value);
742         div = g.element("div", d.body, "class", "download-info", "id", "download-mime-type");
743         label = g.element("div", div, "class", "download-label");
744         g.text("MIME type:", label);
745         value = g.element("div", div, "class", "download-value");
746         g.text(info.MIME_type || "unknown", value);
748         this.transferred_div_node = div = g.element("div", d.body,
749                                                     "class", "download-info",
750                                                     "id", "download-transferred");
751         label = g.element("div", div, "class", "download-label");
752         g.text("Transferred:", label);
753         value = g.element("div", div, "class", "download-value");
754         this.transferred_textnode = g.text("", value);
755         this.progress_container_node = value = g.element("div", div, "id", "download-progress-container");
756         this.progress_bar_node = g.element("div", value, "id", "download-progress-bar");
757         value = g.element("div", div, "class", "download-value", "id", "download-percent");
758         this.percent_textnode = g.text("", value);
760         div = g.element("div", d.body, "class", "download-info", "id", "download-time");
761         label = g.element("div", div, "class", "download-label");
762         g.text("Time:", label);
763         value = g.element("div", div, "class", "download-value");
764         this.time_textnode = g.text("", value);
766         if (info.action_description != null) {
767             div = g.element("div", d.body, "class", "download-info", "id", "download-action");
768             label = g.element("div", div, "class", "download-label");
769             g.text("Action:", label);
770             value = g.element("div", div, "class", "download-value");
771             g.text(info.action_description, value);
772         }
774         this.command_div_node = div = g.element("div", d.body, "class", "download-info", "id", "download-command");
775         label = g.element("div", div, "class", "download-label");
776         this.command_label_textnode = g.text("Run command:", label);
777         value = g.element("div", div, "class", "download-value");
778         this.command_textnode = g.text("", value);
780         this.update_fields();
782         this.update_command_field();
783     },
785     update_fields : function () {
786         if (!this.generated)
787             return;
788         var info = this.info;
789         var label = null;
790         switch(info.state) {
791         case DOWNLOAD_DOWNLOADING:
792             label = "Downloading";
793             break;
794         case DOWNLOAD_FINISHED:
795             label = "Completed";
796             break;
797         case DOWNLOAD_FAILED:
798             label = "Failed";
799             break;
800         case DOWNLOAD_CANCELED:
801             label = "Canceled";
802             break;
803         case DOWNLOAD_PAUSED:
804             label = "Paused";
805             break;
806         case DOWNLOAD_QUEUED:
807         default:
808             label = "Queued";
809             break;
810         }
811         this.status_textnode.nodeValue = label + ":";
812         this.target_file_node.nodeValue = info.target_file_text();
813         this.update_time_field();
815         var tran_text = "";
816         if (info.state == DOWNLOAD_FINISHED)
817             tran_text = pretty_print_file_size(info.size).join(" ");
818         else {
819             var trans = pretty_print_file_size(info.amount_transferred);
820             if (info.size >= 0) {
821                 var total = pretty_print_file_size(info.size);
822                 if (trans[1] == total[1])
823                     tran_text += trans[0] + "/" + total[0] + " " + total[1];
824                 else
825                     tran_text += trans.join(" ") + "/" + total.join(" ");
826             } else
827                 tran_text += trans.join(" ");
828         }
829         this.transferred_textnode.nodeValue = tran_text;
830         if (info.percent_complete >= 0) {
831             this.progress_container_node.style.display = "";
832             this.percent_textnode.nodeValue = info.percent_complete + "%";
833             this.progress_bar_node.style.width = info.percent_complete + "%";
834         } else {
835             this.percent_textnode.nodeValue = "";
836             this.progress_container_node.style.display = "none";
837         }
839         this.update_command_field();
840     },
842     update_time_field : function () {
843         var info = this.info;
844         var elapsed_text = pretty_print_time((Date.now() - info.start_time / 1000) / 1000) + " elapsed";
845         var text = "";
846         if (info.state == DOWNLOAD_DOWNLOADING) {
847             text = pretty_print_file_size(info.speed).join(" ") + "/s, ";
848         }
849         if (info.state == DOWNLOAD_DOWNLOADING &&
850             info.size >= 0 &&
851             info.speed > 0) {
852             let remaining = (info.size - info.amount_transferred) / info.speed;
853             text += pretty_print_time(remaining) + " left (" + elapsed_text + ")";
854         } else {
855             text = elapsed_text;
856         }
857         this.time_textnode.nodeValue = text;
858     },
860     update_command_field : function () {
861         if (!this.generated)
862             return;
863         if (this.info.shell_command != null) {
864             this.command_div_node.style.display = "";
865             var label;
866             if (this.info.running_shell_command)
867                 label = "Running:";
868             else if (this.info.state == DOWNLOAD_FINISHED)
869                 label = "Ran command:";
870             else
871                 label = "Run command:";
872             this.command_label_textnode.nodeValue = label;
873             this.command_textnode.nodeValue = this.info.shell_command;
874         } else {
875             this.command_div_node.style.display = "none";
876         }
877     }
880 function download_cancel(buffer) {
881     check_buffer(buffer, download_buffer);
882     var info = buffer.info;
883     info.cancel();
884     buffer.window.minibuffer.message("Download canceled");
886 interactive("download-cancel",
887             "Cancel the current download.\n" +
888             "The download can later be retried using the `download-retry' command, but any " +
889             "data already transferred will be lost.",
890             function (I) {download_cancel(I.buffer);});
892 function download_retry(buffer) {
893     check_buffer(buffer, download_buffer);
894     var info = buffer.info;
895     info.retry();
896     buffer.window.minibuffer.message("Download retried");
898 interactive("download-retry",
899             "Retry a failed or canceled download.\n" +
900             "This command can be used to retry a download that failed or was cancled using " +
901             "the `download-cancel' command.  The download will begin from the start again.",
902             function (I) {download_retry(I.buffer);});
904 function download_pause(buffer) {
905     check_buffer(buffer, download_buffer);
906     buffer.info.pause();
907     buffer.window.minibuffer.message("Download paused");
909 interactive("download-pause",
910             "Pause the current download.\n" +
911             "The download can later be resumed using the `download-resume' command.  The " +
912             "data already transferred will not be lost.",
913             function (I) {download_pause(I.buffer);});
915 function download_resume(buffer) {
916     check_buffer(buffer, download_buffer);
917     buffer.info.resume();
918     buffer.window.minibuffer.message("Download resumed");
920 interactive("download-resume",
921             "Resume the current download.\n" +
922             "This command can be used to resume a download paused using the `download-pause' command.",
923             function (I) {download_resume(I.buffer);});
925 function download_remove(buffer) {
926     check_buffer(buffer, download_buffer);
927     buffer.info.remove();
928     buffer.window.minibuffer.message("Download removed");
930 interactive("download-remove",
931             "Remove the current download from the download manager.\n" +
932             "This command can only be used on inactive (paused, canceled, completed, or failed) downloads.",
933             function (I) {download_remove(I.buffer);});
935 function download_retry_or_resume(buffer) {
936     check_buffer(buffer, download_buffer);
937     var info = buffer.info;
938     if (info.state == DOWNLOAD_PAUSED)
939         download_resume(buffer);
940     else
941         download_retry(buffer);
943 interactive("download-retry-or-resume",
944             "Retry or resume the current download.\n" +
945             "This command can be used to resume a download paused using the `download-pause' " +
946             "command or canceled using the `download-cancel' command.",
947             function (I) {download_retry_or_resume(I.buffer);});
949 function download_pause_or_resume(buffer) {
950     check_buffer(buffer, download_buffer);
951     var info = buffer.info;
952     if (info.state == DOWNLOAD_PAUSED)
953         download_resume(buffer);
954     else
955         download_pause(buffer);
957 interactive("download-pause-or-resume",
958             "Pause or resume the current download.\n" +
959             "This command toggles the paused state of the current download.",
960             function (I) {download_pause_or_resume(I.buffer);});
962 function download_delete_target(buffer) {
963     check_buffer(buffer, download_buffer);
964     var info = buffer.info;
965     info.delete_target();
966     buffer.window.minibuffer.message("Deleted file: " + info.target_file.path);
968 interactive("download-delete-target",
969             "Delete the target file of the current download.\n"  +
970             "This command can only be used if the download has finished successfully.",
971             function (I) {download_delete_target(I.buffer);});
973 function download_shell_command(buffer, cwd, cmd) {
974     check_buffer(buffer, download_buffer);
975     var info = buffer.info;
976     if (info.state == DOWNLOAD_FINISHED) {
977         shell_command_with_argument_blind(cmd, info.target_file.path, $cwd = cwd);
978         return;
979     }
980     if (info.state != DOWNLOAD_DOWNLOADING && info.state != DOWNLOAD_PAUSED && info.state != DOWNLOAD_QUEUED)
981         info.throw_state_error();
982     if (cmd == null || cmd.length == 0)
983         info.set_shell_command(null, cwd);
984     else
985         info.set_shell_command(cmd, cwd);
986     buffer.window.minibuffer.message("Queued shell command: " + cmd);
988 interactive("download-shell-command",
989             "Run a shell command on the target file of the current download.\n" +
990             "If the download is still in progress, the shell command will be queued " +
991             "to run when the download finishes.",
992             function (I) {
993                 var buffer = check_buffer(I.buffer, download_buffer);
994                 var cwd = buffer.info.shell_command_cwd || buffer.cwd;
995                 var cmd = yield I.minibuffer.read_shell_command(
996                     $cwd = cwd,
997                     $initial_value = buffer.info.shell_command ||
998                         get_mime_type_external_handler(buffer.info.MIME_type));
999                 download_shell_command(buffer, cwd, cmd);
1000             });
1002 function download_manager_ui()
1004 download_manager_ui.prototype = {
1005     QueryInterface : XPCOMUtils.generateQI([Ci.nsIDownloadManagerUI]),
1007     getAttention : function () {},
1008     show : function () {},
1009     visible : false
1013 function download_manager_show_builtin_ui(window) {
1014     download_manager_builtin_ui.show(window);
1016 interactive("download-manager-show-builtin-ui",
1017             "Show the built-in (Firefox-style) download manager user interface.",
1018             function (I) {download_manager_show_builtin_ui(I.window);});
1022 define_variable("download_temporary_file_open_buffer_delay", 500,
1023                      "Delay (in milliseconds) before a download buffer is opened for temporary downloads.\n" +
1024                      "This variable takes effect only if `open_download_buffer_automatically' is in " +
1025                      "`download_added_hook', as it is by default.");
1028 define_variable("download_buffer_automatic_open_target", OPEN_NEW_WINDOW,
1029                      "Target for download buffers created by the `open_download_buffer_automatically' function.\n" +
1030                      "This variable takes effect only if `open_download_buffer_automatically' is in " +
1031                      "`download_added_hook', as it is by default.");
1033 function open_download_buffer_automatically(info) {
1034     var buf = info.source_buffer;
1035     var target = download_buffer_automatic_open_target;
1036     if (buf == null)
1037         target = OPEN_NEW_WINDOW;
1038     if (info.temporary_status == DOWNLOAD_NOT_TEMPORARY ||
1039         !(download_temporary_file_open_buffer_delay > 0))
1040         create_buffer(buf.window, buffer_creator(download_buffer, $info = info), target);
1041     else {
1042         var timer = null;
1043         function finish() {
1044             timer.cancel();
1045         }
1046         add_hook.call(info, "download_finished_hook", finish);
1047         timer = call_after_timeout(function () {
1048                 remove_hook.call(info, "download_finished_hook", finish);
1049                 create_buffer(buf.window, buffer_creator(download_buffer, $info = info), target);
1050             }, download_temporary_file_open_buffer_delay);
1051     }
1053 add_hook("download_added_hook", open_download_buffer_automatically);