1#define _POSIX_C_SOURCE 199309L
2
3#include <stdlib.h>
4#include <time.h>
5
6#include "util.h"
7#include "platform/platform.h"
8
9static MGContext* platform_ctx;
10static i32 mouse_dx;
11static i32 mouse_dy;
12
13void platform_get_drawable_size(MGContext* ctx, i32* width, i32* height)
14{
15 *width = (i32)ctx->win->width;
16 *height = (i32)ctx->win->height;
17}
18
19void platform_get_mouse_state(i32* x, i32* y)
20{
21 *x = mouse_dx;
22 *y = mouse_dy;
23 mouse_dx = 0;
24 mouse_dy = 0;
25}
26
27u64 platform_get_ticks(void)
28{
29 return maus_get_time_ns() / 1000000;
30}
31
32void platform_init(MGContext* ctx)
33{
34 int i;
35
36 for (i = 0; i < MG_KEYS_DOWN_MAX; i++)
37 ctx->keys[i] = MGK_UNKNOWN;
38}
39
40i32 platform_key_down(MGContext* ctx, MGKey key)
41{
42 if (!ctx || !ctx->win || key == MGK_UNKNOWN)
43 return 0;
44 if (key < 0 || key >= MAUS_KEY_LAST)
45 return 0;
46
47 return ctx->win->key_syms[key] != 0;
48}
49
50i32 platform_poll(MGContext* ctx)
51{
52 MausEvent ev;
53
54 while (maus_event_poll(ctx->win, &ev)) {
55 switch (ev.type) {
56 case MAUS_EV_CLOSE:
57 return 0;
58 case MAUS_EV_MOUSE_MOTION:
59 mouse_dx += ev.mouse.motion.dx;
60 mouse_dy += ev.mouse.motion.dy;
61 break;
62 case MAUS_EV_RESIZE:
63 if (ev.resize.width == 0 || ev.resize.height == 0)
64 break;
65 if (ctx->win->width == ev.resize.width && ctx->win->height == ev.resize.height)
66 break;
67 ctx->width = (i32)ev.resize.width;
68 ctx->height = (i32)ev.resize.height;
69 if (!maus_resize(ctx->win, ev.resize.width, ev.resize.height))
70 mg_die(MG_EC_MAUS_RESIZE, "Failed to resize maus framebuffer");
71 break;
72 default:
73 break;
74 }
75 }
76
77 return 1;
78}
79
80void platform_present(MGContext* ctx)
81{
82 maus_present(ctx->win);
83}
84
85void platform_set_mouse_relative(i8 enabled)
86{
87 if (!platform_ctx || !platform_ctx->win)
88 return;
89
90 if (enabled) {
91 maus_cur_set_mode(platform_ctx->win, MAUS_CURSOR_STATE_HIDDEN);
92 maus_cur_set_mode(platform_ctx->win, MAUS_CURSOR_STATE_RELATIVE);
93 }
94 else {
95 maus_cur_set_mode(platform_ctx->win, MAUS_CURSOR_STATE_ABSOLUTE);
96 maus_cur_set_mode(platform_ctx->win, MAUS_CURSOR_STATE_VISIBLE);
97 }
98}
99
100void platform_shutdown(MGContext* ctx)
101{
102 if (!ctx || !ctx->win)
103 return;
104
105 maus_close(ctx->win);
106 ctx->win = NULL;
107 platform_ctx = NULL;
108}
109
110void platform_window_create(MGContext* ctx)
111{
112 platform_ctx = ctx;
113 ctx->win = maus_init(ctx->title, ctx->x, ctx->y, ctx->width, ctx->height);
114 if (!ctx->win)
115 mg_die(MG_EC_MAUS_INIT, "Failed to initialise maus");
116
117 if (!maus_create_window(ctx->win))
118 mg_die(MG_EC_MAUS_CREATE_WIN, "Failed to create maus window");
119}
120
121void platform_wait(u32 ms)
122{
123 maus_sleep(ms);
124}