summaryrefslogtreecommitdiff
path: root/src/handler.c
blob: a5e79e0093e76bbaac34b94e95855f4591bca31a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/**
 * vimb - a webkit based vim like browser.
 *
 * Copyright (C) 2012-2018 Daniel Carl
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 */

#include <string.h>

#include "main.h"
#include "handler.h"
#include "util.h"

extern struct neovimb vb;

struct handler {
    GHashTable *table;  /* holds the protocol handlers */
};

static char *handler_lookup(Handler *h, const char *uri);

Handler *handler_new(void)
{
    Handler *h = g_new(Handler, 1);
    h->table   = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);

    return h;
}

void handler_free(Handler *h)
{
    if (h->table) {
        g_hash_table_destroy(h->table);
        h->table = NULL;
    }
    g_free(h);
}

gboolean handler_add(Handler *h, const char *key, const char *cmd)
{
    g_hash_table_insert(h->table, g_strdup(key), g_strdup(cmd));

    return TRUE;
}

gboolean handler_remove(Handler *h, const char *key)
{
    return g_hash_table_remove(h->table, key);
}

gboolean handler_handle_uri(Handler *h, const char *uri)
{
    char *handler, *cmd;
    GError *error = NULL;
    gboolean res;

    if (!(handler = handler_lookup(h, uri))) {
        return FALSE;
    }

    cmd = g_strdup_printf(handler, uri);
    if (!g_spawn_command_line_async(cmd, &error)) {
        g_warning("Can't run '%s': %s", cmd, error->message);
        g_clear_error(&error);
        res = FALSE;
    } else {
        res = TRUE;
    }

    g_free(cmd);
    return res;
}

gboolean handler_fill_completion(Handler *h, GtkListStore *store, const char *input)
{
    GList *src     = g_hash_table_get_keys(h->table);
    gboolean found = util_fill_completion(store, input, src);
    g_list_free(src);

    return found;
}

static char *handler_lookup(Handler *h, const char *uri)
{
    char *p, *schema, *handler = NULL;

    if ((p = strchr(uri, ':'))) {
        schema  = g_strndup(uri, p - uri);
        handler = g_hash_table_lookup(h->table, schema);
        g_free(schema);
    }

    return handler;
}