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] = "```",
45 const char *parser_name;
51 static void *hash_alloc(size_t, void *);
52 static void *hash_calloc(size_t, size_t, void *);
53 static void hash_free(void *, void *);
56 hash_alloc(size_t len, void *d)
58 if ((d = malloc(len)) == NULL)
64 hash_calloc(size_t nmemb, size_t size, void *d)
66 if ((d = calloc(nmemb, size)) == NULL)
72 hash_free(void *ptr, void *d)
80 struct ohash_info info = {
81 .key_offset = offsetof(struct mcache_entry, url),
82 .calloc = hash_calloc,
87 ohash_init(&mcache.h, 5, &info);
91 mcache_tab(struct tab *tab)
93 struct mcache_entry *e;
99 url = tab->hist_cur->h;
101 len = sizeof(*e) + l + 1;
103 if ((e = calloc(1, len)) == NULL)
105 e->parser_name = tab->buffer.page.name;
106 e->trust = tab->trust;
107 memcpy(e->url, url, l);
109 if ((e->evb = evbuffer_new()) == NULL)
112 TAILQ_FOREACH(line, &tab->buffer.page.head, lines) {
113 const char *text, *alt;
116 if ((text = line->line) == NULL)
119 if ((alt = line->alt) == NULL)
122 switch (line->type) {
130 case LINE_PRE_CONTENT:
132 r = evbuffer_add_printf(e->evb, "%s%s\n",
133 gemtext_prefixes[line->type], text);
137 r = evbuffer_add_printf(e->evb, "=> %s %s\n",
143 case LINE_PATCH_HUNK_HDR:
151 case LINE_COMPL_CURRENT:
154 case LINE_DOWNLOAD_DONE:
155 case LINE_DOWNLOAD_INFO:
165 slot = ohash_qlookup(&mcache.h, url);
166 ohash_insert(&mcache.h, slot, e);
171 evbuffer_free(e->evb);
177 mcache_lookup(const char *url, struct tab *tab)
179 struct mcache_entry *e;
182 slot = ohash_qlookup(&mcache.h, url);
183 if ((e = ohash_find(&mcache.h, slot)) == NULL)
186 parser_init(tab, gemtext_initparser);
187 if (!parser_parse(tab, EVBUFFER_DATA(e->evb), EVBUFFER_LENGTH(e->evb)))
189 if (!parser_free(tab))
192 tab->buffer.page.name = e->parser_name;
193 tab->trust = e->trust;
198 erase_buffer(&tab->buffer);