summaryrefslogtreecommitdiff
path: root/src/hints.c
blob: 07e4ffded10bda5ab7b50e4138c888dc6d62fb15 (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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/**
 * vimb - a webkit based vim like browser.
 *
 * Copyright (C) 2012-2014 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 <ctype.h>
#include "config.h"
#include <gdk/gdkkeysyms.h>
#include <gdk/gdkkeysyms-compat.h>
#include "hints.h"
#include "ascii.h"
#include "dom.h"
#include "command.h"
#include "hints.js.h"
#include "mode.h"
#include "input.h"
#include "map.h"

#define HINT_FILE "hints.js"

static struct {
    JSObjectRef    obj;       /* the js object */
    guint          num;       /* olds the numeric filter for hints typed by the user */
    char           mode;      /* mode identifying char - that last char of the hint prompt */
    int            promptlen; /* lenfth of the hint prompt chars 2 or 3 */
    gboolean       gmode;     /* indicate if the hints g mode is used */
    JSContextRef   ctx;
} hints;


extern VbCore vb;

static JSObjectRef create_hints_object(WebKitWebFrame *frame, const char *script);
static void call_hints_function(const char *func, int count, JSValueRef params[]);
static char *js_ref_to_string(JSContextRef context, JSValueRef ref);
static JSValueRef js_string_to_ref(JSContextRef ctx, const char *string);


void hints_init(WebKitWebFrame *frame)
{
    if (hints.obj) {
        JSValueUnprotect(hints.ctx, hints.obj);
        hints.obj = NULL;
    }
    if (!hints.obj) {
        hints.obj = create_hints_object(frame, HINTS_JS);
        hints.ctx = webkit_web_frame_get_global_context(frame);
    }
}

VbResult hints_keypress(int key)
{
    /* if we are not already in hint mode we expect to get a ; to start
     * hinting */
    if (!(vb.mode->flags & FLAG_HINTING) && key != ';') {
        return RESULT_ERROR;
    }

    if (key == KEY_CR) {
        hints_fire();

        return RESULT_COMPLETE;
    }

    /* if there is an active filter by hint num backspace will remove the
     * number filter first */
    if (hints.num && key == CTRL('H')) {
        hints.num /= 10;
        hints_update(hints.num);

        return RESULT_COMPLETE;
    }
    if (isdigit(key)) {
        int num = key - '0';
        if ((num >= 1 && num <= 9) || (num == 0 && hints.num)) {
            /* allow a zero as non-first number */
            hints.num = (hints.num ? hints.num * 10 : 0) + num;
            hints_update(hints.num);

            return RESULT_COMPLETE;
        }
    }
    if (key == KEY_TAB) {
        hints_focus_next(false);

        return RESULT_COMPLETE;
    }
    if (key == KEY_SHIFT_TAB) {
        hints_focus_next(true);

        return RESULT_COMPLETE;
    }

    return RESULT_ERROR;
}

void hints_clear(void)
{
    if (vb.mode->flags & FLAG_HINTING) {
        vb.mode->flags &= ~FLAG_HINTING;
        vb_set_input_text("");

        call_hints_function("clear", 0, NULL);

        g_signal_emit_by_name(vb.gui.webview, "hovering-over-link", NULL, NULL);
    }
}

void hints_create(const char *input)
{
    /* check if the input contains a valid hinting prompt */
    if (!hints_parse_prompt(input, &hints.mode, &hints.gmode)) {
        /* if input is not valid, clear possible previous hint mode */
        if (vb.mode->flags & FLAG_HINTING) {
            mode_enter('n');
        }
        return;
    }

    if (!(vb.mode->flags & FLAG_HINTING)) {
        vb.mode->flags |= FLAG_HINTING;

        /* unset number filter - this is required to remove the last char from
         * inputbox on backspace also if there was used a number filter prior */
        hints.num       = 0;
        hints.promptlen = hints.gmode ? 3 : 2;

        JSValueRef arguments[] = {
            js_string_to_ref(hints.ctx, (char[]){hints.mode, '\0'}),
            JSValueMakeNumber(hints.ctx, MAXIMUM_HINTS)
        };
        call_hints_function("init", 2, arguments);

        /* if hinting is started there won't be any aditional filter given and
         * we can go out of this function */
        return;
    }

    JSValueRef arguments[] = {js_string_to_ref(hints.ctx, *(input + hints.promptlen) ? input + hints.promptlen : "")};
    call_hints_function("filter", 1, arguments);
}

void hints_update(int num)
{
    JSValueRef arguments[] = {
        JSValueMakeNumber(hints.ctx, num)
    };
    call_hints_function("update", 1, arguments);
}

void hints_focus_next(const gboolean back)
{
    JSValueRef arguments[] = {
        JSValueMakeNumber(hints.ctx, back)
    };
    call_hints_function("focus", 1, arguments);
}

void hints_fire(void)
{
    call_hints_function("fire", 0, NULL);
}

void hints_follow_link(const gboolean back, int count)
{
    char *pattern = back ? vb.config.prevpattern : vb.config.nextpattern;

    JSValueRef arguments[] = {
        js_string_to_ref(hints.ctx, back ? "prev" : "next"),
        js_string_to_ref(hints.ctx, pattern),
        JSValueMakeNumber(hints.ctx, count)
    };
    call_hints_function("followLink", 3, arguments);
}

/**
 * Checks if the given hint prompt belong to a known and valid hints mode and
 * parses the mode and is_gmode into given pointers.
 *
 * The given prompt sting may also contain additional chars after the prompt.
 *
 * @prompt:   String to be parsed as prompt. The Prompt can be followed by
 *            additional characters.
 * @mode:     Pointer to char that will be filled with mode char if prompt was
 *            valid and given pointer is not NULL.
 * @is_gmode: Pointer to gboolean to be filled with the flag to indicate gmode
 *            hinting.
 */
