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
|
// MIT License, Copyright (c) 2020 Marvin Borner
#include <conv.h>
#include <def.h>
#include <gfx.h>
#include <gui.h>
#include <input.h>
#include <mem.h>
#include <net.h>
#include <print.h>
#include <str.h>
#define WIDTH 640
#define HEIGHT 400
#define FONT_HEIGHT 24
#define LABEL_WIDTH 36 // Thx Lars
#define BORDER 2
static struct element *root;
static struct element *code_label;
static struct element *output;
// Temporary: Will be moved to libnet
char **dns_split(char *url, char **buf)
{
strchr(url, '.')[0] = '\0';
char *first = url;
char *second = url + strlen(url) + 1;
buf[0] = first;
buf[1] = second;
return buf;
}
u32 status_color(char *http_code)
{
u32 c = 0;
switch (http_code[0]) {
case '1': // Information response
c = COLOR_BLUE;
break;
case '2': // Successful response
c = COLOR_GREEN;
break;
case '3': // Redirects
c = COLOR_YELLOW;
break;
case '4': // Client error
c = COLOR_RED;
break;
case '5': // Server error
c = COLOR_MAGENTA;
break;
default:
c = COLOR_WHITE;
break;
}
return c;
}
void on_submit(void *event, struct element *box)
{
(void)event;
char *url = ((struct element_text_input *)box->data)->text;
char *path = strchr(url, '/');
if (path) {
path[0] = '\0';
path++;
}
char *query = http_query_get(url, path ? path : "/");
char *dns[2];
dns_split(url, dns);
struct element_text_box *l = output->data;
struct element_label *c = code_label->data;
struct socket *socket = net_open(S_TCP);
if (socket && net_connect(socket, dns_request(dns[0], dns[1]), 80)) {
net_send(socket, query, strlen(query));
char buf[4096] = { 0 };
net_receive(socket, buf, 4096);
l->text = http_data(buf);
c->text = http_code(buf);
c->color_fg = status_color(c->text);
} else {
l->text = strdup("Can't connect to server.");
c->text = strdup("000");
}
gui_sync(root, output);
gui_sync(root, code_label);
/* net_close(socket); */ // TODO: Fix net close before FIN/ACK got ACK'ed
}
int main()
{
// TODO: Dynamic element positioning
root = gui_init("browser", WIDTH + 2 * BORDER, HEIGHT + 2 * BORDER, COLOR_BG);
code_label = gui_add_label(root, BORDER, BORDER, FONT_24, "000", COLOR_BLACK, COLOR_WHITE);
struct element *text_input =
gui_add_text_input(root, LABEL_WIDTH + 2 * BORDER, BORDER,
WIDTH - LABEL_WIDTH - BORDER, FONT_24, COLOR_WHITE, COLOR_BLACK);
output = gui_add_text_box(root, BORDER, FONT_HEIGHT + 2 * BORDER, WIDTH,
HEIGHT - FONT_HEIGHT - BORDER, FONT_16,
"Enter URL and press Enter :)", COLOR_WHITE, COLOR_BLACK);
text_input->event.on_submit = on_submit;
gui_event_loop(root);
return 0;
}
|