summaryrefslogtreecommitdiff
path: root/src/main.c
blob: a91cde3f711f92e102ced55a59212e98c0c776a1 (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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
/**
 * vimb - a webkit based vim like browser.
 *
 * Copyright (C) 2012-2016 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 <gdk/gdkx.h>
#include <gtk/gtk.h>
#include <gtk/gtkx.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <webkit2/webkit2.h>

#include "ascii.h"
#include "completion.h"
#include "config.h"
#include "ex.h"
#include "ext-proxy.h"
#include "input.h"
#include "js.h"
#include "main.h"
#include "map.h"
#include "normal.h"
#include "scripts/scripts.h"
#include "setting.h"
#include "shortcut.h"
#include "util.h"

static void client_destroy(Client *c);
static Client *client_new(WebKitWebView *webview);
static gboolean input_clear(Client *c);
static void input_print(Client *c, gboolean force, MessageType type,
        gboolean hide, const char *message);
static void marks_clear(Client *c);
static void mode_free(Mode *mode);
static void on_webctx_init_web_extension(WebKitWebContext *webctx, gpointer data);
static void on_webview_close(WebKitWebView *webview, Client *c);
static WebKitWebView *on_webview_create(WebKitWebView *webview,
        WebKitNavigationAction *navact, Client *c);
static gboolean on_webview_decide_policy(WebKitWebView *webview,
        WebKitPolicyDecision *dec, WebKitPolicyDecisionType type, Client *c);
static void on_webview_load_changed(WebKitWebView *webview,
        WebKitLoadEvent event, Client *c);
static void on_webview_mouse_target_changed(WebKitWebView *webview,
        WebKitHitTestResult *result, guint modifiers, Client *c);
static void on_webview_notify_estimated_load_progress(WebKitWebView *webview,
        GParamSpec *spec, Client *c);
static void on_webview_notify_title(WebKitWebView *webview, GParamSpec *pspec,
        Client *c);
static void on_webview_notify_uri(WebKitWebView *webview, GParamSpec *pspec,
        Client *c);
static void on_webview_ready_to_show(WebKitWebView *webview, Client *c);
static gboolean on_webview_web_process_crashed(WebKitWebView *webview, Client *c);
static void on_window_destroy(GtkWidget *window, Client *c);
static gboolean quit(Client *c);
static void register_cleanup(Client *c);
static void update_urlbar(Client *c);
static void set_statusbar_style(Client *c, StatusType type);
static void set_title(Client *c, const char *title);
static void spawn_new_instance(const char *uri, gboolean embed);
#ifdef FREE_ON_QUIT
static void vimb_cleanup(void);
#endif
static void vimb_setup(void);
static WebKitWebView *webview_new(Client *c, WebKitWebView *webview);

struct Vimb vb;


/**
 * Write text to the inpubox if this isn't focused.
 */
void vb_echo(Client *c, MessageType type, gboolean hide, const char *error, ...)
{
    char *buffer;
    va_list args;

    va_start(args, error);
    buffer = g_strdup_vprintf(error, args);
    va_end(args);

    input_print(c, FALSE, type, hide, buffer);
    g_free(buffer);
}

/**
 * Write text to the inpubox independent if this is focused or not.
 * Note that this could disturb the user during typing into inputbox.
 */
void vb_echo_force(Client *c, MessageType type, gboolean hide, const char *error, ...)
{
    char *buffer;
    va_list args;

    va_start(args, error);
    buffer = g_strdup_vprintf(error, args);
    va_end(args);

    input_print(c, TRUE, type, hide, buffer);
    g_free(buffer);
}

/**
 * Enter into the new given mode and leave possible active current mode.
 */
void vb_enter(Client *c, char id)
{
    Mode *new = g_hash_table_lookup(vb.modes, GINT_TO_POINTER(id));

    g_return_if_fail(new != NULL);

    if (c->mode) {
        /* don't do anything if the mode isn't a new one */
        if (c->mode == new) {
            return;
        }

        /* if there is a active mode, leave this first */
        if (c->mode->leave) {
            c->mode->leave(c);
        }
    }

    /* reset the flags of the new entered mode */
    new->flags = 0;

    /* set the new mode so that it is available also in enter function */
    c->mode = new;
    /* call enter only if the new mode isn't the current mode */
    if (new->enter) {
        new->enter(c);
    }

#ifndef TESTLIB
    vb_statusbar_update(c);
#endif
}

/**
 * Set the prompt chars and switch to new mode.
 *
 * @id:           Mode id.
 * @prompt:       Prompt string to set as current prompt.
 * @print_prompt: Indicates if the new set prompt should be put into inputbox
 *                after switching the mode.
 */
void vb_enter_prompt(Client *c, char id, const char *prompt, gboolean print_prompt)
{
    /* set the prompt to be accessible in vb_enter */
    strncpy(c->state.prompt, prompt, PROMPT_SIZE - 1);
    c->state.prompt[PROMPT_SIZE - 1] = '\0';

    vb_enter(c, id);

    if (print_prompt) {
        /* set it after the mode was entered so that the modes input change
         * event listener could grep the new prompt */
        vb_echo_force(c, MSG_NORMAL, FALSE, c->state.prompt);
    }
}

/**
 * Retrieves the content of the command line.
 * Returned string must be freed with g_free.
 */
char *vb_input_get_text(Client *c)
{
    GtkTextIter start, end;

    gtk_text_buffer_get_bounds(c->buffer, &start, &end);
    return gtk_text_buffer_get_text(c->buffer, &start, &end, FALSE);
}

/**
 * Writes given text into the command line.
 */
void vb_input_set_text(Client *c, const char *text)
{
    gtk_text_buffer_set_text(c->buffer, text, -1);
    if (c->config.input_autohide) {
        gtk_widget_set_visible(GTK_WIDGET(c->input), *text != '\0');
    }
}

/**
 * Set the style of the inputbox according to current input type (normal or
 * error).
 */
void vb_input_update_style(Client *c)
{
    MessageType type = c->state.input_type;

    if (type == MSG_ERROR) {
        gtk_style_context_add_class(gtk_widget_get_style_context(c->input), "error");
    } else {
        gtk_style_context_remove_class(gtk_widget_get_style_context(c->input), "error");
    }
}

/**
 * Load the a uri given in Arg. This function handles also shortcuts and local
 * file paths.
 *
 * If arg.i = TARGET_CURRENT, the url is opened into the current webview.
 * TARGET_RELATED causes the generation of a new window within the current
 * instance of vimb with a own, but related webview. And TARGET_NEW spawns a
 * new instance of vimb with the given uri.
 */
gboolean vb_load_uri(Client *c, const Arg *arg)
{
    char *uri = NULL, *rp, *path = NULL;
    struct stat st;

    if (arg->s) {
        path = g_strstrip(arg->s);
    }
    if (!path || !*path) {
        path = GET_CHAR(c, "home-page");
    }

    /* If path contains :// but no space we open it direct. This is required
     * to use :// also with shortcuts */
    if ((strstr(path, "://") && !strchr(path, ' ')) || !strncmp(path, "about:", 6)) {
        uri = g_strdup(path);
    } else if (stat(path, &st) == 0) {
        /* check if the path is a file path */
        rp  = realpath(path, NULL);
        uri = g_strconcat("file://", rp, NULL);
        free(rp);
    } else if (strchr(path, ' ') || !strchr(path, '.')) {
        /* use a shortcut if path contains spaces or no dot */
        uri = shortcut_get_uri(c, path);
    }

    if (!uri) {
        uri = g_strconcat("http://", path, NULL);
    }

    if (arg->i == TARGET_CURRENT) {
        /* Load the uri into the browser instance. */
        webkit_web_view_load_uri(c->webview, uri);
        set_title(c, uri);
    } else if (arg->i == TARGET_NEW) {
        spawn_new_instance(uri, TRUE);
    } else { /* TARGET_RELATET */
        Client *newclient = client_new(c->webview);
        /* Load the uri into the new client. */
        webkit_web_view_load_uri(newclient->webview, uri);
        set_title(c, uri);
    }
    g_free(uri);

    return TRUE;
}

/**
 * Creates and add a new mode with given callback functions.
 */
void vb_mode_add(char id, ModeTransitionFunc enter, ModeTransitionFunc leave,
    ModeKeyFunc keypress, ModeInputChangedFunc input_changed)
{
    Mode *new = g_slice_new(Mode);
    new->id            = id;
    new->enter         = enter;
    new->leave         = leave;
    new->keypress      = keypress;
    new->input_changed = input_changed;
    new->flags         = 0;

    /* Initialize the hashmap if this was not done before */
    if (!vb.modes) {
        vb.modes = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, (GDestroyNotify)mode_free);
    }
    g_hash_table_insert(vb.modes, GINT_TO_POINTER(id), new);
}