gboolean hints_parse_prompt(const char *prompt, char *mode, gboolean *is_gmode)
{
    gboolean res;
    char pmode = '\0';
#ifdef FEATURE_QUEUE
    static char *modes   = "eiIoOpPstTy";
    static char *g_modes = "IpPsty";
#else
    static char *modes   = "eiIoOstTy";
    static char *g_modes = "Isty";
#endif

    if (!prompt) {
        return false;
    }

    /* get the mode identifying char from prompt */
    if (*prompt == ';') {
        pmode = prompt[1];
    } else if (*prompt == 'g' && strlen(prompt) >= 3) {
        /* get mode for g;X hint modes */
        pmode = prompt[2];
    }

    /* no mode found in prompt */
    if (!pmode) {
        return false;
    }

    res = *prompt == 'g'
        ? strchr(g_modes, pmode) != NULL
        : strchr(modes, pmode) != NULL;

    /* fill pointer only if the prompt was valid */
    if (res) {
        if (mode != NULL) {
            *mode = pmode;
        }
        if (is_gmode != NULL) {
            *is_gmode = *prompt == 'g';
        }
    }

    return res;
}

static JSObjectRef create_hints_object(WebKitWebFrame *frame, const char *script)
{
    if (!script) {
        return NULL;
    }

    JSStringRef str, file;
    JSValueRef result, exc = NULL;
    JSObjectRef object;

    JSContextRef ctx = webkit_web_frame_get_global_context(frame);
    str              = JSStringCreateWithUTF8CString(script);
    file             = JSStringCreateWithUTF8CString(HINT_FILE);
    result           = JSEvaluateScript(ctx, str, NULL, file, 0, &exc);
    JSStringRelease(str);
    JSStringRelease(file);
    if (exc) {
        return NULL;
    }

    object = JSValueToObject(ctx, result, &exc);
    if (exc) {
        return NULL;
    }
    JSValueProtect(ctx, result);

    return object;
}

static void call_hints_function(const char *func, int count, JSValueRef params[])
{
    JSValueRef js_ret, function;
    JSObjectRef function_object;
    JSStringRef js_func = NULL;
    char *value;

    if (!hints.obj) {
        return;
    }

    js_func = JSStringCreateWithUTF8CString(func);

    if (!JSObjectHasProperty(hints.ctx, hints.obj, js_func)) {
        JSStringRelease(js_func);
        return;
    }

    function        = JSObjectGetProperty(hints.ctx, hints.obj, js_func, NULL);
    function_object = JSValueToObject(hints.ctx, function, NULL);
    js_ret          = JSObjectCallAsFunction(hints.ctx, function_object, NULL, count, params, NULL);
    JSStringRelease(js_func);

    value = js_ref_to_string(hints.ctx, js_ret);

    if (!strncmp(value, "OVER:", 5)) {
        g_signal_emit_by_name(
            vb.gui.webview, "hovering-over-link", NULL, *(value + 5) == '\0' ? NULL : (value + 5)
        );
    } else if (!strncmp(value, "DONE:", 5)) {
        if (hints.gmode) {
            /* if g mode is used reset number filter and keep in hint mode */
            hints.num = 0;
            hints_update(hints.num);
        } else {
            mode_enter('n');
        }
    } else if (!strncmp(value, "INSERT:", 7)) {
        mode_enter('i');
        if (hints.mode == 'e') {
            input_open_editor();
        }
    } else if (!strncmp(value, "DATA:", 5)) {
        if (hints.gmode) {
            /* if g mode is used reset number filter and keep in hint mode */
            hints.num = 0;
            hints_update(hints.num);
        } else {
            /* switch first to normal mode - else we would clear the inputbox
             * on switching mode also if we want to show yanked data */
            mode_enter('n');
        }

        char *v   = (value + 5);
        Arg a     = {0};
        switch (hints.mode) {
            /* used if images should be opened */
            case 'i':
            case 'I':
                a.s = v;
                a.i = (hints.mode == 'I') ? VB_TARGET_NEW : VB_TARGET_CURRENT;
                vb_load_uri(&a);
                break;

            case 'O':
            case 'T':
                vb_echo(VB_MSG_NORMAL, false, "%s %s", (hints.mode == 'T') ? ":tabopen" : ":open", v);
                if (!hints.gmode) {
                    mode_enter('c');
                }
                break;

            case 's':
                a.s = v;
                a.i = COMMAND_SAVE_URI;
                command_save(&a);
                break;

            case 'y':
                a.i = COMMAND_YANK_ARG;
                a.s = v;
                command_yank(&a);
                break;

#ifdef FEATURE_QUEUE
            case 'p':
            case 'P':
                a.s = v;
                a.i = (hints.mode == 'P') ? COMMAND_QUEUE_UNSHIFT : COMMAND_QUEUE_PUSH;
                command_queue(&a);
                break;
#endif
        }
    }
    g_free(value);
}

/* FIXME duplicate to main.c */
static char *js_ref_to_string(JSContextRef ctx, JSValueRef ref)
{
    char *string;
    JSStringRef str_ref = JSValueToStringCopy(ctx, ref, NULL);
    size_t len          = JSStringGetMaximumUTF8CStringSize(str_ref);

    string = g_new0(char, len);
    JSStringGetUTF8CString(str_ref, string, len);
    JSStringRelease(str_ref);

    return string;
}

static JSValueRef js_string_to_ref(JSContextRef ctx, const char *string)
{
    JSStringRef js = JSStringCreateWithUTF8CString(string);
    JSValueRef ret = JSValueMakeString(ctx, js);
    JSStringRelease(js);
    return ret;
}