Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include "compat.h"
19 #include <stdlib.h>
20 #include <string.h>
21 #include <unistd.h>
23 #include "telescope.h"
24 #include "ui.h"
25 #include "xwrapper.h"
27 struct downloads downloads = STAILQ_HEAD_INITIALIZER(downloads);
29 static void
30 no_downloads(void)
31 {
32 struct line *l;
34 l = xcalloc(1, sizeof(*l));
36 l->type = LINE_DOWNLOAD_INFO;
37 l->line = xstrdup("No downloads");
39 TAILQ_INSERT_TAIL(&downloadwin.head, l, lines);
40 }
42 void
43 recompute_downloads(void)
44 {
45 struct download *d;
46 struct line *l;
47 char buf[FMT_SCALED_STRSIZE];
49 downloadwin.mode = "*Downloads*";
50 erase_buffer(&downloadwin);
52 if (STAILQ_EMPTY(&downloads)) {
53 no_downloads();
54 goto end;
55 }
57 STAILQ_FOREACH(d, &downloads, entries) {
58 l = xcalloc(1, sizeof(*l));
60 fmt_scaled(d->bytes, buf);
62 l->type = LINE_DOWNLOAD;
63 if (d->fd == -1)
64 l->type = LINE_DOWNLOAD_DONE;
66 l->line = xstrdup(buf);
67 l->alt = xstrdup(d->path);
69 TAILQ_INSERT_TAIL(&downloadwin.head, l, lines);
70 }
72 end:
73 /*
74 * The exact value doesn't matter, as wrap_page only considers
75 * l->line, which is the human representation of the byte
76 * counter, and we know for sure is < FMT_SCALED_STRSIZE so it
77 * fits.
78 */
79 wrap_page(&downloadwin, download_cols, 0);
80 }
82 struct download *
83 enqueue_download(uint32_t id, const char *path, const char *mime_type)
84 {
85 struct download *d;
87 d = xcalloc(1, sizeof(*d));
89 d->id = id;
90 d->fd = -1;
91 d->path = xstrdup(path);
92 d->mime_type = xstrdup(mime_type);
94 STAILQ_INSERT_HEAD(&downloads, d, entries);
96 return d;
97 }
99 struct download *
100 download_by_id(uint32_t id)
102 struct download *d;
104 STAILQ_FOREACH(d, &downloads, entries) {
105 if (d->id == id)
106 return d;
109 return NULL;
112 void
113 download_finished(struct download *d)
115 if (d == NULL)
116 return;
118 close(d->fd);
119 d->fd = -1;
121 ui_on_download_refresh();
122 ui_prompt_download_cmd(d);