VbResult vb_mode_handle_key(Client *c, int key)
{
    VbResult res;

    if (c->state.ctrlv) {
        c->state.processed_key = FALSE;
        c->state.ctrlv         = FALSE;

        return RESULT_COMPLETE;
    }
    if (c->mode->id != 'p' && key == CTRL('V')) {
        c->mode->flags |= FLAG_NOMAP;
        c->state.ctrlv  = TRUE;

        return RESULT_MORE;
    }

    if (c->mode && c->mode->keypress) {
#ifdef DEBUGDISABLED
        int flags = c->mode->flags;
        int id    = c->mode->id;
        res = c->mode->keypress(c, key);
        if (c->mode) {
            PRINT_DEBUG(
                "%c[%d]: %#.2x '%c' -> %c[%d]",
                id - ' ', flags, key, (key >= 0x20 && key <= 0x7e) ? key : ' ',
                c->mode->id - ' ', c->mode->flags
            );
        }
#else
        res = c->mode->keypress(c, key);
#endif
        return res;
    }
    return RESULT_ERROR;
}

/**
 * Change the label for the current mode in inputbox or on the left of
 * statusbar if inputbox is in autohide mode.
 */
void vb_modelabel_update(Client *c, const char *label)
{
    if (c->config.input_autohide) {
        /* if the inputbox is potentially not shown write mode into statusbar */
        gtk_label_set_text(GTK_LABEL(c->statusbar.mode), label);
    } else {
        vb_echo(c, MSG_NORMAL, FALSE, "%s", label);
    }
    gtk_label_set_text(GTK_LABEL(c->statusbar.mode), label);
}

