2 * Copyright (c) 2022 Omar Polo <op@omarpolo.com>
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.
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.
23 #include "telescope.h"
27 const char *gemtext_prefixes[] = {
29 [LINE_TITLE_1] = "# ",
30 [LINE_TITLE_2] = "## ",
31 [LINE_TITLE_3] = "### ",
34 [LINE_PRE_START] = "``` ",
35 [LINE_PRE_CONTENT] = "",
36 [LINE_PRE_END] = "```",
50 static void *hash_alloc(size_t, void *);
51 static void *hash_calloc(size_t, size_t, void *);
52 static void hash_free(void *, void *);
55 hash_alloc(size_t len, void *d)
57 if ((d = malloc(len)) == NULL)
63 hash_calloc(size_t nmemb, size_t size, void *d)
65 if ((d = calloc(nmemb, size)) == NULL)
71 hash_free(void *ptr, void *d)
79 struct ohash_info info = {
80 .key_offset = offsetof(struct mcache_entry, url),
81 .calloc = hash_calloc,
86 ohash_init(&mcache.h, 5, &info);
90 mcache_tab(struct tab *tab)
92 struct mcache_entry *e;
98 url = tab->hist_cur->h;
100 len = sizeof(*e) + l + 1;
102 if ((e = calloc(1, len)) == NULL)
104 e->trust = tab->trust;
105 memcpy(e->url, url, l);
107 if ((e->evb = evbuffer_new()) == NULL)
110 TAILQ_FOREACH(line, &tab->buffer.page.head, lines) {
111 const char *text, *alt;
114 if ((text = line->line) == NULL)
117 if ((alt = line->alt) == NULL)
120 switch (line->type) {
128 case LINE_PRE_CONTENT:
130 r = evbuffer_add_printf(e->evb, "%s%s\n",
131 gemtext_prefixes[line->type], text);
135 r = evbuffer_add_printf(e->evb, "=> %s %s\n",
141 case LINE_PATCH_HUNK_HDR:
149 case LINE_COMPL_CURRENT:
152 case LINE_DOWNLOAD_DONE:
153 case LINE_DOWNLOAD_INFO:
163 slot = ohash_qlookup(&mcache.h, url);
164 ohash_insert(&mcache.h, slot, e);
169 evbuffer_free(e->evb);
175 mcache_lookup(const char *url, struct tab *tab)
177 struct mcache_entry *e;
180 slot = ohash_qlookup(&mcache.h, url);
181 if ((e = ohash_find(&mcache.h, slot)) == NULL)
184 parser_init(tab, gemtext_initparser);
185 if (!parser_parse(tab, EVBUFFER_DATA(e->evb), EVBUFFER_LENGTH(e->evb)))
187 if (!parser_free(tab))
190 tab->trust = e->trust;
195 erase_buffer(&tab->buffer);