/**
 * Close the given client instances window.
 */
void vb_quit(Client *c, gboolean force)
{
#if 0 /* TODO don't quit on running downloads */
    /* if not forced quit - don't quit if there are still running downloads */
    if (!force && c->state.downloads) {
        vb_echo_force(c, VB_MSG_ERROR, TRUE, "Can't quit: there are running downloads");
        return;
    }
#endif
    /* Don't run the quit synchronously, because this could lead to access of
     * no more existing widget where some command response is written. */
    g_idle_add((GSourceFunc)quit, c);
}

/**
 * Adds content to a named register.
 */
void vb_register_add(Client *c, char buf, const char *value)
{
    char *mark;
    int idx;

    if (!c->state.enable_register || !buf) {
        return;
    }

    /* make sure the mark is a valid mark char */
    if ((mark = strchr(REG_CHARS, buf))) {
        /* get the index of the mark char */
        idx = mark - REG_CHARS;

        OVERWRITE_STRING(c->state.reg[idx], value);
    }
}

/**
 * Lookup register entry by it's name.
 */
const char *vb_register_get(Client *c, char buf)
{
    char *mark;
    int idx;

    /* make sure the mark is a valid mark char */
    if ((mark = strchr(REG_CHARS, buf))) {
        /* get the index of the mark char */
        idx = mark - REG_CHARS;

        return c->state.reg[idx];
    }

    return NULL;
}

void vb_statusbar_update(Client *c)
{
    int num;
    GString *status;

    if (!gtk_widget_get_visible(GTK_WIDGET(c->statusbar.box))) {
        return;
    }

    status = g_string_new("");
    /* show the active downloads */
    if (c->state.downloads) {
        num = g_list_length(c->state.downloads);
        g_string_append_printf(status, " %d %s", num, num == 1 ? "download" : "downloads");
    }

    /* show the number of matches search results */
    if (c->state.search.matches) {
        g_string_append_printf(status, " (%d)", c->state.search.matches);
    }

    /* show load status of page or the downloads */
    if (c->state.progress != 100) {
#ifdef FEATURE_WGET_PROGRESS_BAR
        char bar[PROGRESS_BAR_LEN + 1];
        int i, state;

        state = c->state.progress * PROGRESS_BAR_LEN / 100;
        for (i = 0; i < state; i++) {
            bar[i] = PROGRESS_BAR[0];
        }
        bar[i++] = PROGRESS_BAR[1];
        for (; i < PROGRESS_BAR_LEN; i++) {
            bar[i] = PROGRESS_BAR[2];
        }
        bar[i] = '\0';
        g_string_append_printf(status, " [%s]", bar);
#else
        g_string_append_printf(status, " [%i%%]", c->state.progress);
#endif
    }

    /* show the scroll status */
    if (c->state.scroll_max == 0) {
        g_string_append(status, " All");
    } else if (c->state.scroll_percent == 0) {
        g_string_append(status, " Top");
    } else if (c->state.scroll_percent == 100) {
        g_string_append(status, " Bot");
    } else {
        g_string_append_printf(status, " %d%%", c->state.scroll_percent);
    }

    gtk_label_set_text(GTK_LABEL(c->statusbar.right), status->str);
    g_string_free(status, TRUE);
}

/**
 * Destroys given client and removed it from client queue. If no client is
 * there in queue, quit the gtk main loop.
 */
static void client_destroy(Client *c)
{
    Client *p;
    webkit_web_view_stop_loading(c->webview);
    gtk_widget_destroy(c->window);

    /* Look for the client in the list, if we searched through the list and
     * didn't find it the client must be the first item. */
    for (p = vb.clients; p && p->next != c; p = p->next);
    if (p) {
        p->next = c->next;
    } else {
        vb.clients = c->next;
    }

    completion_cleanup(c);
    map_cleanup(c);
    register_cleanup(c);

    g_slice_free(Client, c);

    /* if there are no clients - quit the main loop */
    if (!vb.clients) {
        gtk_main_quit();
    }
}

/**
 * Creates a new client instance with it's own window.
 *
 * @webview:    Related webview or NULL if a client with an independent
 *              webview shoudl be created.
 */
static Client *client_new(WebKitWebView *webview)
{
    Client *c;
    char *xid;
    GtkWidget *box;

    /* create the client */
    c = g_slice_new0(Client);
    c->state.progress = 100;

    if (vb.embed) {
        c->window = gtk_plug_new(vb.embed);
        xid       = g_strdup_printf("%d", (int)vb.embed);
    } else {
        c->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
        gtk_window_set_role(GTK_WINDOW(c->window), PROJECT_UCFIRST);
        gtk_widget_realize(GTK_WIDGET(c->window));

        xid = g_strdup_printf("%d",
                (int)GDK_WINDOW_XID(gtk_widget_get_window(GTK_WIDGET(c->window))));
    }

    completion_init(c);
    map_init(c);

    g_object_connect(
            G_OBJECT(c->window),
            "signal::destroy", G_CALLBACK(on_window_destroy), c,
            "signal::key-press-event", G_CALLBACK(on_map_keypress), c,
            NULL);

    /* statusbar */
    c->statusbar.box   = GTK_BOX(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0));
    c->statusbar.mode  = gtk_label_new(NULL);
    c->statusbar.left  = gtk_label_new(NULL);
    c->statusbar.right = gtk_label_new(NULL);
    c->statusbar.cmd   = gtk_label_new(NULL);
    gtk_widget_set_name(GTK_WIDGET(c->statusbar.box), "statusbar");
    gtk_label_set_ellipsize(GTK_LABEL(c->statusbar.left), PANGO_ELLIPSIZE_MIDDLE);
    gtk_widget_set_halign(c->statusbar.left, GTK_ALIGN_START);
    gtk_widget_set_halign(c->statusbar.mode, GTK_ALIGN_START);

    gtk_box_pack_start(c->statusbar.box, c->statusbar.mode, FALSE, TRUE, 0);
    gtk_box_pack_start(c->statusbar.box, c->statusbar.left, TRUE, TRUE, 2);
    gtk_box_pack_start(c->statusbar.box, c->statusbar.cmd, FALSE, FALSE, 0);
    gtk_box_pack_start(c->statusbar.box, c->statusbar.right, FALSE, FALSE, 2);

    /* webview */
    c->webview = webview_new(c, webview);
    c->page_id = webkit_web_view_get_page_id(c->webview);

    /* inputbox */
    c->input  = gtk_text_view_new();
    gtk_widget_set_name(c->input, "input");
    c->buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(c->input));
    /* Make sure the user can see the typed text. */
    gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(c->input), GTK_WRAP_WORD_CHAR);

    /* pack the parts together */
    box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
    gtk_container_add(GTK_CONTAINER(c->window), box);
    gtk_box_pack_start(GTK_BOX(box), GTK_WIDGET(c->webview), TRUE, TRUE, 0);
    gtk_box_pack_start(GTK_BOX(box), GTK_WIDGET(c->statusbar.box), FALSE, FALSE, 0);
    gtk_box_pack_end(GTK_BOX(box), GTK_WIDGET(c->input), FALSE, FALSE, 0);

    /* Set the default style for statusbar and inputbox. */
    GtkCssProvider* provider = gtk_css_provider_get_default();
    gtk_css_provider_load_from_data(provider, GUI_STYLE, -1, NULL);
    gtk_style_context_add_provider(gtk_widget_get_style_context(GTK_WIDGET(c->statusbar.box)),
            GTK_STYLE_PROVIDER(provider),
            GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
    gtk_style_context_add_provider(gtk_widget_get_style_context(c->input),
            GTK_STYLE_PROVIDER(provider),
            GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

    /* set the x window id to env */
    g_setenv("VIMB_XID", xid, TRUE);
    g_free(xid);

    /* initialize the settings */
    setting_init(c);

    /* start client in normal mode */
    vb_enter(c, 'n');

    gtk_widget_show_all(c->window);

    /* Prepend the new client to the queue of clients. */
    c->next    = vb.clients;
    vb.clients = c;

    return c;
}

/**
 * Callback that clear the input box after a timeout if this was set on
 * input_print.
 */
static gboolean input_clear(Client *c)
{
    input_print(c, FALSE, MSG_NORMAL, FALSE, "");

    return FALSE;
}

/**
 * Print a message to the input box.
 *
 * @force: If TRUE the message is also written when the inputbox is already
 *         focused, might be the case when the user types text into it.
 * @type: Type of message normal or error
 * @hide: If TRUE the inputbox is cleared after a short timeout.
 * @message: The message to print.
 */
static void input_print(Client *c, gboolean force, MessageType type,
        gboolean hide, const char *message)
{
    /* don't print message if the input is focussed */
    if (!force && gtk_widget_is_focus(GTK_WIDGET(c->input))) {
        return;
    }

    /* apply input style only if the message type was changed */
    if (type != c->state.input_type) {
        c->state.input_type = type;
    }
    vb_input_set_text(c, message);
    if (hide) {
        /* add timeout function */
        c->state.input_timer = g_timeout_add_seconds(MESSAGE_TIMEOUT, (GSourceFunc)input_clear, c);
    } else if (c->state.input_timer > 0) {
        /* If there is already a timeout function but the input box content is
         * changed - remove the timeout. Seems the user started another
         * command or typed into inputbox. */
        g_source_remove(c->state.input_timer);
        c->state.input_timer = 0;
    }
}

/**
 * Reinitializes or clears the set page marks.
 */
static void marks_clear(Client *c)
{
    int i;

    /* init empty marks array */
    for (i = 0; i < MARK_SIZE; i++) {
        c->state.marks[i] = -1;
    }
}

/**
 * Free the memory of given mode. This is used as destroy function of the
 * modes hashmap.
 */
static void mode_free(Mode *mode)
{
    g_slice_free(Mode, mode);
}

/**
 * Set the style of the statusbar.
 */
static void set_statusbar_style(Client *c, StatusType type)
{
    GtkStyleContext *ctx;
    /* Do nothing if the new to set style is the same as the current. */
    if (type == c->state.status_type) {
        return;
    }

    ctx = gtk_widget_get_style_context(GTK_WIDGET(c->statusbar.box));

    if (type == STATUS_SSL_VALID) {
        gtk_style_context_remove_class(ctx, "unsecure");
        gtk_style_context_add_class(ctx, "secure");
    } else if (type == STATUS_SSL_INVALID) {
        gtk_style_context_remove_class(ctx, "secure");
        gtk_style_context_add_class(ctx, "unsecure");
    } else {
        gtk_style_context_remove_class(ctx, "secure");
        gtk_style_context_remove_class(ctx, "unsecure");
    }
    c->state.status_type = type;
}

/**
 * Update the window title of the main window.
 */
static void set_title(Client *c, const char *title)
{
    gtk_window_set_title(GTK_WINDOW(c->window), title);
}

/**
 * Spawns a new browser instance for given uri.
 *
 * @uri:    URI used for the new instance.
 * @embed:  If FALSE, the new instance is not embedded, independent from
 *          current set -e option.
 */
static void spawn_new_instance(const char *uri, gboolean embed)
{
    guint i = 0;
    char xid[64];
    char *cmd[5];

    cmd[i++] = vb.argv0;

    if (vb.embed && embed) {
        cmd[i++] = "-e";
        snprintf(xid, LENGTH(xid), "%d", (int)vb.embed);
        cmd[i++] = xid;
    }
    cmd[i++] = (char*)uri;
    cmd[i++] = NULL;

    /* spawn a new browser instance */
    g_spawn_async(NULL, cmd, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL);
}

/**
 * Callback for the web contexts initialize-web-extensions signal.
 */
static void on_webctx_init_web_extension(WebKitWebContext *webctx, gpointer data)
{
    char *name;
    static guint ext_count = 0;
    GVariant *vdata;

    /* Setup the extension directory. */
    webkit_web_context_set_web_extensions_directory(webctx, EXTPREFIX);

    name = g_strdup_printf("%u-%u", getpid(), ++ext_count);
    ext_proxy_init(name);

    vdata = g_variant_new("(s)", name);
    webkit_web_context_set_web_extensions_initialization_user_data(webctx, vdata);

    g_free(name);
}

/**
 * Callback for the webview close signal.
 */
static void on_webview_close(WebKitWebView *webview, Client *c)
{
    client_destroy(c);
}

/**
 * Callback for the webview create signal.
 * This creates a new client - with it's own window with a related webview.
 */
static WebKitWebView *on_webview_create(WebKitWebView *webview,
        WebKitNavigationAction *navact, Client *c)
{
    Client *new = client_new(webview);

    return new->webview;
}

/**
 * Callback for the webview decide-policy signal.
 * Checks the reasons for some navigation actions and decides if the action is
 * allowed, or should go into a new instance of vimb.
 */
static gboolean on_webview_decide_policy(WebKitWebView *webview,
        WebKitPolicyDecision *dec, WebKitPolicyDecisionType type, Client *c)
{
    guint status;
    WebKitNavigationAction *a;
    WebKitURIRequest *req;
    WebKitURIResponse *res;

    switch (type) {
        case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
            a   = webkit_navigation_policy_decision_get_navigation_action(WEBKIT_NAVIGATION_POLICY_DECISION(dec));
            req = webkit_navigation_action_get_request(a);

            if (webkit_navigation_action_get_navigation_type(a) == WEBKIT_NAVIGATION_TYPE_LINK_CLICKED) {
                if (webkit_navigation_action_get_mouse_button(a) == 2
                        || (webkit_navigation_action_get_mouse_button(a) == 1
                        && webkit_navigation_action_get_modifiers(a) & GDK_CONTROL_MASK)) {
                    webkit_policy_decision_ignore(dec);
                    spawn_new_instance(webkit_uri_request_get_uri(req), TRUE);
                    return TRUE;
                }
            }
            return FALSE;

        case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
            a   = webkit_navigation_policy_decision_get_navigation_action(WEBKIT_NAVIGATION_POLICY_DECISION(dec));
            req = webkit_navigation_action_get_request(a);

            /* Ignore opening new window if this was started without user gesture. */
            if (!webkit_navigation_action_is_user_gesture(a)) {
                webkit_policy_decision_ignore(dec);
                return TRUE;
            }

            if (webkit_navigation_action_get_navigation_type(a) == WEBKIT_NAVIGATION_TYPE_LINK_CLICKED) {
                webkit_policy_decision_ignore(dec);
                /* This is triggered on link click for links with *
                 * target="_blank". Maybe it should be configurable if the
                 * page is opened as tabe or a new instance. */
                spawn_new_instance(webkit_uri_request_get_uri(req), TRUE);
                return TRUE;
            }
            return FALSE;

        case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
            req    = webkit_response_policy_decision_get_request(WEBKIT_RESPONSE_POLICY_DECISION(dec));
            res    = webkit_response_policy_decision_get_response(WEBKIT_RESPONSE_POLICY_DECISION(dec));
            status = webkit_uri_response_get_status_code(res);

            if (!webkit_response_policy_decision_is_mime_type_supported(WEBKIT_RESPONSE_POLICY_DECISION(dec))
                    && (SOUP_STATUS_IS_SUCCESSFUL(status) || status == SOUP_STATUS_NONE)) {

                webkit_policy_decision_download(dec);

                return TRUE;
            }
            return FALSE;

        default:
            return FALSE;
    }
}

static void on_webview_load_changed(WebKitWebView *webview,
        WebKitLoadEvent event, Client *c)
{
    GTlsCertificateFlags tlsflags;
    const char *uri;

    switch (event) {
        case WEBKIT_LOAD_STARTED:
            /* update load progress in statusbar */
            c->state.progress = 0;
            vb_statusbar_update(c);
            set_title(c, webkit_web_view_get_uri(webview));
            break;

        case WEBKIT_LOAD_REDIRECTED:
            break;

        case WEBKIT_LOAD_COMMITTED:
            uri = webkit_web_view_get_uri(webview);
            /* save the current URI in register % */
            vb_register_add(c, '%', uri);
            /* check if tls is on and the page is trusted */
            if (g_str_has_prefix(uri, "https://")) {
                if (webkit_web_view_get_tls_info(webview, NULL, &tlsflags) && tlsflags) {
                    set_statusbar_style(c, STATUS_SSL_INVALID);
                } else {
                    set_statusbar_style(c, STATUS_SSL_VALID);
                }
            } else {
                set_statusbar_style(c, STATUS_NORMAL);
            }

            /* clear possible set marks */
            marks_clear(c);

            break;

        case WEBKIT_LOAD_FINISHED:
            c->state.progress = 100;
            break;
    }
}

/**
 * Callback for the webview mouse-target-changed signal.
 * This is used to print the uri too statusbar if the user hovers over links
 * or images.
 */
static void on_webview_mouse_target_changed(WebKitWebView *webview,
        WebKitHitTestResult *result, guint modifiers, Client *c)
{
    char *msg;
    const char *uri;

    /* Save the hitTestResult to have this later available for events that
     * don't support this. */
    if (c->state.hit_test_result) {
        g_object_unref(c->state.hit_test_result);
    }
    c->state.hit_test_result = g_object_ref(result);

    if (webkit_hit_test_result_context_is_link(result)) {
        uri = webkit_hit_test_result_get_link_uri(result);
        msg = g_strconcat("Link: ", uri, NULL);
        gtk_label_set_text(GTK_LABEL(c->statusbar.left), msg);
        g_free(msg);
    } else if (webkit_hit_test_result_context_is_image(result)) {
        uri = webkit_hit_test_result_get_image_uri(result);
        msg = g_strconcat("Image: ", uri, NULL);
        gtk_label_set_text(GTK_LABEL(c->statusbar.left), msg);
        g_free(msg);
    } else {
        /* No link under cursor - show the current URI. */
        update_urlbar(c);
    }
}

/**
 * Called on webviews notify::estimated-load-progress event. This writes the
 * esitamted load progress in percent in a variable and updates the statusbar
 * to make the changes visible.
 */
static void on_webview_notify_estimated_load_progress(WebKitWebView *webview,
        GParamSpec *spec, Client *c)
{
    c->state.progress = webkit_web_view_get_estimated_load_progress(webview) * 100;
    vb_statusbar_update(c);
}

/**
 * Callback for the webview notify::title signal.
 * Changes the window title according to the title of the current page.
 */
static void on_webview_notify_title(WebKitWebView *webview, GParamSpec *pspec, Client *c)
{
    set_title(c, webkit_web_view_get_title(webview));
}

/**
 * Callback for the webview notify::uri signal.
 * Changes the current uri shown on left of statusbar.
 */
static void on_webview_notify_uri(WebKitWebView *webview, GParamSpec *pspec, Client *c)
{
    OVERWRITE_STRING(c->state.uri, webkit_web_view_get_uri(c->webview));
    update_urlbar(c);
    g_setenv("VIMB_URI", c->state.uri, TRUE);
}

/**
 * Callback for the webview ready-to-show signal.
 * Show the webview only if it's ready to be shown.
 */
static void on_webview_ready_to_show(WebKitWebView *webview, Client *c)
{
    gtk_widget_show(GTK_WIDGET(webview));
}

/**
 * Callback for the webview web-process-crashed signal.
 */
static gboolean on_webview_web_process_crashed(WebKitWebView *webview, Client *c)
{
    g_warning("Webview Crashed on %s", webkit_web_view_get_uri(webview));
    return TRUE;
}

/**
 * Callback for the window destroy signal.
 * Destroys the client that is associated to the window.
 */
static void on_window_destroy(GtkWidget *window, Client *c)
{
    client_destroy(c);
}

/**
 * Callback for to quit given client as idle event source.
 */
static gboolean quit(Client *c)
{
    /* Destroy the main window to tirgger the destruction of the client. */
    gtk_widget_destroy(c->window);

    /* Remove this from the list of event sources. */
    return FALSE;
}

/**
 * Free the register contents memory.
 */
static void register_cleanup(Client *c)
{
    int i;
    for (i = 0; i < REG_SIZE; i++) {
        if (c->state.reg[i]) {
            g_free(c->state.reg[i]);
        }
    }
}

/**
 * Update the contents of the url bar on the left of the statu bar according
 * to current opened url and position in back forward history.
 */
static void update_urlbar(Client *c)
{
#if !defined(FEATURE_HISTORY_INDICATOR)
    /* if only the uri is shown - write it like it is on the label */
    gtk_label_set_text(GTK_LABEL(c->statusbar.left), c->state.uri);
#else
    GString *str = g_string_new(c->state.uri);

#ifdef FEATURE_HISTORY_INDICATOR
    gboolean back, fwd;

    back = webkit_web_view_can_go_back(c->webview);
    fwd  = webkit_web_view_can_go_forward(c->webview);

    /* show history indicator only if there is something to show */
    if (back || fwd) {
        g_string_append_printf(str, " [%s]", back ? (fwd ? "-+" : "-") : "+");
    }
#endif /* FEATURE_HISTORY_INDICATOR */

    gtk_label_set_text(GTK_LABEL(c->statusbar.left), str->str);
    g_string_free(str, TRUE);
#endif /* !defined(FEATURE_HISTORY_INDICATOR) */
}

#ifdef FREE_ON_QUIT
/**
 * Free memory of the whole application.
 */
static void vimb_cleanup(void)
{
    int i;

    while (vb.clients) {
        client_destroy(vb.clients);
    }

    /* free memory of other components */
    util_cleanup();

    for (i = 0; i < FILES_LAST; i++) {
        if (vb.files[i]) {
            g_free(vb.files[i]);
        }
    }
}
#endif

/**
 * Setup resources used on application scope.
 */
static void vimb_setup(void)
{
    WebKitWebContext *ctx;
    WebKitCookieManager *cm;
    char *path;

    /* prepare the file pathes */
    path = util_get_config_dir();

    if (vb.configfile) {
        char *rp = realpath(vb.configfile, NULL);
        vb.files[FILES_CONFIG] = g_strdup(rp);
        free(rp);
    } else {
        vb.files[FILES_CONFIG] = util_get_filepath(path, "config", FALSE);
    }

    /* Setup those files that are use multiple time during runtime */
    vb.files[FILES_CLOSED]     = util_get_filepath(path, "closed", FALSE);
    vb.files[FILES_COOKIE]     = util_get_filepath(path, "cookies", FALSE);
    vb.files[FILES_USER_STYLE] = util_get_filepath(path, "style.css", FALSE);
    vb.files[FILES_SCRIPT]     = util_get_filepath(path, "scripts.js", FALSE);
    vb.files[FILES_HISTORY]    = util_get_filepath(path, "history", FALSE);
    vb.files[FILES_COMMAND]    = util_get_filepath(path, "command", FALSE);
    vb.files[FILES_HSTS]       = util_get_filepath(path, "hsts", FALSE);
    vb.files[FILES_BOOKMARK]   = util_get_filepath(path, "bookmark", FALSE);
    vb.files[FILES_QUEUE]      = util_get_filepath(path, "queue", FALSE);
    vb.files[FILES_SEARCH]     = util_get_filepath(path, "search", FALSE);
    g_free(path);

    /* Use seperate rendering processed for the webview of the clients in the
     * current instance. This must be called as soon as possible according to
     * the documentation. */
    ctx = webkit_web_context_get_default();
    webkit_web_context_set_process_model(ctx, WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
    webkit_web_context_set_cache_model(ctx, WEBKIT_CACHE_MODEL_WEB_BROWSER);

    g_signal_connect(ctx, "initialize-web-extensions", G_CALLBACK(on_webctx_init_web_extension), NULL);

    /* Add cookie support only if the cookie file exists. */
    if (vb.files[FILES_COOKIE]) {
        cm = webkit_web_context_get_cookie_manager(ctx);
        webkit_cookie_manager_set_persistent_storage(
                cm,
                vb.files[FILES_COOKIE],
                WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
    }

    /* TODO move to settings.c */
    webkit_web_context_set_tls_errors_policy(ctx, TRUE ? WEBKIT_TLS_ERRORS_POLICY_FAIL : WEBKIT_TLS_ERRORS_POLICY_IGNORE);

    /* initialize the modes */
    vb_mode_add('n', normal_enter, normal_leave, normal_keypress, NULL);
    vb_mode_add('c', ex_enter, ex_leave, ex_keypress, ex_input_changed);
    vb_mode_add('i', input_enter, input_leave, input_keypress, NULL);
    vb_mode_add('p', pass_enter, pass_leave, pass_keypress, NULL);
}

/**
 * Factory to create a new webview.
 *
 * @webview:    Relates webview or NULL. If given a related webview is
 *              generated.
 */
static WebKitWebView *webview_new(Client *c, WebKitWebView *webview)
{
    WebKitWebView *new;
    WebKitUserContentManager *ucm;
    WebKitUserScript *script;
    char *js = NULL;

    /* create a new webview */
    if (webview) {
        new = WEBKIT_WEB_VIEW(webkit_web_view_new_with_related_view(webview));
        ucm = webkit_web_view_get_user_content_manager(webview);
    } else {
        ucm = webkit_user_content_manager_new();
        new = WEBKIT_WEB_VIEW(webkit_web_view_new_with_user_content_manager(ucm));
    }

    g_object_connect(
        G_OBJECT(new),
        "signal::close", G_CALLBACK(on_webview_close), c,
        "signal::create", G_CALLBACK(on_webview_create), c,
        "signal::decide-policy", G_CALLBACK(on_webview_decide_policy), c,
        "signal::load-changed", G_CALLBACK(on_webview_load_changed), c,
        "signal::mouse-target-changed", G_CALLBACK(on_webview_mouse_target_changed), c,
        "signal::notify::estimated-load-progress", G_CALLBACK(on_webview_notify_estimated_load_progress), c,
        "signal::notify::title", G_CALLBACK(on_webview_notify_title), c,
        "signal::notify::uri", G_CALLBACK(on_webview_notify_uri), c,
        "signal::ready-to-show", G_CALLBACK(on_webview_ready_to_show), c,
        "signal::web-process-crashed", G_CALLBACK(on_webview_web_process_crashed), c,
        NULL
    );

    /* Inject the user script file. */
    if (g_file_get_contents(vb.files[FILES_SCRIPT], &js, NULL, NULL)) {
        script = webkit_user_script_new(js,
                WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
                WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_END, NULL, NULL);
        webkit_user_content_manager_add_script(ucm, script);
        webkit_user_script_unref(script);
    }

    return new;
}

int main(int argc, char* argv[])
{
    Client *c;
    GError *err = NULL;
    char *pidstr, *winid = NULL;
    gboolean ver = FALSE;

    GOptionEntry opts[] = {
        {"embed", 'e', 0, G_OPTION_ARG_STRING, &winid,  "Reparents to window specified by xid", NULL},
        {"config", 'c', 0, G_OPTION_ARG_FILENAME, &vb.configfile, "Custom configuration file", NULL},
        {"version", 'v', 0, G_OPTION_ARG_NONE, &ver, "Print version", NULL},
        {NULL}
    };

    /* initialize GTK+ */
    if (!gtk_init_with_args(&argc, &argv, "[URI]", opts, NULL, &err)) {
        fprintf(stderr, "can't init gtk: %s\n", err->message);
        g_error_free(err);

        return EXIT_FAILURE;
    }

    if (ver) {
        fprintf(stdout, "%s, version %s\n\n", PROJECT, VERSION);
        fprintf(stdout, "Copyright © 2012 - 2016 Daniel Carl <danielcarl@gmx.de>\n");
        fprintf(stdout, "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n");
        fprintf(stdout, "This is free software; you are free to change and redistribute it.\n");
        fprintf(stdout, "There is NO WARRANTY, to the extent permitted by law.\n");

        return EXIT_SUCCESS;
    }

    /* Save the base name for spawning new instances. */
    vb.argv0 = argv[0];

    /* set the current pid in env */
    pidstr = g_strdup_printf("%d", (int)getpid());
    g_setenv("VIMB_PID", pidstr, TRUE);

    vimb_setup();

    if (winid) {
        vb.embed = strtol(winid, NULL, 0);
    }

    c = client_new(NULL);
    if (argc <= 1) {
        vb_load_uri(c, &(Arg){TARGET_CURRENT, NULL});
    } else {
        vb_load_uri(c, &(Arg){TARGET_CURRENT, argv[argc - 1]});
    }

    gtk_main();
#ifdef FREE_ON_QUIT
    vimb_cleanup();
#endif

    return EXIT_SUCCESS;
}