Debian Codegraph @

src/external/RGFW/RGFW.h

raw symbols SCIP
1 /*
2 *
3 * RGFW 2.0.0-dev
4
5 * Copyright (C) 2022-26 Riley Mabb (@ColleagueRiley)
6 *
7 * libpng license
8 *
9 * This software is provided 'as-is', without any express or implied
10 * warranty. In no event will the authors be held liable for any damages
11 * arising from the use of this software.
12
13 * Permission is granted to anyone to use this software for any purpose,
14 * including commercial applications, and to alter it and redistribute it
15 * freely, subject to the following restrictions:
16 *
17 * 1. The origin of this software must not be misrepresented; you must not
18 * claim that you wrote the original software. If you use this software
19 * in a product, an acknowledgment in the product documentation would be
20 * appreciated but is not required.
21 * 2. Altered source versions must be plainly marked as such, and must not be
22 * misrepresented as being the original software.
23 * 3. This notice may not be removed or altered from any source distribution.
24 *
25 *
26 */
27
28 /*
29 (MAKE SURE RGFW_IMPLEMENTATION is in exactly one header or you use -D RGFW_IMPLEMENTATION)
30 #define RGFW_IMPLEMENTATION - makes it so source code is included with header
31 */
32
33 /*
34 #define RGFW_IMPLEMENTATION - (required) makes it so the source code is included
35 #define RGFW_DEBUG - (optional) makes it so RGFW prints debug messages and errors when they're found
36 #define RGFW_EGL - (optional) compile with OpenGL functions, allowing you to use to use EGL instead of the native OpenGL functions
37 #define RGFW_DIRECTX - (optional) include integration directX functions (windows only)
38 #define RGFW_VULKAN - (optional) include helpful vulkan integration functions and macros
39 #define RGFW_WEBGPU - (optional) use WebGPU for rendering
40 #define RGFW_NATIVE - (optional) define native RGFW types that use native API structures
41
42 #define RGFW_X11 (optional) (unix only) if X11 should be used. This option is turned on by default by unix systems except for MacOS
43 #define RGFW_WAYLAND (optional) (unix only) use Wayland. (This can be used with X11)
44 #define RGFW_NO_X11 (optional) (unix only) don't fallback to X11 when using Wayland
45 #define RGFW_NO_LOAD_WGL (optional) (windows only) if WGL should be loaded dynamically during runtime
46 #define RGFW_NO_X11_CURSOR (optional) (unix only) don't use XCursor
47 #define RGFW_NO_X11_CURSOR_PRELOAD (optional) (unix only) use XCursor, but don't link it in code, (you'll have to link it with -lXcursor)
48 #define RGFW_NO_X11_EXT_PRELOAD (optional) (unix only) use Xext, but don't link it in code, (you'll have to link it with -lXext)
49 #define RGFW_NO_LOAD_WINMM (optional) (windows only) use winmm (timeBeginPeriod), but don't link it in code, (you'll have to link it with -lwinmm)
50 #define RGFW_NO_WINMM (optional) (windows only) don't use winmm
51 #define RGFW_NO_IOKIT (optional) (macOS) don't use IOKit
52 #define RGFW_NO_UNIX_CLOCK (optional) (unix) don't link unix clock functions
53 #define RGFW_NO_DWM (windows only) - do not use or link dwmapi
54 #define RGFW_USE_XDL (optional) (X11) if XDL (XLib Dynamic Loader) should be used to load X11 dynamically during runtime (must include XDL.h along with RGFW)
55 #define RGFW_COCOA_GRAPHICS_SWITCHING - (optional) (cocoa) use automatic graphics switching (allow the system to choose to use GPU or iGPU)
56 #define RGFW_COCOA_FRAME_NAME (optional) (cocoa) set frame name
57 #define RGFW_NO_DPI - do not calculate DPI and don't use libShcore (win32)
58 #define RGFW_NO_XRANDR - do use XRandr (X11)
59 #define RGFW_ADVANCED_SMOOTH_RESIZE - use advanced methods for smooth resizing (may result in a spike in memory usage or worse performance) (eg. WM_TIMER and XSyncValue)
60 #define RGFW_NO_INFO - do not define the RGFW_info struct (without RGFW_IMPLEMENTATION)
61 #define RGFW_NO_GLXWINDOW - do not use GLXWindow
62
63 #define RGFW_ALLOC x - choose the default allocation function (defaults to standard malloc)
64 #define RGFW_FREE x - choose the default deallocation function (defaults to standard free)
65 #define RGFW_USERPTR x - choose the default userptr sent to the malloc call, (NULL by default)
66
67 #define RGFW_EXPORT - use when building RGFW
68 #define RGFW_IMPORT - use when linking with RGFW (not as a single-header)
69
70 #define RGFW_USE_INT - force the use c-types rather than stdint.h (for systems that might not have stdint.h (msvc))
71 #define RGFW_bool x - choose what type to use for bool, by default u32 is used
72 */
73
74 /*
75 Example to get you started :
76
77 linux : gcc main.c -lX11 -lXrandr -lGL
78 windows : gcc main.c -lopengl32 -lgdi32
79 macos : gcc main.c -framework Cocoa -framework CoreVideo -framework OpenGL -framework IOKit
80
81 #define RGFW_IMPLEMENTATION
82 #include "RGFW.h"
83
84 u8 icon[4 * 3 * 3] = {0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF};
85
86 int main() {
87 RGFW_window* win = RGFW_createWindow("name", 100, 100, 500, 500, (u64)0);
88 RGFW_event event;
89
90 RGFW_window_setExitKey(win, RGFW_escape);
91 RGFW_window_setIcon(win, icon, 3, 3, RGFW_formatRGBA8);
92
93 while (RGFW_window_shouldClose(win) == RGFW_FALSE) {
94 while (RGFW_window_checkEvent(win, &event)) {
95 if (event.type == RGFW_quit)
96 break;
97 }
98 }
99
100 RGFW_window_close(win);
101 }
102
103 compiling :
104
105 if you wish to compile the library all you have to do is create a new file with this in it
106
107 rgfw.c
108 #define RGFW_IMPLEMENTATION
109 #include "RGFW.h"
110
111 You may also want to add
112 `#define RGFW_EXPORT` when compiling and
113 `#define RGFW_IMPORT`when linking RGFW on it's own:
114 this reduces inline functions and prevents bloat in the object file
115
116 then you can use gcc (or whatever compile you wish to use) to compile the library into object file
117
118 ex. gcc -c RGFW.c -fPIC
119
120 after you compile the library into an object file, you can also turn the object file into an static or shared library
121
122 (commands ar and gcc can be replaced with whatever equivalent your system uses)
123
124 static : ar rcs RGFW.a RGFW.o
125 shared :
126 windows:
127 gcc -shared RGFW.o -lopengl32 -lgdi32 -o RGFW.dll
128 linux:
129 gcc -shared RGFW.o -lX11 -lGL -lXrandr -o RGFW.so
130 macos:
131 gcc -shared RGFW.o -framework CoreVideo -framework Cocoa -framework OpenGL -framework IOKit
132 */
133
134
135
136 /*
137 Credits :
138 EimaMei/Sacode : Code review, helped with X11, MacOS and Windows support, Silicon, siliapp.h -> referencing
139
140 stb : This project is heavily inspired by the stb single header files
141
142 SDL, GLFW and other online resources : reference implementations
143
144 contributors : (feel free to put yourself here if you contribute)
145 krisvers (@krisvers) -> code review
146 EimaMei (@SaCode) -> code review
147 Nycticebus (@Code-Nycticebus) -> bug fixes
148 Rob Rohan (@robrohan) -> X11 bugs and missing features, MacOS/Cocoa fixing memory issues/bugs
149 AICDG (@THISISAGOODNAME) -> vulkan support (example)
150 @Easymode -> support, testing/debugging, bug fixes and reviews
151 Joshua Rowe (omnisci3nce) - bug fix, review (macOS)
152 @lesleyrs -> bug fix, review (OpenGL)
153 Nick Porcino (@meshula) - testing, organization, review (MacOS, examples)
154 @therealmarrakesh -> documentation
155 @DarekParodia -> code review (X11) (C++)
156 @NishiOwO -> fix BSD support, fix OSMesa example
157 @BaynariKattu -> code review and documentation
158 Miguel Pinto (@konopimi) -> code review, fix vulkan example
159 @m-doescode -> code review (wayland)
160 Robert Gonzalez (@uni-dos) -> code review (wayland)
161 @TheLastVoyager -> code review
162 @yehoravramenko -> code review (winapi)
163 @halocupcake -> code review (OpenGL)
164 @GideonSerf -> documentation
165 Alexandre Almeida (@M374LX) -> code review (keycodes)
166 Vũ Xuân Trường (@wanwanvxt) -> code review (winapi)
167 Lucas (@lightspeedlucas) -> code review (msvc++)
168 Jeffery Myers (@JeffM2501) -> code review (msvc)
169 Zeni (@zenitsuyo) -> documentation
170 TheYahton (@TheYahton) -> documentation
171 nonexistant_object (@DiarrheaMcgee)
172 AC Gaudette (@acgaudette)
173 */
174
175 #if _MSC_VER
176 #pragma comment(lib, "gdi32")
177 #pragma comment(lib, "shell32")
178 #pragma comment(lib, "User32")
179 #pragma comment(lib, "Advapi32")
180 #pragma warning( push )
181 #pragma warning( disable : 4996 4191 4127)
182 #if _MSC_VER < 600
183 #define RGFW_C89
184 #endif
185 #else
186 #if defined(__STDC__) && !defined(__STDC_VERSION__)
187 #define RGFW_C89
188 #endif
189 #endif
190
191 #if defined(RGFW_EGL) && !defined(RGFW_OPENGL)
192 #define RGFW_OPENGL
193 #endif
194
195 /* these OS macros look better & are standardized */
196 /* plus it helps with cross-compiling */
197
198 #ifdef __EMSCRIPTEN__
199 #define RGFW_WASM
200 #endif
201
202 #if defined(RGFW_X11) && defined(__APPLE__) && !defined(RGFW_CUSTOM_BACKEND)
203 #define RGFW_MACOS_X11
204 #define RGFW_UNIX
205 #endif
206
207 #if defined(_WIN32) && !defined(RGFW_X11) && !defined(RGFW_UNIX) && !defined(RGFW_WASM) && !defined(RGFW_CUSTOM_BACKEND) /* (if you're using X11 on windows some how) */
208 #define RGFW_WINDOWS
209 #endif
210 #if defined(RGFW_WAYLAND)
211 #define RGFW_DEBUG /* wayland will be in debug mode by default for now */
212 #define RGFW_UNIX
213 #ifdef RGFW_OPENGL
214 #define RGFW_EGL
215 #endif
216 #ifdef RGFW_X11
217 #define RGFW_DYNAMIC
218 #endif
219 #endif
220 #if (!defined(RGFW_WAYLAND) && !defined(RGFW_X11)) && (defined(__unix__) || defined(RGFW_MACOS_X11) || defined(RGFW_X11)) && !defined(RGFW_WASM) && !defined(RGFW_CUSTOM_BACKEND)
221 #define RGFW_MACOS_X11
222 #define RGFW_X11
223 #define RGFW_UNIX
224 #elif defined(__APPLE__) && !defined(RGFW_MACOS_X11) && !defined(RGFW_X11) && !defined(RGFW_WASM) && !defined(RGFW_CUSTOM_BACKEND)
225 #define RGFW_MACOS
226 #endif
227
228 #ifndef RGFW_ASSERT
229 #include <assert.h>
230 #define RGFW_ASSERT assert
231 #endif
232
233 #if !defined(__STDC_VERSION__)
234 #define RGFW_C89
235 #endif
236
237 #if !defined(RGFW_SNPRINTF) && (defined(RGFW_X11) || defined(RGFW_WAYLAND))
238
239 /* required for X11 errors */
240 #include <stdio.h>
241
242 #ifdef RGFW_C89
243 #include <stdarg.h>
244 static int RGFW_c89_snprintf(char *dst, size_t size, const char *format, ...) {
245 va_list args;
246 size_t count = 0;
247 va_start(args, format);
248 count = (size_t)vsprintf(dst, format, args);
249 RGFW_ASSERT(count + 1 < size && "Buffer overflow");
250 va_end(args);
251 return (int)count;
252 }
253 #define RGFW_SNPRINTF RGFW_c89_snprintf
254 #else
255 #define RGFW_SNPRINTF snprintf
256 #endif /*RGFW_C89*/
257 #endif
258
259 #ifndef RGFW_USERPTR
260 #define RGFW_USERPTR NULL
261 #endif
262
263 #ifndef RGFW_UNUSED
264 #define RGFW_UNUSED(x) (void)(x)
265 #endif
266
267 #ifndef RGFW_ROUND
268 #define RGFW_ROUND(x) (i32)((x) >= 0 ? (x) + 0.5f : (x) - 0.5f)
269 #endif
270
271 #ifndef RGFW_ROUNDF
272 #define RGFW_ROUNDF(x) (float)((i32)((x) + ((x) < 0.0f ? -0.5f : 0.5f)))
273 #endif
274
275 #ifndef RGFW_MIN
276 #define RGFW_MIN(x, y) ((x < y) ? x : y)
277 #endif
278
279 #ifndef RGFW_ALLOC
280 #include <stdlib.h>
281 #define RGFW_ALLOC malloc
282 #define RGFW_FREE free
283 #endif
284
285 #if !defined(RGFW_MEMCPY) || !defined(RGFW_STRNCMP) || !defined(RGFW_STRNCPY) || !defined(RGFW_MEMSET)
286 #include <string.h>
287 #endif
288
289 #ifndef RGFW_MEMSET
290 #define RGFW_MEMSET(ptr, value, num) memset(ptr, value, num)
291 #endif
292
293 #ifndef RGFW_MEMCPY
294 #define RGFW_MEMCPY(dist, src, len) memcpy(dist, src, len)
295 #endif
296
297 #ifndef RGFW_STRNCMP
298 #define RGFW_STRNCMP(s1, s2, max) strncmp(s1, s2, max)
299 #endif
300
301 #ifndef RGFW_STRNCPY
302 #define RGFW_STRNCPY(dist, src, len) strncpy(dist, src, len)
303 #endif
304
305 #ifndef RGFW_STRSTR
306 #define RGFW_STRSTR(str, substr) strstr(str, substr)
307 #endif
308
309 #ifndef RGFW_STRTOL
310 /* required for X11 XDnD and X11 Monitor DPI */
311 #include <stdlib.h>
312 #define RGFW_STRTOL(str, endptr, base) strtol(str, endptr, base)
313 #define RGFW_ATOF(num) atof(num)
314 #endif
315
316 #if !defined(RGFW_PRINTF) && ( defined(RGFW_DEBUG) || defined(RGFW_WAYLAND) )
317 /* required when using RGFW_DEBUG */
318 #include <stdio.h>
319 #define RGFW_PRINTF printf
320 #endif
321
322 #ifndef RGFW_MAX_PATH
323 #define RGFW_MAX_PATH 260 /* max length of a path (for drag andn drop) */
324 #endif
325 #ifndef RGFW_MAX_DROPS
326 #define RGFW_MAX_DROPS 260 /* max items you can drop at once */
327 #endif
328
329 #ifndef RGFW_MAX_EVENTS
330 #define RGFW_MAX_EVENTS 32
331 #endif
332
333 #ifndef RGFW_MAX_MONITORS
334 #define RGFW_MAX_MONITORS 6
335 #endif
336
337 #ifndef RGFW_COCOA_FRAME_NAME
338 #define RGFW_COCOA_FRAME_NAME NULL
339 #endif
340
341 #ifdef RGFW_WIN95 /* for windows 95 testing (not that it really works) */
342 #define RGFW_NO_PASSTHROUGH
343 #endif
344
345 #if defined(RGFW_EXPORT) || defined(RGFW_IMPORT)
346 #if defined(_WIN32)
347 #if defined(__TINYC__) && (defined(RGFW_EXPORT) || defined(RGFW_IMPORT))
348 #define __declspec(x) __attribute__((x))
349 #endif
350
351 #if defined(RGFW_EXPORT)
352 #define RGFWDEF __declspec(dllexport)
353 #else
354 #define RGFWDEF __declspec(dllimport)
355 #endif
356 #else
357 #if defined(RGFW_EXPORT)
358 #define RGFWDEF __attribute__((visibility("default")))
359 #endif
360 #endif
361 #ifndef RGFWDEF
362 #define RGFWDEF
363 #endif
364 #endif
365
366 #ifndef RGFWDEF
367 #ifdef RGFW_C89
368 #define RGFWDEF __inline
369 #else
370 #define RGFWDEF inline
371 #endif
372 #endif
373
374 #if defined(__cplusplus) && !defined(__EMSCRIPTEN__)
375 extern "C" {
376 #endif
377
378 /* makes sure the header file part is only defined once by default */
379 #ifndef RGFW_HEADER
380
381 #define RGFW_HEADER
382
383 #include <stddef.h>
384 #ifndef RGFW_INT_DEFINED
385 #ifdef RGFW_USE_INT /* optional for any system that might not have stdint.h */
386 typedef unsigned char u8;
387 typedef signed char i8;
388 typedef unsigned short u16;
389 typedef signed short i16;
390 typedef unsigned long int u32;
391 typedef signed long int i32;
392 typedef unsigned long long u64;
393 typedef signed long long i64;
394 #else /* use stdint standard types instead of c "standard" types */
395 #include <stdint.h>
396
397 typedef uint8_t u8;
398 typedef int8_t i8;
399 typedef uint16_t u16;
400 typedef int16_t i16;
401 typedef uint32_t u32;
402 typedef int32_t i32;
403 typedef uint64_t u64;
404 typedef int64_t i64;
405 #endif
406 #define RGFW_INT_DEFINED
407 #endif
408
409 typedef ptrdiff_t RGFW_ssize_t;
410
411 #ifndef RGFW_BOOL_DEFINED
412 #define RGFW_BOOL_DEFINED
413 typedef u8 RGFW_bool;
414 #endif
415
416 #define RGFW_BOOL(x) (RGFW_bool)((x) != 0) /* force a value to be 0 or 1 */
417 #define RGFW_TRUE (RGFW_bool)1
418 #define RGFW_FALSE (RGFW_bool)0
419
420 #define RGFW_ENUM(type, name) type name; enum
421 #define RGFW_BIT(x) (1 << (x))
422
423 #ifdef RGFW_VULKAN
424
425 #if defined(RGFW_WAYLAND) && defined(RGFW_X11)
426 #define VK_USE_PLATFORM_WAYLAND_KHR
427 #define VK_USE_PLATFORM_XLIB_KHR
428 #define RGFW_VK_SURFACE ((RGFW_usingWayland()) ? ("VK_KHR_wayland_surface") : ("VK_KHR_xlib_surface"))
429 #elif defined(RGFW_WAYLAND)
430 #define VK_USE_PLATFORM_WAYLAND_KHR
431 #define VK_USE_PLATFORM_XLIB_KHR
432 #define RGFW_VK_SURFACE "VK_KHR_wayland_surface"
433 #elif defined(RGFW_X11)
434 #define VK_USE_PLATFORM_XLIB_KHR
435 #define RGFW_VK_SURFACE "VK_KHR_xlib_surface"
436 #elif defined(RGFW_WINDOWS)
437 #define VK_USE_PLATFORM_WIN32_KHR
438 #define OEMRESOURCE
439 #define RGFW_VK_SURFACE "VK_KHR_win32_surface"
440 #elif defined(RGFW_MACOS) && !defined(RGFW_MACOS_X11)
441 #define VK_USE_PLATFORM_MACOS_MVK
442 #define RGFW_VK_SURFACE "VK_MVK_macos_surface"
443 #else
444 #define RGFW_VK_SURFACE NULL
445 #endif
446
447 #endif
448
449
450 /*! @brief The stucture that contains information about the current RGFW instance */
451 typedef struct RGFW_info RGFW_info;
452
453 /*! @brief The window stucture for interfacing with the window */
454 typedef struct RGFW_window RGFW_window;
455
456 /*! @brief The source window stucture for interfacing with the underlying windowing API (e.g. winapi, wayland, cocoa, etc) */
457 typedef struct RGFW_window_src RGFW_window_src;
458
459 /*! @brief The color format for pixel data */
460 typedef RGFW_ENUM(u8, RGFW_format) {
461 RGFW_formatRGB8 = 0, /*!< 8-bit RGB (3 channels) */
462 RGFW_formatBGR8, /*!< 8-bit BGR (3 channels) */
463 RGFW_formatRGBA8, /*!< 8-bit RGBA (4 channels) */
464 RGFW_formatARGB8, /*!< 8-bit RGBA (4 channels) */
465 RGFW_formatBGRA8, /*!< 8-bit BGRA (4 channels) */
466 RGFW_formatABGR8, /*!< 8-bit BGRA (4 channels) */
467 RGFW_formatCount
468 };
469
470 /*! @brief layout struct for mapping out format types */
471 typedef struct RGFW_colorLayout { i32 r, g, b, a; u32 channels; } RGFW_colorLayout;
472
473 /*! @brief function type converting raw image data between formats */
474 typedef void (* RGFW_convertImageDataFunc)(u8* dest_data, u8* src_data, const RGFW_colorLayout* srcLayout, const RGFW_colorLayout* destLayout, size_t count);
475
476 /*! @brief a stucture for interfacing with the underlying native image (e.g. XImage, HBITMAP, etc) */
477 typedef struct RGFW_nativeImage RGFW_nativeImage;
478
479 /*! @brief a stucture for interfacing with pixel data as a renderable surface */
480 typedef struct RGFW_surface RGFW_surface;
481
482 /*! @brief gamma struct for monitors */
483 typedef struct RGFW_gammaRamp {
484 u16* red; /*!< array for the red channel */
485 u16* green; /*!< array for the green channel */
486 u16* blue; /*!< array for the blue channel */
487 size_t count; /*! count of elements in each channel */
488 } RGFW_gammaRamp;
489
490 /*! @brief monitor mode data | can be changed by the user (with functions)*/
491 typedef struct RGFW_monitorMode {
492 i32 w, h; /*!< monitor workarea size */
493 float refreshRate; /*!< monitor refresh rate */
494 u8 red, blue, green; /*!< sizeof rgb values */
495 void* src; /*!< source API mode */
496 } RGFW_monitorMode;
497
498 /*! @brief structure for monitor node and source monitor data */
499 typedef struct RGFW_monitorNode RGFW_monitorNode;
500
501 /*! @brief structure for monitor data */
502 typedef struct RGFW_monitor {
503 i32 x, y; /*!< x - y of the monitor workarea */
504 char name[128]; /*!< monitor name */
505 float scaleX, scaleY; /*!< monitor content scale */
506 float pixelRatio; /*!< pixel ratio for monitor (1.0 for regular, 2.0 for hiDPI) */
507 float physW, physH; /*!< monitor physical size in inches */
508 RGFW_monitorMode mode; /*!< current mode of the monitor */
509 void* userPtr; /*!< pointer for user data */
510 RGFW_monitorNode* node; /*!< source node data of the monitor */
511 } RGFW_monitor;
512
513 /*! @brief what type of request you are making for the monitor */
514 typedef RGFW_ENUM(u8, RGFW_modeRequest) {
515 RGFW_monitorScale = RGFW_BIT(0), /*!< scale the monitor size */
516 RGFW_monitorRefresh = RGFW_BIT(1), /*!< change the refresh rate */
517 RGFW_monitorRGB = RGFW_BIT(2), /*!< change the monitor RGB bits size */
518 RGFW_monitorAll = RGFW_monitorScale | RGFW_monitorRefresh | RGFW_monitorRGB
519 };
520
521 /*! a raw pointer to the underlying mouse handle for setting and creating custom mouse icons */
522 typedef void RGFW_mouse;
523
524 /*! @brief RGFW's abstract keycodes */
525 typedef RGFW_ENUM(u8, RGFW_key) {
526 RGFW_keyNULL = 0,
527 RGFW_escape = '\033',
528 RGFW_backtick = '`',
529 RGFW_0 = '0',
530 RGFW_1 = '1',
531 RGFW_2 = '2',
532 RGFW_3 = '3',
533 RGFW_4 = '4',
534 RGFW_5 = '5',
535 RGFW_6 = '6',
536 RGFW_7 = '7',
537 RGFW_8 = '8',
538 RGFW_9 = '9',
539 RGFW_minus = '-',
540 RGFW_equal = '=',
541 RGFW_equals = RGFW_equal,
542 RGFW_backSpace = '\b',
543 RGFW_tab = '\t',
544 RGFW_space = ' ',
545 RGFW_a = 'a',
546 RGFW_b = 'b',
547 RGFW_c = 'c',
548 RGFW_d = 'd',
549 RGFW_e = 'e',
550 RGFW_f = 'f',
551 RGFW_g = 'g',
552 RGFW_h = 'h',
553 RGFW_i = 'i',
554 RGFW_j = 'j',
555 RGFW_k = 'k',
556 RGFW_l = 'l',
557 RGFW_m = 'm',
558 RGFW_n = 'n',
559 RGFW_o = 'o',
560 RGFW_p = 'p',
561 RGFW_q = 'q',
562 RGFW_r = 'r',
563 RGFW_s = 's',
564 RGFW_t = 't',
565 RGFW_u = 'u',
566 RGFW_v = 'v',
567 RGFW_w = 'w',
568 RGFW_x = 'x',
569 RGFW_y = 'y',
570 RGFW_z = 'z',
571 RGFW_period = '.',
572 RGFW_comma = ',',
573 RGFW_slash = '/',
574 RGFW_bracket = '[',
575 RGFW_closeBracket = ']',
576 RGFW_semicolon = ';',
577 RGFW_apostrophe = '\'',
578 RGFW_backSlash = '\\',
579 RGFW_return = '\n',
580 RGFW_enter = RGFW_return,
581 RGFW_delete = '\177', /* 127 */
582 RGFW_F1,
583 RGFW_F2,
584 RGFW_F3,
585 RGFW_F4,
586 RGFW_F5,
587 RGFW_F6,
588 RGFW_F7,
589 RGFW_F8,
590 RGFW_F9,
591 RGFW_F10,
592 RGFW_F11,
593 RGFW_F12,
594 RGFW_F13,
595 RGFW_F14,
596 RGFW_F15,
597 RGFW_F16,
598 RGFW_F17,
599 RGFW_F18,
600 RGFW_F19,
601 RGFW_F20,
602 RGFW_F21,
603 RGFW_F22,
604 RGFW_F23,
605 RGFW_F24,
606 RGFW_F25,
607 RGFW_capsLock,
608 RGFW_shiftL,
609 RGFW_controlL,
610 RGFW_altL,
611 RGFW_superL,
612 RGFW_shiftR,
613 RGFW_controlR,
614 RGFW_altR,
615 RGFW_superR,
616 RGFW_up,
617 RGFW_down,
618 RGFW_left,
619 RGFW_right,
620 RGFW_insert,
621 RGFW_menu,
622 RGFW_end,
623 RGFW_home,
624 RGFW_pageUp,
625 RGFW_pageDown,
626 RGFW_numLock,
627 RGFW_kpSlash,
628 RGFW_kpMultiply,
629 RGFW_kpPlus,
630 RGFW_kpMinus,
631 RGFW_kpEqual,
632 RGFW_kpEquals = RGFW_kpEqual,
633 RGFW_kp1,
634 RGFW_kp2,
635 RGFW_kp3,
636 RGFW_kp4,
637 RGFW_kp5,
638 RGFW_kp6,
639 RGFW_kp7,
640 RGFW_kp8,
641 RGFW_kp9,
642 RGFW_kp0,
643 RGFW_kpPeriod,
644 RGFW_kpReturn,
645 RGFW_scrollLock,
646 RGFW_printScreen,
647 RGFW_pause,
648 RGFW_world1,
649 RGFW_world2,
650 RGFW_keyLast = 256 /* padding for alignment ~(175 by default) */
651 };
652
653 /*! @brief abstract mouse button codes */
654 typedef RGFW_ENUM(u8, RGFW_mouseButton) {
655 RGFW_mouseLeft = 0, /*!< left mouse button is pressed */
656 RGFW_mouseMiddle, /*!< mouse-wheel-button is pressed */
657 RGFW_mouseRight, /*!< right mouse button is pressed */
658 RGFW_mouseMisc1, RGFW_mouseMisc2, RGFW_mouseMisc3, RGFW_mouseMisc4, RGFW_mouseMisc5,
659 RGFW_mouseFinal
660 };
661
662 /*! abstract key modifier codes */
663 typedef RGFW_ENUM(u8, RGFW_keymod) {
664 RGFW_modCapsLock = RGFW_BIT(0),
665 RGFW_modNumLock = RGFW_BIT(1),
666 RGFW_modControl = RGFW_BIT(2),
667 RGFW_modAlt = RGFW_BIT(3),
668 RGFW_modShift = RGFW_BIT(4),
669 RGFW_modSuper = RGFW_BIT(5),
670 RGFW_modScrollLock = RGFW_BIT(6)
671 };
672
673 /*! @brief codes for the event types that can be sent */
674 typedef RGFW_ENUM(u8, RGFW_eventType) {
675 RGFW_eventNone = 0, /*!< no event has been sent */
676 RGFW_keyPressed, /*!< a key has been pressed */
677 RGFW_keyReleased, /*!< a key has been released */
678 RGFW_keyChar, /*!< keyboard character input event specifically for utf8 input */
679 RGFW_mouseButtonPressed, /*!< a mouse button has been pressed (left,middle,right) */
680 RGFW_mouseButtonReleased, /*!< a mouse button has been released (left,middle,right) */
681 RGFW_mouseScroll, /*!< a mouse scroll event */
682 RGFW_mousePosChanged, /*!< the position of the mouse has been changed */
683 /*! mouse event note
684 the x and y of the mouse can be found in the vector, RGFW_x, y
685
686 RGFW_event.button.value holds which mouse button was pressed
687 */
688 RGFW_windowMoved, /*!< the window was moved (by the user) */
689 RGFW_windowResized, /*!< the window was resized (by the user), [on WASM this means the browser was resized] */
690 RGFW_focusIn, /*!< window is in focus now */
691 RGFW_focusOut, /*!< window is out of focus now */
692 RGFW_mouseEnter, /* mouse entered the window */
693 RGFW_mouseLeave, /* mouse left the window */
694 RGFW_windowRefresh, /* The window content needs to be refreshed */
695
696 /* attribs change event note
697 The event data is sent straight to the window structure
698 with win->x, win->y, win->w and win->h
699 */
700 RGFW_quit, /*!< the user clicked the quit button */
701 RGFW_dataDrop, /*!< a file has been dropped into the window */
702 RGFW_dataDrag, /*!< the start of a drag and drop event, when the file is being dragged */
703 /* drop data note
704 The x and y coords of the drop are stored in the vector RGFW_x, y
705
706 RGFW_event.drop.count holds how many files were dropped
707
708 This is also the size of the array which stores all the dropped file string,
709 RGFW_event.drop.files
710 */
711 RGFW_windowMaximized, /*!< the window was maximized */
712 RGFW_windowMinimized, /*!< the window was minimized */
713 RGFW_windowRestored, /*!< the window was restored */
714 RGFW_scaleUpdated, /*!< content scale factor changed */
715 RGFW_monitorConnected, /*!< a monitor has been connected */
716 RGFW_monitorDisconnected /*!< a monitor has been disconnected */
717 };
718
719 /*! @brief flags for toggling wether or not an event should be processed */
720 typedef RGFW_ENUM(u32, RGFW_eventFlag) {
721 RGFW_keyPressedFlag = RGFW_BIT(RGFW_keyPressed),
722 RGFW_keyReleasedFlag = RGFW_BIT(RGFW_keyReleased),
723 RGFW_keyCharFlag = RGFW_BIT(RGFW_keyChar),
724 RGFW_mouseScrollFlag = RGFW_BIT(RGFW_mouseScroll),
725 RGFW_mouseButtonPressedFlag = RGFW_BIT(RGFW_mouseButtonPressed),
726 RGFW_mouseButtonReleasedFlag = RGFW_BIT(RGFW_mouseButtonReleased),
727 RGFW_mousePosChangedFlag = RGFW_BIT(RGFW_mousePosChanged),
728 RGFW_mouseEnterFlag = RGFW_BIT(RGFW_mouseEnter),
729 RGFW_mouseLeaveFlag = RGFW_BIT(RGFW_mouseLeave),
730 RGFW_windowMovedFlag = RGFW_BIT(RGFW_windowMoved),
731 RGFW_windowResizedFlag = RGFW_BIT(RGFW_windowResized),
732 RGFW_focusInFlag = RGFW_BIT(RGFW_focusIn),
733 RGFW_focusOutFlag = RGFW_BIT(RGFW_focusOut),
734 RGFW_windowRefreshFlag = RGFW_BIT(RGFW_windowRefresh),
735 RGFW_windowMaximizedFlag = RGFW_BIT(RGFW_windowMaximized),
736 RGFW_windowMinimizedFlag = RGFW_BIT(RGFW_windowMinimized),
737 RGFW_windowRestoredFlag = RGFW_BIT(RGFW_windowRestored),
738 RGFW_scaleUpdatedFlag = RGFW_BIT(RGFW_scaleUpdated),
739 RGFW_quitFlag = RGFW_BIT(RGFW_quit),
740 RGFW_dataDropFlag = RGFW_BIT(RGFW_dataDrop),
741 RGFW_dataDragFlag = RGFW_BIT(RGFW_dataDrag),
742 RGFW_monitorConnectedFlag = RGFW_BIT(RGFW_monitorConnected),
743 RGFW_monitorDisconnectedFlag = RGFW_BIT(RGFW_monitorDisconnected),
744
745 RGFW_keyEventsFlag = RGFW_keyPressedFlag | RGFW_keyReleasedFlag | RGFW_keyCharFlag,
746 RGFW_mouseEventsFlag = RGFW_mouseButtonPressedFlag | RGFW_mouseButtonReleasedFlag | RGFW_mousePosChangedFlag | RGFW_mouseEnterFlag | RGFW_mouseLeaveFlag | RGFW_mouseScrollFlag ,
747 RGFW_windowEventsFlag = RGFW_windowMovedFlag | RGFW_windowResizedFlag | RGFW_windowRefreshFlag | RGFW_windowMaximizedFlag | RGFW_windowMinimizedFlag | RGFW_windowRestoredFlag | RGFW_scaleUpdatedFlag,
748 RGFW_focusEventsFlag = RGFW_focusInFlag | RGFW_focusOutFlag,
749 RGFW_dataDropEventsFlag = RGFW_dataDropFlag | RGFW_dataDragFlag,
750 RGFW_monitorEventsFlag = RGFW_monitorConnectedFlag | RGFW_monitorDisconnectedFlag,
751 RGFW_allEventFlags = RGFW_keyEventsFlag | RGFW_mouseEventsFlag | RGFW_windowEventsFlag | RGFW_focusEventsFlag | RGFW_dataDropEventsFlag | RGFW_quitFlag | RGFW_monitorEventsFlag
752 };
753
754 /*! Event structure(s) and union for checking/getting events */
755
756 /*! @brief common event data across all events */
757 typedef struct RGFW_commonEvent {
758 RGFW_eventType type; /*!< which event has been sent?*/
759 RGFW_window* win; /*!< the window this event applies to (for event queue events) */
760 } RGFW_commonEvent;
761
762 /*! @brief event data for any mouse button event (press/release) */
763 typedef struct RGFW_mouseButtonEvent {
764 RGFW_eventType type; /*!< which event has been sent?*/
765 RGFW_window* win; /*!< the window this event applies to (for event queue events) */
766 RGFW_mouseButton value; /* !< which mouse button was pressed */
767 } RGFW_mouseButtonEvent;
768
769 /*! @brief event data for any mouse scroll event */
770 typedef struct RGFW_mouseScrollEvent {
771 RGFW_eventType type; /*!< which event has been sent?*/
772 RGFW_window* win; /*!< the window this event applies to (for event queue events) */
773 float x, y; /*!< the raw mouse scroll value */
774 } RGFW_mouseScrollEvent;
775
776 /*! @brief event data for any mouse position event (RGFW_mousePosChanged) */
777 typedef struct RGFW_mousePosEvent {
778 RGFW_eventType type; /*!< which event has been sent?*/
779 RGFW_window* win; /*!< the window this event applies to (for event queue events) */
780 i32 x, y; /*!< mouse x, y of event (or drop point) */
781 float vecX, vecY; /*!< raw mouse movement */
782 } RGFW_mousePosEvent;
783
784 /*! @brief event data for a key press/release event */
785 typedef struct RGFW_keyEvent {
786 RGFW_eventType type; /*!< which event has been sent?*/
787 RGFW_window* win; /*!< the window this event applies to (for event queue events) */
788 RGFW_key value; /*!< the physical key of the event, refers to where key is physically */
789 RGFW_bool repeat; /*!< key press event repeated (the key is being held) */
790 RGFW_keymod mod;
791 } RGFW_keyEvent;
792
793 /*! @brief event data for a key character event */
794 typedef struct RGFW_keyCharEvent {
795 RGFW_eventType type; /*!< which event has been sent?*/
796 RGFW_window* win; /*!< the window this event applies to (for event queue events) */
797 u32 value; /*!< the unicode value of the key */
798 } RGFW_keyCharEvent;
799
800 /*! @brief event data for any data drop event */
801 typedef struct RGFW_dataDropEvent {
802 RGFW_eventType type; /*!< which event has been sent?*/
803 RGFW_window* win; /*!< the window this event applies to (for event queue events) */
804 /* 260 max paths with a max length of 260 */
805 char** files; /*!< dropped files */
806 size_t count; /*!< how many files were dropped */
807 } RGFW_dataDropEvent;
808
809 /*! @brief event data for any data drag event */
810 typedef struct RGFW_dataDragEvent {
811 RGFW_eventType type; /*!< which event has been sent?*/
812 RGFW_window* win; /*!< the window this event applies to (for event queue events) */
813 i32 x, y; /*!< mouse x, y of event (or drop point) */
814 } RGFW_dataDragEvent;
815
816 /*! @brief event data for when the window scale (DPI) is updated */
817 typedef struct RGFW_scaleUpdatedEvent {
818 RGFW_eventType type; /*!< which event has been sent?*/
819 RGFW_window* win; /*!< the window this event applies to (for event queue events) */
820 float x, y; /*!< DPI scaling */
821 } RGFW_scaleUpdatedEvent;
822
823 /*! @brief event data for when a monitor is connected, disconnected or updated */
824 typedef struct RGFW_monitorEvent {
825 RGFW_eventType type; /*!< which event has been sent?*/
826 RGFW_window* win; /*!< the window this event applies to (for event queue events) */
827 const RGFW_monitor* monitor; /*!< the monitor that this event applies to */
828 } RGFW_monitorEvent;
829
830 /*! @brief union for all of the event stucture types */
831 typedef union RGFW_event {
832 RGFW_eventType type; /*!< which event has been sent?*/
833 RGFW_commonEvent common; /*!< common event data (e.g.) type and win */
834 RGFW_mouseButtonEvent button; /*!< data for a button press/release */
835 RGFW_mouseScrollEvent scroll; /*!< data for a mouse scroll */
836 RGFW_mousePosEvent mouse; /*!< data for mouse motion events */
837 RGFW_keyEvent key; /*!< data for key press/release/hold events */
838 RGFW_keyCharEvent keyChar; /*!< data for key character events */
839 RGFW_dataDropEvent drop; /*!< dropping a file events */
840 RGFW_dataDragEvent drag; /*!< data for dragging a file events */
841 RGFW_scaleUpdatedEvent scale; /*!< data for dpi scaling update events */
842 RGFW_monitorEvent monitor; /*!< data for monitor events */
843 } RGFW_event;
844
845 /*!
846 @!brief codes for for RGFW_the code is stupid and C++ waitForEvent
847 waitMS -> Allows the function to keep checking for events even after there are no more events
848 if waitMS == 0, the loop will not wait for events
849 if waitMS > 0, the loop will wait that many miliseconds after there are no more events until it returns
850 if waitMS == -1 or waitMS == the max size of an unsigned 32-bit int, the loop will not return until it gets another event
851 */
852 typedef RGFW_ENUM(i32, RGFW_eventWait) {
853 RGFW_eventNoWait = 0,
854 RGFW_eventWaitNext = -1
855 };
856
857 /*! @brief optional bitwise arguments for making a windows, these can be OR'd together */
858 typedef RGFW_ENUM(u32, RGFW_windowFlags) {
859 RGFW_windowNoBorder = RGFW_BIT(0), /*!< the window doesn't have a border */
860 RGFW_windowNoResize = RGFW_BIT(1), /*!< the window cannot be resized by the user */
861 RGFW_windowAllowDND = RGFW_BIT(2), /*!< the window supports drag and drop */
862 RGFW_windowHideMouse = RGFW_BIT(3), /*! the window should hide the mouse (can be toggled later on using `RGFW_window_showMouse`) */
863 RGFW_windowFullscreen = RGFW_BIT(4), /*!< the window is fullscreen by default */
864 RGFW_windowTransparent = RGFW_BIT(5), /*!< the window is transparent (only properly works on X11 and MacOS, although it's meant for for windows) */
865 RGFW_windowCenter = RGFW_BIT(6), /*! center the window on the screen */
866 RGFW_windowRawMouse = RGFW_BIT(7), /*!< use raw mouse mouse on window creation */
867 RGFW_windowScaleToMonitor = RGFW_BIT(8), /*! scale the window to the screen */
868 RGFW_windowHide = RGFW_BIT(9), /*! the window is hidden */
869 RGFW_windowMaximize = RGFW_BIT(10), /*!< maximize the window on creation */
870 RGFW_windowCenterCursor = RGFW_BIT(11), /*!< center the cursor to the window on creation */
871 RGFW_windowFloating = RGFW_BIT(12), /*!< create a floating window */
872 RGFW_windowFocusOnShow = RGFW_BIT(13), /*!< focus the window when it's shown */
873 RGFW_windowMinimize = RGFW_BIT(14), /*!< focus the window when it's shown */
874 RGFW_windowFocus = RGFW_BIT(15), /*!< if the window is in focus */
875 RGFW_windowCaptureMouse = RGFW_BIT(16), /*!< capture the mouse mouse mouse on window creation */
876 RGFW_windowOpenGL = RGFW_BIT(17), /*!< create an OpenGL context (you can also do this manually with RGFW_window_createContext_OpenGL) */
877 RGFW_windowEGL = RGFW_BIT(18), /*!< create an EGL context (you can also do this manually with RGFW_window_createContext_EGL) */
878 RGFW_noDeinitOnClose = RGFW_BIT(19), /*!< do not auto deinit RGFW if the window closes and this is the last window open */
879 RGFW_windowedFullscreen = RGFW_windowNoBorder | RGFW_windowMaximize,
880 RGFW_windowCaptureRawMouse = RGFW_windowCaptureMouse | RGFW_windowRawMouse
881 };
882
883 /*! @brief the types of icon to set */
884 typedef RGFW_ENUM(u8, RGFW_icon) {
885 RGFW_iconTaskbar = RGFW_BIT(0),
886 RGFW_iconWindow = RGFW_BIT(1),
887 RGFW_iconBoth = RGFW_iconTaskbar | RGFW_iconWindow
888 };
889
890 /*! @brief standard mouse icons */
891 typedef RGFW_ENUM(u8, RGFW_mouseIcons) {
892 RGFW_mouseNormal = 0,
893 RGFW_mouseArrow,
894 RGFW_mouseIbeam,
895 RGFW_mouseText = RGFW_mouseIbeam,
896 RGFW_mouseCrosshair,
897 RGFW_mousePointingHand,
898 RGFW_mouseResizeEW,
899 RGFW_mouseResizeNS,
900 RGFW_mouseResizeNWSE,
901 RGFW_mouseResizeNESW,
902 RGFW_mouseResizeNW,
903 RGFW_mouseResizeN,
904 RGFW_mouseResizeNE,
905 RGFW_mouseResizeE,
906 RGFW_mouseResizeSE,
907 RGFW_mouseResizeS,
908 RGFW_mouseResizeSW,
909 RGFW_mouseResizeW,
910 RGFW_mouseResizeAll,
911 RGFW_mouseNotAllowed,
912 RGFW_mouseWait,
913 RGFW_mouseProgress,
914 RGFW_mouseIconCount,
915 RGFW_mouseIconFinal = 16 /* padding for alignment */
916 };
917
918 /*! @breif flash request type */
919 typedef RGFW_ENUM(u8, RGFW_flashRequest) {
920 RGFW_flashCancel = 0,
921 RGFW_flashBriefly,
922 RGFW_flashUntilFocused
923 };
924
925 /*! @brief the type of debug message */
926 typedef RGFW_ENUM(u8, RGFW_debugType) {
927 RGFW_typeError = 0, RGFW_typeWarning, RGFW_typeInfo
928 };
929
930 /*! @brief error codes for known failure types */
931 typedef RGFW_ENUM(u8, RGFW_errorCode) {
932 RGFW_noError = 0, /*!< no error */
933 RGFW_errOutOfMemory,
934 RGFW_errOpenGLContext, RGFW_errEGLContext, /*!< error with the OpenGL context */
935 RGFW_errWayland, RGFW_errX11,
936 RGFW_errDirectXContext,
937 RGFW_errIOKit,
938 RGFW_errClipboard,
939 RGFW_errFailedFuncLoad,
940 RGFW_errBuffer,
941 RGFW_errMetal,
942 RGFW_errPlatform,
943 RGFW_errEventQueue,
944 RGFW_infoWindow, RGFW_infoBuffer, RGFW_infoGlobal, RGFW_infoOpenGL,
945 RGFW_warningWayland, RGFW_warningOpenGL
946 };
947
948 /*! @brief callback function type for debug messags */
949 typedef void (* RGFW_debugfunc)(RGFW_debugType type, RGFW_errorCode err, const char* msg);
950
951 /*! @brief RGFW_windowMoved, the window and its new rect value */
952 typedef void (* RGFW_windowMovedfunc)(RGFW_window* win, i32 x, i32 y);
953 /*! @brief RGFW_windowResized, the window and its new rect value */
954 typedef void (* RGFW_windowResizedfunc)(RGFW_window* win, i32 w, i32 h);
955 /*! @brief RGFW_windowRestored, the window and its new rect value */
956 typedef void (* RGFW_windowRestoredfunc)(RGFW_window* win, i32 x, i32 y, i32 w, i32 h);
957 /*! @brief RGFW_windowMaximized, the window and its new rect value */
958 typedef void (* RGFW_windowMaximizedfunc)(RGFW_window* win, i32 x, i32 y, i32 w, i32 h);
959 /*! @brief RGFW_windowMinimized, the window and its new rect value */
960 typedef void (* RGFW_windowMinimizedfunc)(RGFW_window* win);
961 /*! @brief RGFW_quit, the window that was closed */
962 typedef void (* RGFW_windowQuitfunc)(RGFW_window* win);
963 /*! @brief RGFW_focusIn / RGFW_focusOut, the window who's focus has changed and if its in focus */
964 typedef void (* RGFW_focusfunc)(RGFW_window* win, RGFW_bool inFocus);
965 /*! @brief RGFW_mouseEnter / RGFW_mouseLeave, the window that changed, the point of the mouse (enter only) and if the mouse has entered */
966 typedef void (* RGFW_mouseNotifyfunc)(RGFW_window* win, i32 x, i32 y, RGFW_bool status);
967 /*! @brief RGFW_mousePosChanged, the window that the move happened on, and the new point of the mouse */
968 typedef void (* RGFW_mousePosfunc)(RGFW_window* win, i32 x, i32 y, float vecX, float vecY);
969 /*! @brief RGFW_dataDrag, the window, the point of the drop on the windows */
970 typedef void (* RGFW_dataDragfunc)(RGFW_window* win, i32 x, i32 y);
971 /*! @brief RGFW_windowRefresh, the window that needs to be refreshed */
972 typedef void (* RGFW_windowRefreshfunc)(RGFW_window* win);
973 /*! @brief RGFW_keyChar, the window that got the event, the unicode key value */
974 typedef void (* RGFW_keyCharfunc)(RGFW_window* win, u32 codepoint);
975 /*! @brief RGFW_mouseButtonPressed / RGFW_mouseButtonReleased, the window that got the event, the button that was pressed, the scroll value, if it was a press (else it's a release) */
976
977 /*! @brief RGFW_keyPressed / RGFW_keyReleased, the window that got the event, the mapped key, the physical key, the string version, the state of the mod keys, if it was a press (else it's a release) */
978 typedef void (* RGFW_keyfunc)(RGFW_window* win, u8 key, RGFW_keymod mod, RGFW_bool repeat, RGFW_bool pressed);
979 /*! @brief RGFW_mouseButtonPressed / RGFW_mouseButtonReleased, the window that got the event, the button that was pressed, the scroll value, if it was a press (else it's a release) */
980 typedef void (* RGFW_mouseButtonfunc)(RGFW_window* win, RGFW_mouseButton button, RGFW_bool pressed);
981 /*! @brief RGFW_mouseScroll, the window that got the event, the x scroll value, the y scroll value */
982 typedef void (* RGFW_mouseScrollfunc)(RGFW_window* win, float x, float y);
983 /*! @brief RGFW_dataDrop the window that had the drop, the drop data and the number of files dropped */
984 typedef void (* RGFW_dataDropfunc)(RGFW_window* win, char** files, size_t count);
985 /*! @brief RGFW_scaleUpdated, the window the event was sent to, content scaleX, content scaleY */
986 typedef void (* RGFW_scaleUpdatedfunc)(RGFW_window* win, float scaleX, float scaleY);
987 /*! @brief RGFW_monitorConnected / RGFW_monitorDisconnected, there was a monitor connected/disconnected */
988 typedef void (* RGFW_monitorfunc)(RGFW_window* win, const RGFW_monitor* monitor, RGFW_bool connected);
989
990 /*! @brief function pointer equivalent of void* */
991 typedef void (*RGFW_proc)(void);
992
993 #if defined(RGFW_OPENGL)
994
995 /*! @brief abstract structure for interfacing with the underlying OpenGL API */
996 typedef struct RGFW_glContext RGFW_glContext;
997
998 /*! @brief abstract structure for interfacing with the underlying EGL API */
999 typedef struct RGFW_eglContext RGFW_eglContext;
1000
1001 /*! values for the releaseBehavior hint */
1002 typedef RGFW_ENUM(i32, RGFW_glReleaseBehavior) {
1003 RGFW_glReleaseFlush = 0, /*!< flush the pipeline will be flushed when the context is release */
1004 RGFW_glReleaseNone /*!< do nothing on release */
1005 };
1006
1007 /*! values for the profile hint */
1008 typedef RGFW_ENUM(i32, RGFW_glProfile) {
1009 RGFW_glCore = 0, /*!< the core OpenGL version, e.g. just support for that version */
1010 RGFW_glForwardCompatibility, /*!< only compatibility for newer versions of OpenGL as well as the requested version */
1011 RGFW_glCompatibility, /*!< allow compatibility for older versions of OpenGL as well as the requested version */
1012 RGFW_glES /*!< use OpenGL ES */
1013 };
1014
1015 /*! values for the renderer hint */
1016 typedef RGFW_ENUM(i32, RGFW_glRenderer) {
1017 RGFW_glAccelerated = 0, /*!< hardware accelerated (GPU) */
1018 RGFW_glSoftware /*!< software rendered (CPU) */
1019 };
1020
1021 /*! OpenGL initalization hints */
1022 typedef struct RGFW_glHints {
1023 i32 stencil; /*!< set stencil buffer bit size (0 by default) */
1024 i32 samples; /*!< set number of sample buffers (0 by default) */
1025 i32 stereo; /*!< hint the context to use stereoscopic frame buffers for 3D (false by default) */
1026 i32 auxBuffers; /*!< number of aux buffers (0 by default) */
1027 i32 doubleBuffer; /*!< request double buffering (true by default) */
1028 i32 red, green, blue, alpha; /*!< set color bit sizes (all 8 by default) */
1029 i32 depth; /*!< set depth buffer bit size (24 by default) */
1030 i32 accumRed, accumGreen, accumBlue, accumAlpha; /*!< set accumulated RGBA bit sizes (all 0 by default) */
1031 RGFW_bool sRGB; /*!< request sRGA format (false by default) */
1032 RGFW_bool robustness; /*!< request a "robust" (as in memory-safe) context (false by default). For more information check the overview section: https://registry.khronos.org/OpenGL/extensions/EXT/EXT_robustness.txt */
1033 RGFW_bool debug; /*!< request OpenGL debugging (false by default). */
1034 RGFW_bool noError; /*!< request no OpenGL errors (false by default). This causes OpenGL errors to be undefined behavior. For more information check the overview section: https://registry.khronos.org/OpenGL/extensions/KHR/KHR_no_error.txt */
1035 RGFW_glReleaseBehavior releaseBehavior; /*!< hint how the OpenGL driver should behave when changing contexts (RGFW_glReleaseNone by default). For more information check the overview section: https://registry.khronos.org/OpenGL/extensions/KHR/KHR_context_flush_control.txt */
1036 RGFW_glProfile profile; /*!< set OpenGL API profile (RGFW_glCore by default) */
1037 i32 major, minor; /*!< set the OpenGL API profile version (by default RGFW_glMajor is 1, RGFW_glMinor is 0) */
1038 RGFW_glContext* share; /*!< Share this OpenGL context with newly created OpenGL contexts; defaults to NULL. */
1039 RGFW_eglContext* shareEGL; /*!< Share this EGL context with newly created OpenGL contexts; defaults to NULL. */
1040 RGFW_glRenderer renderer; /*!< renderer to use e.g. accelerated or software defaults to accelerated */
1041 } RGFW_glHints;
1042
1043 #endif
1044
1045 /**!
1046 * @brief Allocates memory using the allocator defined by RGFW_ALLOC at compile time.
1047 * @param size The size (in bytes) of the memory block to allocate.
1048 * @return A pointer to the allocated memory block.
1049 */
1050 RGFWDEF void* RGFW_alloc(size_t size);
1051
1052 /**!
1053 * @brief Frees memory using the deallocator defined by RGFW_FREE at compile time.
1054 * @param ptr A pointer to the memory block to free.
1055 */
1056 RGFWDEF void RGFW_free(void* ptr);
1057
1058 /**!
1059 * @brief Returns the size (in bytes) of the RGFW_window structure.
1060 * @return The size of the RGFW_window structure.
1061 */
1062 RGFWDEF size_t RGFW_sizeofWindow(void);
1063
1064 /**!
1065 * @brief Returns the size (in bytes) of the RGFW_window_src structure.
1066 * @return The size of the RGFW_window_src structure.
1067 */
1068 RGFWDEF size_t RGFW_sizeofWindowSrc(void);
1069
1070 /**!
1071 * @brief (Unix) Toggles the use of Wayland.
1072 * This is enabled by default when compiled with `RGFW_WAYLAND`.
1073 * If not using `RGFW_WAYLAND`, Wayland functions are not exposed.
1074 * This function can be used to force the use of XWayland.
1075 * @param wayland A boolean value indicating whether to use Wayland (true) or not (false).
1076 */
1077 RGFWDEF void RGFW_useWayland(RGFW_bool wayland);
1078
1079 /**!
1080 * @brief Checks if Wayland is currently being used.
1081 * @return RGFW_TRUE if using Wayland, RGFW_FALSE otherwise.
1082 */
1083 RGFWDEF RGFW_bool RGFW_usingWayland(void);
1084
1085 /**!
1086 * @brief Retrieves the current Cocoa layer (macOS only).
1087 * @return A pointer to the Cocoa layer, or NULL if the platform is not in use.
1088 */
1089 RGFWDEF void* RGFW_getLayer_OSX(void);
1090
1091 /**!
1092 * @brief Retrieves the current X11 display connection.
1093 * @return A pointer to the X11 display, or NULL if the platform is not in use.
1094 */
1095 RGFWDEF void* RGFW_getDisplay_X11(void);
1096
1097 /**!
1098 * @brief Retrieves the current Wayland display connection.
1099 * @return A pointer to the Wayland display (`struct wl_display*`), or NULL if the platform is not in use.
1100 */
1101 RGFWDEF struct wl_display* RGFW_getDisplay_Wayland(void);
1102
1103 /**!
1104 * @brief Sets the class name for X11 and WinAPI windows.
1105 * Windows with the same class name will be grouped by the window manager.
1106 * By default, the class name matches the root window’s name.
1107 * @param name The class name to assign.
1108 */
1109 RGFWDEF void RGFW_setClassName(const char* name);
1110
1111 /**!
1112 * @brief Sets the X11 instance name.
1113 * By default, the window name will be used as the instance name.
1114 * @param name The X11 instance name to set.
1115 */
1116 RGFWDEF void RGFW_setXInstName(const char* name);
1117
1118 /**!
1119 * @brief (macOS only) Changes the current working directory to the application’s resource folder.
1120 */
1121 RGFWDEF void RGFW_moveToMacOSResourceDir(void);
1122
1123 /*! copy image to another image, respecting each image's format */
1124 RGFWDEF void RGFW_copyImageData(u8* dest_data, i32 w, i32 h, RGFW_format dest_format, u8* src_data, RGFW_format src_format, RGFW_convertImageDataFunc func);
1125
1126 /**!
1127 * @brief Returns the size (in bytes) of the RGFW_nativeImage structure.
1128 * @return The size of the RGFW_nativeImage structure.
1129 */
1130 RGFWDEF size_t RGFW_sizeofNativeImage(void);
1131
1132 /**!
1133 * @brief Returns the size (in bytes) of the RGFW_surface structure.
1134 * @return The size of the RGFW_surface structure.
1135 */
1136 RGFWDEF size_t RGFW_sizeofSurface(void);
1137
1138 /**!
1139 * @brief Returns the native format type for the system
1140 * @return the native format type for the system as a RGFW_format enum value
1141 */
1142 RGFWDEF RGFW_format RGFW_nativeFormat(void);
1143
1144 /**!
1145 * @brief Creates a new surface from raw pixel data.
1146 * @param data A pointer to the pixel data buffer.
1147 * @param w The width of the surface in pixels.
1148 * @param h The height of the surface in pixels.
1149 * @param format The pixel format of the data.
1150 * @return A pointer to the newly created RGFW_surface.
1151 *
1152 * NOTE: when you create a surface using RGFW_createSurface / ptr, on X11 it uses the root window's visual
1153 * this means it may fail to render on any other window if the visual does not match
1154 * RGFW_window_createSurface and RGFW_window_createSurfacePtr exist only for X11 to address this issues
1155 * Of course, you can also manually set the root window with RGFW_setRootWindow
1156 */
1157 RGFWDEF RGFW_surface* RGFW_createSurface(u8* data, i32 w, i32 h, RGFW_format format);
1158
1159 /**!
1160 * @brief Creates a surface using a pre-allocated RGFW_surface structure.
1161 * @param data A pointer to the pixel data buffer.
1162 * @param w The width of the surface in pixels.
1163 * @param h The height of the surface in pixels.
1164 * @param format The pixel format of the data.
1165 * @param surface A pointer to a pre-allocated RGFW_surface structure.
1166 * @return RGFW_TRUE if successful, RGFW_FALSE otherwise.
1167 */
1168 RGFWDEF RGFW_bool RGFW_createSurfacePtr(u8* data, i32 w, i32 h, RGFW_format format, RGFW_surface* surface);
1169
1170 /**!
1171 * @brief Retrieves the native image associated with a surface.
1172 * @param surface A pointer to the RGFW_surface.
1173 * @return A pointer to the native RGFW_nativeImage associated with the surface.
1174 */
1175 RGFWDEF RGFW_nativeImage* RGFW_surface_getNativeImage(RGFW_surface* surface);
1176
1177 /**!
1178 * @brief Frees the surface pointer and any buffers used for software rendering.
1179 * @param surface A pointer to the RGFW_surface to free.
1180 */
1181 RGFWDEF void RGFW_surface_free(RGFW_surface* surface);
1182
1183 /**!
1184 * @brief Frees only the internal buffers used for software rendering, leaving the surface struct intact.
1185 * @param surface A pointer to the RGFW_surface whose buffers should be freed.
1186 */
1187 RGFWDEF void RGFW_surface_freePtr(RGFW_surface* surface);
1188
1189
1190 /**!
1191 * @brief Loads a mouse icon from bitmap data (similar to RGFW_window_setIcon).
1192 * @param data A pointer to the bitmap pixel data.
1193 * @param w The width of the mouse icon in pixels.
1194 * @param h The height of the mouse icon in pixels.
1195 * @param format The pixel format of the data.
1196 * @return A pointer to the newly loaded RGFW_mouse structure.
1197 *
1198 * @note The icon is not resized by default.
1199 */
1200 RGFWDEF RGFW_mouse* RGFW_loadMouse(u8* data, i32 w, i32 h, RGFW_format format);
1201
1202 /**!
1203 * @brief Frees the data associated with an RGFW_mouse structure.
1204 * @param mouse A pointer to the RGFW_mouse to free.
1205 */
1206 RGFWDEF void RGFW_freeMouse(RGFW_mouse* mouse);
1207
1208 /**!
1209 * @brief Get an allocated array of the supported modes of a monitor
1210 * @param monitor the source monitor object
1211 * @param count [OUTPUT] the count of the array
1212 * @return the allocated array of supported modes
1213 */
1214 RGFWDEF RGFW_monitorMode* RGFW_monitor_getModes(RGFW_monitor* monitor, size_t* count);
1215
1216 /**!
1217 * @brief Free RGFW allocated modes array
1218 * @param monitor the source monitor object
1219 * @param modes a pointer to an allocated array of modes
1220 */
1221 RGFWDEF void RGFW_freeModes(RGFW_monitorMode* modes);
1222
1223 /**!
1224 * @brief Get the supported modes of a monitor using a pre-allocated array
1225 * @param monitor the source monitor object
1226 * @param modes [OUTPUT] a pointer to an allocated array of modes
1227 * @return the number of (possible) modes, if [modes == NULL] the possible nodes *may* be less than the actual modes
1228 */
1229 RGFWDEF size_t RGFW_monitor_getModesPtr(RGFW_monitor* monitor, RGFW_monitorMode** modes);
1230
1231 /**!
1232 * @brief find the closest monitor mode based on the give mode with size being the highest priority, format being the second and refreshrate being the third.
1233 * @param monitor the source monitor object
1234 * @param mode user filled mode to use for comparison
1235 * @param modes [OUTPUT] a pointer to be filled with the output closest monitor
1236 * @return returns true if a suitable monitor was found and false if no suitable monitor was found at all
1237 */
1238
1239 RGFWDEF RGFW_bool RGFW_monitor_findClosestMode(RGFW_monitor* monitor, RGFW_monitorMode* mode, RGFW_monitorMode* closest);
1240
1241 /**!
1242 * @brief Get the allocated gamma ramp
1243 * @param monitor the source monitor object
1244 */
1245 RGFWDEF RGFW_gammaRamp* RGFW_monitor_getGammaRamp(RGFW_monitor* monitor);
1246
1247 /**!
1248 * @brief Free the gamma ramp allocated by RGFW
1249 * @param allocated gamma ramp
1250 */
1251 RGFWDEF void RGFW_freeGammaRamp(RGFW_gammaRamp* ramp);
1252
1253 /**!
1254 * @brief Get the monitor's gamma ramp using a pre-allocated struct with allocated data
1255 * @param monitor the source monitor object
1256 * @param ramp [OUTPUT] a pointer to an allocated gamma ramp (can be NULL to just get the count)
1257 * @return the count of the gamma ramp
1258 */
1259 RGFWDEF size_t RGFW_monitor_getGammaRampPtr(RGFW_monitor* monitor, RGFW_gammaRamp* ramp);
1260
1261 /**!
1262 * @brief Set the monitor's gamma ramp using a pre-allocated struct with allocated data
1263 * @param monitor the source monitor object
1264 * @param ramp a pointer to an allocated gamma ramp
1265 * @return a bool if the function was successful
1266 */
1267 RGFWDEF RGFW_bool RGFW_monitor_setGammaRamp(RGFW_monitor* monitor, RGFW_gammaRamp* ramp);
1268
1269 /**!
1270 * @brief Create and set the monitor's gamma ramp with a base gamma exponent
1271 * @param monitor the source monitor object
1272 * @param the gamma exponent
1273 * @return a bool if the function was successful
1274 */
1275 RGFWDEF RGFW_bool RGFW_monitor_setGamma(RGFW_monitor* monitor, float gamma);
1276
1277 /**!
1278 * @brief Create and set the monitor's gamma ramp with a base gamma exponent using a pre-allocated array
1279 * @param monitor the source monitor object
1280 * @param gamma the gamma exponent
1281 * @param pre-allocated gammaramp channel
1282 * @param count the length of the allocated channel array
1283 * @return a bool if the function was successful
1284 */
1285 RGFWDEF RGFW_bool RGFW_monitor_setGammaPtr(RGFW_monitor* monitor, float gamma, u16* ptr, size_t count);
1286
1287 /**!
1288 * @brief Get the workarea of a monitor, meaning the parts not occupied by OS graphics (i.e. the taskbar)
1289 * @param monitor the source monitor object
1290 * @param x [OUTPUT] the x pos of the workarea
1291 * @param y [OUTPUT] the y pos of the workarea
1292 * @param w [OUTPUT] the width of the workarea
1293 * @param h [OUTPUT] the height of the workarea
1294 * @return a bool if the function was successful
1295 */
1296 RGFWDEF RGFW_bool RGFW_monitor_getWorkarea(RGFW_monitor* monitor, i32* x, i32* y, i32* width, i32* height);
1297
1298 /**!
1299 * @brief Get the position of a monitor (the same as monitor.x / monitor.y)
1300 * @param x [OUTPUT] the x position of the monitor
1301 * @param y [OUTPUT] the y position of the monitor
1302 * @return a bool if the function was successful
1303 */
1304 RGFWDEF RGFW_bool RGFW_monitor_getPosition(RGFW_monitor* monitor, i32* x, i32* y);
1305
1306 /**!
1307 * @brief Get the name of a monitor (the same as monitor.name)
1308 * @return the cstring of the monitor's name
1309 */
1310 RGFWDEF const char* RGFW_monitor_getName(RGFW_monitor* monitor);
1311
1312 /**!
1313 * @brief Get the scale of a monitor (the same as monitor.scaleX / monitor.scaleY)
1314 * @param monitor the source monitor object
1315 * @param x [OUTPUT] the x scale of the monitor
1316 * @param y [OUTPUT] the y scale of the monitor
1317 * @return a bool if the function was successful
1318 */
1319 RGFWDEF RGFW_bool RGFW_monitor_getScale(RGFW_monitor* monitor, float* x, float* y);
1320
1321 /**!
1322 * @brief Get the physical size of a monitor (the same as monitor.physW / monitor.physH)
1323 * @param monitor the source monitor object
1324 * @param w [OUTPUT] the physical width of the monitor
1325 * @param h [OUTPUT] the physical height of the monitor
1326 * @return a bool if the function was successful
1327 */
1328 RGFWDEF RGFW_bool RGFW_monitor_getPhysicalSize(RGFW_monitor* monitor, float* w, float* h);
1329
1330 /**!
1331 * @brief Set the user pointer of a monitor (the same as monitor.userPtr = userPtr)
1332 * @param monitor the source monitor object
1333 * @param userPtr the new user pointer for the monitor
1334 */
1335 RGFWDEF void RGFW_monitor_setUserPtr(RGFW_monitor* monitor, void* userPtr);
1336
1337 /**!
1338 * @brief Get the user pointer of a monitor (the same as monitor.userPtr)
1339 * @param monitor the source monitor object
1340 * @return the user pointer of the monitor
1341 */
1342 RGFWDEF void* RGFW_monitor_getUserPtr(RGFW_monitor* monitor);
1343
1344 /**!
1345 * @brief Get the mode of a monitor (the same as monitor.mode)
1346 * @param monitor the source monitor object
1347 * @param mode [OUTPUT] current mode the monitor
1348 * @return a bool if the function was successful
1349 */
1350 RGFWDEF RGFW_bool RGFW_monitor_getMode(RGFW_monitor* monitor, RGFW_monitorMode* mode);
1351
1352 /**!
1353 * @brief Poll and check for monitor updates (this is called internally on monitor update events and RGFW_init)
1354 */
1355 RGFWDEF void RGFW_pollMonitors(void);
1356
1357 /**!
1358 * @brief Retrieves an array of all available monitors.
1359 * @param len [OUTPUT] A pointer to store the number of monitors found (maximum of RGFW_MAX_MONITORS [6 by default]).
1360 * @return An array of pointers to RGFW_monitor structures.
1361 */
1362 RGFWDEF RGFW_monitor** RGFW_getMonitors(size_t* len);
1363
1364 /**!
1365 * @brief Retrieves the primary monitor.
1366 * @return A pointer to the RGFW_monitor structure representing the primary monitor.
1367 */
1368 RGFWDEF RGFW_monitor* RGFW_getPrimaryMonitor(void);
1369
1370 /**!
1371 * @brief Requests the display mode for a monitor (based on what attributes are directly requested).
1372 * @param mon The monitor to apply the mode change to.
1373 * @param mode The desired RGFW_monitorMode.
1374 * @param request The RGFW_modeRequest describing how to handle the mode change.
1375 * @return RGFW_TRUE if the mode was successfully applied, otherwise RGFW_FALSE.
1376 */
1377 RGFWDEF RGFW_bool RGFW_monitor_requestMode(RGFW_monitor* mon, RGFW_monitorMode* mode, RGFW_modeRequest request);
1378
1379 /**!
1380 * @brief Sets a specific display mode for a monitor directly.
1381 * @param mon The monitor to apply the mode change to.
1382 * @param mode The desired RGFW_monitorMode.
1383 * @param request The RGFW_modeRequest describing how to handle the mode change.
1384 * @return RGFW_TRUE if the mode was successfully applied, otherwise RGFW_FALSE.
1385 */
1386 RGFWDEF RGFW_bool RGFW_monitor_setMode(RGFW_monitor* mon, RGFW_monitorMode* mode);
1387
1388 /**!
1389 * @brief Compares two monitor modes to check if they are equivalent.
1390 * @param mon The first monitor mode.
1391 * @param mon2 The second monitor mode.
1392 * @param request The RGFW_modeRequest that defines the comparison parameters.
1393 * @return RGFW_TRUE if both modes are equivalent, otherwise RGFW_FALSE.
1394 */
1395 RGFWDEF RGFW_bool RGFW_monitorModeCompare(RGFW_monitorMode* mon, RGFW_monitorMode* mon2, RGFW_modeRequest request);
1396
1397 /**!
1398 * @brief Scales a monitor’s mode to match a window’s size.
1399 * @param mon The monitor to be scaled.
1400 * @param win The window whose size should be used as a reference.
1401 * @return RGFW_TRUE if the scaling was successful, otherwise RGFW_FALSE.
1402 */
1403 RGFWDEF RGFW_bool RGFW_monitor_scaleToWindow(RGFW_monitor* mon, struct RGFW_window* win);
1404
1405 /**!
1406 * @brief set (enable or disable) raw mouse mode globally
1407 * @param the boolean state of raw mouse mode
1408 *
1409 */
1410 RGFWDEF void RGFW_setRawMouseMode(RGFW_bool state);
1411
1412 /**!
1413 * @brief sleep until RGFW gets an event or the timer ends (defined by OS)
1414 * @param waitMS how long to wait for the next event (in miliseconds)
1415 */
1416 RGFWDEF void RGFW_waitForEvent(i32 waitMS);
1417
1418 /**!
1419 * @brief Set if events should be queued or not (enabled by default if the event queue is checked)
1420 * @param queue boolean value if RGFW should queue events or not
1421 */
1422 RGFWDEF void RGFW_setQueueEvents(RGFW_bool queue);
1423
1424 /**!
1425 * @brief check all the events until there are none left and updates window structure attributes
1426 */
1427 RGFWDEF void RGFW_pollEvents(void);
1428
1429 /**!
1430 * @brief check all the events until there are none left and updates window structure attributes
1431 * queues events if the queue is checked and/or requested
1432 */
1433 RGFWDEF void RGFW_stopCheckEvents(void);
1434
1435 /**!
1436 * @brief polls and pops the next event
1437 * @param event [OUTPUT] a pointer to store the retrieved event
1438 * @return RGFW_TRUE if an event was found, RGFW_FALSE otherwise
1439 *
1440 * NOTE: Using this function without a loop may cause event lag.
1441 * For multi-threaded systems, use RGFW_pollEvents combined with RGFW_checkQueuedEvent.
1442 *
1443 * Example:
1444 * RGFW_event event;
1445 * while (RGFW_checkEvent(win, &event)) {
1446 * // handle event
1447 * }
1448 */
1449 RGFWDEF RGFW_bool RGFW_checkEvent(RGFW_event* event);
1450
1451 /**!
1452 * @brief pops the first queued event
1453 * @param event [OUTPUT] a pointer to store the retrieved event
1454 * @return RGFW_TRUE if an event was found, RGFW_FALSE otherwise
1455 */
1456 RGFWDEF RGFW_bool RGFW_checkQueuedEvent(RGFW_event* event);
1457
1458 /** * @defgroup Input
1459 * @{ */
1460
1461 /**!
1462 * @brief returns true if the key is pressed during the current frame
1463 * @param key the key code of the key you want to check
1464 * @return The boolean value if the key is pressed or not
1465 */
1466 RGFWDEF RGFW_bool RGFW_isKeyPressed(RGFW_key key);
1467
1468 /**!
1469 * @brief returns true if the key was released during the current frame
1470 * @param key the key code of the key you want to check
1471 * @return The boolean value if the key is released or not
1472 */
1473 RGFWDEF RGFW_bool RGFW_isKeyReleased(RGFW_key key);
1474
1475 /**!
1476 * @brief returns true if the key is down
1477 * @param key the key code of the key you want to check
1478 * @return The boolean value if the key is down or not
1479 */
1480 RGFWDEF RGFW_bool RGFW_isKeyDown(RGFW_key key);
1481
1482 /**!
1483 * @brief returns true if the mouse button is pressed during the current frame
1484 * @param button the mouse button code of the button you want to check
1485 * @return The boolean value if the button is pressed or not
1486 */
1487 RGFWDEF RGFW_bool RGFW_isMousePressed(RGFW_mouseButton button);
1488
1489 /**!
1490 * @brief returns true if the mouse button is released during the current frame
1491 * @param button the mouse button code of the button you want to check
1492 * @return The boolean value if the button is released or not
1493 */
1494 RGFWDEF RGFW_bool RGFW_isMouseReleased(RGFW_mouseButton button);
1495
1496 /**!
1497 * @brief returns true if the mouse button is down
1498 * @param button the mouse button code of the button you want to check
1499 * @return The boolean value if the button is down or not
1500 */
1501 RGFWDEF RGFW_bool RGFW_isMouseDown(RGFW_mouseButton button);
1502
1503 /**!
1504 * @brief outputs the current x, y position of the mouse
1505 * @param X [OUTPUT] a pointer for the output X value
1506 * @param Y [OUTPUT] a pointer for the output Y value
1507 */
1508 RGFWDEF void RGFW_getMouseScroll(float* x, float* y);
1509
1510 /**!
1511 * @brief outputs the current x, y movement vector of the mouse
1512 * @param X [OUTPUT] a pointer for the output X vector value
1513 * @param Y [OUTPUT] a pointer for the output Y vector value
1514 */
1515 RGFWDEF void RGFW_getMouseVector(float* x, float* y);
1516 /** @} */
1517
1518 /**!
1519 * @brief creates a new window
1520 * @param name the requested title of the window
1521 * @param x the requested x position of the window
1522 * @param y the requested y position of the window
1523 * @param w the requested width of the window
1524 * @param h the requested height of the window
1525 * @param flags extra arguments ((u32)0 means no flags used)
1526 * @return A pointer to the newly created window structure
1527 *
1528 * NOTE: (windows) if the executable has an icon resource named RGFW_ICON, it will be set as the initial icon for the window
1529 */
1530 RGFWDEF RGFW_window* RGFW_createWindow(const char* name, i32 x, i32 y, i32 w, i32 h, RGFW_windowFlags flags);
1531
1532 /**!
1533 * @brief creates a new window using a pre-allocated window structure
1534 * @param name the requested title of the window
1535 * @param x the requested x position of the window
1536 * @param y the requested y position of the window
1537 * @param w the requested width of the window
1538 * @param h the requested height of the window
1539 * @param flags extra arguments ((u32)0 means no flags used)
1540 * @param win a pointer the pre-allocated window structure
1541 * @return A pointer to the newly created window structure
1542 */
1543 RGFWDEF RGFW_window* RGFW_createWindowPtr(const char* name, i32 x, i32 y, i32 w, i32 h, RGFW_windowFlags flags, RGFW_window* win);
1544
1545 /**!
1546 * @brief creates a new surface structure
1547 * @param win the source window of the surface
1548 * @param data a pointer to the raw data of the structure (you allocate this)
1549 * @param w the width the data
1550 * @param h the height of the data
1551 * @return A pointer to the newly created surface structure
1552 *
1553 * NOTE: when you create a surface using RGFW_createSurface / ptr, on X11 it uses the root window's visual
1554 * this means it may fail to render on any other window if the visual does not match
1555 * RGFW_window_createSurface and RGFW_window_createSurfacePtr exist only for X11 to address this issues
1556 * Of course, you can also manually set the root window with RGFW_setRootWindow
1557 */
1558 RGFWDEF RGFW_surface* RGFW_window_createSurface(RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format);
1559
1560 /**!
1561 * @brief creates a new surface structure using a pre-allocated surface structure
1562 * @param win the source window of the surface
1563 * @param data a pointer to the raw data of the structure (you allocate this)
1564 * @param w the width the data
1565 * @param h the height of the data
1566 * @param a pointer to the pre-allocated surface structure
1567 * @return a bool if the creation was successful or not
1568 */
1569 RGFWDEF RGFW_bool RGFW_window_createSurfacePtr(RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format, RGFW_surface* surface);
1570
1571 /**!
1572 * @brief set the function/callback used for converting surface data between formats
1573 * @param surface a pointer to the surface
1574 * @param a function pointer for the function to use [if NULL the default function is used]
1575 */
1576 RGFWDEF void RGFW_surface_setConvertFunc(RGFW_surface* surface, RGFW_convertImageDataFunc func);
1577
1578 /**!
1579 * @brief blits a surface stucture to the window
1580 * @param win a pointer the window to blit to
1581 * @param surface a pointer to the surface
1582 */
1583 RGFWDEF void RGFW_window_blitSurface(RGFW_window* win, RGFW_surface* surface);
1584
1585 /**!
1586 * @brief gets the position of the window | with RGFW_window.x and window.y
1587 * @param x [OUTPUT] the x position of the window
1588 * @param y [OUTPUT] the y position of the window
1589 * @return a bool if the function was successful
1590 */
1591 RGFWDEF RGFW_bool RGFW_window_getPosition(RGFW_window* win, i32* x, i32* y); /*!< */
1592
1593 /**!
1594 * @brief gets the size of the window | with RGFW_window.w and window.h
1595 * @param win a pointer to the window
1596 * @param w [OUTPUT] the width of the window
1597 * @param h [OUTPUT] the height of the window
1598 * @return a bool if the function was successful
1599 */
1600 RGFWDEF RGFW_bool RGFW_window_getSize(RGFW_window* win, i32* w, i32* h);
1601
1602 /**!
1603 * @brief gets the size of the window in exact pixels
1604 * @param win a pointer to the window
1605 * @param w [OUTPUT] the width of the window
1606 * @param h [OUTPUT] the height of the window
1607 * @return a bool if the function was successful
1608 */
1609 RGFWDEF RGFW_bool RGFW_window_getSizeInPixels(RGFW_window* win, i32* w, i32* h);
1610
1611 /**!
1612 * @brief gets the flags of the window | returns RGFW_window._flags
1613 * @param win a pointer to the window
1614 * @return the window flags
1615 */
1616 RGFWDEF u32 RGFW_window_getFlags(RGFW_window* win);
1617
1618 /**!
1619 * @brief returns the exit key assigned to the window
1620 * @param win a pointer to the target window
1621 * @return The key code assigned as the exit key
1622 */
1623 RGFWDEF RGFW_key RGFW_window_getExitKey(RGFW_window* win);
1624
1625 /**!
1626 * @brief sets the exit key for the window
1627 * @param win a pointer to the target window
1628 * @param key the key code to assign as the exit key
1629 */
1630 RGFWDEF void RGFW_window_setExitKey(RGFW_window* win, RGFW_key key);
1631
1632 /**!
1633 * @brief sets the types of events you want the window to receive
1634 * @param win a pointer to the target window
1635 * @param events the event flags to enable (use RGFW_allEventFlags for all)
1636 */
1637 RGFWDEF void RGFW_window_setEnabledEvents(RGFW_window* win, RGFW_eventFlag events);
1638
1639 /**!
1640 * @brief gets the currently enabled events for the window
1641 * @param win a pointer to the target window
1642 * @return The enabled event flags for the window
1643 */
1644 RGFWDEF RGFW_eventFlag RGFW_window_getEnabledEvents(RGFW_window* win);
1645
1646 /**!
1647 * @brief enables all events and disables selected ones
1648 * @param win a pointer to the target window
1649 * @param events the event flags to disable
1650 */
1651 RGFWDEF void RGFW_window_setDisabledEvents(RGFW_window* win, RGFW_eventFlag events);
1652
1653 /**!
1654 * @brief directly enables or disables a specific event or group of events
1655 * @param win a pointer to the target window
1656 * @param event the event flag or group of flags to modify
1657 * @param state RGFW_TRUE to enable, RGFW_FALSE to disable
1658 */
1659 RGFWDEF void RGFW_window_setEventState(RGFW_window* win, RGFW_eventFlag event, RGFW_bool state);
1660
1661 /**!
1662 * @brief gets the user pointer associated with the window
1663 * @param win a pointer to the target window
1664 * @return The user-defined pointer stored in the window
1665 */
1666 RGFWDEF void* RGFW_window_getUserPtr(RGFW_window* win);
1667
1668 /**!
1669 * @brief sets a user pointer for the window
1670 * @param win a pointer to the target window
1671 * @param ptr a pointer to associate with the window
1672 */
1673 RGFWDEF void RGFW_window_setUserPtr(RGFW_window* win, void* ptr);
1674
1675 /**!
1676 * @brief retrieves the platform-specific window source pointer
1677 * @param win a pointer to the target window
1678 * @return A pointer to the internal RGFW_window_src structure
1679 */
1680 RGFWDEF RGFW_window_src* RGFW_window_getSrc(RGFW_window* win);
1681
1682 /**!
1683 * @brief sets the macOS layer object associated with the window
1684 * @param win a pointer to the target window
1685 * @param layer a pointer to the macOS layer object
1686 * @note Only available on macOS platforms
1687 */
1688 RGFWDEF void RGFW_window_setLayer_OSX(RGFW_window* win, void* layer);
1689
1690 /**!
1691 * @brief retrieves the macOS view object associated with the window
1692 * @param win a pointer to the target window
1693 * @return A pointer to the macOS view object, or NULL if not on macOS
1694 */
1695 RGFWDEF void* RGFW_window_getView_OSX(RGFW_window* win);
1696
1697 /**!
1698 * @brief retrieves the macOS window object
1699 * @param win a pointer to the target window
1700 * @return A pointer to the macOS window object, or NULL if not on macOS
1701 */
1702 RGFWDEF void* RGFW_window_getWindow_OSX(RGFW_window* win);
1703
1704 /**!
1705 * @brief retrieves the HWND handle for the window
1706 * @param win a pointer to the target window
1707 * @return A pointer to the Windows HWND handle, or NULL if not on Windows
1708 */
1709 RGFWDEF void* RGFW_window_getHWND(RGFW_window* win);
1710
1711 /**!
1712 * @brief retrieves the HDC handle for the window
1713 * @param win a pointer to the target window
1714 * @return A pointer to the Windows HDC handle, or NULL if not on Windows
1715 */
1716 RGFWDEF void* RGFW_window_getHDC(RGFW_window* win);
1717
1718 /**!
1719 * @brief retrieves the X11 Window handle for the window
1720 * @param win a pointer to the target window
1721 * @return The X11 Window handle, or 0 if not on X11
1722 */
1723 RGFWDEF u64 RGFW_window_getWindow_X11(RGFW_window* win);
1724
1725 /**!
1726 * @brief retrieves the Wayland surface handle for the window
1727 * @param win a pointer to the target window
1728 * @return A pointer to the Wayland wl_surface, or NULL if not on Wayland
1729 */
1730 RGFWDEF struct wl_surface* RGFW_window_getWindow_Wayland(RGFW_window* win);
1731
1732 /** * @defgroup Window_management
1733 * @{ */
1734
1735 /*! set the window flags (will undo flags if they don't match the old ones) */
1736 RGFWDEF void RGFW_window_setFlags(RGFW_window* win, RGFW_windowFlags);
1737
1738 /**!
1739 * @brief polls and pops the next event with the matching target window in event queue, pushes back events that don't match
1740 * @param win a pointer to the target window
1741 * @param event [OUTPUT] a pointer to store the retrieved event
1742 * @return RGFW_TRUE if an event was found, RGFW_FALSE otherwise
1743 *
1744 * NOTE: Using this function without a loop may cause event lag.
1745 * For multi-threaded systems, use RGFW_pollEvents combined with RGFW_window_checkQueuedEvent.
1746 *
1747 * Example:
1748 * RGFW_event event;
1749 * while (RGFW_window_checkEvent(win, &event)) {
1750 * // handle event
1751 * }
1752 */
1753 RGFWDEF RGFW_bool RGFW_window_checkEvent(RGFW_window* win, RGFW_event* event);
1754
1755 /**!
1756 * @brief pops the first queued event with the matching target window, pushes back events that don't match
1757 * @param win a pointer to the target window
1758 * @param event [OUTPUT] a pointer to store the retrieved event
1759 * @return RGFW_TRUE if an event was found, RGFW_FALSE otherwise
1760 */
1761 RGFWDEF RGFW_bool RGFW_window_checkQueuedEvent(RGFW_window* win, RGFW_event* event);
1762
1763 /**!
1764 * @brief checks if a key was pressed while the window is in focus
1765 * @param win a pointer to the target window
1766 * @param key the key code to check
1767 * @return RGFW_TRUE if the key was pressed, RGFW_FALSE otherwise
1768 */
1769 RGFWDEF RGFW_bool RGFW_window_isKeyPressed(RGFW_window* win, RGFW_key key);
1770
1771 /**!
1772 * @brief checks if a key is currently being held down
1773 * @param win a pointer to the target window
1774 * @param key the key code to check
1775 * @return RGFW_TRUE if the key is held down, RGFW_FALSE otherwise
1776 */
1777 RGFWDEF RGFW_bool RGFW_window_isKeyDown(RGFW_window* win, RGFW_key key);
1778
1779 /**!
1780 * @brief checks if a key was released
1781 * @param win a pointer to the target window
1782 * @param key the key code to check
1783 * @return RGFW_TRUE if the key was released, RGFW_FALSE otherwise
1784 */
1785 RGFWDEF RGFW_bool RGFW_window_isKeyReleased(RGFW_window* win, RGFW_key key);
1786
1787 /**!
1788 * @brief checks if a mouse button was pressed
1789 * @param win a pointer to the target window
1790 * @param button the mouse button code to check
1791 * @return RGFW_TRUE if the mouse button was pressed, RGFW_FALSE otherwise
1792 */
1793 RGFWDEF RGFW_bool RGFW_window_isMousePressed(RGFW_window* win, RGFW_mouseButton button);
1794
1795 /**!
1796 * @brief checks if a mouse button is currently held down
1797 * @param win a pointer to the target window
1798 * @param button the mouse button code to check
1799 * @return RGFW_TRUE if the mouse button is down, RGFW_FALSE otherwise
1800 */
1801 RGFWDEF RGFW_bool RGFW_window_isMouseDown(RGFW_window* win, RGFW_mouseButton button);
1802
1803 /**!
1804 * @brief checks if a mouse button was released
1805 * @param win a pointer to the target window
1806 * @param button the mouse button code to check
1807 * @return RGFW_TRUE if the mouse button was released, RGFW_FALSE otherwise
1808 */
1809 RGFWDEF RGFW_bool RGFW_window_isMouseReleased(RGFW_window* win, RGFW_mouseButton button);
1810
1811 /**!
1812 * @brief checks if the mouse left the window (true only for the first frame)
1813 * @param win a pointer to the target window
1814 * @return RGFW_TRUE if the mouse left, RGFW_FALSE otherwise
1815 */
1816 RGFWDEF RGFW_bool RGFW_window_didMouseLeave(RGFW_window* win);
1817
1818 /**!
1819 * @brief checks if the mouse entered the window (true only for the first frame)
1820 * @param win a pointer to the target window
1821 * @return RGFW_TRUE if the mouse entered, RGFW_FALSE otherwise
1822 */
1823 RGFWDEF RGFW_bool RGFW_window_didMouseEnter(RGFW_window* win);
1824
1825 /**!
1826 * @brief checks if the mouse is currently inside the window bounds
1827 * @param win a pointer to the target window
1828 * @return RGFW_TRUE if the mouse is inside, RGFW_FALSE otherwise
1829 */
1830 RGFWDEF RGFW_bool RGFW_window_isMouseInside(RGFW_window* win);
1831
1832 /**!
1833 * @brief checks if there is data being dragged into or within the window
1834 * @param win a pointer to the target window
1835 * @return RGFW_TRUE if data is being dragged, RGFW_FALSE otherwise
1836 */
1837 RGFWDEF RGFW_bool RGFW_window_isDataDragging(RGFW_window* win);
1838
1839 /**!
1840 * @brief gets the position of a data drag
1841 * @param win a pointer to the target window
1842 * @param x [OUTPUT] pointer to store the x position
1843 * @param y [OUTPUT] pointer to store the y position
1844 * @return RGFW_TRUE if there is an active drag, RGFW_FALSE otherwise
1845 */
1846 RGFWDEF RGFW_bool RGFW_window_getDataDrag(RGFW_window* win, i32* x, i32* y);
1847
1848 /**!
1849 * @brief checks if a data drop occurred in the window (first frame only)
1850 * @param win a pointer to the target window
1851 * @return RGFW_TRUE if data was dropped, RGFW_FALSE otherwise
1852 */
1853 RGFWDEF RGFW_bool RGFW_window_didDataDrop(RGFW_window* win);
1854
1855 /**!
1856 * @brief retrieves files from a data drop (drag and drop)
1857 * @param win a pointer to the target window
1858 * @param files [OUTPUT] a pointer to the array of file paths
1859 * @param count [OUTPUT] the number of dropped files
1860 * @return RGFW_TRUE if a data drop occurred, RGFW_FALSE otherwise
1861 */
1862 RGFWDEF RGFW_bool RGFW_window_getDataDrop(RGFW_window* win, const char*** files, size_t* count);
1863
1864 /**!
1865 * @brief closes the window and frees its associated structure
1866 * @param win a pointer to the target window
1867 */
1868 RGFWDEF void RGFW_window_close(RGFW_window* win);
1869
1870 /**!
1871 * @brief closes the window without freeing its structure
1872 * @param win a pointer to the target window
1873 */
1874 RGFWDEF void RGFW_window_closePtr(RGFW_window* win);
1875
1876 /**!
1877 * @brief moves the window to a new position on the screen
1878 * @param win a pointer to the target window
1879 * @param x the new x position
1880 * @param y the new y position
1881 */
1882 RGFWDEF void RGFW_window_move(RGFW_window* win, i32 x, i32 y);
1883
1884 /**!
1885 * @brief moves the window to a specific monitor
1886 * @param win a pointer to the target window
1887 * @param m the target monitor
1888 */
1889 RGFWDEF void RGFW_window_moveToMonitor(RGFW_window* win, RGFW_monitor* m);
1890
1891 /**!
1892 * @brief resizes the window to the given dimensions
1893 * @param win a pointer to the target window
1894 * @param w the new width
1895 * @param h the new height
1896 */
1897 RGFWDEF void RGFW_window_resize(RGFW_window* win, i32 w, i32 h);
1898
1899 /**!
1900 * @brief sets the aspect ratio of the window
1901 * @param win a pointer to the target window
1902 * @param w the width ratio
1903 * @param h the height ratio
1904 */
1905 RGFWDEF void RGFW_window_setAspectRatio(RGFW_window* win, i32 w, i32 h);
1906
1907 /**!
1908 * @brief sets the minimum size of the window
1909 * @param win a pointer to the target window
1910 * @param w the minimum width
1911 * @param h the minimum height
1912 */
1913 RGFWDEF void RGFW_window_setMinSize(RGFW_window* win, i32 w, i32 h);
1914
1915 /**!
1916 * @brief sets the maximum size of the window
1917 * @param win a pointer to the target window
1918 * @param w the maximum width
1919 * @param h the maximum height
1920 */
1921 RGFWDEF void RGFW_window_setMaxSize(RGFW_window* win, i32 w, i32 h);
1922
1923 /**!
1924 * @brief sets focus to the window
1925 * @param win a pointer to the target window
1926 */
1927 RGFWDEF void RGFW_window_focus(RGFW_window* win);
1928
1929 /**!
1930 * @brief checks if the window is currently in focus
1931 * @param win a pointer to the target window
1932 * @return RGFW_TRUE if the window is in focus, RGFW_FALSE otherwise
1933 */
1934 RGFWDEF RGFW_bool RGFW_window_isInFocus(RGFW_window* win);
1935
1936 /**!
1937 * @brief raises the window to the top of the stack
1938 * @param win a pointer to the target window
1939 */
1940 RGFWDEF void RGFW_window_raise(RGFW_window* win);
1941
1942 /**!
1943 * @brief maximizes the window
1944 * @param win a pointer to the target window
1945 */
1946 RGFWDEF void RGFW_window_maximize(RGFW_window* win);
1947
1948 /**!
1949 * @brief toggles fullscreen mode for the window
1950 * @param win a pointer to the target window
1951 * @param fullscreen RGFW_TRUE to enable fullscreen, RGFW_FALSE to disable
1952 */
1953 RGFWDEF void RGFW_window_setFullscreen(RGFW_window* win, RGFW_bool fullscreen);
1954
1955 /**!
1956 * @brief centers the window on the screen
1957 * @param win a pointer to the target window
1958 */
1959 RGFWDEF void RGFW_window_center(RGFW_window* win);
1960
1961 /**!
1962 * @brief minimizes the window
1963 * @param win a pointer to the target window
1964 */
1965 RGFWDEF void RGFW_window_minimize(RGFW_window* win);
1966
1967 /**!
1968 * @brief restores the window from minimized state
1969 * @param win a pointer to the target window
1970 */
1971 RGFWDEF void RGFW_window_restore(RGFW_window* win);
1972
1973 /**!
1974 * @brief makes the window a floating window
1975 * @param win a pointer to the target window
1976 * @param floating RGFW_TRUE to float, RGFW_FALSE to disable
1977 */
1978 RGFWDEF void RGFW_window_setFloating(RGFW_window* win, RGFW_bool floating);
1979
1980 /**!
1981 * @brief sets the opacity level of the window
1982 * @param win a pointer to the target window
1983 * @param opacity the opacity level (0–255)
1984 */
1985 RGFWDEF void RGFW_window_setOpacity(RGFW_window* win, u8 opacity);
1986
1987 /**!
1988 * @brief toggles window borders
1989 * @param win a pointer to the target window
1990 * @param border RGFW_TRUE for bordered, RGFW_FALSE for borderless
1991 */
1992 RGFWDEF void RGFW_window_setBorder(RGFW_window* win, RGFW_bool border);
1993
1994 /**!
1995 * @brief checks if the window is borderless
1996 * @param win a pointer to the target window
1997 * @return RGFW_TRUE if borderless, RGFW_FALSE otherwise
1998 */
1999 RGFWDEF RGFW_bool RGFW_window_borderless(RGFW_window* win);
2000
2001 /**!
2002 * @brief toggles drag-and-drop (DND) support for the window
2003 * @param win a pointer to the target window
2004 * @param allow RGFW_TRUE to allow DND, RGFW_FALSE to disable
2005 * @note RGFW_windowAllowDND must still be passed when creating the window
2006 */
2007 RGFWDEF void RGFW_window_setDND(RGFW_window* win, RGFW_bool allow);
2008
2009 /**!
2010 * @brief checks if drag-and-drop (DND) is allowed
2011 * @param win a pointer to the target window
2012 * @return RGFW_TRUE if DND is enabled, RGFW_FALSE otherwise
2013 */
2014 RGFWDEF RGFW_bool RGFW_window_allowsDND(RGFW_window* win);
2015
2016 #ifndef RGFW_NO_PASSTHROUGH
2017 /**!
2018 * @brief toggles mouse passthrough for the window
2019 * @param win a pointer to the target window
2020 * @param passthrough RGFW_TRUE to enable passthrough, RGFW_FALSE to disable
2021 */
2022 RGFWDEF void RGFW_window_setMousePassthrough(RGFW_window* win, RGFW_bool passthrough);
2023 #endif
2024
2025 /**!
2026 * @brief renames the window
2027 * @param win a pointer to the target window
2028 * @param name the new title string for the window
2029 */
2030 RGFWDEF void RGFW_window_setName(RGFW_window* win, const char* name);
2031
2032 /**!
2033 * @brief sets the icon for the window and taskbar
2034 * @param win a pointer to the target window
2035 * @param data the image data
2036 * @param w the width of the icon
2037 * @param h the height of the icon
2038 * @param format the image format
2039 * @return RGFW_TRUE if successful, RGFW_FALSE otherwise
2040 *
2041 * NOTE: The image may be resized by default.
2042 */
2043 RGFWDEF RGFW_bool RGFW_window_setIcon(RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format);
2044
2045 /**!
2046 * @brief sets the icon for the window and/or taskbar
2047 * @param win a pointer to the target window
2048 * @param data the image data
2049 * @param w the width of the icon
2050 * @param h the height of the icon
2051 * @param format the image format
2052 * @param type the target icon type (taskbar, window, or both)
2053 * @return RGFW_TRUE if successful, RGFW_FALSE otherwise
2054 */
2055 RGFWDEF RGFW_bool RGFW_window_setIconEx(RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format, RGFW_icon type);
2056
2057 /**!
2058 * @brief sets the mouse icon for the window using a loaded bitmap
2059 * @param win a pointer to the target window
2060 * @param mouse a pointer to the RGFW_mouse struct containing the icon
2061 */
2062 RGFWDEF void RGFW_window_setMouse(RGFW_window* win, RGFW_mouse* mouse);
2063
2064 /**!
2065 * @brief Sets the mouse to a standard system cursor.
2066 * @param win The target window.
2067 * @param mouse The standard cursor type (see RGFW_MOUSE enum).
2068 * @return True if the standard cursor was successfully applied.
2069 */
2070 RGFWDEF RGFW_bool RGFW_window_setMouseStandard(RGFW_window* win, RGFW_mouseIcons mouse);
2071
2072 /**!
2073 * @brief Sets the mouse to the default cursor icon.
2074 * @param win The target window.
2075 * @return True if the default cursor was successfully set.
2076 */
2077 RGFWDEF RGFW_bool RGFW_window_setMouseDefault(RGFW_window* win);
2078
2079 /**!
2080 * @brief set (enable or disable) raw mouse mode only for the select window
2081 * @param win The target window.
2082 * @param the boolean state of raw mouse mode
2083 *
2084 */
2085 RGFWDEF void RGFW_window_setRawMouseMode(RGFW_window* win, RGFW_bool state);
2086
2087 /**!
2088 * @brief lock/unlock the cursor.
2089 * @param win The target window.
2090 * @param the boolean state of the mouse's capture state
2091 *
2092 */
2093 RGFWDEF void RGFW_window_captureMouse(RGFW_window* win, RGFW_bool state);
2094
2095 /**!
2096 * @brief lock/unlock the cursor and enable raw mpuise mode.
2097 * @param win The target window.
2098 * @param the boolean state of raw mouse mode
2099 *
2100 */
2101 RGFWDEF void RGFW_window_captureRawMouse(RGFW_window* win, RGFW_bool state);
2102
2103 /**!
2104 * @brief Returns true if the mouse is using raw mouse mode
2105 * @param win The target window.
2106 * @return True if the mouse is using raw mouse input mode.
2107 */
2108 RGFWDEF RGFW_bool RGFW_window_isRawMouseMode(RGFW_window* win);
2109
2110
2111 /**!
2112 * @brief Returns true if the mouse is captured
2113 * @param win The target window.
2114 * @return True if the mouse is being captured.
2115 */
2116 RGFWDEF RGFW_bool RGFW_window_isCaptured(RGFW_window* win);
2117
2118 /**!
2119 * @brief Hides the window from view.
2120 * @param win The target window.
2121 */
2122 RGFWDEF void RGFW_window_hide(RGFW_window* win);
2123
2124 /**!
2125 * @brief Shows the window if it was hidden.
2126 * @param win The target window.
2127 */
2128 RGFWDEF void RGFW_window_show(RGFW_window* win);
2129
2130 /**!
2131 * @breif request a window flash to get attention from the user
2132 * @param win the target window
2133 * @param request the flash operation requested
2134 */
2135 RGFWDEF void RGFW_window_flash(RGFW_window* win, RGFW_flashRequest request);
2136
2137 /**!
2138 * @brief Sets whether the window should close.
2139 * @param win The target window.
2140 * @param shouldClose True to signal the window should close, false to keep it open.
2141 *
2142 * This can override or trigger the `RGFW_window_shouldClose` state by modifying window flags.
2143 */
2144 RGFWDEF void RGFW_window_setShouldClose(RGFW_window* win, RGFW_bool shouldClose);
2145
2146 /**!
2147 * @brief Retrieves the current global mouse position.
2148 * @param x [OUTPUT] Pointer to store the X position of the mouse on the screen.
2149 * @param y [OUTPUT] Pointer to store the Y position of the mouse on the screen.
2150 * @return True if the position was successfully retrieved.
2151 */
2152 RGFWDEF RGFW_bool RGFW_getGlobalMouse(i32* x, i32* y);
2153
2154 /**!
2155 * @brief Retrieves the mouse position relative to the window.
2156 * @param win The target window.
2157 * @param x [OUTPUT] Pointer to store the X position within the window.
2158 * @param y [OUTPUT] Pointer to store the Y position within the window.
2159 * @return True if the position was successfully retrieved.
2160 */
2161 RGFWDEF RGFW_bool RGFW_window_getMouse(RGFW_window* win, i32* x, i32* y);
2162
2163 /**!
2164 * @brief Shows or hides the mouse cursor for the window.
2165 * @param win The target window.
2166 * @param show True to show the mouse, false to hide it.
2167 */
2168 RGFWDEF void RGFW_window_showMouse(RGFW_window* win, RGFW_bool show);
2169
2170 /**!
2171 * @brief Checks if the mouse is currently hidden in the window.
2172 * @param win The target window.
2173 * @return True if the mouse is hidden.
2174 */
2175 RGFWDEF RGFW_bool RGFW_window_isMouseHidden(RGFW_window* win);
2176
2177 /**!
2178 * @brief Moves the mouse to the specified position within the window.
2179 * @param win The target window.
2180 * @param x The new X position.
2181 * @param y The new Y position.
2182 */
2183 RGFWDEF void RGFW_window_moveMouse(RGFW_window* win, i32 x, i32 y);
2184
2185 /**!
2186 * @brief Checks if the window should close.
2187 * @param win The target window.
2188 * @return True if the window should close (for example, if ESC was pressed or a close event occurred).
2189 */
2190 RGFWDEF RGFW_bool RGFW_window_shouldClose(RGFW_window* win);
2191
2192 /**!
2193 * @brief Checks if the window is currently fullscreen.
2194 * @param win The target window.
2195 * @return True if the window is fullscreen.
2196 */
2197 RGFWDEF RGFW_bool RGFW_window_isFullscreen(RGFW_window* win);
2198
2199 /**!
2200 * @brief Checks if the window is currently hidden.
2201 * @param win The target window.
2202 * @return True if the window is hidden.
2203 */
2204 RGFWDEF RGFW_bool RGFW_window_isHidden(RGFW_window* win);
2205
2206 /**!
2207 * @brief Checks if the window is minimized.
2208 * @param win The target window.
2209 * @return True if the window is minimized.
2210 */
2211 RGFWDEF RGFW_bool RGFW_window_isMinimized(RGFW_window* win);
2212
2213 /**!
2214 * @brief Checks if the window is maximized.
2215 * @param win The target window.
2216 * @return True if the window is maximized.
2217 */
2218 RGFWDEF RGFW_bool RGFW_window_isMaximized(RGFW_window* win);
2219
2220 /**!
2221 * @brief Checks if the window is floating.
2222 * @param win The target window.
2223 * @return True if the window is floating.
2224 */
2225 RGFWDEF RGFW_bool RGFW_window_isFloating(RGFW_window* win);
2226 /** @} */
2227
2228 /** * @defgroup Monitor
2229 * @{ */
2230
2231 /**!
2232 * @brief Scales the window to match its monitor’s resolution.
2233 * @param win The target window.
2234 *
2235 * This function is automatically called when the flag `RGFW_scaleToMonitor`
2236 * is used during window creation.
2237 */
2238 RGFWDEF void RGFW_window_scaleToMonitor(RGFW_window* win);
2239
2240 /**!
2241 * @brief Retrieves the monitor structure associated with the window.
2242 * @param win The target window.
2243 * @return The monitor structure of the window.
2244 */
2245 RGFWDEF RGFW_monitor* RGFW_window_getMonitor(RGFW_window* win);
2246
2247 /** @} */
2248
2249 /** * @defgroup Clipboard
2250 * @{ */
2251
2252 /**!
2253 * @brief Reads clipboard data.
2254 * @param size [OUTPUT] A pointer that will be filled with the size of the clipboard data.
2255 * @return A pointer to the clipboard data as a string.
2256 */
2257 RGFWDEF const char* RGFW_readClipboard(size_t* size);
2258
2259 /**!
2260 * @brief Reads clipboard data into a provided buffer, or returns the required length if str is NULL.
2261 * @param str [OUTPUT] A pointer to the buffer that will receive the clipboard data (or NULL to get required size).
2262 * @param strCapacity The capacity of the provided buffer.
2263 * @return The number of bytes read or required length of clipboard data.
2264 */
2265 RGFWDEF RGFW_ssize_t RGFW_readClipboardPtr(char* str, size_t strCapacity);
2266
2267 /**!
2268 * @brief Writes text to the clipboard.
2269 * @param text The text to be written to the clipboard.
2270 * @param textLen The length of the text being written.
2271 */
2272 RGFWDEF void RGFW_writeClipboard(const char* text, u32 textLen);
2273 /** @} */
2274
2275
2276
2277 /** * @defgroup error handling
2278 * @{ */
2279 /**!
2280 * @brief Sets the callback function to handle debug messages from RGFW.
2281 * @param func The function pointer to be used as the debug callback.
2282 * @return The previously set debug callback function.
2283 */
2284 RGFWDEF RGFW_debugfunc RGFW_setDebugCallback(RGFW_debugfunc func);
2285
2286 /**!
2287 * @brief Sends a debug message manually through the currently set debug callback.
2288 * @param type The type of debug message being sent.
2289 * @param err The associated error code.
2290 * @param msg The debug message text.
2291 */
2292 RGFWDEF void RGFW_sendDebugInfo(RGFW_debugType type, RGFW_errorCode err, const char* msg);
2293 /** @} */
2294
2295 /**
2296
2297
2298 event callbacks.
2299 These are completely optional, so you can use the normal
2300 RGFW_checkEvent() method if you prefer that
2301
2302 * @defgroup Callbacks
2303 * @{
2304 */
2305
2306 /**!
2307 * @brief Sets the callback function for window move events.
2308 * @param func The function to be called when the window is moved.
2309 * @return The previously set callback function, if any.
2310 */
2311 RGFWDEF RGFW_windowMovedfunc RGFW_setWindowMovedCallback(RGFW_windowMovedfunc func);
2312
2313 /**!
2314 * @brief Sets the callback function for window resize events.
2315 * @param func The function to be called when the window is resized.
2316 * @return The previously set callback function, if any.
2317 */
2318 RGFWDEF RGFW_windowResizedfunc RGFW_setWindowResizedCallback(RGFW_windowResizedfunc func);
2319
2320 /**!
2321 * @brief Sets the callback function for window quit events.
2322 * @param func The function to be called when the window receives a quit signal.
2323 * @return The previously set callback function, if any.
2324 */
2325 RGFWDEF RGFW_windowQuitfunc RGFW_setWindowQuitCallback(RGFW_windowQuitfunc func);
2326
2327 /**!
2328 * @brief Sets the callback function for mouse move events.
2329 * @param func The function to be called when the mouse moves within the window.
2330 * @return The previously set callback function, if any.
2331 */
2332 RGFWDEF RGFW_mousePosfunc RGFW_setMousePosCallback(RGFW_mousePosfunc func);
2333
2334 /**!
2335 * @brief Sets the callback function for window refresh events.
2336 * @param func The function to be called when the window needs to be refreshed.
2337 * @return The previously set callback function, if any.
2338 */
2339 RGFWDEF RGFW_windowRefreshfunc RGFW_setWindowRefreshCallback(RGFW_windowRefreshfunc func);
2340
2341 /**!
2342 * @brief Sets the callback function for focus change events.
2343 * @param func The function to be called when the window gains or loses focus.
2344 * @return The previously set callback function, if any.
2345 */
2346 RGFWDEF RGFW_focusfunc RGFW_setFocusCallback(RGFW_focusfunc func);
2347
2348 /**!
2349 * @brief Sets the callback function for mouse notification events.
2350 * @param func The function to be called when a mouse notification event occurs.
2351 * @return The previously set callback function, if any.
2352 */
2353 RGFWDEF RGFW_mouseNotifyfunc RGFW_setMouseNotifyCallback(RGFW_mouseNotifyfunc func);
2354
2355 /**!
2356 * @brief Sets the callback function for data drop events.
2357 * @param func The function to be called when data is dropped into the window.
2358 * @return The previously set callback function, if any.
2359 */
2360 RGFWDEF RGFW_dataDropfunc RGFW_setDataDropCallback(RGFW_dataDropfunc func);
2361
2362 /**!
2363 * @brief Sets the callback function for the start of a data drag event.
2364 * @param func The function to be called when data dragging begins.
2365 * @return The previously set callback function, if any.
2366 */
2367 RGFWDEF RGFW_dataDragfunc RGFW_setDataDragCallback(RGFW_dataDragfunc func);
2368
2369 /**!
2370 * @brief Sets the callback function for key press and release events.
2371 * @param func The function to be called when a key is pressed or released.
2372 * @return The previously set callback function, if any.
2373 */
2374 RGFWDEF RGFW_keyfunc RGFW_setKeyCallback(RGFW_keyfunc func);
2375
2376 /**!
2377 * @brief Sets the callback function for key character events.
2378 * @param func The function to be called when a key is pressed or released.
2379 * @return The previously set callback function, if any.
2380 */
2381 RGFWDEF RGFW_keyCharfunc RGFW_setKeyCharCallback(RGFW_keyCharfunc func);
2382
2383 /**!
2384 * @brief Sets the callback function for mouse button press and release events.
2385 * @param func The function to be called when a mouse button is pressed or released.
2386 * @return The previously set callback function, if any.
2387 */
2388 RGFWDEF RGFW_mouseButtonfunc RGFW_setMouseButtonCallback(RGFW_mouseButtonfunc func);
2389
2390 /**!
2391 * @brief Sets the callback function for mouse scroll events.
2392 * @param func The function to be called when the mouse wheel is scrolled.
2393 * @return The previously set callback function, if any.
2394 */
2395 RGFWDEF RGFW_mouseScrollfunc RGFW_setMouseScrollCallback(RGFW_mouseScrollfunc func);
2396
2397 /**!
2398 * @brief Sets the callback function for window maximize events.
2399 * @param func The function to be called when the window is maximized.
2400 * @return The previously set callback function, if any.
2401 */
2402 RGFWDEF RGFW_windowMaximizedfunc RGFW_setWindowMaximizedCallback(RGFW_windowMaximizedfunc func);
2403
2404 /**!
2405 * @brief Sets the callback function for window minimize events.
2406 * @param func The function to be called when the window is minimized.
2407 * @return The previously set callback function, if any.
2408 */
2409 RGFWDEF RGFW_windowMinimizedfunc RGFW_setWindowMinimizedCallback(RGFW_windowMinimizedfunc func);
2410
2411 /**!
2412 * @brief Sets the callback function for window restore events.
2413 * @param func The function to be called when the window is restored from a minimized or maximized state.
2414 * @return The previously set callback function, if any.
2415 */
2416 RGFWDEF RGFW_windowRestoredfunc RGFW_setWindowRestoredCallback(RGFW_windowRestoredfunc func);
2417
2418 /**!
2419 * @brief Sets the callback function for DPI (scale) update events.
2420 * @param func The function to be called when the window’s DPI or scale changes.
2421 * @return The previously set callback function, if any.
2422 */
2423 RGFWDEF RGFW_scaleUpdatedfunc RGFW_setScaleUpdatedCallback(RGFW_scaleUpdatedfunc func);
2424
2425 /**!
2426 * @brief Sets the callback function for monitor connected and disconnect events.
2427 * @param func The function to be called when a monitor is connected or disconnected.
2428 * @return The previously set callback function, if any.
2429 */
2430 RGFWDEF RGFW_monitorfunc RGFW_setMonitorCallback(RGFW_monitorfunc func);
2431
2432 /** @} */
2433
2434 /** * @defgroup graphics_API
2435 * @{ */
2436
2437 /*! native rendering API functions */
2438 #if defined(RGFW_OPENGL)
2439 /* these are native opengl specific functions and will NOT work with EGL */
2440
2441 /*!< make the window the current OpenGL drawing context
2442
2443 NOTE:
2444 if you want to switch the graphics context's thread,
2445 you have to run RGFW_window_makeCurrentContext_OpenGL(NULL); on the old thread
2446 then RGFW_window_makeCurrentContext_OpenGL(valid_window) on the new thread
2447 */
2448
2449 /**!
2450 * @brief Sets the global OpenGL hints to the specified pointer.
2451 * @param hints A pointer to the RGFW_glHints structure containing the desired OpenGL settings.
2452 */
2453 RGFWDEF void RGFW_setGlobalHints_OpenGL(RGFW_glHints* hints);
2454
2455 /**!
2456 * @brief Resets the global OpenGL hints to their default values.
2457 */
2458 RGFWDEF void RGFW_resetGlobalHints_OpenGL(void);
2459
2460 /**!
2461 * @brief Gets the current global OpenGL hints pointer.
2462 * @return A pointer to the currently active RGFW_glHints structure.
2463 */
2464 RGFWDEF RGFW_glHints* RGFW_getGlobalHints_OpenGL(void);
2465
2466 /**!
2467 * @brief Creates and allocates an OpenGL context for the specified window.
2468 * @param win A pointer to the target RGFW_window.
2469 * @param hints A pointer to an RGFW_glHints structure defining context creation parameters.
2470 * @return A pointer to the newly created RGFW_glContext.
2471 */
2472 RGFWDEF RGFW_glContext* RGFW_window_createContext_OpenGL(RGFW_window* win, RGFW_glHints* hints);
2473
2474 /**!
2475 * @brief Creates an OpenGL context for the specified window using a preallocated context structure.
2476 * @param win A pointer to the target RGFW_window.
2477 * @param ctx A pointer to an already allocated RGFW_glContext structure.
2478 * @param hints A pointer to an RGFW_glHints structure defining context creation parameters.
2479 * @return RGFW_TRUE on success, RGFW_FALSE on failure.
2480 */
2481 RGFWDEF RGFW_bool RGFW_window_createContextPtr_OpenGL(RGFW_window* win, RGFW_glContext* ctx, RGFW_glHints* hints);
2482
2483 /**!
2484 * @brief Retrieves the OpenGL context associated with a window.
2485 * @param win A pointer to the RGFW_window.
2486 * @return A pointer to the associated RGFW_glContext, or NULL if none exists or if the context is EGL-based.
2487 */
2488 RGFWDEF RGFW_glContext* RGFW_window_getContext_OpenGL(RGFW_window* win);
2489
2490 /**!
2491 * @brief Deletes and frees the OpenGL context.
2492 * @param win A pointer to the RGFW_window.
2493 * @param ctx A pointer to the RGFW_glContext to delete.
2494 *
2495 * @note This is automatically called by RGFW_window_close if the window’s context is not NULL.
2496 */
2497 RGFWDEF void RGFW_window_deleteContext_OpenGL(RGFW_window* win, RGFW_glContext* ctx);
2498
2499 /**!
2500 * @brief Deletes the OpenGL context without freeing its memory.
2501 * @param win A pointer to the RGFW_window.
2502 * @param ctx A pointer to the RGFW_glContext to delete.
2503 *
2504 * @note This is automatically called by RGFW_window_close if the window’s context is not NULL.
2505 */
2506 RGFWDEF void RGFW_window_deleteContextPtr_OpenGL(RGFW_window* win, RGFW_glContext* ctx);
2507
2508 /**!
2509 * @brief Retrieves the native source context from an RGFW_glContext.
2510 * @param ctx A pointer to the RGFW_glContext.
2511 * @return A pointer to the native OpenGL context handle.
2512 */
2513 RGFWDEF void* RGFW_glContext_getSourceContext(RGFW_glContext* ctx);
2514
2515 /**!
2516 * @brief Makes the specified window the current OpenGL rendering target.
2517 * @param win A pointer to the RGFW_window to make current.
2518 *
2519 * @note This is typically called internally by RGFW_window_makeCurrent.
2520 */
2521 RGFWDEF void RGFW_window_makeCurrentWindow_OpenGL(RGFW_window* win);
2522
2523 /**!
2524 * @brief Makes the OpenGL context of the specified window current.
2525 * @param win A pointer to the RGFW_window whose context should be made current.
2526 *
2527 * @note To move a context between threads, call RGFW_window_makeCurrentContext_OpenGL(NULL)
2528 * on the old thread before making it current on the new one.
2529 */
2530 RGFWDEF void RGFW_window_makeCurrentContext_OpenGL(RGFW_window* win);
2531
2532 /**!
2533 * @brief Swaps the OpenGL buffers for the specified window.
2534 * @param win A pointer to the RGFW_window whose buffers should be swapped.
2535 */
2536 RGFWDEF void RGFW_window_swapBuffers_OpenGL(RGFW_window* win);
2537
2538 /**!
2539 * @brief Retrieves the current OpenGL context.
2540 * @return A pointer to the currently active OpenGL context (GLX, WGL, Cocoa, or WebGL backend).
2541 */
2542 RGFWDEF void* RGFW_getCurrentContext_OpenGL(void);
2543
2544 /**!
2545 * @brief Retrieves the current OpenGL window.
2546 * @return A pointer to the RGFW_window currently bound as the OpenGL context target.
2547 */
2548 RGFWDEF RGFW_window* RGFW_getCurrentWindow_OpenGL(void);
2549
2550 /**!
2551 * @brief Sets the OpenGL swap interval (vsync).
2552 * @param win A pointer to the RGFW_window.
2553 * @param swapInterval The desired swap interval value (0 to disable vsync, 1 to enable).
2554 */
2555 RGFWDEF void RGFW_window_swapInterval_OpenGL(RGFW_window* win, i32 swapInterval);
2556
2557 /**!
2558 * @brief Retrieves the address of a native OpenGL procedure.
2559 * @param procname The name of the OpenGL function to look up.
2560 * @return A pointer to the function, or NULL if not found.
2561 */
2562 RGFWDEF RGFW_proc RGFW_getProcAddress_OpenGL(const char* procname);
2563
2564 /**!
2565 * @brief Checks whether a specific OpenGL or OpenGL ES API extension is supported.
2566 * @param extension The name of the extension to check.
2567 * @param len The length of the extension string.
2568 * @return RGFW_TRUE if supported, RGFW_FALSE otherwise.
2569 */
2570 RGFWDEF RGFW_bool RGFW_extensionSupported_OpenGL(const char* extension, size_t len);
2571
2572 /**!
2573 * @brief Checks whether a specific platform-dependent OpenGL extension is supported.
2574 * @param extension The name of the extension to check.
2575 * @param len The length of the extension string.
2576 * @return RGFW_TRUE if supported, RGFW_FALSE otherwise.
2577 */
2578 RGFWDEF RGFW_bool RGFW_extensionSupportedPlatform_OpenGL(const char* extension, size_t len);
2579
2580 /* these are EGL specific functions, they may fallback to OpenGL */
2581 #ifdef RGFW_EGL
2582 /**!
2583 * @brief Creates and allocates an OpenGL/EGL context for the specified window.
2584 * @param win A pointer to the target RGFW_window.
2585 * @param hints A pointer to an RGFW_glHints structure defining context creation parameters.
2586 * @return A pointer to the newly created RGFW_eglContext.
2587 */
2588 RGFWDEF RGFW_eglContext* RGFW_window_createContext_EGL(RGFW_window* win, RGFW_glHints* hints);
2589
2590 /**!
2591 * @brief Creates an OpenGL/EGL context for the specified window using a preallocated context structure.
2592 * @param win A pointer to the target RGFW_window.
2593 * @param ctx A pointer to an already allocated RGFW_eglContext structure.
2594 * @param hints A pointer to an RGFW_glHints structure defining context creation parameters.
2595 * @return RGFW_TRUE on success, RGFW_FALSE on failure.
2596 */
2597 RGFWDEF RGFW_bool RGFW_window_createContextPtr_EGL(RGFW_window* win, RGFW_eglContext* ctx, RGFW_glHints* hints);
2598
2599 /**!
2600 * @brief Frees and deletes an OpenGL/EGL context.
2601 * @param win A pointer to the RGFW_window.
2602 * @param ctx A pointer to the RGFW_eglContext to delete.
2603 *
2604 * @note Automatically called by RGFW_window_close if RGFW owns the context.
2605 */
2606 RGFWDEF void RGFW_window_deleteContext_EGL(RGFW_window* win, RGFW_eglContext* ctx);
2607
2608 /**!
2609 * @brief Deletes an OpenGL/EGL context without freeing its memory.
2610 * @param win A pointer to the RGFW_window.
2611 * @param ctx A pointer to the RGFW_eglContext to delete.
2612 *
2613 * @note Automatically called by RGFW_window_close if RGFW owns the context.
2614 */
2615 RGFWDEF void RGFW_window_deleteContextPtr_EGL(RGFW_window* win, RGFW_eglContext* ctx);
2616
2617 /**!
2618 * @brief Retrieves the OpenGL/EGL context associated with a window.
2619 * @param win A pointer to the RGFW_window.
2620 * @return A pointer to the associated RGFW_eglContext, or NULL if none exists or if the context is a native OpenGL context.
2621 */
2622 RGFWDEF RGFW_eglContext* RGFW_window_getContext_EGL(RGFW_window* win);
2623
2624 /**!
2625 * @brief Retrieves the EGL display handle.
2626 * @return A pointer to the native EGLDisplay.
2627 */
2628 RGFWDEF void* RGFW_getDisplay_EGL(void);
2629
2630 /**!
2631 * @brief Retrieves the native source context from an RGFW_eglContext.
2632 * @param ctx A pointer to the RGFW_eglContext.
2633 * @return A pointer to the native EGLContext handle.
2634 */
2635 RGFWDEF void* RGFW_eglContext_getSourceContext(RGFW_eglContext* ctx);
2636
2637 /**!
2638 * @brief Retrieves the EGL surface handle from an RGFW_eglContext.
2639 * @param ctx A pointer to the RGFW_eglContext.
2640 * @return A pointer to the EGLSurface associated with the context.
2641 */
2642 RGFWDEF void* RGFW_eglContext_getSurface(RGFW_eglContext* ctx);
2643
2644 /**!
2645 * @brief Retrieves the Wayland EGL window handle from an RGFW_eglContext.
2646 * @param ctx A pointer to the RGFW_eglContext.
2647 * @return A pointer to the wl_egl_window associated with the EGL context.
2648 */
2649 RGFWDEF struct wl_egl_window* RGFW_eglContext_wlEGLWindow(RGFW_eglContext* ctx);
2650
2651 /**!
2652 * @brief Swaps the EGL buffers for the specified window.
2653 * @param win A pointer to the RGFW_window whose buffers should be swapped.
2654 *
2655 * @note Typically called by RGFW_window_swapInterval.
2656 */
2657 RGFWDEF void RGFW_window_swapBuffers_EGL(RGFW_window* win);
2658
2659 /**!
2660 * @brief Makes the specified window the current EGL rendering target.
2661 * @param win A pointer to the RGFW_window to make current.
2662 *
2663 * @note This is typically called internally by RGFW_window_makeCurrent.
2664 */
2665 RGFWDEF void RGFW_window_makeCurrentWindow_EGL(RGFW_window* win);
2666
2667 /**!
2668 * @brief Makes the EGL context of the specified window current.
2669 * @param win A pointer to the RGFW_window whose context should be made current.
2670 *
2671 * @note To move a context between threads, call RGFW_window_makeCurrentContext_EGL(NULL)
2672 * on the old thread before making it current on the new one.
2673 */
2674 RGFWDEF void RGFW_window_makeCurrentContext_EGL(RGFW_window* win);
2675
2676 /**!
2677 * @brief Retrieves the current EGL context.
2678 * @return A pointer to the currently active EGLContext.
2679 */
2680 RGFWDEF void* RGFW_getCurrentContext_EGL(void);
2681
2682 /**!
2683 * @brief Retrieves the current EGL window.
2684 * @return A pointer to the RGFW_window currently bound as the EGL context target.
2685 */
2686 RGFWDEF RGFW_window* RGFW_getCurrentWindow_EGL(void);
2687
2688 /**!
2689 * @brief Sets the EGL swap interval (vsync).
2690 * @param win A pointer to the RGFW_window.
2691 * @param swapInterval The desired swap interval value (0 to disable vsync, 1 to enable).
2692 */
2693 RGFWDEF void RGFW_window_swapInterval_EGL(RGFW_window* win, i32 swapInterval);
2694
2695 /**!
2696 * @brief Retrieves the address of a native OpenGL or OpenGL ES procedure in an EGL context.
2697 * @param procname The name of the OpenGL function to look up.
2698 * @return A pointer to the function, or NULL if not found.
2699 */
2700 RGFWDEF RGFW_proc RGFW_getProcAddress_EGL(const char* procname);
2701
2702 /**!
2703 * @brief Checks whether a specific OpenGL or OpenGL ES API extension is supported in the current EGL context.
2704 * @param extension The name of the extension to check.
2705 * @param len The length of the extension string.
2706 * @return RGFW_TRUE if supported, RGFW_FALSE otherwise.
2707 */
2708 RGFWDEF RGFW_bool RGFW_extensionSupported_EGL(const char* extension, size_t len);
2709
2710 /**!
2711 * @brief Checks whether a specific platform-dependent EGL extension is supported in the current context.
2712 * @param extension The name of the extension to check.
2713 * @param len The length of the extension string.
2714 * @return RGFW_TRUE if supported, RGFW_FALSE otherwise.
2715 */
2716 RGFWDEF RGFW_bool RGFW_extensionSupportedPlatform_EGL(const char* extension, size_t len);
2717 #endif
2718 #endif
2719
2720 #ifdef RGFW_VULKAN
2721 #include <vulkan/vulkan.h>
2722
2723 /* if you don't want to use the above macros */
2724
2725 /**!
2726 * @brief Retrieves the Vulkan instance extensions required by RGFW.
2727 * @param count [OUTPUT] A pointer that will receive the number of required extensions (typically 2).
2728 * @return A pointer to a static array of required Vulkan instance extension names.
2729 */
2730 RGFWDEF const char** RGFW_getRequiredInstanceExtensions_Vulkan(size_t* count);
2731
2732 /**!
2733 * @brief Creates a Vulkan surface for the specified window.
2734 * @param win A pointer to the RGFW_window for which to create the Vulkan surface.
2735 * @param instance The Vulkan instance used to create the surface.
2736 * @param surface [OUTPUT] A pointer to a VkSurfaceKHR handle that will receive the created surface.
2737 * @return A VkResult indicating success or failure.
2738 */
2739 RGFWDEF VkResult RGFW_window_createSurface_Vulkan(RGFW_window* win, VkInstance instance, VkSurfaceKHR* surface);
2740
2741 /**!
2742 * @brief Checks whether the specified Vulkan physical device and queue family support presentation for RGFW.
2743 * @param instance The Vulkan instance.
2744 * @param physicalDevice The Vulkan physical device to check.
2745 * @param queueFamilyIndex The index of the queue family to query for presentation support.
2746 * @return RGFW_TRUE if presentation is supported, RGFW_FALSE otherwise.
2747 */
2748 RGFWDEF RGFW_bool RGFW_getPresentationSupport_Vulkan(VkPhysicalDevice physicalDevice, u32 queueFamilyIndex);
2749 #endif
2750
2751 #ifdef RGFW_DIRECTX
2752 #ifndef RGFW_WINDOWS
2753 #undef RGFW_DIRECTX
2754 #else
2755 #define OEMRESOURCE
2756 #include <dxgi.h>
2757
2758 #ifndef __cplusplus
2759 #define __uuidof(T) IID_##T
2760 #endif
2761 /**!
2762 * @brief Creates a DirectX swap chain for the specified RGFW window.
2763 * @param win A pointer to the RGFW_window for which to create the swap chain.
2764 * @param pFactory A pointer to the IDXGIFactory used to create the swap chain.
2765 * @param pDevice A pointer to the DirectX device (e.g., ID3D11Device or ID3D12Device).
2766 * @param swapchain [OUTPUT] A pointer to an IDXGISwapChain pointer that will receive the created swap chain.
2767 * @return An integer result code (0 on success, or a DirectX error code on failure).
2768 */
2769 RGFWDEF int RGFW_window_createSwapChain_DirectX(RGFW_window* win, IDXGIFactory* pFactory, IUnknown* pDevice, IDXGISwapChain** swapchain);
2770 #endif
2771 #endif
2772
2773 #ifdef RGFW_WEBGPU
2774 #include <webgpu/webgpu.h>
2775 /**!
2776 * @brief Creates a WebGPU surface for the specified RGFW window.
2777 * @param window A pointer to the RGFW_window for which to create the surface.
2778 * @param instance The WebGPU instance used to create the surface.
2779 * @return The created WGPUSurface handle.
2780 */
2781 RGFWDEF WGPUSurface RGFW_window_createSurface_WebGPU(RGFW_window* window, WGPUInstance instance);
2782 #endif
2783
2784 /** @} */
2785
2786 /** * @defgroup Supporting
2787 * @{ */
2788
2789 /**!
2790 * @brief Sets the root (main) RGFW window.
2791 * @param win A pointer to the RGFW_window to set as the root window.
2792 */
2793 RGFWDEF void RGFW_setRootWindow(RGFW_window* win);
2794
2795 /**!
2796 * @brief Retrieves the current root RGFW window.
2797 * @return A pointer to the current root RGFW_window.
2798 */
2799 RGFWDEF RGFW_window* RGFW_getRootWindow(void);
2800
2801 /**!
2802 * @brief Pushes an event into the standard RGFW event queue.
2803 * @param event A pointer to the RGFW_event to be added to the queue.
2804 */
2805 RGFWDEF void RGFW_eventQueuePush(const RGFW_event* event);
2806
2807 /**!
2808 * @brief Clears all events from the RGFW event queue without processing them.
2809 */
2810 RGFWDEF void RGFW_eventQueueFlush(void);
2811
2812 /**!
2813 * @brief Pops the next event from the RGFW event queue.
2814 * @return A pointer to the popped RGFW_event, or NULL if the queue is empty.
2815 */
2816 RGFWDEF RGFW_event* RGFW_eventQueuePop(void);
2817
2818 /**!
2819 * @brief Pops the next event from the RGFW event queue that matches the target window, pushes back events that don't matchj.
2820 * @param win A pointer to the target RGFW_window.
2821 * @return A pointer to the popped RGFW_event, or NULL if the queue is empty.
2822 */
2823 RGFWDEF RGFW_event* RGFW_window_eventQueuePop(RGFW_window* win);
2824
2825 /**!
2826 * @brief Converts an API keycode to the RGFW unmapped (physical) key.
2827 * @param keycode The platform-specific keycode.
2828 * @return The corresponding RGFW keycode.
2829 */
2830 RGFWDEF RGFW_key RGFW_apiKeyToRGFW(u32 keycode);
2831
2832 /**!
2833 * @brief Converts an RGFW keycode to the unmapped (physical) API key.
2834 * @param keycode The RGFW keycode.
2835 * @return The corresponding platform-specific keycode.
2836 */
2837 RGFWDEF u32 RGFW_rgfwToApiKey(RGFW_key keycode);
2838
2839 /**!
2840 * @brief Converts an physical RGFW keycode to a mapped RGFW keycode.
2841 * @param keycode the physical RGFW keycode.
2842 * @return The corresponding mapped RGFW keycode.
2843 */
2844 RGFWDEF RGFW_key RGFW_physicalToMappedKey(RGFW_key keycode);
2845
2846 /**!
2847 * @brief Retrieves the size of the RGFW_info structure.
2848 * @return The size (in bytes) of RGFW_info.
2849 */
2850 RGFWDEF size_t RGFW_sizeofInfo(void);
2851
2852 /**!
2853 * @brief Initializes the RGFW library.
2854 * @return 0 on success, or a negative error code on failure.
2855 * @note This is automatically called when the first window is created.
2856 */
2857 RGFWDEF i32 RGFW_init(void);
2858
2859 /**!
2860 * @brief Deinitializes the RGFW library.
2861 * @note This is automatically called when the last open window is closed.
2862 */
2863 RGFWDEF void RGFW_deinit(void);
2864
2865 /**!
2866 * @brief Initializes RGFW using a user-provided RGFW_info structure.
2867 * @param info A pointer to an RGFW_info structure to be used for initialization.
2868 * @return 0 on success, or a negative error code on failure.
2869 */
2870 RGFWDEF i32 RGFW_init_ptr(RGFW_info* info);
2871
2872 /**!
2873 * @brief Deinitializes a specific RGFW instance stored in the provided RGFW_info pointer.
2874 * @param info A pointer to the RGFW_info structure representing the instance to deinitialize.
2875 */
2876 RGFWDEF void RGFW_deinit_ptr(RGFW_info* info);
2877
2878 /**!
2879 * @brief Sets the global RGFW_info structure pointer.
2880 * @param info A pointer to the RGFW_info structure to set.
2881 */
2882 RGFWDEF void RGFW_setInfo(RGFW_info* info);
2883
2884 /**!
2885 * @brief Retrieves the global RGFW_info structure pointer.
2886 * @return A pointer to the current RGFW_info structure.
2887 */
2888 RGFWDEF RGFW_info* RGFW_getInfo(void);
2889
2890 /** @} */
2891 #endif /* RGFW_HEADER */
2892
2893 #if !defined(RGFW_NATIVE_HEADER) && (defined(RGFW_NATIVE) || defined(RGFW_IMPLEMENTATION))
2894 #define RGFW_NATIVE_HEADER
2895 #if (defined(RGFW_OPENGL) || defined(RGFW_WEGL)) && defined(_MSC_VER)
2896 #pragma comment(lib, "opengl32")
2897 #endif
2898
2899 #ifdef RGFW_OPENGL
2900 struct RGFW_eglContext {
2901 void* ctx;
2902 void* surface;
2903 struct wl_egl_window* eglWindow;
2904 };
2905
2906 typedef union RGFW_gfxContext {
2907 RGFW_glContext* native;
2908 RGFW_eglContext* egl;
2909 } RGFW_gfxContext;
2910
2911 typedef RGFW_ENUM(u32, RGFW_gfxContextType) {
2912 RGFW_gfxNativeOpenGL = RGFW_BIT(0),
2913 RGFW_gfxEGL = RGFW_BIT(1),
2914 RGFW_gfxOwnedByRGFW = RGFW_BIT(2)
2915 };
2916 #endif
2917
2918 /*! source data for the window (used by the APIs) */
2919 #ifdef RGFW_WINDOWS
2920
2921 #ifndef WIN32_LEAN_AND_MEAN
2922 #define WIN32_LEAN_AND_MEAN
2923 #endif
2924 #ifndef OEMRESOURCE
2925 #define OEMRESOURCE
2926 #endif
2927
2928 #include <windows.h>
2929
2930 struct RGFW_nativeImage {
2931 HBITMAP bitmap;
2932 u8* bitmapBits;
2933 RGFW_format format;
2934 HDC hdcMem;
2935 };
2936
2937 #ifdef RGFW_OPENGL
2938 struct RGFW_glContext { HGLRC ctx; };
2939 #endif
2940
2941 struct RGFW_window_src {
2942 HWND window; /*!< source window */
2943 HDC hdc; /*!< source HDC */
2944 HICON hIconSmall, hIconBig; /*!< source window icons */
2945 i32 maxSizeW, maxSizeH, minSizeW, minSizeH, aspectRatioW, aspectRatioH; /*!< for setting max/min resize (RGFW_WINDOWS) */
2946 RGFW_bool actionFrame; /* frame after a caption button was toggled (e.g. minimize, maximize or close) */
2947 WCHAR highSurrogate;
2948 #ifdef RGFW_OPENGL
2949 RGFW_gfxContext ctx;
2950 RGFW_gfxContextType gfxType;
2951 #endif
2952 };
2953
2954 #elif defined(RGFW_UNIX)
2955 #ifdef RGFW_X11
2956 #include <X11/Xlib.h>
2957 #include <X11/Xutil.h>
2958
2959 #ifndef RGFW_NO_XRANDR
2960 #include <X11/extensions/Xrandr.h>
2961 #include <X11/Xresource.h>
2962 #endif
2963 #endif
2964
2965 #ifdef RGFW_WAYLAND
2966 #ifdef RGFW_LIBDECOR
2967 #include <libdecor-0/libdecor.h>
2968 #endif
2969
2970 #include <wayland-client.h>
2971 #include <errno.h>
2972 #endif
2973
2974 struct RGFW_nativeImage {
2975 #ifdef RGFW_X11
2976 XImage* bitmap;
2977 #endif
2978 #ifdef RGFW_WAYLAND
2979 struct wl_buffer* wl_buffer;
2980 i32 fd;
2981 struct wl_shm_pool* pool;
2982 #endif
2983 u8* buffer;
2984 RGFW_format format;
2985 };
2986
2987 #ifdef RGFW_OPENGL
2988 struct RGFW_glContext {
2989 #ifdef RGFW_X11
2990 struct __GLXcontextRec* ctx; /*!< source graphics context */
2991 Window window;
2992 #endif
2993 #ifdef RGFW_WAYLAND
2994 RGFW_eglContext egl;
2995 #endif
2996 };
2997 #endif
2998
2999 struct RGFW_window_src {
3000 i32 x, y, w, h;
3001 #ifdef RGFW_OPENGL
3002 RGFW_gfxContext ctx;
3003 RGFW_gfxContextType gfxType;
3004 #endif
3005 #ifdef RGFW_X11
3006 Window window; /*!< source window */
3007 Window parent; /*!< parent window */
3008 GC gc;
3009 XIC ic;
3010 u64 flashEnd;
3011 #ifdef RGFW_ADVANCED_SMOOTH_RESIZE
3012 i64 counter_value;
3013 XID counter;
3014 #endif
3015 #endif /* RGFW_X11 */
3016
3017 #if defined(RGFW_WAYLAND)
3018 struct wl_surface* surface;
3019 struct xdg_surface* xdg_surface;
3020 struct xdg_toplevel* xdg_toplevel;
3021 struct zxdg_toplevel_decoration_v1* decoration;
3022 struct zwp_locked_pointer_v1 *locked_pointer;
3023 struct xdg_toplevel_icon_v1 *icon;
3024 u32 decoration_mode;
3025 /* State flags to configure the window */
3026 RGFW_bool pending_activated;
3027 RGFW_bool activated;
3028 RGFW_bool resizing;
3029 RGFW_bool pending_maximized;
3030 RGFW_bool maximized;
3031 RGFW_bool minimized;
3032 RGFW_bool configured;
3033
3034 RGFW_bool using_custom_cursor;
3035 struct wl_surface* custom_cursor_surface;
3036
3037 RGFW_monitorNode* active_monitor;
3038
3039 struct wl_data_source *data_source; // offer data to other clients
3040
3041 #ifdef RGFW_LIBDECOR
3042 struct libdecor* decorContext;
3043 #endif
3044 #endif /* RGFW_WAYLAND */
3045 };
3046
3047 #elif defined(RGFW_MACOS)
3048 #include <CoreVideo/CoreVideo.h>
3049
3050 struct RGFW_nativeImage {
3051 RGFW_format format;
3052 u8* buffer;
3053 void* rep;
3054 };
3055
3056 #ifdef RGFW_OPENGL
3057 struct RGFW_glContext {
3058 void* ctx;
3059 void* format;
3060 };
3061 #endif
3062
3063 struct RGFW_window_src {
3064 void* window;
3065 void* view; /* apple viewpoint thingy */
3066 void* mouse;
3067 void* delegate;
3068 #ifdef RGFW_OPENGL
3069 RGFW_gfxContext ctx;
3070 RGFW_gfxContextType gfxType;
3071 #endif
3072 };
3073
3074 #elif defined(RGFW_WASM)
3075
3076 #include <emscripten/html5.h>
3077 #include <emscripten/key_codes.h>
3078
3079 struct RGFW_nativeImage {
3080 RGFW_format format;
3081 };
3082
3083 #ifdef RGFW_OPENGL
3084 struct RGFW_glContext {
3085 EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx;
3086 };
3087 #endif
3088
3089 struct RGFW_window_src {
3090 #ifdef RGFW_OPENGL
3091 RGFW_gfxContext ctx;
3092 RGFW_gfxContextType gfxType;
3093 #endif
3094 };
3095
3096 #endif
3097
3098 struct RGFW_surface {
3099 u8* data;
3100 i32 w, h;
3101 RGFW_format format;
3102 RGFW_convertImageDataFunc convertFunc;
3103 RGFW_nativeImage native;
3104 };
3105
3106 /*! internal window data that is not specific to the OS */
3107 typedef struct RGFW_windowInternal {
3108 /*! which key RGFW_window_shouldClose checks. Settting this to RGFW_keyNULL disables the feature. */
3109 RGFW_key exitKey;
3110 i32 lastMouseX, lastMouseY; /*!< last cusor point (for raw mouse data) */
3111
3112 RGFW_bool shouldClose;
3113 RGFW_bool rawMouse;
3114 RGFW_bool captureMouse;
3115 RGFW_bool inFocus;
3116 RGFW_bool mouseInside;
3117 RGFW_keymod mod;
3118 RGFW_eventFlag enabledEvents;
3119 u32 flags; /*!< windows flags (for RGFW to check and modify) */
3120 i32 oldX, oldY, oldW, oldH;
3121 } RGFW_windowInternal;
3122
3123 struct RGFW_window {
3124 RGFW_window_src src; /*!< src window data */
3125 RGFW_windowInternal internal; /*!< internal window data that is not specific to the OS */
3126 void* userPtr; /* ptr for user data */
3127 i32 x, y, w, h; /*!< position and size of the window */
3128 }; /*!< window structure for the window */
3129
3130 typedef struct RGFW_windowState {
3131 RGFW_bool mouseEnter;
3132 RGFW_bool dataDragging;
3133 RGFW_bool dataDrop;
3134 size_t filesCount;
3135 i32 dropX, dropY;
3136 RGFW_window* win; /*!< it's not possible for one of these events to happen in the frame that the other event happened */
3137
3138 RGFW_bool mouseLeave;
3139 RGFW_window* winLeave; /*!< if a mouse leaves one window and enters the next */
3140 } RGFW_windowState;
3141
3142 typedef struct {
3143 RGFW_bool current;
3144 RGFW_bool prev;
3145 } RGFW_keyState;
3146
3147 struct RGFW_monitorNode {
3148 RGFW_monitor mon;
3149 RGFW_bool disconnected;
3150 RGFW_monitorNode* next;
3151 #ifdef RGFW_WAYLAND
3152 u32 id; /* Add id so wl_outputs can be removed */
3153 struct wl_output *output;
3154 struct zxdg_output_v1 *xdg_output;
3155 RGFW_monitorMode* modes;
3156 size_t modeCount;
3157 #endif
3158 #if defined(RGFW_X11) && !defined(RGFW_NO_XRANDR)
3159 i32 screen;
3160 RROutput rrOutput;
3161 RRCrtc crtc;
3162 #endif
3163 #ifdef RGFW_WINDOWS
3164 HMONITOR hMonitor;
3165 WCHAR adapterName[32];
3166 WCHAR deviceName[32];
3167 #endif
3168 #ifdef RGFW_MACOS
3169 void* screen;
3170 CGDirectDisplayID display;
3171 u32 uintNum;
3172 #endif
3173 };
3174
3175 typedef struct RGFW_monitorList {
3176 RGFW_monitorNode* head;
3177 RGFW_monitorNode* cur;
3178 } RGFW_monitorList;
3179
3180 typedef struct RGFW_monitors {
3181 RGFW_monitorList list;
3182 RGFW_monitorList freeList;
3183 size_t count;
3184
3185 RGFW_monitorNode* primary;
3186 RGFW_monitorNode data[RGFW_MAX_MONITORS];
3187 } RGFW_monitors;
3188
3189 RGFWDEF RGFW_monitorNode* RGFW_monitors_add(const RGFW_monitor* mon);
3190 RGFWDEF void RGFW_monitors_remove(RGFW_monitorNode* node, RGFW_monitorNode* prev);
3191
3192 struct RGFW_info {
3193 RGFW_window* root;
3194 i32 windowCount;
3195
3196 RGFW_mouse* hiddenMouse;
3197
3198 RGFW_event events[RGFW_MAX_EVENTS]; /* A circular buffer (FIFO), using eventBottom/Len */
3199
3200 i32 eventBottom;
3201 i32 eventLen;
3202 RGFW_bool queueEvents;
3203 RGFW_bool polledEvents;
3204
3205 u32 apiKeycodes[RGFW_keyLast];
3206 #if defined(RGFW_X11) || defined(RGFW_WAYLAND)
3207 RGFW_key keycodes[256];
3208 #elif defined(RGFW_WINDOWS)
3209 RGFW_key keycodes[512];
3210 #elif defined(RGFW_MACOS)
3211 RGFW_key keycodes[128];
3212 #elif defined(RGFW_WASM)
3213 RGFW_key keycodes[256];
3214 #endif
3215
3216 const char* className;
3217 RGFW_bool useWaylandBool;
3218 RGFW_bool stopCheckEvents_bool ;
3219 u64 timerOffset;
3220
3221 char* clipboard_data;
3222 char* clipboard; /* for writing to the clipboard selection */
3223 size_t clipboard_len;
3224 char filesSrc[RGFW_MAX_PATH * RGFW_MAX_DROPS];
3225 char** files;
3226 #ifdef RGFW_X11
3227 Display* display;
3228 XContext context;
3229 Window helperWindow;
3230 const char* instName;
3231 XErrorEvent* x11Error;
3232 i32 xrandrEventBase;
3233 XIM im;
3234 #endif
3235 #ifdef RGFW_WAYLAND
3236 struct wl_display* wl_display;
3237 struct xkb_context *xkb_context;
3238 struct xkb_keymap *keymap;
3239 struct xkb_state *xkb_state;
3240 struct zxdg_decoration_manager_v1 *decoration_manager;
3241 struct zwp_relative_pointer_manager_v1 *relative_pointer_manager;
3242 struct zwp_relative_pointer_v1 *relative_pointer;
3243 struct zwp_pointer_constraints_v1 *constraint_manager;
3244 struct xdg_toplevel_icon_manager_v1 *icon_manager;
3245
3246 struct zxdg_output_manager_v1 *xdg_output_manager;
3247
3248 struct wl_data_device_manager *data_device_manager;
3249 struct wl_data_device *data_device; // supports clipboard and DND
3250 struct wp_pointer_warp_v1* wp_pointer_warp;
3251
3252 struct wl_keyboard* wl_keyboard;
3253 struct wl_pointer* wl_pointer;
3254 struct wl_compositor* compositor;
3255 struct xdg_wm_base* xdg_wm_base;
3256 struct wl_shm* shm;
3257 struct wl_seat *seat;
3258 struct wl_registry *registry;
3259 u32 mouse_enter_serial;
3260 struct wl_cursor_theme* wl_cursor_theme;
3261 struct wl_surface* cursor_surface;
3262 struct xkb_compose_state* composeState;
3263
3264 RGFW_window* kbOwner;
3265 RGFW_window* mouseOwner; /* what window has access to the mouse */
3266
3267 #endif
3268
3269 RGFW_monitors monitors;
3270
3271 #ifdef RGFW_UNIX
3272 int eventWait_forceStop[3];
3273 i32 clock;
3274 #endif
3275
3276 #ifdef RGFW_MACOS
3277 void* NSApp;
3278 i64 flash;
3279 void* customViewClasses[2]; /* NSView and NSOpenGLView */
3280 void* customNSAppDelegateClass;
3281 void* customWindowDelegateClass;
3282 void* customNSAppDelegate;
3283 void* tisBundle;
3284 #endif
3285
3286 #ifdef RGFW_OPENGL
3287 RGFW_window* current;
3288 #endif
3289 #ifdef RGFW_EGL
3290 void* EGL_display;
3291 #endif
3292
3293 RGFW_bool rawMouse; /* global raw mouse toggle */
3294
3295 RGFW_windowState windowState; /*! for checking window state events */
3296
3297 RGFW_keyState mouseButtons[RGFW_mouseFinal];
3298 RGFW_keyState keyboard[RGFW_keyLast];
3299 float scrollX, scrollY;
3300 float vectorX, vectorY;
3301 };
3302 #endif /* RGFW_NATIVE_HEADER */
3303
3304 #ifdef RGFW_IMPLEMENTATION
3305
3306 #ifndef RGFW_NO_MATH
3307 #include <math.h>
3308 #endif
3309
3310 /* global private API */
3311
3312 /* for C++ / C89 */
3313 RGFWDEF RGFW_window* RGFW_createWindowPlatform(const char* name, RGFW_windowFlags flags, RGFW_window* win);
3314 RGFWDEF void RGFW_window_closePlatform(RGFW_window* win);
3315
3316 RGFWDEF void RGFW_window_setFlagsInternal(RGFW_window* win, RGFW_windowFlags flags, RGFW_windowFlags cmpFlags);
3317
3318 RGFWDEF void RGFW_initKeycodes(void);
3319 RGFWDEF void RGFW_initKeycodesPlatform(void);
3320 RGFWDEF void RGFW_resetPrevState(void);
3321 RGFWDEF void RGFW_resetKey(void);
3322 RGFWDEF void RGFW_unloadEGL(void);
3323 RGFWDEF void RGFW_updateKeyModsEx(RGFW_window* win, RGFW_bool capital, RGFW_bool numlock, RGFW_bool control, RGFW_bool alt, RGFW_bool shift, RGFW_bool super, RGFW_bool scroll);
3324 RGFWDEF void RGFW_updateKeyMods(RGFW_window* win, RGFW_bool capital, RGFW_bool numlock, RGFW_bool scroll);
3325 RGFWDEF void RGFW_window_showMouseFlags(RGFW_window* win, RGFW_bool show);
3326 RGFWDEF void RGFW_updateKeyMod(RGFW_window* win, RGFW_keymod mod, RGFW_bool value);
3327 RGFWDEF void RGFW_monitors_refresh(void);
3328
3329 RGFWDEF void RGFW_windowMaximizedCallback(RGFW_window* win, i32 x, i32 y, i32 w, i32 h);
3330 RGFWDEF void RGFW_windowMinimizedCallback(RGFW_window* win);
3331 RGFWDEF void RGFW_windowRestoredCallback(RGFW_window* win, i32 x, i32 y, i32 w, i32 h);
3332 RGFWDEF void RGFW_windowMovedCallback(RGFW_window* win, i32 x, i32 y);
3333 RGFWDEF void RGFW_windowResizedCallback(RGFW_window* win, i32 w, i32 h);
3334 RGFWDEF void RGFW_windowQuitCallback(RGFW_window* win);
3335 RGFWDEF void RGFW_mousePosCallback(RGFW_window* win, i32 x, i32 y, float vecX, float vecY);
3336 RGFWDEF void RGFW_windowRefreshCallback(RGFW_window* win);
3337 RGFWDEF void RGFW_focusCallback(RGFW_window* win, RGFW_bool inFocus);
3338 RGFWDEF void RGFW_mouseNotifyCallback(RGFW_window* win, i32 x, i32 y, RGFW_bool status);
3339 RGFWDEF void RGFW_dataDropCallback(RGFW_window* win, char** files, size_t count);
3340 RGFWDEF void RGFW_dataDragCallback(RGFW_window* win, i32 x, i32 y);
3341 RGFWDEF void RGFW_keyCharCallback(RGFW_window* win, u32 codepoint);
3342 RGFWDEF void RGFW_keyCallback(RGFW_window* win, RGFW_key key, RGFW_keymod mod, RGFW_bool repeat, RGFW_bool press);
3343 RGFWDEF void RGFW_mouseButtonCallback(RGFW_window* win, RGFW_mouseButton button, RGFW_bool press);
3344 RGFWDEF void RGFW_mouseScrollCallback(RGFW_window* win, float x, float y);
3345 RGFWDEF void RGFW_scaleUpdatedCallback(RGFW_window* win, float scaleX, float scaleY);
3346 RGFWDEF void RGFW_monitorCallback(RGFW_window* win, const RGFW_monitor* monitor, RGFW_bool connected);
3347
3348 RGFWDEF void RGFW_setBit(u32* var, u32 mask, RGFW_bool set);
3349 RGFWDEF void RGFW_splitBPP(u32 bpp, RGFW_monitorMode* mode);
3350
3351 RGFWDEF void RGFW_window_captureMousePlatform(RGFW_window* win, RGFW_bool state);
3352 RGFWDEF void RGFW_window_setRawMouseModePlatform(RGFW_window *win, RGFW_bool state);
3353
3354 RGFWDEF void RGFW_copyImageData64(u8* dest_data, i32 w, i32 h, RGFW_format dest_format,
3355 u8* src_data, RGFW_format src_format, RGFW_bool is64bit, RGFW_convertImageDataFunc func);
3356
3357 RGFWDEF RGFW_bool RGFW_loadEGL(void);
3358
3359 #ifdef RGFW_OPENGL
3360 typedef struct RGFW_attribStack {
3361 i32* attribs;
3362 size_t count;
3363 size_t max;
3364 } RGFW_attribStack;
3365 RGFWDEF void RGFW_attribStack_init(RGFW_attribStack* stack, i32* attribs, size_t max);
3366 RGFWDEF void RGFW_attribStack_pushAttrib(RGFW_attribStack* stack, i32 attrib);
3367 RGFWDEF void RGFW_attribStack_pushAttribs(RGFW_attribStack* stack, i32 attrib1, i32 attrib2);
3368
3369 RGFWDEF RGFW_bool RGFW_extensionSupportedStr(const char* extensions, const char* ext, size_t len);
3370 #endif
3371
3372 #ifdef RGFW_X11
3373 RGFWDEF void RGFW_XCreateWindow (XVisualInfo visual, const char* name, RGFW_windowFlags flags, RGFW_window* win);
3374 #endif
3375 #ifdef RGFW_MACOS
3376 RGFWDEF void RGFW_osx_initView(RGFW_window* win);
3377 #endif
3378 /* end of global private API defs */
3379
3380 RGFW_info* _RGFW = NULL;
3381 void RGFW_setInfo(RGFW_info* info) { _RGFW = info; }
3382 RGFW_info* RGFW_getInfo(void) { return _RGFW; }
3383
3384
3385 void* RGFW_alloc(size_t size) { return RGFW_ALLOC(size); }
3386 void RGFW_free(void* ptr) { RGFW_FREE(ptr); }
3387
3388 void RGFW_useWayland(RGFW_bool wayland) { RGFW_init(); _RGFW->useWaylandBool = RGFW_BOOL(wayland); }
3389 RGFW_bool RGFW_usingWayland(void) { return _RGFW->useWaylandBool; }
3390
3391 void RGFW_setRawMouseMode(RGFW_bool state) {
3392 _RGFW->rawMouse = state;
3393 RGFW_window_setRawMouseModePlatform(_RGFW->root, state);
3394 }
3395
3396 void RGFW_clipboard_switch(char* newstr);
3397 void RGFW_clipboard_switch(char* newstr) {
3398 if (_RGFW->clipboard_data != NULL)
3399 RGFW_FREE(_RGFW->clipboard_data);
3400 _RGFW->clipboard_data = newstr;
3401 }
3402
3403 #define RGFW_CHECK_CLIPBOARD() \
3404 if (size <= 0 && _RGFW->clipboard_data != NULL) \
3405 return (const char*)_RGFW->clipboard_data; \
3406 else if (size <= 0) \
3407 return "\0";
3408
3409 const char* RGFW_readClipboard(size_t* len) {
3410 RGFW_ssize_t size = RGFW_readClipboardPtr(NULL, 0);
3411 RGFW_CHECK_CLIPBOARD();
3412 char* str = (char*)RGFW_ALLOC((size_t)size);
3413 RGFW_ASSERT(str != NULL);
3414 str[0] = '\0';
3415
3416 size = RGFW_readClipboardPtr(str, (size_t)size);
3417
3418 RGFW_CHECK_CLIPBOARD();
3419
3420 if (len != NULL) *len = (size_t)size;
3421
3422 RGFW_clipboard_switch(str);
3423 return (const char*)str;
3424 }
3425
3426 /*
3427 RGFW_IMPLEMENTATION starts with generic RGFW defines
3428
3429 This is the start of keycode data
3430 */
3431
3432
3433
3434 void RGFW_initKeycodes(void) {
3435 RGFW_MEMSET(_RGFW->keycodes, 0, sizeof(_RGFW->keycodes));
3436 RGFW_initKeycodesPlatform();
3437 size_t i, y;
3438 for (i = 0; i < RGFW_keyLast; i++) {
3439 for (y = 0; y < (sizeof(_RGFW->keycodes) / sizeof(RGFW_key)); y++) {
3440 if (_RGFW->keycodes[y] == i) {
3441 _RGFW->apiKeycodes[i] = (RGFW_key)y;
3442 break;
3443 }
3444 }
3445 }
3446
3447
3448 RGFW_resetKey();
3449 }
3450
3451 RGFW_key RGFW_apiKeyToRGFW(u32 keycode) {
3452 /* make sure the key isn't out of bounds */
3453 if (keycode > (sizeof(_RGFW->keycodes) / sizeof(RGFW_key)))
3454 return 0;
3455
3456 return _RGFW->keycodes[keycode];
3457 }
3458
3459 u32 RGFW_rgfwToApiKey(RGFW_key keycode) {
3460 /* make sure the key isn't out of bounds */
3461 return _RGFW->apiKeycodes[keycode];
3462 }
3463
3464 void RGFW_resetKey(void) { RGFW_MEMSET(_RGFW->keyboard, 0, sizeof(_RGFW->keyboard)); }
3465 /*
3466 this is the end of keycode data
3467 */
3468
3469 /*
3470 event callback defines start here
3471 */
3472
3473
3474 /*
3475 These exist to avoid the
3476 if (func == NULL) check
3477 for (allegedly) better performance
3478
3479 RGFW_EMPTY_DEF exists to prevent the missing-prototypes warning
3480 */
3481 #define RGFW_CALLBACK_DEFINE(x, x2) \
3482 RGFW_##x##func RGFW_##x##CallbackSrc = NULL; \
3483 RGFW_##x##func RGFW_set##x2##Callback(RGFW_##x##func func) { \
3484 RGFW_##x##func prev = RGFW_##x##CallbackSrc; \
3485 RGFW_##x##CallbackSrc = func; \
3486 return prev; \
3487 }
3488
3489 RGFW_CALLBACK_DEFINE(windowMaximized, WindowMaximized)
3490 RGFW_CALLBACK_DEFINE(windowMinimized, WindowMinimized)
3491 RGFW_CALLBACK_DEFINE(windowRestored, WindowRestored)
3492 RGFW_CALLBACK_DEFINE(windowMoved, WindowMoved)
3493 RGFW_CALLBACK_DEFINE(windowResized, WindowResized)
3494 RGFW_CALLBACK_DEFINE(windowQuit, WindowQuit)
3495 RGFW_CALLBACK_DEFINE(mousePos, MousePos)
3496 RGFW_CALLBACK_DEFINE(windowRefresh, WindowRefresh)
3497 RGFW_CALLBACK_DEFINE(focus, Focus)
3498 RGFW_CALLBACK_DEFINE(mouseNotify, MouseNotify)
3499 RGFW_CALLBACK_DEFINE(dataDrop, DataDrop)
3500 RGFW_CALLBACK_DEFINE(dataDrag, DataDrag)
3501 RGFW_CALLBACK_DEFINE(key, Key)
3502 RGFW_CALLBACK_DEFINE(keyChar, KeyChar)
3503 RGFW_CALLBACK_DEFINE(mouseButton, MouseButton)
3504 RGFW_CALLBACK_DEFINE(mouseScroll, MouseScroll)
3505 RGFW_CALLBACK_DEFINE(scaleUpdated, ScaleUpdated)
3506 RGFW_CALLBACK_DEFINE(monitor, Monitor)
3507 RGFW_CALLBACK_DEFINE(debug, Debug)
3508 #define RGFW_debugCallback(type, err, msg) if (RGFW_debugCallbackSrc) RGFW_debugCallbackSrc(type, err, msg);
3509 #undef RGFW_CALLBACK_DEFINE
3510
3511 void RGFW_windowMaximizedCallback(RGFW_window* win, i32 x, i32 y, i32 w, i32 h) {
3512 win->internal.flags |= RGFW_windowMaximize;
3513
3514 if (!(win->internal.enabledEvents & RGFW_windowMaximizedFlag)) return;
3515
3516 RGFW_event event;
3517 event.type = RGFW_windowMaximized;
3518 event.common.win = win;
3519 RGFW_eventQueuePush(&event);
3520
3521 if (RGFW_windowMaximizedCallbackSrc) RGFW_windowMaximizedCallbackSrc(win, x, y, w, h);
3522 }
3523
3524 void RGFW_windowMinimizedCallback(RGFW_window* win) {
3525 win->internal.flags |= RGFW_windowMinimize;
3526
3527 if (!(win->internal.enabledEvents & RGFW_windowMinimizedFlag)) return;
3528
3529 RGFW_event event;
3530 event.type = RGFW_windowMinimized;
3531 event.common.win = win;
3532 RGFW_eventQueuePush(&event);
3533
3534 if (RGFW_windowMinimizedCallbackSrc) RGFW_windowMinimizedCallbackSrc(win);
3535 }
3536
3537 void RGFW_windowRestoredCallback(RGFW_window* win, i32 x, i32 y, i32 w, i32 h) {
3538 win->internal.flags &= ~(u32)RGFW_windowMinimize;
3539 if (RGFW_window_isMaximized(win) == RGFW_FALSE) win->internal.flags &= ~(u32)RGFW_windowMaximize;
3540
3541 if (!(win->internal.enabledEvents & RGFW_windowRestoredFlag)) return;
3542
3543 RGFW_event event;
3544 event.type = RGFW_windowRestored;
3545 event.common.win = win;
3546 RGFW_eventQueuePush(&event);
3547
3548 if (RGFW_windowRestoredCallbackSrc) RGFW_windowRestoredCallbackSrc(win, x, y, w, h);
3549 }
3550
3551 void RGFW_windowMovedCallback(RGFW_window* win, i32 x, i32 y) {
3552 win->x = x;
3553 win->y = y;
3554 if (!(win->internal.enabledEvents & RGFW_windowMovedFlag)) return;
3555
3556 RGFW_event event;
3557 event.type = RGFW_windowMoved;
3558 event.common.win = win;
3559 RGFW_eventQueuePush(&event);
3560
3561 if (RGFW_windowMovedCallbackSrc) RGFW_windowMovedCallbackSrc(win, x, y);
3562 }
3563
3564 void RGFW_windowResizedCallback(RGFW_window* win, i32 w, i32 h) {
3565 win->w = w;
3566 win->h = h;
3567
3568 if (!(win->internal.enabledEvents & RGFW_windowResizedFlag)) return;
3569 RGFW_event event;
3570 event.type = RGFW_windowResized;
3571 event.common.win = win;
3572 RGFW_eventQueuePush(&event);
3573
3574 if (RGFW_windowResizedCallbackSrc) RGFW_windowResizedCallbackSrc(win, w, h);
3575 }
3576
3577 void RGFW_windowQuitCallback(RGFW_window* win) {
3578 win->internal.shouldClose = RGFW_TRUE;
3579
3580 RGFW_event event;
3581 event.type = RGFW_quit;
3582 event.common.win = win;
3583 RGFW_eventQueuePush(&event);
3584
3585 if (RGFW_windowQuitCallbackSrc) RGFW_windowQuitCallbackSrc(win);
3586 }
3587
3588 void RGFW_mousePosCallback(RGFW_window* win, i32 x, i32 y, float vecX, float vecY) {
3589 win->internal.lastMouseX = x;
3590 win->internal.lastMouseY = y;
3591 _RGFW->vectorX = vecX;
3592 _RGFW->vectorY = vecY;
3593
3594 if (!(win->internal.enabledEvents & RGFW_mousePosChangedFlag)) return;
3595
3596 RGFW_event event;
3597 event.type = RGFW_mousePosChanged;
3598 event.mouse.x = x;
3599 event.mouse.y = y;
3600 event.mouse.vecX = vecX;
3601 event.mouse.vecY = vecY;
3602 event.common.win = win;
3603
3604 RGFW_eventQueuePush(&event);
3605
3606 if (RGFW_mousePosCallbackSrc) RGFW_mousePosCallbackSrc(win, x, y, vecX, vecY);
3607 }
3608
3609 void RGFW_windowRefreshCallback(RGFW_window* win) {
3610 if (!(win->internal.enabledEvents & RGFW_windowRefreshFlag)) return;
3611 RGFW_event event;
3612 event.type = RGFW_windowRefresh;
3613 event.common.win = win;
3614 RGFW_eventQueuePush(&event);
3615
3616 if (RGFW_windowRefreshCallbackSrc) RGFW_windowRefreshCallbackSrc(win);
3617 }
3618
3619 void RGFW_focusCallback(RGFW_window* win, RGFW_bool inFocus) {
3620 win->internal.inFocus = inFocus;
3621
3622 if (win->internal.captureMouse) {
3623 RGFW_window_captureMousePlatform(win, inFocus);
3624 }
3625
3626 RGFW_event event;
3627 event.common.win = win;
3628
3629 if (inFocus == RGFW_TRUE) {
3630 if ((win->internal.flags & RGFW_windowFullscreen))
3631 RGFW_window_raise(win);
3632
3633 event.type = RGFW_focusIn;
3634 } else if (inFocus == RGFW_FALSE) {
3635 if ((win->internal.flags & RGFW_windowFullscreen))
3636 RGFW_window_minimize(win);
3637
3638 size_t key;
3639 for (key = 0; key < RGFW_keyLast; key++) {
3640 if (RGFW_isKeyDown((u8)key) == RGFW_FALSE) continue;
3641
3642 _RGFW->keyboard[key].current = RGFW_FALSE;
3643 if ((win->internal.enabledEvents & RGFW_BIT(RGFW_keyReleased))) {
3644 RGFW_keyCallback(win, (u8)key, win->internal.mod, RGFW_FALSE, RGFW_FALSE);
3645 }
3646 }
3647
3648 RGFW_resetKey();
3649 event.type = RGFW_focusOut;
3650 }
3651
3652 event.common.win = win;
3653
3654 RGFW_eventQueuePush(&event);
3655
3656 if (RGFW_focusCallbackSrc) RGFW_focusCallbackSrc(win, inFocus);
3657 }
3658
3659 void RGFW_mouseNotifyCallback(RGFW_window* win, i32 x, i32 y, RGFW_bool status) {
3660 win->internal.mouseInside = status;
3661 _RGFW->windowState.win = win;
3662
3663 win->internal.lastMouseX = x;
3664 win->internal.lastMouseY = y;
3665
3666 RGFW_event event;
3667 event.common.win = win;
3668 event.mouse.x = x;
3669 event.mouse.y = y;
3670
3671 if (status) {
3672 if (!(win->internal.enabledEvents & RGFW_mouseEnterFlag)) return;
3673 _RGFW->windowState.mouseEnter = RGFW_TRUE;
3674 _RGFW->windowState.win = win;
3675 event.type = RGFW_mouseEnter;
3676 } else {
3677 if (!(win->internal.enabledEvents & RGFW_mouseLeaveFlag)) return;
3678 _RGFW->windowState.winLeave = win;
3679 _RGFW->windowState.mouseLeave = RGFW_TRUE;
3680 event.type = RGFW_mouseLeave;
3681 }
3682
3683 RGFW_eventQueuePush(&event);
3684
3685 if (RGFW_mouseNotifyCallbackSrc) RGFW_mouseNotifyCallbackSrc(win, x, y, status);
3686 }
3687
3688 void RGFW_dataDropCallback(RGFW_window* win, char** files, size_t count) {
3689 if (!(win->internal.enabledEvents & RGFW_dataDropFlag) || !(win->internal.flags & RGFW_windowAllowDND))
3690 return;
3691
3692 _RGFW->windowState.win = win;
3693 _RGFW->windowState.dataDrop = RGFW_TRUE;
3694 _RGFW->windowState.filesCount = count;
3695
3696 RGFW_event event;
3697 event.type = RGFW_dataDrop;
3698 event.drop.files = files;
3699 event.drop.count = count;
3700 event.common.win = win;
3701 RGFW_eventQueuePush(&event);
3702
3703 if (RGFW_dataDropCallbackSrc) RGFW_dataDropCallbackSrc(win, files, count);
3704 }
3705
3706 void RGFW_dataDragCallback(RGFW_window* win, i32 x, i32 y) {
3707 _RGFW->windowState.win = win;
3708 _RGFW->windowState.dataDragging = RGFW_TRUE;
3709 _RGFW->windowState.dropX = x;
3710 _RGFW->windowState.dropY = y;
3711
3712 if (win->internal.enabledEvents & RGFW_dataDragFlag) return;
3713
3714 RGFW_event event;
3715 event.type = RGFW_dataDrag;
3716 event.drag.x = x;
3717 event.drag.y = y;
3718 event.common.win = win;
3719 RGFW_eventQueuePush(&event);
3720
3721 if (RGFW_dataDragCallbackSrc) RGFW_dataDragCallbackSrc(win, x, y);
3722 }
3723
3724 void RGFW_keyCharCallback(RGFW_window* win, u32 codepoint) {
3725 if (!(win->internal.enabledEvents & RGFW_keyCharFlag)) return;
3726
3727 RGFW_event event;
3728 event.type = RGFW_keyChar;
3729 event.keyChar.value = codepoint;
3730 event.common.win = win;
3731 RGFW_eventQueuePush(&event);
3732
3733 if (RGFW_keyCharCallbackSrc) RGFW_keyCharCallbackSrc(win, codepoint);
3734 }
3735
3736 void RGFW_keyCallback(RGFW_window* win, RGFW_key key, RGFW_keymod mod, RGFW_bool repeat, RGFW_bool press) {
3737 RGFW_event event;
3738
3739 if (press) {
3740 if (!(win->internal.enabledEvents & RGFW_keyPressedFlag)) return;
3741 event.type = RGFW_keyPressed;
3742 } else {
3743 if (!(win->internal.enabledEvents & RGFW_keyReleasedFlag)) return;
3744 event.type = RGFW_keyReleased;
3745 }
3746
3747 _RGFW->keyboard[key].prev = _RGFW->keyboard[key].current;
3748 _RGFW->keyboard[key].current = press;
3749
3750 event.key.value = key;
3751 event.key.mod = repeat;
3752 event.key.mod = mod;
3753 event.common.win = win;
3754 RGFW_eventQueuePush(&event);
3755
3756 if (RGFW_keyCallbackSrc) RGFW_keyCallbackSrc(win, key, mod, repeat, press);
3757 }
3758
3759 void RGFW_mouseButtonCallback(RGFW_window* win, RGFW_mouseButton button, RGFW_bool press) {
3760 RGFW_event event;
3761 if (press) {
3762 if (!(win->internal.enabledEvents & RGFW_mouseButtonPressedFlag)) return;
3763 event.type = RGFW_mouseButtonPressed;
3764 } else {
3765 if (!(win->internal.enabledEvents & RGFW_mouseButtonReleasedFlag)) return;
3766 event.type = RGFW_mouseButtonReleased;
3767 }
3768
3769 _RGFW->mouseButtons[button].prev = _RGFW->mouseButtons[button].current;
3770 _RGFW->mouseButtons[button].current = press;
3771
3772 event.button.value = button;
3773 event.common.win = win;
3774 RGFW_eventQueuePush(&event);
3775
3776 if (RGFW_mouseButtonCallbackSrc) RGFW_mouseButtonCallbackSrc(win, button, press);
3777 }
3778
3779 void RGFW_mouseScrollCallback(RGFW_window* win, float x, float y) {
3780 if (!(win->internal.enabledEvents & RGFW_mouseScrollFlag)) return;
3781 _RGFW->scrollX = x;
3782 _RGFW->scrollY = y;
3783
3784 RGFW_event event;
3785 event.type = RGFW_mouseScroll;
3786 event.scroll.x = x;
3787 event.scroll.y = y;
3788 event.common.win = win;
3789 RGFW_eventQueuePush(&event);
3790
3791 if (RGFW_mouseScrollCallbackSrc) RGFW_mouseScrollCallbackSrc(win, x, y);
3792 }
3793
3794 void RGFW_scaleUpdatedCallback(RGFW_window* win, float scaleX, float scaleY) {
3795 if (win->internal.flags & RGFW_windowScaleToMonitor) RGFW_window_scaleToMonitor(win);
3796 if (!(win->internal.enabledEvents & RGFW_scaleUpdatedFlag)) return;
3797
3798 RGFW_event event;
3799 event.type = RGFW_scaleUpdated;
3800 event.scale.x = scaleX;
3801 event.scale.y = scaleY;
3802 event.common.win = win;
3803 RGFW_eventQueuePush(&event);
3804
3805 if (RGFW_scaleUpdatedCallbackSrc) RGFW_scaleUpdatedCallbackSrc(win, scaleX, scaleY);
3806 }
3807
3808 void RGFW_monitorCallback(RGFW_window* win, const RGFW_monitor* monitor, RGFW_bool connected) {
3809 if (win) {
3810 if (connected && !(win->internal.enabledEvents & RGFW_monitorConnectedFlag)) return;
3811 if (!connected && !(win->internal.enabledEvents & RGFW_monitorDisconnectedFlag)) return;
3812 }
3813
3814 RGFW_event event;
3815 event.type = (connected) ? (RGFW_monitorConnected) : (RGFW_monitorDisconnected);
3816 event.monitor.monitor = monitor;
3817 event.common.win = win;
3818 RGFW_eventQueuePush(&event);
3819
3820 if (RGFW_monitorCallbackSrc) RGFW_monitorCallbackSrc(win, monitor, connected);
3821 }
3822
3823 #ifdef RGFW_DEBUG
3824 #include <stdio.h>
3825 #endif
3826
3827 void RGFW_sendDebugInfo(RGFW_debugType type, RGFW_errorCode err, const char* msg) {
3828 RGFW_debugCallback(type, err, msg);
3829
3830 #ifdef RGFW_DEBUG
3831 switch (type) {
3832 case RGFW_typeInfo: RGFW_PRINTF("RGFW INFO (%i %i): %s", type, err, msg); break;
3833 case RGFW_typeError: RGFW_PRINTF("RGFW DEBUG (%i %i): %s", type, err, msg); break;
3834 case RGFW_typeWarning: RGFW_PRINTF("RGFW WARNING (%i %i): %s", type, err, msg); break;
3835 default: break;
3836 }
3837
3838 RGFW_PRINTF("\n");
3839 #endif
3840 }
3841
3842 void RGFW_window_checkMode(RGFW_window* win);
3843 void RGFW_window_checkMode(RGFW_window* win) {
3844 if (RGFW_window_isMinimized(win) && (win->internal.enabledEvents & RGFW_windowMinimizedFlag)) {
3845 RGFW_windowMinimizedCallback(win);
3846 } else if (RGFW_window_isMaximized(win) && (win->internal.enabledEvents & RGFW_windowMaximizedFlag)) {
3847 RGFW_windowMaximizedCallback(win, win->x, win->y, win->w, win->h);
3848 } else if ((((win->internal.flags & RGFW_windowMinimize) && !RGFW_window_isMaximized(win)) ||
3849 (win->internal.flags & RGFW_windowMaximize && !RGFW_window_isMaximized(win))) && (win->internal.enabledEvents & RGFW_windowRestoredFlag)) {
3850 RGFW_windowRestoredCallback(win, win->x, win->y, win->w, win->h);
3851 }
3852 }
3853
3854 /*
3855 no more event call back defines
3856 */
3857
3858 size_t RGFW_sizeofInfo(void) { return sizeof(RGFW_info); }
3859 size_t RGFW_sizeofNativeImage(void) { return sizeof(RGFW_nativeImage); }
3860 size_t RGFW_sizeofSurface(void) { return sizeof(RGFW_surface); }
3861 size_t RGFW_sizeofWindow(void) { return sizeof(RGFW_window); }
3862 size_t RGFW_sizeofWindowSrc(void) { return sizeof(RGFW_window_src); }
3863
3864 RGFW_window_src* RGFW_window_getSrc(RGFW_window* win) { return &win->src; }
3865 RGFW_bool RGFW_window_getPosition(RGFW_window* win, i32* x, i32* y) { if (x) *x = win->x; if (y) *y = win->y; return RGFW_TRUE; }
3866 RGFW_bool RGFW_window_getSize(RGFW_window* win, i32* w, i32* h) { if (w) *w = win->w; if (h) *h = win->h; return RGFW_TRUE; }
3867 u32 RGFW_window_getFlags(RGFW_window* win) { return win->internal.flags; }
3868 RGFW_key RGFW_window_getExitKey(RGFW_window* win) { return win->internal.exitKey; }
3869 void RGFW_window_setExitKey(RGFW_window* win, RGFW_key key) { win->internal.exitKey = key; }
3870 void RGFW_window_setEnabledEvents(RGFW_window* win, RGFW_eventFlag events) { win->internal.enabledEvents = events; }
3871 RGFW_eventFlag RGFW_window_getEnabledEvents(RGFW_window* win) { return win->internal.enabledEvents; }
3872 void RGFW_window_setDisabledEvents(RGFW_window* win, RGFW_eventFlag events) { RGFW_window_setEnabledEvents(win, (RGFW_allEventFlags) & ~(u32)events); }
3873 void RGFW_window_setEventState(RGFW_window* win, RGFW_eventFlag event, RGFW_bool state) { RGFW_setBit(&win->internal.enabledEvents, event, state); }
3874 void* RGFW_window_getUserPtr(RGFW_window* win) { return win->userPtr; }
3875 void RGFW_window_setUserPtr(RGFW_window* win, void* ptr) { win->userPtr = ptr; }
3876
3877 RGFW_bool RGFW_window_getSizeInPixels(RGFW_window* win, i32* w, i32* h) {
3878 RGFW_monitor* mon = RGFW_window_getMonitor(win);
3879 if (mon == NULL) return RGFW_FALSE;
3880
3881 if (w) *w = (i32)((float)win->w * mon->pixelRatio);
3882 if (h) *h = (i32)((float)win->h * mon->pixelRatio);
3883
3884 return RGFW_TRUE;
3885 }
3886
3887
3888 #if defined(RGFW_USE_XDL) && defined(RGFW_X11)
3889 #define XDL_IMPLEMENTATION
3890 #include "XDL.h"
3891 #endif
3892
3893 #ifndef RGFW_FORCE_INIT
3894 RGFW_info _rgfwGlobal;
3895 #endif
3896
3897 i32 RGFW_init(void) { return RGFW_init_ptr(&_rgfwGlobal); }
3898 void RGFW_deinit(void) { RGFW_deinit_ptr(&_rgfwGlobal); }
3899
3900 i32 RGFW_initPlatform(void);
3901 void RGFW_deinitPlatform(void);
3902
3903 i32 RGFW_init_ptr(RGFW_info* info) {
3904 if (info == _RGFW || info == NULL) return 1;
3905
3906 RGFW_setInfo(info);
3907 RGFW_MEMSET(_RGFW, 0, sizeof(RGFW_info));
3908 _RGFW->queueEvents = RGFW_FALSE;
3909 _RGFW->polledEvents = RGFW_FALSE;
3910 #ifdef RGFW_WAYLAND
3911 _RGFW->useWaylandBool = RGFW_TRUE;
3912 #endif
3913
3914 _RGFW->files = (char**)(void*)_RGFW->filesSrc;
3915 u32 i;
3916 for (i = 0; i < RGFW_MAX_DROPS; i++)
3917 _RGFW->files[i] = (char*)(_RGFW->filesSrc + RGFW_MAX_DROPS + (i * RGFW_MAX_PATH));
3918
3919 _RGFW->monitors.freeList.head = &_RGFW->monitors.data[0];
3920 _RGFW->monitors.freeList.cur = _RGFW->monitors.freeList.head;
3921
3922 for (i = 1; i < RGFW_MAX_MONITORS; i++) {
3923 RGFW_monitorNode* newNode = &_RGFW->monitors.data[i];
3924 _RGFW->monitors.freeList.cur->next = newNode;
3925 _RGFW->monitors.freeList.cur = _RGFW->monitors.freeList.cur->next;
3926 }
3927
3928 _RGFW->monitors.list.head = NULL;
3929 _RGFW->monitors.list.head = NULL;
3930 RGFW_initKeycodes();
3931 i32 out = RGFW_initPlatform();
3932
3933 RGFW_pollMonitors();
3934
3935 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoGlobal, "global context initialized");
3936
3937 return out;
3938 }
3939
3940 #ifndef RGFW_EGL
3941 void RGFW_unloadEGL(void) { }
3942 #endif
3943
3944 void RGFW_deinit_ptr(RGFW_info* info) {
3945 if (info == NULL) return;
3946
3947 RGFW_setInfo(info);
3948 RGFW_unloadEGL();
3949 RGFW_deinitPlatform();
3950
3951 _RGFW->root = NULL;
3952 _RGFW->windowCount = 0;
3953 RGFW_setInfo(NULL);
3954 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoGlobal, "global context deinitialized");
3955 }
3956
3957 RGFW_window* RGFW_createWindow(const char* name, i32 x, i32 y, i32 w, i32 h, RGFW_windowFlags flags) {
3958 RGFW_window* win = (RGFW_window*)RGFW_ALLOC(sizeof(RGFW_window));
3959 RGFW_ASSERT(win != NULL);
3960 return RGFW_createWindowPtr(name, x, y, w, h, flags, win);
3961 }
3962
3963 void RGFW_window_close(RGFW_window* win) {
3964 RGFW_ASSERT(win != NULL);
3965 RGFW_window_closePtr(win);
3966 RGFW_FREE(win);
3967 }
3968
3969 RGFW_window* RGFW_createWindowPtr(const char* name, i32 x, i32 y, i32 w, i32 h, RGFW_windowFlags flags, RGFW_window* win) {
3970 RGFW_ASSERT(win != NULL);
3971 if (name == NULL) name = "\0";
3972
3973 RGFW_MEMSET(win, 0, sizeof(RGFW_window));
3974
3975 if (_RGFW == NULL) RGFW_init();
3976 _RGFW->windowCount++;
3977
3978 /* rect based the requested flags */
3979 if (_RGFW->root == NULL) {
3980 RGFW_setRootWindow(win);
3981 }
3982
3983 /* set and init the new window's data */
3984 win->x = x;
3985 win->y = y;
3986 win->w = w;
3987 win->h = h;
3988 win->internal.flags = flags;
3989 win->internal.enabledEvents = RGFW_allEventFlags;
3990
3991 RGFW_window* ret = RGFW_createWindowPlatform(name, flags, win);
3992
3993 #ifndef RGFW_X11
3994 RGFW_window_setFlagsInternal(win, flags, 0);
3995 #endif
3996
3997 #ifdef RGFW_OPENGL
3998 win->src.gfxType = 0;
3999 if (flags & RGFW_windowOpenGL)
4000 RGFW_window_createContext_OpenGL(win, RGFW_getGlobalHints_OpenGL());
4001 #endif
4002
4003 #ifdef RGFW_EGL
4004 if (flags & RGFW_windowEGL)
4005 RGFW_window_createContext_EGL(win, RGFW_getGlobalHints_OpenGL());
4006 #endif
4007
4008 /* X11 creates the window after the OpenGL context is created (because of visual garbage),
4009 * so we have to wait to set the flags
4010 * This is required so that way the user can create their own OpenGL context after RGFW_createWindow is used
4011 * if a window is created, CreateContext will delete the window and create a new one
4012 * */
4013 #ifdef RGFW_X11
4014 RGFW_window_setFlagsInternal(win, flags, 0);
4015 #endif
4016
4017 #ifdef RGFW_MACOS
4018 /*NOTE: another OpenGL/setFlags related hack, this because OSX the 'view' class must be setup after the NSOpenGL view is made AND after setFlags happens */
4019 RGFW_osx_initView(win);
4020 #endif
4021
4022 #ifdef RGFW_WAYLAND
4023 /* recieve all events needed to configure the surface */
4024 /* also gets the wl_outputs */
4025 if (RGFW_usingWayland()) {
4026 wl_display_roundtrip(_RGFW->wl_display);
4027 /* NOTE: this is a hack so that way wayland spawns a window, even if nothing is drawn */
4028 if (!(flags & RGFW_windowOpenGL) && !(flags & RGFW_windowEGL)) {
4029 u8* data = (u8*)RGFW_ALLOC((u32)(win->w * win->h * 3));
4030 RGFW_MEMSET(data, 0, (u32)(win->w * win->h * 3) * sizeof(u8));
4031 RGFW_surface* surface = RGFW_createSurface(data, win->w, win->h, RGFW_formatBGR8);
4032 RGFW_window_blitSurface(win, surface);
4033 RGFW_FREE(data);
4034 RGFW_surface_free(surface);
4035 }
4036 }
4037 #endif
4038
4039 if (!(flags & RGFW_windowHideMouse)) {
4040 RGFW_window_setMouseDefault(win);
4041 }
4042
4043 RGFW_window_setName(win, name);
4044 if (!(flags & RGFW_windowHide)) {
4045 flags |= RGFW_windowHide;
4046 RGFW_window_show(win);
4047 }
4048
4049 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoWindow, "a new window was created");
4050
4051 return ret;
4052 }
4053
4054 void RGFW_window_closePtr(RGFW_window* win) {
4055 RGFW_ASSERT(win != NULL);
4056
4057 if (win->internal.captureMouse) {
4058 RGFW_window_captureMouse(win, RGFW_FALSE);
4059 }
4060
4061 #ifdef RGFW_EGL
4062 if ((win->src.gfxType & RGFW_gfxEGL) && win->src.ctx.egl) {
4063 RGFW_window_deleteContext_EGL(win, win->src.ctx.egl);
4064 win->src.ctx.egl = NULL;
4065 }
4066 #endif
4067
4068 #ifdef RGFW_OPENGL
4069 if ((win->src.gfxType & RGFW_gfxNativeOpenGL) && win->src.ctx.native) {
4070 RGFW_window_deleteContext_OpenGL(win, win->src.ctx.native);
4071 win->src.ctx.native = NULL;
4072 }
4073 #endif
4074
4075 RGFW_window_closePlatform(win);
4076
4077 RGFW_clipboard_switch(NULL);
4078
4079 _RGFW->windowCount--;
4080 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoWindow, "a window was freed");
4081
4082 if (_RGFW->windowCount == 0 && !(win->internal.flags & RGFW_noDeinitOnClose)) RGFW_deinit();
4083 }
4084
4085 void RGFW_setQueueEvents(RGFW_bool queue) { _RGFW->queueEvents = RGFW_BOOL(queue); }
4086
4087 void RGFW_eventQueueFlush(void) { _RGFW->eventLen = 0; }
4088
4089 void RGFW_eventQueuePush(const RGFW_event* event) {
4090 if (_RGFW->queueEvents == RGFW_FALSE) return;
4091 RGFW_ASSERT(_RGFW->eventLen >= 0);
4092
4093 if (_RGFW->eventLen >= RGFW_MAX_EVENTS) {
4094 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errEventQueue, "Event queue limit 'RGFW_MAX_EVENTS' has been reached automatically flushing queue.");
4095 RGFW_eventQueueFlush();
4096 return;
4097 }
4098
4099 i32 eventTop = (_RGFW->eventBottom + _RGFW->eventLen) % RGFW_MAX_EVENTS;
4100 _RGFW->eventLen += 1;
4101 _RGFW->events[eventTop] = *event;
4102 }
4103
4104 RGFW_event* RGFW_eventQueuePop(void) {
4105 RGFW_ASSERT(_RGFW->eventLen >= 0 && _RGFW->eventLen <= RGFW_MAX_EVENTS);
4106 RGFW_event* ev;
4107
4108 if (_RGFW->eventLen == 0) {
4109 return NULL;
4110 }
4111
4112 ev = &_RGFW->events[_RGFW->eventBottom];
4113 _RGFW->eventLen -= 1;
4114 _RGFW->eventBottom = (_RGFW->eventBottom + 1) % RGFW_MAX_EVENTS;
4115
4116 return ev;
4117 }
4118
4119 RGFW_bool RGFW_checkEvent(RGFW_event* event) {
4120 if (_RGFW->eventLen == 0 && _RGFW->polledEvents == RGFW_FALSE) {
4121 _RGFW->queueEvents = RGFW_TRUE;
4122 RGFW_pollEvents();
4123 _RGFW->polledEvents = RGFW_TRUE;
4124 }
4125
4126 if (RGFW_checkQueuedEvent(event) == RGFW_FALSE) {
4127 _RGFW->polledEvents = RGFW_FALSE;
4128 return RGFW_FALSE;
4129 }
4130
4131 return RGFW_TRUE;
4132 }
4133
4134 RGFW_bool RGFW_checkQueuedEvent(RGFW_event* event) {
4135 RGFW_event* ev;
4136 _RGFW->queueEvents = RGFW_TRUE;
4137 /* check queued events */
4138 ev = RGFW_eventQueuePop();
4139 if (ev != NULL) {
4140 *event = *ev;
4141 return RGFW_TRUE;
4142 }
4143
4144 return RGFW_FALSE;
4145 }
4146
4147 void RGFW_resetPrevState(void) {
4148 size_t i; /*!< reset each previous state */
4149 for (i = 0; i < RGFW_keyLast; i++) _RGFW->keyboard[i].prev = _RGFW->keyboard[i].current;
4150 for (i = 0; i < RGFW_mouseFinal; i++) _RGFW->mouseButtons[i].prev = _RGFW->mouseButtons[i].current;
4151 _RGFW->scrollX = 0.0f;
4152 _RGFW->scrollY = 0.0f;
4153 _RGFW->vectorX = (float)0.0f;
4154 _RGFW->vectorY = (float)0.0f;
4155 RGFW_MEMSET(&_RGFW->windowState, 0, sizeof(_RGFW->windowState));
4156 }
4157
4158 RGFW_bool RGFW_isKeyPressed(RGFW_key key) {
4159 RGFW_ASSERT(_RGFW != NULL);
4160 return _RGFW->keyboard[key].current && !_RGFW->keyboard[key].prev;
4161 }
4162 RGFW_bool RGFW_isKeyDown(RGFW_key key) {
4163 RGFW_ASSERT(_RGFW != NULL);
4164 return _RGFW->keyboard[key].current;
4165 }
4166 RGFW_bool RGFW_isKeyReleased(RGFW_key key) {
4167 RGFW_ASSERT(_RGFW != NULL);
4168 return !_RGFW->keyboard[key].current && _RGFW->keyboard[key].prev;
4169 }
4170
4171
4172 RGFW_bool RGFW_isMousePressed(RGFW_mouseButton button) {
4173 RGFW_ASSERT(_RGFW != NULL);
4174 return _RGFW->mouseButtons[button].current && !_RGFW->mouseButtons[button].prev;
4175 }
4176 RGFW_bool RGFW_isMouseDown(RGFW_mouseButton button) {
4177 RGFW_ASSERT(_RGFW != NULL);
4178 return _RGFW->mouseButtons[button].current;
4179 }
4180 RGFW_bool RGFW_isMouseReleased(RGFW_mouseButton button) {
4181 RGFW_ASSERT(_RGFW != NULL);
4182 return !_RGFW->mouseButtons[button].current && _RGFW->mouseButtons[button].prev;
4183 }
4184
4185 void RGFW_getMouseScroll(float* x, float* y) {
4186 RGFW_ASSERT(_RGFW != NULL);
4187 if (x) *x = _RGFW->scrollX;
4188 if (y) *y = _RGFW->scrollY;
4189 }
4190
4191 void RGFW_getMouseVector(float* x, float* y) {
4192 RGFW_ASSERT(_RGFW != NULL);
4193 if (x) *x = _RGFW->vectorX;
4194 if (y) *y = _RGFW->vectorY;
4195 }
4196
4197 RGFW_bool RGFW_window_didMouseLeave(RGFW_window* win) { return _RGFW->windowState.winLeave == win && _RGFW->windowState.mouseLeave; }
4198 RGFW_bool RGFW_window_didMouseEnter(RGFW_window* win) { return _RGFW->windowState.win == win && _RGFW->windowState.mouseEnter; }
4199 RGFW_bool RGFW_window_isMouseInside(RGFW_window* win) { return win->internal.mouseInside; }
4200
4201 RGFW_bool RGFW_window_isDataDragging(RGFW_window* win) { return RGFW_window_getDataDrag(win, (i32*)NULL, (i32*)NULL); }
4202 RGFW_bool RGFW_window_didDataDrop(RGFW_window* win) { return RGFW_window_getDataDrop(win, (const char***)NULL, (size_t*)NULL);}
4203
4204
4205 RGFW_bool RGFW_window_getDataDrag(RGFW_window* win, i32* x, i32* y) {
4206 if (_RGFW->windowState.win != win || _RGFW->windowState.dataDragging == RGFW_FALSE) return RGFW_FALSE;
4207 if (x) *x = _RGFW->windowState.dropX;
4208 if (y) *y = _RGFW->windowState.dropY;
4209 return RGFW_TRUE;
4210 }
4211 RGFW_bool RGFW_window_getDataDrop(RGFW_window* win, const char*** files, size_t* count) {
4212 if (_RGFW->windowState.win != win || _RGFW->windowState.dataDrop == RGFW_FALSE) return RGFW_FALSE;
4213 if (files) *files = (const char**)_RGFW->files;
4214 if (count) *count = _RGFW->windowState.filesCount;
4215 return RGFW_TRUE;
4216 }
4217
4218 RGFW_bool RGFW_window_checkEvent(RGFW_window* win, RGFW_event* event) {
4219 if (_RGFW->eventLen == 0 && _RGFW->polledEvents == RGFW_FALSE) {
4220 _RGFW->queueEvents = RGFW_TRUE;
4221 RGFW_pollEvents();
4222 _RGFW->polledEvents = RGFW_TRUE;
4223 }
4224
4225 if (RGFW_window_checkQueuedEvent(win, event) == RGFW_FALSE) {
4226 _RGFW->polledEvents = RGFW_FALSE;
4227 return RGFW_FALSE;
4228 }
4229
4230 return RGFW_TRUE;
4231 }
4232
4233 RGFW_bool RGFW_window_checkQueuedEvent(RGFW_window* win, RGFW_event* event) {
4234 RGFW_event* ev;
4235 RGFW_ASSERT(win != NULL);
4236 _RGFW->queueEvents = RGFW_TRUE;
4237 /* check queued events */
4238 ev = RGFW_window_eventQueuePop(win);
4239 if (ev == NULL) return RGFW_FALSE;
4240
4241 *event = *ev;
4242 return RGFW_TRUE;
4243 }
4244
4245 RGFW_event* RGFW_window_eventQueuePop(RGFW_window* win) {
4246 RGFW_event* ev = RGFW_eventQueuePop();
4247 if (ev == NULL) return ev;
4248
4249 for (i32 i = 1; i < _RGFW->eventLen && ev->common.win != win && ev->common.win != NULL; i++) {
4250 RGFW_eventQueuePush(ev);
4251 ev = RGFW_eventQueuePop();
4252 }
4253
4254 if (ev->common.win != win && ev->common.win != NULL) {
4255 return NULL;
4256 }
4257
4258 return ev;
4259 }
4260
4261 void RGFW_setRootWindow(RGFW_window* win) { _RGFW->root = win; }
4262 RGFW_window* RGFW_getRootWindow(void) { return _RGFW->root; }
4263
4264 #ifndef RGFW_EGL
4265 RGFW_bool RGFW_loadEGL(void) { return RGFW_FALSE; }
4266 #endif
4267
4268 void RGFW_window_setFlagsInternal(RGFW_window* win, RGFW_windowFlags flags, RGFW_windowFlags cmpFlags) {
4269 if (flags & RGFW_windowNoBorder) RGFW_window_setBorder(win, 0);
4270 else if (cmpFlags & RGFW_windowNoBorder) RGFW_window_setBorder(win, 1);
4271 if (flags & RGFW_windowScaleToMonitor) RGFW_window_scaleToMonitor(win);
4272 if (flags & RGFW_windowMaximize) RGFW_window_maximize(win);
4273 else if (cmpFlags & RGFW_windowMaximize) RGFW_window_restore(win);
4274 if (flags & RGFW_windowMinimize) RGFW_window_minimize(win);
4275 else if (cmpFlags & RGFW_windowMinimize) RGFW_window_restore(win);
4276 if (flags & RGFW_windowCenter) RGFW_window_center(win);
4277 if (flags & RGFW_windowCenterCursor) RGFW_window_moveMouse(win, win->x + (win->w / 2), win->y + (win->h / 2));
4278 if (flags & RGFW_windowFullscreen) RGFW_window_setFullscreen(win, RGFW_TRUE);
4279 else if (cmpFlags & RGFW_windowFullscreen) RGFW_window_setFullscreen(win, 0);
4280 if (flags & RGFW_windowHideMouse) RGFW_window_showMouse(win, 0);
4281 else if (cmpFlags & RGFW_windowHideMouse) RGFW_window_showMouse(win, 1);
4282 if (flags & RGFW_windowHide) RGFW_window_hide(win);
4283 else if (cmpFlags & RGFW_windowHide) RGFW_window_show(win);
4284 if (flags & RGFW_windowFloating) RGFW_window_setFloating(win, 1);
4285 else if (cmpFlags & RGFW_windowFloating) RGFW_window_setFloating(win, 0);
4286 if (flags & RGFW_windowRawMouse) RGFW_window_setRawMouseMode(win, RGFW_TRUE);
4287 else if (cmpFlags & RGFW_windowRawMouse) RGFW_window_setRawMouseMode(win, RGFW_FALSE);
4288 if (flags & RGFW_windowCaptureMouse) RGFW_window_captureRawMouse(win, RGFW_TRUE);
4289 else if (cmpFlags & RGFW_windowCaptureMouse) RGFW_window_captureMouse(win, RGFW_FALSE);
4290 if (flags & RGFW_windowFocus) RGFW_window_focus(win);
4291
4292 if (flags & RGFW_windowNoResize) {
4293 RGFW_window_setMaxSize(win, win->w, win->h);
4294 RGFW_window_setMinSize(win, win->w, win->h);
4295 } else if (cmpFlags & RGFW_windowNoResize) {
4296 RGFW_window_setMaxSize(win, 0, 0);
4297 RGFW_window_setMinSize(win, 0, 0);
4298 }
4299
4300 win->internal.flags = flags;
4301 }
4302
4303
4304 void RGFW_window_setFlags(RGFW_window* win, RGFW_windowFlags flags) { RGFW_window_setFlagsInternal(win, flags, win->internal.flags); }
4305
4306 RGFW_bool RGFW_window_isInFocus(RGFW_window* win) {
4307 #ifdef RGFW_WASM
4308 return RGFW_TRUE;
4309 #else
4310 return RGFW_BOOL(win->internal.inFocus);
4311 #endif
4312 }
4313
4314 void RGFW_setClassName(const char* name) { RGFW_init(); _RGFW->className = name; }
4315
4316 #ifndef RGFW_X11
4317 void RGFW_setXInstName(const char* name) { RGFW_UNUSED(name); }
4318 #endif
4319
4320 RGFW_bool RGFW_window_getMouse(RGFW_window* win, i32* x, i32* y) {
4321 RGFW_ASSERT(win != NULL);
4322 if (x) *x = win->internal.lastMouseX;
4323 if (y) *y = win->internal.lastMouseY;
4324 return RGFW_TRUE;
4325 }
4326
4327 RGFW_bool RGFW_window_isKeyPressed(RGFW_window* win, RGFW_key key) { return RGFW_isKeyPressed(key) && RGFW_window_isInFocus(win); }
4328 RGFW_bool RGFW_window_isKeyDown(RGFW_window* win, RGFW_key key) { return RGFW_isKeyDown(key) && RGFW_window_isInFocus(win); }
4329 RGFW_bool RGFW_window_isKeyReleased(RGFW_window* win, RGFW_key key) { return RGFW_isKeyReleased(key) && RGFW_window_isInFocus(win); }
4330
4331 RGFW_bool RGFW_window_isMousePressed(RGFW_window* win, RGFW_mouseButton button) { return RGFW_isMousePressed(button) && RGFW_window_isInFocus(win); }
4332 RGFW_bool RGFW_window_isMouseDown(RGFW_window* win, RGFW_mouseButton button) { return RGFW_isMouseDown(button) && RGFW_window_isInFocus(win); }
4333 RGFW_bool RGFW_window_isMouseReleased(RGFW_window* win, RGFW_mouseButton button) { return RGFW_isMouseReleased(button) && RGFW_window_isInFocus(win); }
4334
4335
4336
4337 #ifndef RGFW_X11
4338 void* RGFW_getDisplay_X11(void) { return NULL; }
4339 u64 RGFW_window_getWindow_X11(RGFW_window* win) { RGFW_UNUSED(win); return 0; }
4340 #endif
4341
4342 #ifndef RGFW_WAYLAND
4343 struct wl_display* RGFW_getDisplay_Wayland(void) { return NULL; }
4344 struct wl_surface* RGFW_window_getWindow_Wayland(RGFW_window* win) { RGFW_UNUSED(win); return NULL; }
4345 #endif
4346
4347 #ifndef RGFW_WINDOWS
4348 void* RGFW_window_getHWND(RGFW_window* win) { RGFW_UNUSED(win); return NULL; }
4349 void* RGFW_window_getHDC(RGFW_window* win) { RGFW_UNUSED(win); return NULL; }
4350 #endif
4351
4352 #ifndef RGFW_MACOS
4353 void* RGFW_window_getView_OSX(RGFW_window* win) { RGFW_UNUSED(win); return NULL; }
4354 void RGFW_window_setLayer_OSX(RGFW_window* win, void* layer) { RGFW_UNUSED(win); RGFW_UNUSED(layer); }
4355 void* RGFW_getLayer_OSX(void) { return NULL; }
4356 void* RGFW_window_getWindow_OSX(RGFW_window* win) { RGFW_UNUSED(win); return NULL; }
4357 #endif
4358
4359 void RGFW_setBit(u32* var, u32 mask, RGFW_bool set) {
4360 if (set) *var |= mask;
4361 else *var &= ~mask;
4362 }
4363
4364 void RGFW_window_center(RGFW_window* win) {
4365 RGFW_ASSERT(win != NULL);
4366 RGFW_monitor* mon = RGFW_window_getMonitor(win);
4367 if (mon == NULL) return;
4368
4369 RGFW_window_move(win, (i32)(mon->mode.w - win->w) / 2, (mon->mode.h - win->h) / 2);
4370 }
4371
4372 RGFW_bool RGFW_monitor_scaleToWindow(RGFW_monitor* mon, RGFW_window* win) {
4373 RGFW_monitorMode mode;
4374 RGFW_ASSERT(win != NULL);
4375
4376 mode.w = win->w;
4377 mode.h = win->h;
4378 RGFW_bool ret = RGFW_monitor_requestMode(mon, &mode, RGFW_monitorScale);
4379
4380
4381 /* move window to monitor origin so it doesn't move to the next monitor */
4382 RGFW_window_move(win, mon->x, mon->y);
4383
4384 return ret;
4385 }
4386
4387 void RGFW_splitBPP(u32 bpp, RGFW_monitorMode* mode) {
4388 if (bpp == 32) bpp = 24;
4389 mode->red = mode->green = mode->blue = (u8)(bpp / 3);
4390
4391 u32 delta = bpp - (mode->red * 3); /* handle leftovers */
4392 if (delta >= 1) mode->green = mode->green + 1;
4393 if (delta == 2) mode->red = mode->red + 1;
4394 }
4395
4396 RGFW_bool RGFW_monitorModeCompare(RGFW_monitorMode* mon, RGFW_monitorMode* mon2, RGFW_modeRequest request) {
4397 RGFW_ASSERT(mon);
4398 RGFW_ASSERT(mon2);
4399
4400 return (((mon->w == mon2->w && mon->h == mon2->h) || !(request & RGFW_monitorScale)) &&
4401 ((mon->refreshRate == mon2->refreshRate) || !(request & RGFW_monitorRefresh)) &&
4402 ((mon->red == mon2->red && mon->green == mon2->green && mon->blue == mon2->blue) || !(request & RGFW_monitorRGB)));
4403 }
4404
4405 RGFW_bool RGFW_window_shouldClose(RGFW_window* win) {
4406 return (win == NULL || win->internal.shouldClose || (win->internal.exitKey && RGFW_window_isKeyDown(win, win->internal.exitKey)));
4407 }
4408
4409 void RGFW_window_setShouldClose(RGFW_window* win, RGFW_bool shouldClose) {
4410 if (shouldClose) {
4411 RGFW_windowQuitCallback(win);
4412 } else {
4413 win->internal.shouldClose = RGFW_FALSE;
4414 }
4415 }
4416
4417 void RGFW_window_scaleToMonitor(RGFW_window* win) {
4418 RGFW_monitor* monitor = RGFW_window_getMonitor(win);
4419 if (monitor->scaleX == 0 && monitor->scaleY == 0)
4420 return;
4421
4422 RGFW_window_resize(win, (i32)(monitor->scaleX * (float)win->w), (i32)(monitor->scaleY * (float)win->h));
4423 }
4424
4425 void RGFW_window_moveToMonitor(RGFW_window* win, RGFW_monitor* m) {
4426 RGFW_window_move(win, m->x + win->x, m->y + win->y);
4427 }
4428
4429 RGFW_surface* RGFW_createSurface(u8* data, i32 w, i32 h, RGFW_format format) {
4430 RGFW_surface* surface = (RGFW_surface*)RGFW_ALLOC(sizeof(RGFW_surface));
4431 RGFW_MEMSET(surface, 0, sizeof(RGFW_surface));
4432 RGFW_createSurfacePtr(data, w, h, format, surface);
4433 return surface;
4434 }
4435
4436 void RGFW_surface_setConvertFunc(RGFW_surface* surface, RGFW_convertImageDataFunc func) {
4437 surface->convertFunc = func;
4438 }
4439
4440 void RGFW_surface_free(RGFW_surface* surface) {
4441 RGFW_surface_freePtr(surface);
4442 RGFW_FREE(surface);
4443 }
4444
4445 RGFW_nativeImage* RGFW_surface_getNativeImage(RGFW_surface* surface) {
4446 return &surface->native;
4447 }
4448
4449 RGFW_surface* RGFW_window_createSurface(RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format) {
4450 RGFW_surface* surface = (RGFW_surface*)RGFW_ALLOC(sizeof(RGFW_surface));
4451 RGFW_MEMSET(surface, 0, sizeof(RGFW_surface));
4452 RGFW_window_createSurfacePtr(win, data, w, h, format, surface);
4453 return surface;
4454 }
4455
4456 #ifndef RGFW_X11
4457 RGFW_bool RGFW_window_createSurfacePtr(RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format, RGFW_surface* surface) {
4458 RGFW_UNUSED(win);
4459 return RGFW_createSurfacePtr(data, w, h, format, surface);
4460 }
4461 #endif
4462
4463 const RGFW_colorLayout RGFW_layouts[RGFW_formatCount] = {
4464 { 0, 1, 2, 3, 3 }, /* RGFW_formatRGB8 */
4465 { 2, 1, 0, 3, 3 }, /* RGFW_formatBGR8 */
4466 { 0, 1, 2, 3, 4 }, /* RGFW_formatRGBA8 */
4467 { 1, 2, 3, 0, 4 }, /* RGFW_formatARGB8 */
4468 { 2, 1, 0, 3, 4 }, /* RGFW_formatBGRA8 */
4469 { 3, 2, 1, 0, 4 }, /* RGFW_formatABGR8 */
4470 };
4471
4472
4473 void RGFW_copyImageData(u8* dest_data, i32 w, i32 h, RGFW_format dest_format, u8* src_data, RGFW_format src_format, RGFW_convertImageDataFunc func) {
4474 RGFW_copyImageData64(dest_data, w, h, dest_format, src_data, src_format, RGFW_FALSE, func);
4475 }
4476
4477 RGFWDEF void RGFW_convertImageData64(u8* dest_data, u8* src_data, const RGFW_colorLayout* srcLayout, const RGFW_colorLayout* destLayout, size_t count, RGFW_bool is64bit);
4478 void RGFW_convertImageData64(u8* dest_data, u8* src_data, const RGFW_colorLayout* srcLayout, const RGFW_colorLayout* destLayout, size_t count, RGFW_bool is64bit) {
4479 u32 i, i2 = 0;
4480 u8 rgba[4] = {0};
4481
4482 for (i = 0; i < count; i++) {
4483 const u8* src_px = &src_data[i * srcLayout->channels];
4484 u8* dst_px = &dest_data[i2 * destLayout->channels];
4485 rgba[0] = src_px[srcLayout->r];
4486 rgba[1] = src_px[srcLayout->g];
4487 rgba[2] = src_px[srcLayout->b];
4488 rgba[3] = (srcLayout->channels == 4) ? src_px[srcLayout->a] : 255;
4489
4490 dst_px[destLayout->r] = rgba[0];
4491 dst_px[destLayout->g] = rgba[1];
4492 dst_px[destLayout->b] = rgba[2];
4493 if (destLayout->channels == 4)
4494 dst_px[destLayout->a] = rgba[3];
4495
4496 i2 += 1 + is64bit;
4497 }
4498 }
4499
4500 void RGFW_copyImageData64(u8* dest_data, i32 dest_w, i32 dest_h, RGFW_format dest_format, u8* src_data, RGFW_format src_format, RGFW_bool is64bit, RGFW_convertImageDataFunc func) {
4501 RGFW_ASSERT(dest_data && src_data);
4502
4503 u32 count = (u32)(dest_w * dest_h);
4504
4505 if (src_format == dest_format) {
4506 u32 channels = (dest_format >= RGFW_formatRGBA8) ? 4 : 3;
4507 RGFW_MEMCPY(dest_data, src_data, count * channels);
4508 return;
4509 }
4510
4511 const RGFW_colorLayout* srcLayout = &RGFW_layouts[src_format];
4512 const RGFW_colorLayout* destLayout = &RGFW_layouts[dest_format];
4513
4514 if (is64bit || func == NULL) {
4515 RGFW_convertImageData64(dest_data, src_data, srcLayout, destLayout, count, is64bit);
4516 } else {
4517 func(dest_data, src_data, srcLayout, destLayout, count);
4518 }
4519 }
4520
4521 RGFW_monitorNode* RGFW_monitors_add(const RGFW_monitor* mon) {
4522 RGFW_monitorNode* node = NULL;
4523 if (_RGFW->monitors.freeList.head == NULL) return node;
4524
4525 node = _RGFW->monitors.freeList.head;
4526
4527 _RGFW->monitors.freeList.head = node->next;
4528 if (_RGFW->monitors.freeList.head == NULL) {
4529 _RGFW->monitors.freeList.cur = NULL;
4530 }
4531
4532 node->next = NULL;
4533
4534 if (_RGFW->monitors.list.head == NULL) {
4535 _RGFW->monitors.list.head = node;
4536 } else {
4537 _RGFW->monitors.list.cur->next = node;
4538 }
4539
4540 _RGFW->monitors.list.cur = node;
4541
4542 if (mon) node->mon = *mon;
4543 node->mon.node = node;
4544 node->disconnected = RGFW_FALSE;
4545
4546 _RGFW->monitors.count += 1;
4547 return node;
4548 }
4549
4550 void RGFW_monitors_remove(RGFW_monitorNode* node, RGFW_monitorNode* prev) {
4551 _RGFW->monitors.count -= 1;
4552
4553 /* remove node from the list */
4554 if (prev != node) {
4555 prev->next = node->next;
4556 } else { /* node is the head */
4557 _RGFW->monitors.list.head = NULL;
4558 }
4559
4560 node->next = NULL;
4561
4562 /* move node to the free list */
4563 if (_RGFW->monitors.freeList.head == NULL) {
4564 _RGFW->monitors.freeList.head = node;
4565 } else {
4566 _RGFW->monitors.freeList.cur->next = node;
4567 }
4568
4569 _RGFW->monitors.freeList.cur = node;
4570 }
4571
4572 void RGFW_monitors_refresh(void) {
4573 RGFW_monitorNode* prev = _RGFW->monitors.list.head;
4574 for (RGFW_monitorNode* node = _RGFW->monitors.list.head; node; node = node->next) {
4575 if (node->disconnected == RGFW_FALSE) continue;
4576
4577 RGFW_monitorCallback(_RGFW->root, &node->mon, RGFW_FALSE);
4578 RGFW_monitors_remove(node, prev);
4579 prev = node;
4580 }
4581 }
4582
4583 RGFW_monitorMode* RGFW_monitor_getModes(RGFW_monitor* monitor, size_t* count) {
4584 size_t num = RGFW_monitor_getModesPtr(monitor, NULL);
4585 RGFW_monitorMode* modes = (RGFW_monitorMode*)RGFW_ALLOC(num * sizeof(RGFW_monitorNode));
4586 num = RGFW_monitor_getModesPtr(monitor, &modes);
4587
4588 if (count) *count = num;
4589 return modes;
4590 }
4591
4592 void RGFW_freeModes(RGFW_monitorMode* modes) {
4593 RGFW_FREE(modes);
4594 }
4595
4596 RGFW_bool RGFW_monitor_findClosestMode(RGFW_monitor* monitor, RGFW_monitorMode* mode, RGFW_monitorMode* closest) {
4597 size_t count = RGFW_monitor_getModesPtr(monitor, NULL);
4598 RGFW_monitorMode* modes = (RGFW_monitorMode*)RGFW_ALLOC(count * sizeof(RGFW_monitorNode));
4599 count = RGFW_monitor_getModesPtr(monitor, &modes);
4600
4601 RGFW_monitorMode* chosen = NULL;
4602
4603 u32 topScore = 1;
4604 for (size_t i = 0; i < count; i++) {
4605 RGFW_monitorMode* mode2 = &modes[i];
4606
4607 u32 score = 0;
4608 if (mode->w == mode2->w && mode->h == mode2->h) score += 1000;
4609 if (mode->red == mode2->red && mode->green == mode2->green && mode->blue == mode2->blue) score += 100;
4610 if (mode->refreshRate == mode->refreshRate) score += 10;
4611
4612 if (score > topScore) {
4613 topScore = score;
4614 chosen = mode2;
4615 }
4616 }
4617
4618 if (chosen && closest) *closest = *chosen;
4619
4620
4621 RGFW_FREE(modes);
4622
4623 return (chosen == NULL) ? RGFW_FALSE : RGFW_TRUE;
4624 }
4625
4626 RGFW_bool RGFW_monitor_getPosition(RGFW_monitor* monitor, i32* x, i32* y) {
4627 if (x) *x = monitor->x;
4628 if (y) *y = monitor->y;
4629 return RGFW_TRUE;
4630 }
4631
4632 const char* RGFW_monitor_getName(RGFW_monitor* monitor) {
4633 return monitor->name;
4634 }
4635
4636 RGFW_bool RGFW_monitor_getScale(RGFW_monitor* monitor, float* x, float* y) {
4637 if (x) *x = monitor->scaleX;
4638 if (y) *y = monitor->scaleY;
4639 return RGFW_TRUE;
4640 }
4641
4642 RGFW_bool RGFW_monitor_getPhysicalSize(RGFW_monitor* monitor, float* w, float* h) {
4643 if (w) *w = monitor->physW;
4644 if (h) *h = monitor->physH;
4645 return RGFW_TRUE;
4646 }
4647
4648 void RGFW_monitor_setUserPtr(RGFW_monitor* monitor, void* userPtr) {
4649 monitor->userPtr = userPtr;
4650 }
4651
4652 void* RGFW_monitor_getUserPtr(RGFW_monitor* monitor) {
4653 return monitor->userPtr;
4654 }
4655
4656 RGFW_bool RGFW_monitor_getMode(RGFW_monitor* monitor, RGFW_monitorMode* mode) {
4657 if (mode) *mode = monitor->mode;
4658 return RGFW_TRUE;
4659 }
4660
4661 RGFW_gammaRamp* RGFW_monitor_getGammaRamp(RGFW_monitor* monitor) {
4662 RGFW_gammaRamp* ramp = (RGFW_gammaRamp*)RGFW_ALLOC(sizeof(RGFW_gammaRamp));
4663 ramp->count = RGFW_monitor_getGammaRampPtr(monitor, NULL);
4664 ramp->red = (u16*)RGFW_ALLOC(sizeof(u16) * ramp->count);
4665 ramp->green = (u16*)RGFW_ALLOC(sizeof(u16) * ramp->count);
4666 ramp->blue = (u16*)RGFW_ALLOC(sizeof(u16) * ramp->count);
4667 ramp->count = RGFW_monitor_getGammaRampPtr(monitor, ramp);
4668
4669 return ramp;
4670 }
4671
4672 void RGFW_freeGammaRamp(RGFW_gammaRamp* ramp) {
4673 RGFW_FREE(ramp->red);
4674 RGFW_FREE(ramp->green);
4675 RGFW_FREE(ramp->blue);
4676 RGFW_FREE(ramp);
4677 }
4678
4679 RGFW_bool RGFW_monitor_setGammaPtr(RGFW_monitor* monitor, float gamma, u16* ptr, size_t count) {
4680 RGFW_ASSERT(monitor);
4681 RGFW_ASSERT(gamma > 0.0f);
4682
4683 size_t i;
4684 for (i = 0; i < count; i++) {
4685 float value = (float)i / (float) (count - 1);
4686 #ifndef RGFW_NO_MATH
4687 value = powf(value, 1.f / gamma) * 65535.f + 0.5f;
4688 #endif
4689 value = RGFW_MIN(value, 65535.f);
4690
4691 ptr[i] = (u16)value;
4692 }
4693
4694 RGFW_gammaRamp ramp;
4695 ramp.red = ptr;
4696 ramp.green = ptr;
4697 ramp.blue = ptr;
4698 ramp.count = count;
4699
4700 return RGFW_monitor_setGammaRamp(monitor, &ramp);
4701 }
4702
4703 RGFW_bool RGFW_monitor_setGamma(RGFW_monitor* monitor, float gamma) {
4704 size_t count = RGFW_monitor_getGammaRampPtr(monitor, NULL);
4705 u16* ptr = (u16*)RGFW_ALLOC(count * sizeof(u16));
4706
4707 RGFW_bool ret = RGFW_monitor_setGammaPtr(monitor, gamma, ptr, count);
4708 RGFW_FREE(ptr);
4709
4710 return ret;
4711 }
4712
4713 RGFW_monitor** RGFW_getMonitors(size_t* len) {
4714 static RGFW_monitor* monitors[RGFW_MAX_MONITORS];
4715 RGFW_init();
4716 if (len != NULL) {
4717 *len = _RGFW->monitors.count;
4718 }
4719
4720 u8 i = 0;
4721 RGFW_monitorNode* cur_node = _RGFW->monitors.list.head;
4722 while (cur_node != NULL) {
4723 monitors[i] = &cur_node->mon;
4724 i++;
4725 cur_node = cur_node->next;
4726 }
4727 return monitors;
4728 }
4729
4730 RGFW_monitor* RGFW_getPrimaryMonitor(void) {
4731 if (_RGFW->monitors.primary == NULL) {
4732 _RGFW->monitors.primary = _RGFW->monitors.list.head;
4733 }
4734
4735 return &_RGFW->monitors.primary->mon;
4736 }
4737
4738 RGFW_bool RGFW_window_setIcon(RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format) {
4739 return RGFW_window_setIconEx(win, data, w, h, format, RGFW_iconBoth);
4740 }
4741
4742 void RGFW_window_captureMouse(RGFW_window* win, RGFW_bool state) {
4743 win->internal.captureMouse = state;
4744 RGFW_window_captureMousePlatform(win, state);
4745 }
4746
4747 void RGFW_window_setRawMouseMode(RGFW_window* win, RGFW_bool state) {
4748 win->internal.rawMouse = state;
4749 RGFW_window_setRawMouseModePlatform(win, state);
4750 }
4751
4752 void RGFW_window_captureRawMouse(RGFW_window* win, RGFW_bool state) {
4753 RGFW_window_captureMouse(win, state);
4754 RGFW_window_setRawMouseMode(win, state);
4755 }
4756
4757 RGFW_bool RGFW_window_isRawMouseMode(RGFW_window* win) { return RGFW_BOOL(win->internal.rawMouse); }
4758 RGFW_bool RGFW_window_isCaptured(RGFW_window* win) { return RGFW_BOOL(win->internal.captureMouse); }
4759
4760 void RGFW_updateKeyMod(RGFW_window* win, RGFW_keymod mod, RGFW_bool value) {
4761 if (value) win->internal.mod |= mod;
4762 else win->internal.mod &= ~mod;
4763 }
4764
4765 void RGFW_updateKeyModsEx(RGFW_window* win, RGFW_bool capital, RGFW_bool numlock, RGFW_bool control, RGFW_bool alt, RGFW_bool shift, RGFW_bool super, RGFW_bool scroll) {
4766 RGFW_updateKeyMod(win, RGFW_modCapsLock, capital);
4767 RGFW_updateKeyMod(win, RGFW_modNumLock, numlock);
4768 RGFW_updateKeyMod(win, RGFW_modControl, control);
4769 RGFW_updateKeyMod(win, RGFW_modAlt, alt);
4770 RGFW_updateKeyMod(win, RGFW_modShift, shift);
4771 RGFW_updateKeyMod(win, RGFW_modSuper, super);
4772 RGFW_updateKeyMod(win, RGFW_modScrollLock, scroll);
4773 }
4774
4775 void RGFW_updateKeyMods(RGFW_window* win, RGFW_bool capital, RGFW_bool numlock, RGFW_bool scroll) {
4776 RGFW_updateKeyModsEx(win, capital, numlock,
4777 RGFW_window_isKeyDown(win, RGFW_controlL) || RGFW_window_isKeyDown(win, RGFW_controlR),
4778 RGFW_window_isKeyDown(win, RGFW_altL) || RGFW_window_isKeyDown(win, RGFW_altR),
4779 RGFW_window_isKeyDown(win, RGFW_shiftL) || RGFW_window_isKeyDown(win, RGFW_shiftR),
4780 RGFW_window_isKeyDown(win, RGFW_superL) || RGFW_window_isKeyDown(win, RGFW_superR),
4781 scroll);
4782 }
4783
4784 void RGFW_window_showMouseFlags(RGFW_window* win, RGFW_bool show) {
4785 if (show && (win->internal.flags & RGFW_windowHideMouse))
4786 win->internal.flags ^= RGFW_windowHideMouse;
4787 else if (!show && !(win->internal.flags & RGFW_windowHideMouse))
4788 win->internal.flags |= RGFW_windowHideMouse;
4789 }
4790
4791 RGFW_bool RGFW_window_isMouseHidden(RGFW_window* win) {
4792 return (RGFW_bool)RGFW_BOOL(((RGFW_window*)win)->internal.flags & RGFW_windowHideMouse);
4793 }
4794
4795 RGFW_bool RGFW_window_borderless(RGFW_window* win) {
4796 return (RGFW_bool)RGFW_BOOL(win->internal.flags & RGFW_windowNoBorder);
4797 }
4798
4799 RGFW_bool RGFW_window_isFullscreen(RGFW_window* win){ return RGFW_BOOL(win->internal.flags & RGFW_windowFullscreen); }
4800 RGFW_bool RGFW_window_allowsDND(RGFW_window* win) { return RGFW_BOOL(win->internal.flags & RGFW_windowAllowDND); }
4801
4802 #ifndef RGFW_WINDOWS
4803 void RGFW_window_setDND(RGFW_window* win, RGFW_bool allow) {
4804 RGFW_setBit(&win->internal.flags, RGFW_windowAllowDND, allow);
4805 }
4806 #endif
4807
4808 #if defined(RGFW_X11) || defined(RGFW_MACOS) || defined(RGFW_WASM) || defined(RGFW_WAYLAND)
4809 #ifndef __USE_POSIX199309
4810 #define __USE_POSIX199309
4811 #endif
4812 #include <time.h>
4813 struct timespec;
4814 #endif
4815
4816 #if defined(RGFW_WAYLAND) || defined(RGFW_X11) || defined(RGFW_WINDOWS)
4817 void RGFW_window_showMouse(RGFW_window* win, RGFW_bool show) {
4818 RGFW_window_showMouseFlags(win, show);
4819 if (show == RGFW_FALSE)
4820 RGFW_window_setMouse(win, _RGFW->hiddenMouse);
4821 else
4822 RGFW_window_setMouseDefault(win);
4823 }
4824 #endif
4825
4826 #ifndef RGFW_MACOS
4827 void RGFW_moveToMacOSResourceDir(void) { }
4828 #endif
4829
4830 RGFWDEF RGFW_bool RGFW_isLatin(const char *string, size_t length);
4831 RGFW_bool RGFW_isLatin(const char *string, size_t length) {
4832 for (size_t i = 0; i < length; i++) {
4833 if ((u8)string[i] >= 0x80) {
4834 return RGFW_TRUE;
4835 }
4836 }
4837 return RGFW_FALSE;
4838 }
4839
4840 RGFWDEF u32 RGFW_decodeUTF8(const char* string, size_t* starting_index);
4841 u32 RGFW_decodeUTF8(const char* string, size_t* starting_index) {
4842 static const u32 offsets[] = {
4843 0x00000000u, 0x00003080u, 0x000e2080u,
4844 0x03c82080u, 0xfa082080u, 0x82082080u
4845 };
4846
4847 u32 codepoint = (u8)string[(*starting_index)];
4848 size_t count;
4849 for (count = 1; (string[count + (*starting_index)] & 0xc0) == 0x80; count++) {
4850 codepoint = (codepoint << 6) + (u8)string[count + (*starting_index)];
4851 }
4852
4853 *starting_index += count;
4854
4855 RGFW_ASSERT(count <= 6);
4856 return codepoint - offsets[count - 1];
4857 }
4858
4859 /*
4860 graphics API specific code (end of generic code)
4861 starts here
4862 */
4863
4864
4865 /*
4866 OpenGL defines start here (Normal, EGL, OSMesa)
4867 */
4868
4869 #if defined(RGFW_OPENGL)
4870 /* EGL, OpenGL */
4871 #define RGFW_DEFAULT_GL_HINTS { \
4872 /* Stencil */ 0, \
4873 /* Samples */ 0, \
4874 /* Stereo */ RGFW_FALSE, \
4875 /* AuxBuffers */ 0, \
4876 /* DoubleBuffer */ RGFW_TRUE, \
4877 /* Red */ 8, \
4878 /* Green */ 8, \
4879 /* Blue */ 8, \
4880 /* Alpha */ 8, \
4881 /* Depth */ 24, \
4882 /* AccumRed */ 0, \
4883 /* AccumGreen */ 0, \
4884 /* AccumBlue */ 0, \
4885 /* AccumAlpha */ 0, \
4886 /* SRGB */ RGFW_FALSE, \
4887 /* Robustness */ RGFW_FALSE, \
4888 /* Debug */ RGFW_FALSE, \
4889 /* NoError */ RGFW_FALSE, \
4890 /* ReleaseBehavior */ RGFW_glReleaseNone, \
4891 /* Profile */ RGFW_glCore, \
4892 /* Major */ 1, \
4893 /* Minor */ 0, \
4894 /* Share */ NULL, \
4895 /* Share_EGL */ NULL, \
4896 /* renderer */ RGFW_glAccelerated \
4897 }
4898
4899 RGFW_glHints RGFW_globalHints_OpenGL_SRC = RGFW_DEFAULT_GL_HINTS;
4900 RGFW_glHints* RGFW_globalHints_OpenGL = &RGFW_globalHints_OpenGL_SRC;
4901
4902 void RGFW_resetGlobalHints_OpenGL(void) {
4903 #if !defined(__cplusplus) || defined(RGFW_MACOS)
4904 RGFW_globalHints_OpenGL_SRC = (RGFW_glHints)RGFW_DEFAULT_GL_HINTS;
4905 #else
4906 RGFW_globalHints_OpenGL_SRC = RGFW_DEFAULT_GL_HINTS;
4907 #endif
4908 }
4909 void RGFW_setGlobalHints_OpenGL(RGFW_glHints* hints) { RGFW_globalHints_OpenGL = hints; }
4910 RGFW_glHints* RGFW_getGlobalHints_OpenGL(void) { RGFW_init(); return RGFW_globalHints_OpenGL; }
4911
4912
4913 void* RGFW_glContext_getSourceContext(RGFW_glContext* ctx) {
4914 RGFW_UNUSED(ctx);
4915
4916 #ifdef RGFW_WAYLAND
4917 if (RGFW_usingWayland()) return (void*)ctx->egl.ctx;
4918 #endif
4919
4920 #if defined(RGFW_X11)
4921 return (void*)ctx->ctx;
4922 #else
4923 return NULL;
4924 #endif
4925 }
4926
4927 RGFW_glContext* RGFW_window_createContext_OpenGL(RGFW_window* win, RGFW_glHints* hints) {
4928 #ifdef RGFW_WAYLAND
4929 if (RGFW_usingWayland()) {
4930 return (RGFW_glContext*)RGFW_window_createContext_EGL(win, hints);
4931 }
4932 #endif
4933 RGFW_glContext* ctx = (RGFW_glContext*)RGFW_ALLOC(sizeof(RGFW_glContext));
4934 if (RGFW_window_createContextPtr_OpenGL(win, ctx, hints) == RGFW_FALSE) {
4935 RGFW_FREE(ctx);
4936 win->src.ctx.native = NULL;
4937 return NULL;
4938 }
4939 win->src.gfxType |= RGFW_gfxOwnedByRGFW;
4940 return ctx;
4941 }
4942
4943 RGFW_glContext* RGFW_window_getContext_OpenGL(RGFW_window* win) {
4944 if (win->src.gfxType & RGFW_windowEGL) return NULL;
4945 return win->src.ctx.native;
4946 }
4947
4948 void RGFW_window_deleteContext_OpenGL(RGFW_window* win, RGFW_glContext* ctx) {
4949 RGFW_window_deleteContextPtr_OpenGL(win, ctx);
4950 if (win->src.gfxType & RGFW_gfxOwnedByRGFW) RGFW_FREE(ctx);
4951 }
4952
4953 RGFW_bool RGFW_extensionSupportedStr(const char* extensions, const char* ext, size_t len) {
4954 const char *start = extensions;
4955 const char *where;
4956 const char* terminator;
4957
4958 if (extensions == NULL || ext == NULL) {
4959 return RGFW_FALSE;
4960 }
4961
4962 while (ext[len - 1] == '\0' && len > 3) {
4963 len--;
4964 }
4965
4966 where = RGFW_STRSTR(extensions, ext);
4967 while (where) {
4968 terminator = where + len;
4969 if ((where == start || *(where - 1) == ' ') &&
4970 (*terminator == ' ' || *terminator == '\0')) {
4971 return RGFW_TRUE;
4972 }
4973 where = RGFW_STRSTR(terminator, ext);
4974 }
4975
4976 return RGFW_FALSE;
4977 }
4978
4979 RGFWDEF RGFW_bool RGFW_extensionSupported_base(const char* extension, size_t len);
4980 RGFW_bool RGFW_extensionSupported_base(const char* extension, size_t len) {
4981 #ifdef GL_NUM_EXTENSIONS
4982 if (RGFW_globalHints_OpenGL->major >= 3) {
4983 i32 i;
4984
4985 GLint count = 0;
4986
4987 RGFW_proc RGFW_glGetStringi = RGFW_getProcAddress_OpenGL("glGetStringi");
4988 RGFW_proc RGFW_glGetIntegerv = RGFW_getProcAddress_OpenGL("glGetIntegerv");
4989 if (RGFW_glGetIntegerv)
4990 ((void(*)(GLenum, GLint*))RGFW_glGetIntegerv)(GL_NUM_EXTENSIONS, &count);
4991
4992 for (i = 0; RGFW_glGetStringi && i < count; i++) {
4993 const char* en = ((const char* (*)(u32, u32))RGFW_glGetStringi)(GL_EXTENSIONS, (u32)i);
4994 if (en && RGFW_STRNCMP(en, extension, len) == 0) {
4995 return RGFW_TRUE;
4996 }
4997 }
4998 } else
4999 #endif
5000 {
5001 RGFW_proc RGFW_glGetString = RGFW_getProcAddress_OpenGL("glGetString");
5002 #define RGFW_GL_EXTENSIONS 0x1F03
5003 if (RGFW_glGetString) {
5004 const char* extensions = ((const char*(*)(u32))RGFW_glGetString)(RGFW_GL_EXTENSIONS);
5005
5006 if ((extensions != NULL) && RGFW_extensionSupportedStr(extensions, extension, len)) {
5007 return RGFW_TRUE;
5008 }
5009 }
5010 }
5011 return RGFW_FALSE;
5012 }
5013
5014 RGFW_bool RGFW_extensionSupported_OpenGL(const char* extension, size_t len) {
5015 if (RGFW_extensionSupported_base(extension, len)) return RGFW_TRUE;
5016 return RGFW_extensionSupportedPlatform_OpenGL(extension, len);
5017 }
5018
5019 void RGFW_window_makeCurrentWindow_OpenGL(RGFW_window* win) {
5020 if (win) {
5021 _RGFW->current = win;
5022 }
5023
5024 RGFW_window_makeCurrentContext_OpenGL(win);
5025 }
5026
5027 RGFW_window* RGFW_getCurrentWindow_OpenGL(void) { return _RGFW->current; }
5028 void RGFW_attribStack_init(RGFW_attribStack* stack, i32* attribs, size_t max) { stack->attribs = attribs; stack->count = 0; stack->max = max; }
5029 void RGFW_attribStack_pushAttrib(RGFW_attribStack* stack, i32 attrib) {
5030 RGFW_ASSERT(stack->count < stack->max);
5031 stack->attribs[stack->count] = attrib;
5032 stack->count += 1;
5033 }
5034 void RGFW_attribStack_pushAttribs(RGFW_attribStack* stack, i32 attrib1, i32 attrib2) {
5035 RGFW_attribStack_pushAttrib(stack, attrib1);
5036 RGFW_attribStack_pushAttrib(stack, attrib2);
5037 }
5038
5039 /* EGL */
5040 #ifdef RGFW_EGL
5041 #include <EGL/eglplatform.h>
5042 #include <EGL/egl.h>
5043
5044 PFNEGLINITIALIZEPROC RGFW_eglInitialize;
5045 PFNEGLGETCONFIGSPROC RGFW_eglGetConfigs;
5046 PFNEGLCHOOSECONFIGPROC RGFW_eglChooseConfig;
5047 PFNEGLCREATEWINDOWSURFACEPROC RGFW_eglCreateWindowSurface;
5048 PFNEGLCREATECONTEXTPROC RGFW_eglCreateContext;
5049 PFNEGLMAKECURRENTPROC RGFW_eglMakeCurrent;
5050 PFNEGLGETDISPLAYPROC RGFW_eglGetDisplay;
5051 PFNEGLSWAPBUFFERSPROC RGFW_eglSwapBuffers;
5052 PFNEGLSWAPINTERVALPROC RGFW_eglSwapInterval;
5053 PFNEGLBINDAPIPROC RGFW_eglBindAPI;
5054 PFNEGLDESTROYCONTEXTPROC RGFW_eglDestroyContext;
5055 PFNEGLTERMINATEPROC RGFW_eglTerminate;
5056 PFNEGLDESTROYSURFACEPROC RGFW_eglDestroySurface;
5057 PFNEGLGETCURRENTCONTEXTPROC RGFW_eglGetCurrentContext;
5058 PFNEGLGETPROCADDRESSPROC RGFW_eglGetProcAddress = NULL;
5059 PFNEGLQUERYSTRINGPROC RGFW_eglQueryString;
5060 PFNEGLGETCONFIGATTRIBPROC RGFW_eglGetConfigAttrib;
5061
5062 #define EGL_SURFACE_MAJOR_VERSION_KHR 0x3098
5063 #define EGL_SURFACE_MINOR_VERSION_KHR 0x30fb
5064
5065 #ifdef RGFW_WINDOWS
5066 #include <windows.h>
5067 #elif defined(RGFW_MACOS) || defined(RGFW_UNIX)
5068 #include <dlfcn.h>
5069 #endif
5070
5071 #ifdef RGFW_WAYLAND
5072 #include <wayland-egl.h>
5073 #endif
5074
5075 void* RGFW_eglLibHandle = NULL;
5076
5077 void* RGFW_getDisplay_EGL(void) { return _RGFW->EGL_display; }
5078 void* RGFW_eglContext_getSourceContext(RGFW_eglContext* ctx) { return ctx->ctx; }
5079 void* RGFW_eglContext_getSurface(RGFW_eglContext* ctx) { return ctx->surface; }
5080 struct wl_egl_window* RGFW_eglContext_wlEGLWindow(RGFW_eglContext* ctx) { return ctx->eglWindow; }
5081
5082 RGFW_bool RGFW_loadEGL(void) {
5083 RGFW_init();
5084 if (RGFW_eglGetProcAddress != NULL) {
5085 return RGFW_TRUE;
5086 }
5087
5088 #ifndef RGFW_WASM
5089 #ifdef RGFW_WINDOWS
5090 const char* libNames[] = { "libEGL.dll", "EGL.dll" };
5091 #elif defined(RGFW_MACOS) || defined(RGFW_UNIX)
5092 /* Linux and macOS */
5093 const char* libNames[] = {
5094 "libEGL.so.1", /* most common */
5095 "libEGL.so", /* fallback */
5096 "/System/Library/Frameworks/OpenGL.framework/OpenGL" /* fallback for older macOS EGL-like systems */
5097 };
5098 #endif
5099
5100 for (size_t i = 0; i < sizeof(libNames) / sizeof(libNames[0]); i++) {
5101 #ifdef RGFW_WINDOWS
5102 RGFW_eglLibHandle = (void*)LoadLibraryA(libNames[i]);
5103 if (RGFW_eglLibHandle) {
5104 RGFW_eglGetProcAddress = (PFNEGLGETPROCADDRESSPROC)(RGFW_proc)GetProcAddress((HMODULE)RGFW_eglLibHandle, "eglGetProcAddress");
5105 break;
5106 }
5107 #elif defined(RGFW_MACOS) || defined(RGFW_UNIX)
5108 RGFW_eglLibHandle = dlopen(libNames[i], RTLD_LAZY | RTLD_GLOBAL);
5109 if (RGFW_eglLibHandle) {
5110 void* lib = dlsym(RGFW_eglLibHandle, "eglGetProcAddress");
5111 if (lib != NULL) RGFW_MEMCPY(&RGFW_eglGetProcAddress, &lib, sizeof(PFNEGLGETPROCADDRESSPROC));
5112 break;
5113 }
5114 #endif
5115 }
5116
5117 if (!RGFW_eglLibHandle || !RGFW_eglGetProcAddress) {
5118 return RGFW_FALSE;
5119 }
5120
5121 RGFW_eglInitialize = (PFNEGLINITIALIZEPROC) RGFW_eglGetProcAddress("eglInitialize");
5122 RGFW_eglGetConfigs = (PFNEGLGETCONFIGSPROC) RGFW_eglGetProcAddress("eglGetConfigs");
5123 RGFW_eglChooseConfig = (PFNEGLCHOOSECONFIGPROC) RGFW_eglGetProcAddress("eglChooseConfig");
5124 RGFW_eglCreateWindowSurface = (PFNEGLCREATEWINDOWSURFACEPROC) RGFW_eglGetProcAddress("eglCreateWindowSurface");
5125 RGFW_eglCreateContext = (PFNEGLCREATECONTEXTPROC) RGFW_eglGetProcAddress("eglCreateContext");
5126 RGFW_eglMakeCurrent = (PFNEGLMAKECURRENTPROC) RGFW_eglGetProcAddress("eglMakeCurrent");
5127 RGFW_eglGetDisplay = (PFNEGLGETDISPLAYPROC) RGFW_eglGetProcAddress("eglGetDisplay");
5128 RGFW_eglSwapBuffers = (PFNEGLSWAPBUFFERSPROC) RGFW_eglGetProcAddress("eglSwapBuffers");
5129 RGFW_eglSwapInterval = (PFNEGLSWAPINTERVALPROC) RGFW_eglGetProcAddress("eglSwapInterval");
5130 RGFW_eglBindAPI = (PFNEGLBINDAPIPROC) RGFW_eglGetProcAddress("eglBindAPI");
5131 RGFW_eglDestroyContext = (PFNEGLDESTROYCONTEXTPROC) RGFW_eglGetProcAddress("eglDestroyContext");
5132 RGFW_eglTerminate = (PFNEGLTERMINATEPROC) RGFW_eglGetProcAddress("eglTerminate");
5133 RGFW_eglDestroySurface = (PFNEGLDESTROYSURFACEPROC) RGFW_eglGetProcAddress("eglDestroySurface");
5134 RGFW_eglQueryString = (PFNEGLQUERYSTRINGPROC) RGFW_eglGetProcAddress("eglQueryString");
5135 RGFW_eglGetCurrentContext = (PFNEGLGETCURRENTCONTEXTPROC) RGFW_eglGetProcAddress("eglGetCurrentContext");
5136 RGFW_eglGetConfigAttrib = (PFNEGLGETCONFIGATTRIBPROC) RGFW_eglGetProcAddress("eglGetConfigAttrib");
5137
5138 #else
5139 RGFW_eglGetProcAddress = eglGetProcAddress;
5140 RGFW_eglInitialize = (PFNEGLINITIALIZEPROC) eglInitialize;
5141 RGFW_eglGetConfigs = (PFNEGLGETCONFIGSPROC) eglGetConfigs;
5142 RGFW_eglChooseConfig = (PFNEGLCHOOSECONFIGPROC) eglChooseConfig;
5143 RGFW_eglCreateWindowSurface = (PFNEGLCREATEWINDOWSURFACEPROC) eglCreateWindowSurface;
5144 RGFW_eglCreateContext = (PFNEGLCREATECONTEXTPROC) eglCreateContext;
5145 RGFW_eglMakeCurrent = (PFNEGLMAKECURRENTPROC) eglMakeCurrent;
5146 RGFW_eglGetDisplay = (PFNEGLGETDISPLAYPROC) eglGetDisplay;
5147 RGFW_eglSwapBuffers = (PFNEGLSWAPBUFFERSPROC) eglSwapBuffers;
5148 RGFW_eglSwapInterval = (PFNEGLSWAPINTERVALPROC) eglSwapInterval;
5149 RGFW_eglBindAPI = (PFNEGLBINDAPIPROC) eglBindAPI;
5150 RGFW_eglDestroyContext = (PFNEGLDESTROYCONTEXTPROC) eglDestroyContext;
5151 RGFW_eglTerminate = (PFNEGLTERMINATEPROC) eglTerminate;
5152 RGFW_eglDestroySurface = (PFNEGLDESTROYSURFACEPROC) eglDestroySurface;
5153 RGFW_eglQueryString = (PFNEGLQUERYSTRINGPROC) eglQueryString;
5154 RGFW_eglGetCurrentContext = (PFNEGLGETCURRENTCONTEXTPROC) eglGetCurrentContext;
5155 RGFW_eglGetConfigAttrib = (PFNEGLGETCONFIGATTRIBPROC)eglGetConfigAttrib;
5156 #endif
5157
5158 RGFW_bool out = RGFW_BOOL(RGFW_eglInitialize!= NULL &&
5159 RGFW_eglGetConfigs!= NULL &&
5160 RGFW_eglChooseConfig!= NULL &&
5161 RGFW_eglCreateWindowSurface!= NULL &&
5162 RGFW_eglCreateContext!= NULL &&
5163 RGFW_eglMakeCurrent!= NULL &&
5164 RGFW_eglGetDisplay!= NULL &&
5165 RGFW_eglSwapBuffers!= NULL &&
5166 RGFW_eglSwapInterval != NULL &&
5167 RGFW_eglBindAPI!= NULL &&
5168 RGFW_eglDestroyContext!= NULL &&
5169 RGFW_eglTerminate!= NULL &&
5170 RGFW_eglDestroySurface!= NULL &&
5171 RGFW_eglQueryString != NULL &&
5172 RGFW_eglGetCurrentContext != NULL &&
5173 RGFW_eglGetConfigAttrib != NULL);
5174
5175 if (out) {
5176 #ifdef RGFW_WINDOWS
5177 HDC dc = GetDC(NULL);
5178 _RGFW->EGL_display = RGFW_eglGetDisplay((EGLNativeDisplayType) dc);
5179 ReleaseDC(NULL, dc);
5180 #elif defined(RGFW_WAYLAND)
5181 if (_RGFW->useWaylandBool)
5182 _RGFW->EGL_display = RGFW_eglGetDisplay((EGLNativeDisplayType) _RGFW->wl_display);
5183 else
5184 #endif
5185 #ifdef RGFW_X11
5186 _RGFW->EGL_display = RGFW_eglGetDisplay((EGLNativeDisplayType) _RGFW->display);
5187 #else
5188 {}
5189 #endif
5190 #if !defined(RGFW_WAYLAND) && !defined(RGFW_WINDOWS) && !defined(RGFW_X11)
5191 _RGFW->EGL_display = RGFW_eglGetDisplay(EGL_DEFAULT_DISPLAY);
5192 #endif
5193 }
5194
5195 RGFW_eglInitialize(_RGFW->EGL_display, NULL, NULL);
5196 return out;
5197 }
5198
5199
5200 void RGFW_unloadEGL(void) {
5201 if (!RGFW_eglLibHandle) return;
5202 RGFW_eglTerminate(_RGFW->EGL_display);
5203 #ifdef RGFW_WINDOWS
5204 FreeLibrary((HMODULE)RGFW_eglLibHandle);
5205 #elif defined(RGFW_MACOS) || defined(RGFW_UNIX)
5206 dlclose(RGFW_eglLibHandle);
5207 #endif
5208
5209 RGFW_eglLibHandle = NULL;
5210 RGFW_eglGetProcAddress = NULL;
5211 }
5212
5213 RGFW_bool RGFW_window_createContextPtr_EGL(RGFW_window* win, RGFW_eglContext* ctx, RGFW_glHints* hints) {
5214 if (RGFW_loadEGL() == RGFW_FALSE) return RGFW_FALSE;
5215 win->src.ctx.egl = ctx;
5216 win->src.gfxType = RGFW_gfxEGL;
5217
5218 #ifdef RGFW_WAYLAND
5219 if (_RGFW->useWaylandBool)
5220 win->src.ctx.egl->eglWindow = wl_egl_window_create(win->src.surface, win->w, win->h);
5221 #endif
5222
5223 #ifndef EGL_OPENGL_ES1_BIT
5224 #define EGL_OPENGL_ES1_BIT 0x1
5225 #endif
5226
5227 EGLint egl_config[24];
5228
5229 {
5230 RGFW_attribStack stack;
5231 RGFW_attribStack_init(&stack, egl_config, 24);
5232
5233 RGFW_attribStack_pushAttribs(&stack, EGL_SURFACE_TYPE, EGL_WINDOW_BIT);
5234 RGFW_attribStack_pushAttrib(&stack, EGL_RENDERABLE_TYPE);
5235
5236 if (hints->profile == RGFW_glES) {
5237 switch (hints->major) {
5238 case 1: RGFW_attribStack_pushAttrib(&stack, EGL_OPENGL_ES1_BIT); break;
5239 case 2: RGFW_attribStack_pushAttrib(&stack, EGL_OPENGL_ES2_BIT); break;
5240 case 3: RGFW_attribStack_pushAttrib(&stack, EGL_OPENGL_ES3_BIT); break;
5241 default: break;
5242 }
5243 } else {
5244 RGFW_attribStack_pushAttrib(&stack, EGL_OPENGL_BIT);
5245 }
5246
5247 RGFW_attribStack_pushAttribs(&stack, EGL_RED_SIZE, hints->red);
5248 RGFW_attribStack_pushAttribs(&stack, EGL_GREEN_SIZE, hints->green);
5249 RGFW_attribStack_pushAttribs(&stack, EGL_BLUE_SIZE, hints->blue);
5250 RGFW_attribStack_pushAttribs(&stack, EGL_ALPHA_SIZE, hints->alpha);
5251 RGFW_attribStack_pushAttribs(&stack, EGL_DEPTH_SIZE, hints->depth);
5252
5253 RGFW_attribStack_pushAttribs(&stack, EGL_STENCIL_SIZE, hints->stencil);
5254 if (hints->samples) {
5255 RGFW_attribStack_pushAttribs(&stack, EGL_SAMPLE_BUFFERS, 1);
5256 RGFW_attribStack_pushAttribs(&stack, EGL_SAMPLES, hints->samples);
5257 }
5258
5259 RGFW_attribStack_pushAttribs(&stack, EGL_NONE, EGL_NONE);
5260 }
5261
5262 EGLint numConfigs, best_config = -1, best_samples = 0;
5263
5264 RGFW_eglChooseConfig(_RGFW->EGL_display, egl_config, NULL, 0, &numConfigs);
5265 EGLConfig* configs = (EGLConfig*)RGFW_ALLOC(sizeof(EGLConfig) * (u32)numConfigs);
5266
5267 RGFW_eglChooseConfig(_RGFW->EGL_display, egl_config, configs, numConfigs, &numConfigs);
5268
5269 #ifdef RGFW_X11
5270 RGFW_bool transparent = (win->internal.flags & RGFW_windowTransparent);
5271 EGLint best_depth = 0;
5272 #endif
5273
5274 for (EGLint i = 0; i < numConfigs; i++) {
5275 EGLint visual_id = 0;
5276 EGLint samples = 0;
5277
5278 RGFW_eglGetConfigAttrib(_RGFW->EGL_display, configs[i], EGL_NATIVE_VISUAL_ID, &visual_id);
5279 RGFW_eglGetConfigAttrib(_RGFW->EGL_display, configs[i], EGL_SAMPLES, &samples);
5280
5281 if (best_config == -1) best_config = i;
5282
5283 #ifdef RGFW_X11
5284 if (_RGFW->useWaylandBool == RGFW_FALSE) {
5285 XVisualInfo vinfo_template;
5286 vinfo_template.visualid = (VisualID)visual_id;
5287
5288 int num_visuals = 0;
5289 XVisualInfo* vi = XGetVisualInfo(_RGFW->display, VisualIDMask, &vinfo_template, &num_visuals);
5290 if (!vi) continue;
5291 if ((!transparent || vi->depth == 32) && best_depth == 0) {
5292 best_config = i;
5293 best_depth = vi->depth;
5294 }
5295
5296 if ((!(transparent) || vi->depth == 32) && (samples <= hints->samples && samples > best_samples)) {
5297 best_depth = vi->depth;
5298 best_config = i;
5299 best_samples = samples;
5300 XFree(vi);
5301 continue;
5302 }
5303 }
5304 #endif
5305
5306 if (samples <= hints->samples && samples > best_samples) {
5307 best_config = i;
5308 best_samples = samples;
5309 }
5310 }
5311
5312 EGLConfig config = configs[best_config];
5313 RGFW_FREE(configs);
5314 #ifdef RGFW_X11
5315 if (_RGFW->useWaylandBool == RGFW_FALSE) {
5316 /* This is required so that way the user can create their own OpenGL context after RGFW_createWindow is used */
5317 XVisualInfo* result;
5318 XVisualInfo desired;
5319 EGLint visualID = 0, count = 0;
5320
5321 RGFW_eglGetConfigAttrib(_RGFW->EGL_display, config, EGL_NATIVE_VISUAL_ID, &visualID);
5322 if (visualID) {
5323 desired.visualid = (VisualID)visualID;
5324 result = XGetVisualInfo(_RGFW->display, VisualIDMask, &desired, &count);
5325 } else RGFW_sendDebugInfo(RGFW_typeError, RGFW_errEGLContext, "Failed to fetch a valid EGL VisualID");
5326
5327 if (result == NULL || count == 0) {
5328 if (win->src.window == 0) {
5329 /* try to create a EGL context anyway (this will work if you're not using a NVidia driver) */
5330 win->internal.flags &= ~(u32)RGFW_windowEGL;
5331 RGFW_createWindowPlatform("", win->internal.flags, win);
5332 }
5333 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errEGLContext, "Failed to find a valid visual for the EGL config");
5334 } else {
5335 RGFW_bool showWindow = RGFW_FALSE;
5336 if (win->src.window) {
5337 showWindow = (RGFW_window_isMinimized(win) == RGFW_FALSE);
5338 RGFW_window_closePlatform(win);
5339 }
5340
5341 RGFW_XCreateWindow(*result, "", win->internal.flags, win);
5342
5343 if (showWindow) {
5344 RGFW_window_show(win);
5345 }
5346 XFree(result);
5347 }
5348 }
5349 #endif
5350
5351 EGLint surf_attribs[9];
5352
5353 {
5354 RGFW_attribStack stack;
5355 RGFW_attribStack_init(&stack, surf_attribs, 9);
5356
5357 const char present_opaque_str[] = "EGL_EXT_present_opaque";
5358 RGFW_bool opaque_extension_Found = RGFW_extensionSupportedPlatform_EGL(present_opaque_str, sizeof(present_opaque_str));
5359
5360 #ifndef EGL_PRESENT_OPAQUE_EXT
5361 #define EGL_PRESENT_OPAQUE_EXT 0x31df
5362 #endif
5363
5364 #ifndef EGL_GL_COLORSPACE_KHR
5365 #define EGL_GL_COLORSPACE_KHR 0x309D
5366 #ifndef EGL_GL_COLORSPACE_SRGB_KHR
5367 #define EGL_GL_COLORSPACE_SRGB_KHR 0x3089
5368 #endif
5369 #endif
5370
5371 const char gl_colorspace_str[] = "EGL_KHR_gl_colorspace";
5372 RGFW_bool gl_colorspace_Found = RGFW_extensionSupportedPlatform_EGL(gl_colorspace_str, sizeof(gl_colorspace_str));
5373
5374 if (hints->sRGB && gl_colorspace_Found) {
5375 RGFW_attribStack_pushAttribs(&stack, EGL_GL_COLORSPACE_KHR, EGL_GL_COLORSPACE_SRGB_KHR);
5376 }
5377
5378 if (!(win->internal.flags & RGFW_windowTransparent) && opaque_extension_Found)
5379 RGFW_attribStack_pushAttribs(&stack, EGL_PRESENT_OPAQUE_EXT, EGL_TRUE);
5380
5381 if (hints->doubleBuffer == 0) {
5382 RGFW_attribStack_pushAttribs(&stack, EGL_RENDER_BUFFER, EGL_SINGLE_BUFFER);
5383 }
5384
5385 RGFW_attribStack_pushAttribs(&stack, EGL_NONE, EGL_NONE);
5386 }
5387 #if defined(RGFW_MACOS)
5388 void* layer = RGFW_getLayer_OSX();
5389
5390 RGFW_window_setLayer_OSX(win, layer);
5391
5392 win->src.ctx.egl->surface = RGFW_eglCreateWindowSurface(_RGFW->EGL_display, config, (EGLNativeWindowType) layer, surf_attribs);
5393 #elif defined(RGFW_WINDOWS)
5394 win->src.ctx.egl->surface = RGFW_eglCreateWindowSurface(_RGFW->EGL_display, config, (EGLNativeWindowType) win->src.window, surf_attribs);
5395 #elif defined(RGFW_WAYLAND)
5396 if (_RGFW->useWaylandBool)
5397 win->src.ctx.egl->surface = RGFW_eglCreateWindowSurface(_RGFW->EGL_display, config, (EGLNativeWindowType) win->src.ctx.egl->eglWindow, surf_attribs);
5398 else
5399 #endif
5400 #ifdef RGFW_X11
5401 win->src.ctx.egl->surface = RGFW_eglCreateWindowSurface(_RGFW->EGL_display, config, (EGLNativeWindowType) win->src.window, surf_attribs);
5402 #else
5403 {}
5404 #endif
5405 #ifdef RGFW_WASM
5406 win->src.ctx.egl->surface = eglCreateWindowSurface(_RGFW->EGL_display, config, 0, 0);
5407 #endif
5408
5409 if (win->src.ctx.egl->surface == NULL) {
5410 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errEGLContext, "Failed to create an EGL surface.");
5411 return RGFW_FALSE;
5412 }
5413
5414 EGLint attribs[20];
5415 {
5416 RGFW_attribStack stack;
5417 RGFW_attribStack_init(&stack, attribs, 20);
5418
5419 if (hints->major || hints->minor) {
5420 RGFW_attribStack_pushAttribs(&stack, EGL_CONTEXT_MAJOR_VERSION, hints->major);
5421 RGFW_attribStack_pushAttribs(&stack, EGL_CONTEXT_MINOR_VERSION, hints->minor);
5422 }
5423
5424 if (hints->profile == RGFW_glCore) {
5425 RGFW_attribStack_pushAttribs(&stack, EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT);
5426 } else if (hints->profile == RGFW_glCompatibility) {
5427 RGFW_attribStack_pushAttribs(&stack, EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT);
5428 } else if (hints->profile == RGFW_glForwardCompatibility) {
5429 RGFW_attribStack_pushAttribs(&stack, EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE, EGL_TRUE);
5430 }
5431
5432
5433 RGFW_attribStack_pushAttribs(&stack, EGL_CONTEXT_OPENGL_ROBUST_ACCESS, hints->robustness);
5434 RGFW_attribStack_pushAttribs(&stack, EGL_CONTEXT_OPENGL_DEBUG, hints->debug);
5435
5436 #ifndef EGL_CONTEXT_RELEASE_BEHAVIOR_KHR
5437 #define EGL_CONTEXT_RELEASE_BEHAVIOR_KHR 0x2097
5438 #endif
5439
5440 #ifndef EGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_KHR
5441 #define EGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_KHR 0x2098
5442 #endif
5443
5444 if (hints->releaseBehavior == RGFW_glReleaseFlush) {
5445 RGFW_attribStack_pushAttribs(&stack, EGL_CONTEXT_RELEASE_BEHAVIOR_KHR, EGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_KHR);
5446 } else {
5447 RGFW_attribStack_pushAttribs(&stack, EGL_CONTEXT_RELEASE_BEHAVIOR_KHR, 0x0000);
5448 }
5449
5450 RGFW_attribStack_pushAttribs(&stack, EGL_NONE, EGL_NONE);
5451 }
5452
5453 if (hints->profile == RGFW_glES)
5454 RGFW_eglBindAPI(EGL_OPENGL_ES_API);
5455 else
5456 RGFW_eglBindAPI(EGL_OPENGL_API);
5457
5458 win->src.ctx.egl->ctx = RGFW_eglCreateContext(_RGFW->EGL_display, config, hints->shareEGL, attribs);
5459
5460 if (win->src.ctx.egl->ctx == NULL) {
5461 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errEGLContext, "Failed to create an EGL context.");
5462 return RGFW_FALSE;
5463 }
5464
5465 RGFW_eglMakeCurrent(_RGFW->EGL_display, win->src.ctx.egl->surface, win->src.ctx.egl->surface, win->src.ctx.egl->ctx);
5466 RGFW_eglSwapBuffers(_RGFW->EGL_display, win->src.ctx.egl->surface);
5467 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoOpenGL, "EGL context initalized.");
5468 return RGFW_TRUE;
5469 }
5470
5471 RGFW_eglContext* RGFW_window_getContext_EGL(RGFW_window* win) {
5472 if (win->src.gfxType == RGFW_windowOpenGL) return NULL;
5473 return win->src.ctx.egl;
5474 }
5475
5476 void RGFW_window_deleteContextPtr_EGL(RGFW_window* win, RGFW_eglContext* ctx) {
5477 if (_RGFW->EGL_display == NULL) return;
5478
5479 RGFW_eglDestroySurface(_RGFW->EGL_display, ctx->surface);
5480 RGFW_eglDestroyContext(_RGFW->EGL_display, ctx->ctx);
5481 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoOpenGL, "EGL context freed");
5482 #ifdef RGFW_WAYLAND
5483 if (_RGFW->useWaylandBool == RGFW_FALSE) return;
5484 wl_egl_window_destroy(win->src.ctx.egl->eglWindow);
5485 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoOpenGL, "EGL window context freed");
5486 #endif
5487 win->src.ctx.egl = NULL;
5488 }
5489
5490 void RGFW_window_makeCurrentContext_EGL(RGFW_window* win) { if (win) RGFW_ASSERT(win->src.ctx.egl);
5491 if (win == NULL)
5492 RGFW_eglMakeCurrent(_RGFW->EGL_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
5493 else {
5494 RGFW_eglMakeCurrent(_RGFW->EGL_display, win->src.ctx.egl->surface, win->src.ctx.egl->surface, win->src.ctx.egl->ctx);
5495 }
5496 }
5497
5498 void RGFW_window_swapBuffers_EGL(RGFW_window* win) {
5499 if (RGFW_eglSwapBuffers)
5500 RGFW_eglSwapBuffers(_RGFW->EGL_display, win->src.ctx.egl->surface);
5501 else RGFW_window_swapBuffers_OpenGL(win);
5502 }
5503
5504 void* RGFW_getCurrentContext_EGL(void) {
5505 return RGFW_eglGetCurrentContext();
5506 }
5507
5508 RGFW_proc RGFW_getProcAddress_EGL(const char* procname) {
5509 #if defined(RGFW_WINDOWS)
5510 RGFW_proc proc = (RGFW_proc) GetProcAddress(RGFW_wgl_dll, procname);
5511
5512 if (proc)
5513 return proc;
5514 #endif
5515
5516 return (RGFW_proc) RGFW_eglGetProcAddress(procname);
5517 }
5518
5519 RGFW_bool RGFW_extensionSupportedPlatform_EGL(const char* extension, size_t len) {
5520 if (RGFW_loadEGL() == RGFW_FALSE) return RGFW_FALSE;
5521 const char* extensions = RGFW_eglQueryString(_RGFW->EGL_display, EGL_EXTENSIONS);
5522 return extensions != NULL && RGFW_extensionSupportedStr(extensions, extension, len);
5523 }
5524
5525 void RGFW_window_swapInterval_EGL(RGFW_window* win, i32 swapInterval) {
5526 RGFW_ASSERT(win != NULL);
5527 RGFW_eglSwapInterval(_RGFW->EGL_display, swapInterval);
5528 }
5529
5530 RGFW_bool RGFW_extensionSupported_EGL(const char* extension, size_t len) {
5531 if (RGFW_extensionSupported_base(extension, len)) return RGFW_TRUE;
5532 return RGFW_extensionSupportedPlatform_EGL(extension, len);
5533 }
5534
5535 void RGFW_window_makeCurrentWindow_EGL(RGFW_window* win) {
5536 _RGFW->current = win;
5537 RGFW_window_makeCurrentContext_EGL(win);
5538 }
5539
5540 RGFW_window* RGFW_getCurrentWindow_EGL(void) { return _RGFW->current; }
5541
5542 RGFW_eglContext* RGFW_window_createContext_EGL(RGFW_window* win, RGFW_glHints* hints) {
5543 RGFW_eglContext* ctx = (RGFW_eglContext*)RGFW_ALLOC(sizeof(RGFW_eglContext));
5544 if (RGFW_window_createContextPtr_EGL(win, ctx, hints) == RGFW_FALSE) {
5545 RGFW_FREE(ctx);
5546 win->src.ctx.egl = NULL;
5547 return NULL;
5548 }
5549 win->src.gfxType |= RGFW_gfxOwnedByRGFW;
5550 return ctx;
5551 }
5552
5553 void RGFW_window_deleteContext_EGL(RGFW_window* win, RGFW_eglContext* ctx) {
5554 RGFW_window_deleteContextPtr_EGL(win, ctx);
5555 if (win->src.gfxType & RGFW_gfxOwnedByRGFW) RGFW_FREE(ctx);
5556 }
5557
5558 #endif /* RGFW_EGL */
5559
5560 /*
5561 end of RGFW_EGL defines
5562 */
5563 #endif /* end of RGFW_GL (OpenGL, EGL, OSMesa )*/
5564
5565 /*
5566 RGFW_VULKAN defines
5567 */
5568 #ifdef RGFW_VULKAN
5569 #ifdef RGFW_MACOS
5570 #include <objc/message.h>
5571 #endif
5572
5573 const char** RGFW_getRequiredInstanceExtensions_Vulkan(size_t* count) {
5574 static const char* arr[2] = {VK_KHR_SURFACE_EXTENSION_NAME};
5575 arr[1] = RGFW_VK_SURFACE;
5576 if (count != NULL) *count = 2;
5577
5578 return (const char**)arr;
5579 }
5580
5581 #ifndef RGFW_MACOS
5582 VkResult RGFW_window_createSurface_Vulkan(RGFW_window* win, VkInstance instance, VkSurfaceKHR* surface) {
5583 RGFW_ASSERT(win != NULL); RGFW_ASSERT(instance);
5584 RGFW_ASSERT(surface != NULL);
5585
5586 *surface = VK_NULL_HANDLE;
5587
5588 #ifdef RGFW_X11
5589
5590 VkXlibSurfaceCreateInfoKHR x11 = { VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR, 0, 0, (Display*) _RGFW->display, (Window) win->src.window };
5591 return vkCreateXlibSurfaceKHR(instance, &x11, NULL, surface);
5592 #endif
5593 #if defined(RGFW_WAYLAND)
5594
5595 VkWaylandSurfaceCreateInfoKHR wayland = { VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR, 0, 0, (struct wl_display*) _RGFW->wl_display, (struct wl_surface*) win->src.surface };
5596 return vkCreateWaylandSurfaceKHR(instance, &wayland, NULL, surface);
5597 #elif defined(RGFW_WINDOWS)
5598 VkWin32SurfaceCreateInfoKHR win32 = { VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR, 0, 0, GetModuleHandle(NULL), (HWND)win->src.window };
5599
5600 return vkCreateWin32SurfaceKHR(instance, &win32, NULL, surface);
5601 #endif
5602 }
5603 #endif
5604
5605 RGFW_bool RGFW_getPresentationSupport_Vulkan(VkPhysicalDevice physicalDevice, u32 queueFamilyIndex) {
5606 if (_RGFW == NULL) RGFW_init();
5607 #ifdef RGFW_X11
5608
5609 Visual* visual = DefaultVisual(_RGFW->display, DefaultScreen(_RGFW->display));
5610 RGFW_bool out = vkGetPhysicalDeviceXlibPresentationSupportKHR(physicalDevice, queueFamilyIndex, _RGFW->display, XVisualIDFromVisual(visual));
5611 return out;
5612 #endif
5613 #if defined(RGFW_WAYLAND)
5614
5615 RGFW_bool wlout = vkGetPhysicalDeviceWaylandPresentationSupportKHR(physicalDevice, queueFamilyIndex, _RGFW->wl_display);
5616 return wlout;
5617 #elif defined(RGFW_WINDOWS)
5618 RGFW_bool out = vkGetPhysicalDeviceWin32PresentationSupportKHR(physicalDevice, queueFamilyIndex);
5619 return out;
5620 #elif defined(RGFW_MACOS) && !defined(RGFW_MACOS_X11)
5621 RGFW_UNUSED(physicalDevice);
5622 RGFW_UNUSED(queueFamilyIndex);
5623 return RGFW_FALSE; /* TODO */
5624 #endif
5625 }
5626 #endif /* end of RGFW_vulkan */
5627
5628 /*
5629 This is where OS specific stuff starts
5630 */
5631
5632 /* start of unix (wayland or X11 (unix) ) defines */
5633
5634 #ifdef RGFW_UNIX
5635 #include <fcntl.h>
5636 #include <poll.h>
5637 #include <unistd.h>
5638
5639 void RGFW_stopCheckEvents(void) {
5640
5641 _RGFW->eventWait_forceStop[2] = 1;
5642 while (1) {
5643 const char byte = 0;
5644 const ssize_t result = write(_RGFW->eventWait_forceStop[1], &byte, 1);
5645 if (result == 1 || result == -1)
5646 break;
5647 }
5648 }
5649
5650 RGFWDEF u64 RGFW_linux_getTimeNS(void);
5651 u64 RGFW_linux_getTimeNS(void) {
5652 struct timespec ts;
5653 const u64 scale_factor = 1000000000;
5654 clock_gettime(_RGFW->clock, &ts);
5655 return (u64)ts.tv_sec * scale_factor + (u64)ts.tv_nsec;
5656 }
5657
5658 void RGFW_waitForEvent(i32 waitMS) {
5659 if (waitMS == 0) return;
5660
5661 if (_RGFW->eventWait_forceStop[0] == 0 || _RGFW->eventWait_forceStop[1] == 0) {
5662 if (pipe(_RGFW->eventWait_forceStop) != -1) {
5663 fcntl(_RGFW->eventWait_forceStop[0], F_GETFL, 0);
5664 fcntl(_RGFW->eventWait_forceStop[0], F_GETFD, 0);
5665 fcntl(_RGFW->eventWait_forceStop[1], F_GETFL, 0);
5666 fcntl(_RGFW->eventWait_forceStop[1], F_GETFD, 0);
5667 }
5668 }
5669
5670 struct pollfd fds[2];
5671 fds[0].fd = 0;
5672 fds[0].events = POLLIN;
5673 fds[0].revents = 0;
5674 fds[1].fd = _RGFW->eventWait_forceStop[0];
5675 fds[1].events = POLLIN;
5676 fds[1].revents = 0;
5677
5678
5679 if (RGFW_usingWayland()) {
5680 #ifdef RGFW_WAYLAND
5681 fds[0].fd = wl_display_get_fd(_RGFW->wl_display);
5682
5683 /* empty the queue */
5684 while (wl_display_prepare_read(_RGFW->wl_display) != 0) {
5685 /* error occured when dispatching the queue */
5686 if (wl_display_dispatch_pending(_RGFW->wl_display) == -1) {
5687 return;
5688 }
5689 }
5690
5691 /* send any pending requests to the compositor */
5692 while (wl_display_flush(_RGFW->wl_display) == -1) {
5693
5694 /* queue is full dispatch them */
5695 if (errno == EAGAIN) {
5696 if (wl_display_dispatch_pending(_RGFW->wl_display) == -1) {
5697 return;
5698 }
5699 } else {
5700 return;
5701 }
5702 }
5703 #endif
5704 } else {
5705 #ifdef RGFW_X11
5706 fds[0].fd = ConnectionNumber(_RGFW->display);
5707 #endif
5708 }
5709
5710
5711 u64 start = RGFW_linux_getTimeNS();
5712 if (RGFW_usingWayland()) {
5713 #ifdef RGFW_WAYLAND
5714 while (wl_display_dispatch_pending(_RGFW->wl_display) == 0) {
5715 if (poll(fds, 1, waitMS) <= 0) {
5716 wl_display_cancel_read(_RGFW->wl_display);
5717 break;
5718 } else {
5719 if (wl_display_read_events(_RGFW->wl_display) == -1)
5720 return;
5721 }
5722
5723 if (waitMS != RGFW_eventWaitNext) {
5724 waitMS -= (i32)(RGFW_linux_getTimeNS() - start) / (i32)1e+6;
5725 }
5726 }
5727
5728 /* queue contains events from read, dispatch them */
5729 if (wl_display_dispatch_pending(_RGFW->wl_display) == -1) {
5730 return;
5731 }
5732 #endif
5733 } else {
5734 #ifdef RGFW_X11
5735 while (XPending(_RGFW->display) == 0) {
5736 if (poll(fds, 1, waitMS) <= 0)
5737 break;
5738
5739 if (waitMS != RGFW_eventWaitNext) {
5740 waitMS -= (i32)(RGFW_linux_getTimeNS() - start) / (i32)1e+6;
5741 }
5742 }
5743 #endif
5744 }
5745
5746 /* drain any data in the stop request */
5747 if (_RGFW->eventWait_forceStop[2]) {
5748 char data[64];
5749 RGFW_MEMSET(data, 0, sizeof(data));
5750 (void)!read(_RGFW->eventWait_forceStop[0], data, sizeof(data));
5751
5752 _RGFW->eventWait_forceStop[2] = 0;
5753 }
5754 }
5755
5756 char* RGFW_strtok(char* str, const char* delimStr);
5757 char* RGFW_strtok(char* str, const char* delimStr) {
5758 static char* static_str = NULL;
5759
5760 if (str != NULL)
5761 static_str = str;
5762
5763 if (static_str == NULL) {
5764 return NULL;
5765 }
5766
5767 while (*static_str != '\0') {
5768 RGFW_bool delim = 0;
5769 const char* d;
5770 for (d = delimStr; *d != '\0'; d++) {
5771 if (*static_str == *d) {
5772 delim = 1;
5773 break;
5774 }
5775 }
5776 if (!delim)
5777 break;
5778 static_str++;
5779 }
5780
5781 if (*static_str == '\0')
5782 return NULL;
5783
5784 char* token_start = static_str;
5785 while (*static_str != '\0') {
5786 int delim = 0;
5787 const char* d;
5788 for (d = delimStr; *d != '\0'; d++) {
5789 if (*static_str == *d) {
5790 delim = 1;
5791 break;
5792 }
5793 }
5794
5795 if (delim) {
5796 *static_str = '\0';
5797 static_str++;
5798 break;
5799 }
5800 static_str++;
5801 }
5802
5803 return token_start;
5804 }
5805
5806 #ifdef RGFW_X11
5807 RGFWDEF i32 RGFW_initPlatform_X11(void);
5808 RGFWDEF void RGFW_deinitPlatform_X11(void);
5809 #endif
5810 #ifdef RGFW_WAYLAND
5811 RGFWDEF i32 RGFW_initPlatform_Wayland(void);
5812 RGFWDEF void RGFW_deinitPlatform_Wayland(void);
5813 #endif
5814
5815 RGFWDEF void RGFW_load_X11(void);
5816 RGFWDEF void RGFW_load_Wayland(void);
5817
5818 #if !defined(RGFW_X11) || !defined(RGFW_WAYLAND)
5819 void RGFW_load_X11(void) { }
5820 void RGFW_load_Wayland(void) { }
5821 #endif
5822
5823 /*
5824 * Sadly we have to use magic linux keycodes
5825 * We can't use X11 functions, because that breaks Wayland, but they use the same keycodes so there's no use redeffing them
5826 * We can't use linux enums, because the headers don't exist on BSD
5827 */
5828 void RGFW_initKeycodesPlatform(void) {
5829 _RGFW->keycodes[49] = RGFW_backtick;
5830 _RGFW->keycodes[19] = RGFW_0;
5831 _RGFW->keycodes[10] = RGFW_1;
5832 _RGFW->keycodes[11] = RGFW_2;
5833 _RGFW->keycodes[12] = RGFW_3;
5834 _RGFW->keycodes[13] = RGFW_4;
5835 _RGFW->keycodes[14] = RGFW_5;
5836 _RGFW->keycodes[15] = RGFW_6;
5837 _RGFW->keycodes[16] = RGFW_7;
5838 _RGFW->keycodes[17] = RGFW_8;
5839 _RGFW->keycodes[18] = RGFW_9;
5840 _RGFW->keycodes[65] = RGFW_space;
5841 _RGFW->keycodes[38] = RGFW_a;
5842 _RGFW->keycodes[56] = RGFW_b;
5843 _RGFW->keycodes[54] = RGFW_c;
5844 _RGFW->keycodes[40] = RGFW_d;
5845 _RGFW->keycodes[26] = RGFW_e;
5846 _RGFW->keycodes[41] = RGFW_f;
5847 _RGFW->keycodes[42] = RGFW_g;
5848 _RGFW->keycodes[43] = RGFW_h;
5849 _RGFW->keycodes[31] = RGFW_i;
5850 _RGFW->keycodes[44] = RGFW_j;
5851 _RGFW->keycodes[45] = RGFW_k;
5852 _RGFW->keycodes[46] = RGFW_l;
5853 _RGFW->keycodes[58] = RGFW_m;
5854 _RGFW->keycodes[57] = RGFW_n;
5855 _RGFW->keycodes[32] = RGFW_o;
5856 _RGFW->keycodes[33] = RGFW_p;
5857 _RGFW->keycodes[24] = RGFW_q;
5858 _RGFW->keycodes[27] = RGFW_r;
5859 _RGFW->keycodes[39] = RGFW_s;
5860 _RGFW->keycodes[28] = RGFW_t;
5861 _RGFW->keycodes[30] = RGFW_u;
5862 _RGFW->keycodes[55] = RGFW_v;
5863 _RGFW->keycodes[25] = RGFW_w;
5864 _RGFW->keycodes[53] = RGFW_x;
5865 _RGFW->keycodes[29] = RGFW_y;
5866 _RGFW->keycodes[52] = RGFW_z;
5867 _RGFW->keycodes[60] = RGFW_period;
5868 _RGFW->keycodes[59] = RGFW_comma;
5869 _RGFW->keycodes[61] = RGFW_slash;
5870 _RGFW->keycodes[34] = RGFW_bracket;
5871 _RGFW->keycodes[35] = RGFW_closeBracket;
5872 _RGFW->keycodes[47] = RGFW_semicolon;
5873 _RGFW->keycodes[48] = RGFW_apostrophe;
5874 _RGFW->keycodes[51] = RGFW_backSlash;
5875 _RGFW->keycodes[36] = RGFW_return;
5876 _RGFW->keycodes[119] = RGFW_delete;
5877 _RGFW->keycodes[77] = RGFW_numLock;
5878 _RGFW->keycodes[106] = RGFW_kpSlash;
5879 _RGFW->keycodes[63] = RGFW_kpMultiply;
5880 _RGFW->keycodes[86] = RGFW_kpPlus;
5881 _RGFW->keycodes[82] = RGFW_kpMinus;
5882 _RGFW->keycodes[87] = RGFW_kp1;
5883 _RGFW->keycodes[88] = RGFW_kp2;
5884 _RGFW->keycodes[89] = RGFW_kp3;
5885 _RGFW->keycodes[83] = RGFW_kp4;
5886 _RGFW->keycodes[84] = RGFW_kp5;
5887 _RGFW->keycodes[85] = RGFW_kp6;
5888 _RGFW->keycodes[81] = RGFW_kp9;
5889 _RGFW->keycodes[90] = RGFW_kp0;
5890 _RGFW->keycodes[91] = RGFW_kpPeriod;
5891 _RGFW->keycodes[104] = RGFW_kpReturn;
5892 _RGFW->keycodes[20] = RGFW_minus;
5893 _RGFW->keycodes[21] = RGFW_equals;
5894 _RGFW->keycodes[22] = RGFW_backSpace;
5895 _RGFW->keycodes[23] = RGFW_tab;
5896 _RGFW->keycodes[66] = RGFW_capsLock;
5897 _RGFW->keycodes[50] = RGFW_shiftL;
5898 _RGFW->keycodes[37] = RGFW_controlL;
5899 _RGFW->keycodes[64] = RGFW_altL;
5900 _RGFW->keycodes[133] = RGFW_superL;
5901 _RGFW->keycodes[105] = RGFW_controlR;
5902 _RGFW->keycodes[134] = RGFW_superR;
5903 _RGFW->keycodes[62] = RGFW_shiftR;
5904 _RGFW->keycodes[108] = RGFW_altR;
5905 _RGFW->keycodes[67] = RGFW_F1;
5906 _RGFW->keycodes[68] = RGFW_F2;
5907 _RGFW->keycodes[69] = RGFW_F3;
5908 _RGFW->keycodes[70] = RGFW_F4;
5909 _RGFW->keycodes[71] = RGFW_F5;
5910 _RGFW->keycodes[72] = RGFW_F6;
5911 _RGFW->keycodes[73] = RGFW_F7;
5912 _RGFW->keycodes[74] = RGFW_F8;
5913 _RGFW->keycodes[75] = RGFW_F9;
5914 _RGFW->keycodes[76] = RGFW_F10;
5915 _RGFW->keycodes[95] = RGFW_F11;
5916 _RGFW->keycodes[96] = RGFW_F12;
5917 _RGFW->keycodes[111] = RGFW_up;
5918 _RGFW->keycodes[116] = RGFW_down;
5919 _RGFW->keycodes[113] = RGFW_left;
5920 _RGFW->keycodes[114] = RGFW_right;
5921 _RGFW->keycodes[118] = RGFW_insert;
5922 _RGFW->keycodes[115] = RGFW_end;
5923 _RGFW->keycodes[112] = RGFW_pageUp;
5924 _RGFW->keycodes[117] = RGFW_pageDown;
5925 _RGFW->keycodes[9] = RGFW_escape;
5926 _RGFW->keycodes[110] = RGFW_home;
5927 _RGFW->keycodes[78] = RGFW_scrollLock;
5928 _RGFW->keycodes[107] = RGFW_printScreen;
5929 _RGFW->keycodes[128] = RGFW_pause;
5930 _RGFW->keycodes[191] = RGFW_F13;
5931 _RGFW->keycodes[192] = RGFW_F14;
5932 _RGFW->keycodes[193] = RGFW_F15;
5933 _RGFW->keycodes[194] = RGFW_F16;
5934 _RGFW->keycodes[195] = RGFW_F17;
5935 _RGFW->keycodes[196] = RGFW_F18;
5936 _RGFW->keycodes[197] = RGFW_F19;
5937 _RGFW->keycodes[198] = RGFW_F20;
5938 _RGFW->keycodes[199] = RGFW_F21;
5939 _RGFW->keycodes[200] = RGFW_F22;
5940 _RGFW->keycodes[201] = RGFW_F23;
5941 _RGFW->keycodes[202] = RGFW_F24;
5942 _RGFW->keycodes[203] = RGFW_F25;
5943 _RGFW->keycodes[142] = RGFW_kpEqual;
5944 _RGFW->keycodes[161] = RGFW_world1; /* non-US key #1 */
5945 _RGFW->keycodes[162] = RGFW_world2; /* non-US key #2 */
5946 }
5947
5948 i32 RGFW_initPlatform(void) {
5949 #if defined(_POSIX_MONOTONIC_CLOCK)
5950 struct timespec ts;
5951 RGFW_MEMSET(&ts, 0, sizeof(struct timespec));
5952
5953 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
5954 _RGFW->clock = CLOCK_MONOTONIC;
5955 #else
5956 _RGFW->clock = CLOCK_REALTIME;
5957 #endif
5958
5959 #ifdef RGFW_WAYLAND
5960 RGFW_load_Wayland();
5961 i32 ret = RGFW_initPlatform_Wayland();
5962 if (ret == 0) {
5963 return 0;
5964 } else {
5965 #ifdef RGFW_X11
5966 RGFW_sendDebugInfo(RGFW_typeWarning, RGFW_warningWayland, "Falling back to X11");
5967 RGFW_useWayland(0);
5968 #else
5969 return ret;
5970 #endif
5971 }
5972 #endif
5973 #ifdef RGFW_X11
5974 RGFW_load_X11();
5975 return RGFW_initPlatform_X11();
5976 #else
5977 return 0;
5978 #endif
5979 }
5980
5981
5982 void RGFW_deinitPlatform(void) {
5983 if (_RGFW->eventWait_forceStop[0] || _RGFW->eventWait_forceStop[1]){
5984 close(_RGFW->eventWait_forceStop[0]);
5985 close(_RGFW->eventWait_forceStop[1]);
5986 }
5987 #ifdef RGFW_WAYLAND
5988 if (_RGFW->useWaylandBool) {
5989 RGFW_deinitPlatform_Wayland();
5990 return;
5991 }
5992 #endif
5993 #ifdef RGFW_X11
5994 RGFW_deinitPlatform_X11();
5995 #endif
5996 }
5997
5998 RGFWDEF size_t RGFW_unix_stringlen(const char* name);
5999 size_t RGFW_unix_stringlen(const char* name) {
6000 size_t i = 0;
6001 while (name[i]) { i++; }
6002 return i;
6003 }
6004
6005 #endif /* end of wayland or X11 defines */
6006
6007
6008 /*
6009
6010
6011 Start of Linux / Unix defines
6012
6013
6014 */
6015
6016 #ifdef RGFW_X11
6017 #ifdef RGFW_WAYLAND
6018 #define RGFW_FUNC(func) func##_X11
6019 #else
6020 #define RGFW_FUNC(func) func
6021 #endif
6022
6023 #include <dlfcn.h>
6024 #include <unistd.h>
6025
6026 #include <limits.h> /* for data limits (mainly used in drag and drop functions) */
6027 #include <poll.h>
6028
6029 void RGFW_setXInstName(const char* name) { _RGFW->instName = name; }
6030 #if !defined(RGFW_NO_X11_CURSOR) && defined(RGFW_X11)
6031 #include <X11/Xcursor/Xcursor.h>
6032 #endif
6033
6034 #include <X11/Xatom.h>
6035 #include <X11/keysymdef.h>
6036 #include <X11/extensions/sync.h>
6037
6038 #include <X11/XKBlib.h> /* for converting keycode to string */
6039 #include <X11/cursorfont.h> /* for hiding */
6040 #include <X11/extensions/shapeconst.h>
6041 #include <X11/extensions/shape.h>
6042 #include <X11/extensions/XInput2.h>
6043
6044 #ifdef RGFW_OPENGL
6045 #ifndef __gl_h_
6046 #define __gl_h_
6047 #define RGFW_gl_ndef
6048 #define GLubyte unsigned char
6049 #define GLenum unsigned int
6050 #define GLint int
6051 #define GLuint unsigned int
6052 #define GLsizei int
6053 #define GLfloat float
6054 #define GLvoid void
6055 #define GLbitfield unsigned int
6056 #define GLintptr ptrdiff_t
6057 #define GLsizeiptr ptrdiff_t
6058 #define GLboolean unsigned char
6059 #endif
6060
6061 #include <GL/glx.h> /* GLX defs, xlib.h, gl.h */
6062 #ifndef GLX_MESA_swap_control
6063 #define GLX_MESA_swap_control
6064 #endif
6065
6066 #ifdef RGFW_gl_ndef
6067 #undef __gl_h_
6068 #undef GLubyte
6069 #undef GLenum
6070 #undef GLint
6071 #undef GLuint
6072 #undef GLsizei
6073 #undef GLfloat
6074 #undef GLvoid
6075 #undef GLbitfield
6076 #undef GLintptr
6077 #undef GLsizeiptr
6078 #undef GLboolean
6079 #endif
6080 typedef GLXContext(*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
6081 #endif
6082
6083 /* atoms needed for drag and drop */
6084 #if !defined(RGFW_NO_X11_CURSOR) && !defined(RGFW_NO_X11_CURSOR_PRELOAD)
6085 typedef XcursorImage* (*PFN_XcursorImageCreate)(int, int);
6086 typedef void (*PFN_XcursorImageDestroy)(XcursorImage*);
6087 typedef Cursor(*PFN_XcursorImageLoadCursor)(Display*, const XcursorImage*);
6088 #endif
6089
6090 #if !defined(RGFW_NO_X11_XI_PRELOAD)
6091 typedef int (* PFN_XISelectEvents)(Display*,Window,XIEventMask*,int);
6092 PFN_XISelectEvents XISelectEventsSRC = NULL;
6093 #define XISelectEvents XISelectEventsSRC
6094
6095 void* X11Xihandle = NULL;
6096 #endif
6097
6098 #if !defined(RGFW_NO_X11_EXT_PRELOAD)
6099 typedef void (* PFN_XSyncIntToValue)(XSyncValue*, int);
6100 PFN_XSyncIntToValue XSyncIntToValueSRC = NULL;
6101 #define XSyncIntToValue XSyncIntToValueSRC
6102
6103 typedef Status (* PFN_XSyncSetCounter)(Display*, XSyncCounter, XSyncValue);
6104 PFN_XSyncSetCounter XSyncSetCounterSRC = NULL;
6105 #define XSyncSetCounter XSyncSetCounterSRC
6106
6107 typedef XSyncCounter (* PFN_XSyncCreateCounter)(Display*, XSyncValue);
6108 PFN_XSyncCreateCounter XSyncCreateCounterSRC = NULL;
6109 #define XSyncCreateCounter XSyncCreateCounterSRC
6110
6111 typedef void (* PFN_XShapeCombineMask)(Display*,Window,int,int,int,Pixmap,int);
6112 PFN_XShapeCombineMask XShapeCombineMaskSRC;
6113 #define XShapeCombineMask XShapeCombineMaskSRC
6114
6115 typedef void (* PFN_XShapeCombineRegion)(Display*,Window,int,int,int,Region,int);
6116 PFN_XShapeCombineRegion XShapeCombineRegionSRC;
6117 #define XShapeCombineRegion XShapeCombineRegionSRC
6118 void* X11XEXThandle = NULL;
6119 #endif
6120
6121 #if !defined(RGFW_NO_X11_CURSOR) && !defined(RGFW_NO_X11_CURSOR_PRELOAD)
6122 PFN_XcursorImageLoadCursor XcursorImageLoadCursorSRC = NULL;
6123 PFN_XcursorImageCreate XcursorImageCreateSRC = NULL;
6124 PFN_XcursorImageDestroy XcursorImageDestroySRC = NULL;
6125
6126 #define XcursorImageLoadCursor XcursorImageLoadCursorSRC
6127 #define XcursorImageCreate XcursorImageCreateSRC
6128 #define XcursorImageDestroy XcursorImageDestroySRC
6129
6130 void* X11Cursorhandle = NULL;
6131 #endif
6132
6133 RGFWDEF RGFW_bool RGFW_waitForShowEvent_X11(RGFW_window* win);
6134 RGFW_bool RGFW_waitForShowEvent_X11(RGFW_window* win) {
6135 XEvent dummy;
6136 while (!XCheckTypedWindowEvent(_RGFW->display, win->src.window, VisibilityNotify, &dummy)) {
6137 RGFW_waitForEvent(100);
6138 }
6139
6140 return RGFW_TRUE;
6141 }
6142
6143 RGFWDEF void RGFW_x11_icCallback(XIC ic, char* clientData, char* callData);
6144 void RGFW_x11_icCallback(XIC ic, char* clientData, char* callData) {
6145 RGFW_UNUSED(ic); RGFW_UNUSED(callData);
6146 RGFW_window* win = (RGFW_window*)(void*)clientData;
6147 win->src.ic = NULL;
6148 }
6149
6150 RGFWDEF void RGFW_x11_imCallback(XIM im, char* clientData, char* callData);
6151 void RGFW_x11_imCallback(XIM im, char* clientData, char* callData) {
6152 RGFW_UNUSED(im); RGFW_UNUSED(clientData); RGFW_UNUSED(callData);
6153 _RGFW->im = NULL;
6154 }
6155
6156 RGFWDEF void RGFW_x11_imInitCallback(Display* display, XPointer clientData, XPointer callData);
6157 void RGFW_x11_imInitCallback(Display* display, XPointer clientData, XPointer callData) {
6158 RGFW_UNUSED(display); RGFW_UNUSED(clientData); RGFW_UNUSED(callData);
6159
6160 if (_RGFW->im) {
6161 return;
6162 }
6163
6164 _RGFW->im = XOpenIM(_RGFW->display, 0, NULL, NULL);
6165 if (_RGFW->im == NULL) {
6166 return;
6167 }
6168
6169 RGFW_bool found = RGFW_FALSE;
6170 XIMStyles* styles = NULL;
6171
6172 if (XGetIMValues(_RGFW->im, XNQueryInputStyle, &styles, NULL) != NULL) {
6173 found = RGFW_FALSE;
6174 } else {
6175 for (unsigned int i = 0; i < styles->count_styles; i++) {
6176 if (styles->supported_styles[i] == (XIMPreeditNothing | XIMStatusNothing)) {
6177 found = RGFW_TRUE;
6178 break;
6179 }
6180 }
6181
6182 XFree(styles);
6183 }
6184
6185 if (found == RGFW_FALSE) {
6186 XCloseIM(_RGFW->im);
6187 _RGFW->im = NULL;
6188 }
6189
6190 XIMCallback callback;
6191 callback.callback = (XIMProc) RGFW_x11_imCallback;
6192 callback.client_data = NULL;
6193 XSetIMValues(_RGFW->im, XNDestroyCallback, &callback, NULL);
6194 }
6195
6196 void* RGFW_getDisplay_X11(void) { return _RGFW->display; }
6197 u64 RGFW_window_getWindow_X11(RGFW_window* win) { return (u64)win->src.window; }
6198
6199 RGFWDEF RGFW_format RGFW_XImage_getFormat(XImage* image);
6200 RGFW_format RGFW_XImage_getFormat(XImage* image) {
6201 switch (image->bits_per_pixel) {
6202 case 24:
6203 if (image->red_mask == 0xFF0000 && image->green_mask == 0x00FF00 && image->blue_mask == 0x0000FF)
6204 return RGFW_formatRGB8;
6205 if (image->red_mask == 0x0000FF && image->green_mask == 0x00FF00 && image->blue_mask == 0xFF0000)
6206 return RGFW_formatBGR8;
6207 break;
6208 case 32:
6209 if (image->red_mask == 0x00FF0000 && image->green_mask == 0x0000FF00 && image->blue_mask == 0x000000FF)
6210 return RGFW_formatBGRA8;
6211 if (image->red_mask == 0x000000FF && image->green_mask == 0x0000FF00 && image->blue_mask == 0x00FF0000)
6212 return RGFW_formatRGBA8;
6213 if (image->red_mask == 0x0000FF00 && image->green_mask == 0x00FF0000 && image->blue_mask == 0xFF000000)
6214 return RGFW_formatABGR8;
6215 if (image->red_mask == 0x00FF0000 && image->green_mask == 0x0000FF00 && image->blue_mask == 0x000000FF)
6216 return RGFW_formatARGB8; /* ambiguous without alpha */
6217 break;
6218 }
6219 return RGFW_formatARGB8;
6220 }
6221
6222
6223 RGFW_bool RGFW_window_createSurfacePtr(RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format, RGFW_surface* surface) {
6224 RGFW_ASSERT(surface != NULL);
6225 surface->data = data;
6226 surface->w = w;
6227 surface->h = h;
6228 surface->format = format;
6229
6230 XWindowAttributes attrs;
6231 if (XGetWindowAttributes(_RGFW->display, win->src.window, &attrs) == 0) {
6232 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errBuffer, "Failed to get window attributes.");
6233 return RGFW_FALSE;
6234 }
6235
6236 surface->native.bitmap = XCreateImage(_RGFW->display, attrs.visual, (u32)attrs.depth,
6237 ZPixmap, 0, NULL, (u32)surface->w, (u32)surface->h, 32, 0);
6238
6239 surface->native.buffer = (u8*)RGFW_ALLOC((size_t)(w * h * 4));
6240 surface->native.format = RGFW_XImage_getFormat(surface->native.bitmap);
6241
6242 if (surface->native.bitmap == NULL) {
6243 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errBuffer, "Failed to create XImage.");
6244 return RGFW_FALSE;
6245 }
6246
6247 surface->native.format = RGFW_formatBGRA8;
6248 return RGFW_TRUE;
6249 }
6250
6251 RGFW_format RGFW_FUNC(RGFW_nativeFormat)(void) { return RGFW_formatBGRA8; }
6252
6253 RGFW_bool RGFW_FUNC(RGFW_createSurfacePtr) (u8* data, i32 w, i32 h, RGFW_format format, RGFW_surface* surface) {
6254 return RGFW_window_createSurfacePtr(_RGFW->root, data, w, h, format, surface);
6255 }
6256
6257 void RGFW_FUNC(RGFW_window_blitSurface) (RGFW_window* win, RGFW_surface* surface) {
6258 RGFW_ASSERT(surface != NULL);
6259 surface->native.bitmap->data = (char*)surface->native.buffer;
6260 RGFW_copyImageData((u8*)surface->native.buffer, surface->w, RGFW_MIN(win->h, surface->h), surface->native.format, surface->data, surface->format, surface->convertFunc);
6261
6262 XPutImage(_RGFW->display, win->src.window, win->src.gc, surface->native.bitmap, 0, 0, 0, 0, (u32)RGFW_MIN(win->w, surface->w), (u32)RGFW_MIN(win->h, surface->h));
6263 surface->native.bitmap->data = NULL;
6264 return;
6265 }
6266
6267 void RGFW_FUNC(RGFW_surface_freePtr) (RGFW_surface* surface) {
6268 RGFW_ASSERT(surface != NULL);
6269 RGFW_FREE(surface->native.buffer);
6270 XDestroyImage(surface->native.bitmap);
6271 return;
6272 }
6273
6274 #define RGFW_LOAD_ATOM(name) \
6275 static Atom name = 0; \
6276 if (name == 0) name = XInternAtom(_RGFW->display, #name, False);
6277
6278 void RGFW_FUNC(RGFW_window_setBorder) (RGFW_window* win, RGFW_bool border) {
6279 RGFW_setBit(&win->internal.flags, RGFW_windowNoBorder, !border);
6280 RGFW_LOAD_ATOM(_MOTIF_WM_HINTS);
6281
6282 struct __x11WindowHints {
6283 unsigned long flags, functions, decorations, status;
6284 long input_mode;
6285 } hints;
6286 hints.flags = 2;
6287 hints.decorations = border;
6288
6289 XChangeProperty(_RGFW->display, win->src.window, _MOTIF_WM_HINTS, _MOTIF_WM_HINTS, 32, PropModeReplace, (u8*)&hints, 5);
6290
6291 if (RGFW_window_isHidden(win) == 0) {
6292 RGFW_window_hide(win);
6293 RGFW_window_show(win);
6294 }
6295 }
6296
6297 void RGFW_FUNC(RGFW_window_setRawMouseModePlatform) (RGFW_window* win, RGFW_bool state) {
6298 RGFW_UNUSED(win); RGFW_UNUSED(state);
6299 }
6300
6301 void RGFW_FUNC(RGFW_window_captureMousePlatform) (RGFW_window* win, RGFW_bool state) {
6302 if (state) {
6303 unsigned int event_mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
6304 XGrabPointer(_RGFW->display, win->src.window, True, event_mask, GrabModeAsync, GrabModeAsync, win->src.window, None, CurrentTime);
6305 } else {
6306 XUngrabPointer(_RGFW->display, CurrentTime);
6307 }
6308 }
6309
6310 #define RGFW_LOAD_LIBRARY(x, lib) if (x == NULL) x = dlopen(lib, RTLD_LAZY | RTLD_LOCAL)
6311 #define RGFW_PROC_DEF(proc, name) if (name##SRC == NULL && proc != NULL) { \
6312 void* ptr = dlsym(proc, #name); \
6313 if (ptr != NULL) RGFW_MEMCPY(&name##SRC, &ptr, sizeof(PFN_##name)); \
6314 }
6315
6316 RGFWDEF void RGFW_window_getVisual(XVisualInfo* visual, RGFW_bool transparent);
6317 void RGFW_window_getVisual(XVisualInfo* visual, RGFW_bool transparent) {
6318 visual->visual = DefaultVisual(_RGFW->display, DefaultScreen(_RGFW->display));
6319 visual->depth = DefaultDepth(_RGFW->display, DefaultScreen(_RGFW->display));
6320 if (transparent) {
6321 XMatchVisualInfo(_RGFW->display, DefaultScreen(_RGFW->display), 32, TrueColor, visual); /*!< for RGBA backgrounds */
6322 if (visual->depth != 32)
6323 RGFW_sendDebugInfo(RGFW_typeWarning, RGFW_warningOpenGL, "Failed to load a 32-bit depth.");
6324 }
6325 }
6326
6327 RGFWDEF int RGFW_XErrorHandler(Display* display, XErrorEvent* ev);
6328 int RGFW_XErrorHandler(Display* display, XErrorEvent* ev) {
6329 char errorText[512];
6330 XGetErrorText(display, ev->error_code, errorText, sizeof(errorText));
6331
6332 char buf[1024];
6333 RGFW_SNPRINTF(buf, sizeof(buf), "[X Error] %s\n Error code: %d\n Request code: %d\n Minor code: %d\n Serial: %lu\n",
6334 errorText,
6335 ev->error_code, ev->request_code, ev->minor_code, ev->serial);
6336
6337 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errX11, buf);
6338 _RGFW->x11Error = ev;
6339 return 0;
6340 }
6341
6342 void RGFW_XCreateWindow (XVisualInfo visual, const char* name, RGFW_windowFlags flags, RGFW_window* win) {
6343 i64 event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask | FocusChangeMask |
6344 LeaveWindowMask | EnterWindowMask | ExposureMask | VisibilityChangeMask | PropertyChangeMask;
6345
6346 /* make X window attrubutes */
6347 XSetWindowAttributes swa;
6348 RGFW_MEMSET(&swa, 0, sizeof(swa));
6349
6350 win->src.parent = DefaultRootWindow(_RGFW->display);
6351
6352 Colormap cmap;
6353 swa.colormap = cmap = XCreateColormap(_RGFW->display,
6354 win->src.parent,
6355 visual.visual, AllocNone);
6356 swa.event_mask = event_mask;
6357 swa.background_pixmap = None;
6358
6359 /* create the window */
6360 win->src.window = XCreateWindow(_RGFW->display, win->src.parent, win->x, win->y, (u32)win->w, (u32)win->h,
6361 0, visual.depth, InputOutput, visual.visual,
6362 CWBorderPixel | CWColormap | CWEventMask, &swa);
6363
6364 win->src.flashEnd = 0;
6365
6366 XFreeColors(_RGFW->display, cmap, NULL, 0, 0);
6367
6368 XSaveContext(_RGFW->display, win->src.window, _RGFW->context, (XPointer)win);
6369
6370 win->src.gc = XCreateGC(_RGFW->display, win->src.window, 0, NULL);
6371
6372 if (_RGFW->im) {
6373 XIMCallback callback;
6374 callback.callback = (XIMProc) RGFW_x11_icCallback;
6375 callback.client_data = (XPointer) win;
6376
6377 win->src.ic = XCreateIC(_RGFW->im, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, win->src.window, XNFocusWindow, win->src.window, XNDestroyCallback, &callback, NULL);
6378 }
6379
6380
6381 /* In your .desktop app, if you set the property
6382 StartupWMClass=RGFW that will assoicate the launcher icon
6383 with your application - robrohan */
6384 if (_RGFW->className == NULL)
6385 _RGFW->className = (char*)name;
6386
6387 XClassHint hint;
6388 hint.res_class = (char*)_RGFW->className;
6389
6390 if (_RGFW->instName == NULL) hint.res_name = (char*)name;
6391 else hint.res_name = (char*)_RGFW->instName;
6392
6393 XSetClassHint(_RGFW->display, win->src.window, &hint);
6394
6395 XWMHints hints;
6396 hints.flags = StateHint;
6397 hints.initial_state = NormalState;
6398
6399 XSetWMHints(_RGFW->display, win->src.window, &hints);
6400
6401 if (flags & RGFW_windowScaleToMonitor)
6402 RGFW_window_scaleToMonitor(win);
6403
6404 XSelectInput(_RGFW->display, (Drawable) win->src.window, event_mask); /*!< tell X11 what events we want */
6405
6406 /* make it so the user can't close the window until the program does */
6407 RGFW_LOAD_ATOM(WM_DELETE_WINDOW);
6408 XSetWMProtocols(_RGFW->display, (Drawable) win->src.window, &WM_DELETE_WINDOW, 1);
6409 /* set the background */
6410 RGFW_window_setName(win, name);
6411
6412 XMoveWindow(_RGFW->display, (Drawable) win->src.window, win->x, win->y); /*!< move the window to it's proper cords */
6413
6414 if (flags & RGFW_windowAllowDND) { /* init drag and drop atoms and turn on drag and drop for this window */
6415 win->internal.flags |= RGFW_windowAllowDND;
6416
6417 /* actions */
6418 Atom XdndAware = XInternAtom(_RGFW->display, "XdndAware", False);
6419 const u8 version = 5;
6420
6421 XChangeProperty(_RGFW->display, win->src.window,
6422 XdndAware, 4, 32,
6423 PropModeReplace, &version, 1); /*!< turns on drag and drop */
6424 }
6425
6426 #ifdef RGFW_ADVANCED_SMOOTH_RESIZE
6427 RGFW_LOAD_ATOM(_NET_WM_SYNC_REQUEST_COUNTER)
6428 RGFW_LOAD_ATOM(_NET_WM_SYNC_REQUEST)
6429
6430 Atom protcols[2] = {_NET_WM_SYNC_REQUEST, WM_DELETE_WINDOW};
6431 XSetWMProtocols(_RGFW->display, win->src.window, protcols, 2);
6432
6433 XSyncValue initial_value;
6434 XSyncIntToValue(&initial_value, 0);
6435 win->src.counter = XSyncCreateCounter(_RGFW->display, initial_value);
6436
6437 XChangeProperty(_RGFW->display, win->src.window, _NET_WM_SYNC_REQUEST_COUNTER, XA_CARDINAL, 32, PropModeReplace, (u8*)&win->src.counter, 1);
6438 #endif
6439
6440 win->src.x = win->x;
6441 win->src.y = win->y;
6442 win->src.w = win->w;
6443 win->src.h = win->h;
6444
6445 XSetWindowBackground(_RGFW->display, win->src.window, None);
6446 XClearWindow(_RGFW->display, win->src.window);
6447
6448 /* stupid hack to make resizing the window less bad */
6449 XSetWindowBackgroundPixmap(_RGFW->display, win->src.window, None);
6450 }
6451
6452 RGFW_window* RGFW_FUNC(RGFW_createWindowPlatform) (const char* name, RGFW_windowFlags flags, RGFW_window* win) {
6453 if ((flags & RGFW_windowOpenGL) || (flags & RGFW_windowEGL)) {
6454 win->src.window = 0;
6455 return win;
6456 }
6457
6458 XVisualInfo visual;
6459 RGFW_window_getVisual(&visual, RGFW_BOOL(win->internal.flags & RGFW_windowTransparent));
6460 RGFW_XCreateWindow(visual, name, flags, win);
6461 return win; /*return newly created window */
6462 }
6463
6464 RGFW_bool RGFW_FUNC(RGFW_getGlobalMouse) (i32* fX, i32* fY) {
6465 RGFW_init();
6466 i32 x, y;
6467 u32 z;
6468 Window window1, window2;
6469 XQueryPointer(_RGFW->display, XDefaultRootWindow(_RGFW->display), &window1, &window2, fX, fY, &x, &y, &z);
6470 return RGFW_TRUE;
6471 }
6472
6473 RGFWDEF void RGFW_XHandleClipboardSelection(XEvent* event);
6474 void RGFW_XHandleClipboardSelection(XEvent* event) { RGFW_UNUSED(event);
6475 RGFW_LOAD_ATOM(ATOM_PAIR);
6476 RGFW_LOAD_ATOM(MULTIPLE);
6477 RGFW_LOAD_ATOM(TARGETS);
6478 RGFW_LOAD_ATOM(SAVE_TARGETS);
6479 RGFW_LOAD_ATOM(UTF8_STRING);
6480
6481 const XSelectionRequestEvent* request = &event->xselectionrequest;
6482 Atom formats[2] = {0};
6483 formats[0] = UTF8_STRING;
6484 formats[1] = XA_STRING;
6485 const int formatCount = sizeof(formats) / sizeof(formats[0]);
6486
6487 if (request->target == TARGETS) {
6488 Atom targets[4] = {0};
6489 targets[0] = TARGETS;
6490 targets[1] = MULTIPLE;
6491 targets[2] = UTF8_STRING;
6492 targets[3] = XA_STRING;
6493
6494 XChangeProperty(_RGFW->display, request->requestor, request->property,
6495 XA_ATOM, 32, PropModeReplace, (u8*) targets, sizeof(targets) / sizeof(Atom));
6496 } else if (request->target == MULTIPLE) {
6497 Atom* targets = NULL;
6498
6499 Atom actualType = 0;
6500 int actualFormat = 0;
6501 unsigned long count = 0, bytesAfter = 0;
6502
6503 XGetWindowProperty(_RGFW->display, request->requestor, request->property, 0, LONG_MAX,
6504 False, ATOM_PAIR, &actualType, &actualFormat, &count, &bytesAfter, (u8**) &targets);
6505
6506 unsigned long i;
6507 for (i = 0; i < (u32)count; i += 2) {
6508 if (targets[i] == UTF8_STRING || targets[i] == XA_STRING)
6509 XChangeProperty(_RGFW->display, request->requestor, targets[i + 1], targets[i],
6510 8, PropModeReplace, (const unsigned char *)_RGFW->clipboard, (i32)_RGFW->clipboard_len);
6511 else
6512 targets[i + 1] = None;
6513 }
6514
6515 XChangeProperty(_RGFW->display,
6516 request->requestor, request->property, ATOM_PAIR, 32,
6517 PropModeReplace, (u8*) targets, (i32)count);
6518
6519 XFlush(_RGFW->display);
6520 XFree(targets);
6521 } else if (request->target == SAVE_TARGETS)
6522 XChangeProperty(_RGFW->display, request->requestor, request->property, 0, 32, PropModeReplace, NULL, 0);
6523 else {
6524 int i;
6525 for (i = 0; i < formatCount; i++) {
6526 if (request->target != formats[i])
6527 continue;
6528 XChangeProperty(_RGFW->display, request->requestor, request->property, request->target,
6529 8, PropModeReplace, (u8*) _RGFW->clipboard, (i32)_RGFW->clipboard_len);
6530 }
6531 }
6532
6533 XEvent reply = { SelectionNotify };
6534 reply.xselection.property = request->property;
6535 reply.xselection.display = request->display;
6536 reply.xselection.requestor = request->requestor;
6537 reply.xselection.selection = request->selection;
6538 reply.xselection.target = request->target;
6539 reply.xselection.time = request->time;
6540
6541 XSendEvent(_RGFW->display, request->requestor, False, 0, &reply);
6542 XFlush(_RGFW->display);
6543 }
6544
6545 i32 RGFW_XHandleClipboardSelectionHelper(void);
6546
6547 RGFW_key RGFW_FUNC(RGFW_physicalToMappedKey) (RGFW_key key) {
6548 KeyCode keycode = (KeyCode)RGFW_rgfwToApiKey(key);
6549 KeySym sym = XkbKeycodeToKeysym(_RGFW->display, keycode, 0, 0);
6550
6551 if (sym < 256) {
6552 return (RGFW_key)sym;
6553 }
6554
6555 switch (sym) {
6556 case XK_F1: return RGFW_F1;
6557 case XK_F2: return RGFW_F2;
6558 case XK_F3: return RGFW_F3;
6559 case XK_F4: return RGFW_F4;
6560 case XK_F5: return RGFW_F5;
6561 case XK_F6: return RGFW_F6;
6562 case XK_F7: return RGFW_F7;
6563 case XK_F8: return RGFW_F8;
6564 case XK_F9: return RGFW_F9;
6565 case XK_F10: return RGFW_F10;
6566 case XK_F11: return RGFW_F11;
6567 case XK_F12: return RGFW_F12;
6568 case XK_F13: return RGFW_F13;
6569 case XK_F14: return RGFW_F14;
6570 case XK_F15: return RGFW_F15;
6571 case XK_F16: return RGFW_F16;
6572 case XK_F17: return RGFW_F17;
6573 case XK_F18: return RGFW_F18;
6574 case XK_F19: return RGFW_F19;
6575 case XK_F20: return RGFW_F20;
6576 case XK_F21: return RGFW_F21;
6577 case XK_F22: return RGFW_F22;
6578 case XK_F23: return RGFW_F23;
6579 case XK_F24: return RGFW_F24;
6580 case XK_F25: return RGFW_F25;
6581 case XK_Shift_L: return RGFW_shiftL;
6582 case XK_Shift_R: return RGFW_shiftR;
6583 case XK_Control_L: return RGFW_controlL;
6584 case XK_Control_R: return RGFW_controlR;
6585 case XK_Alt_L: return RGFW_altL;
6586 case XK_Alt_R: return RGFW_altR;
6587 case XK_Super_L: return RGFW_superL;
6588 case XK_Super_R: return RGFW_superR;
6589 case XK_Caps_Lock: return RGFW_capsLock;
6590 case XK_Num_Lock: return RGFW_numLock;
6591 case XK_Scroll_Lock:return RGFW_scrollLock;
6592 case XK_Up: return RGFW_up;
6593 case XK_Down: return RGFW_down;
6594 case XK_Left: return RGFW_left;
6595 case XK_Right: return RGFW_right;
6596 case XK_Home: return RGFW_home;
6597 case XK_End: return RGFW_end;
6598 case XK_Page_Up: return RGFW_pageUp;
6599 case XK_Page_Down: return RGFW_pageDown;
6600 case XK_Insert: return RGFW_insert;
6601 case XK_Menu: return RGFW_menu;
6602 case XK_KP_Add: return RGFW_kpPlus;
6603 case XK_KP_Subtract: return RGFW_kpMinus;
6604 case XK_KP_Multiply: return RGFW_kpMultiply;
6605 case XK_KP_Divide: return RGFW_kpSlash;
6606 case XK_KP_Equal: return RGFW_kpEqual;
6607 case XK_KP_Enter: return RGFW_kpReturn;
6608 case XK_KP_Decimal: return RGFW_kpPeriod;
6609 case XK_KP_0: return RGFW_kp0;
6610 case XK_KP_1: return RGFW_kp1;
6611 case XK_KP_2: return RGFW_kp2;
6612 case XK_KP_3: return RGFW_kp3;
6613 case XK_KP_4: return RGFW_kp4;
6614 case XK_KP_5: return RGFW_kp5;
6615 case XK_KP_6: return RGFW_kp6;
6616 case XK_KP_7: return RGFW_kp7;
6617 case XK_KP_8: return RGFW_kp8;
6618 case XK_KP_9: return RGFW_kp9;
6619 case XK_Print: return RGFW_printScreen;
6620 case XK_Pause: return RGFW_pause;
6621 default: break;
6622 }
6623
6624 return RGFW_keyNULL;
6625 }
6626
6627 RGFWDEF void RGFW_XHandleEvent(void);
6628 void RGFW_XHandleEvent(void) {
6629 RGFW_LOAD_ATOM(XdndTypeList);
6630 RGFW_LOAD_ATOM(XdndSelection);
6631 RGFW_LOAD_ATOM(XdndEnter);
6632 RGFW_LOAD_ATOM(XdndPosition);
6633 RGFW_LOAD_ATOM(XdndStatus);
6634 RGFW_LOAD_ATOM(XdndLeave);
6635 RGFW_LOAD_ATOM(XdndDrop);
6636 RGFW_LOAD_ATOM(XdndFinished);
6637 RGFW_LOAD_ATOM(XdndActionCopy);
6638 RGFW_LOAD_ATOM(_NET_WM_SYNC_REQUEST);
6639 RGFW_LOAD_ATOM(WM_PROTOCOLS);
6640 RGFW_LOAD_ATOM(WM_STATE);
6641 RGFW_LOAD_ATOM(_NET_WM_STATE);
6642
6643 /* xdnd data */
6644 static Window source = 0;
6645 static long version = 0;
6646 static i32 format = 0;
6647
6648 static float deltaX = 0.0f;
6649 static float deltaY = 0.0f;
6650
6651 XEvent reply = { ClientMessage };
6652 XEvent E;
6653
6654 XNextEvent(_RGFW->display, &E);
6655
6656 if (E.type != GenericEvent) {
6657 deltaX = 0.0f;
6658 deltaY = 0.0f;
6659 }
6660
6661 #ifndef RGFW_NO_XRANDR
6662 if (E.type == _RGFW->xrandrEventBase + RRNotify) {
6663 RGFW_pollMonitors();
6664 return;
6665 }
6666 #endif
6667
6668 switch (E.type) {
6669 case SelectionRequest:
6670 RGFW_XHandleClipboardSelection(&E);
6671 return;
6672 case GenericEvent: {
6673 XGetEventData(_RGFW->display, &E.xcookie);
6674 switch (E.xcookie.evtype) {
6675 case XI_RawMotion: {
6676 XIRawEvent* raw = (XIRawEvent *)E.xcookie.data;
6677 if (raw->valuators.mask_len == 0) {
6678 XFreeEventData(_RGFW->display, &E.xcookie);
6679 return;
6680 }
6681
6682 i32 index = 0;
6683 if (XIMaskIsSet(raw->valuators.mask, 0) != 0) {
6684 deltaX += (float)raw->raw_values[index];
6685 index += 1;
6686 }
6687
6688 if (XIMaskIsSet(raw->valuators.mask, 1) != 0)
6689 deltaY += (float)raw->raw_values[index];
6690
6691 _RGFW->vectorX = (float)deltaX;
6692 _RGFW->vectorY = (float)deltaY;
6693 }
6694 default: break;
6695 }
6696
6697 XFreeEventData(_RGFW->display, &E.xcookie);
6698 return;
6699 }
6700 }
6701
6702 RGFW_window* win = NULL;
6703 if (XFindContext(_RGFW->display, E.xany.window, _RGFW->context, (XPointer*) &win) != 0) {
6704 return;
6705 }
6706
6707 if (win->src.flashEnd) {
6708 if ((win->src.flashEnd <= RGFW_linux_getTimeNS()) || RGFW_window_isInFocus(win)) {
6709 RGFW_window_flash(win, RGFW_flashCancel);
6710 }
6711 }
6712
6713
6714 /*
6715 Repeated key presses are sent as a release followed by another press at the same time.
6716 We want to convert that into a single key press event with the repeat flag set
6717 */
6718
6719 RGFW_bool keyRepeat = RGFW_FALSE;
6720
6721 if (E.type == KeyRelease && XEventsQueued(_RGFW->display, QueuedAfterReading)) {
6722 XEvent NE;
6723 XPeekEvent(_RGFW->display, &NE);
6724 if (NE.type == KeyPress && E.xkey.time == NE.xkey.time && E.xkey.keycode == NE.xkey.keycode) {
6725 /* Use the next KeyPress event */
6726 XNextEvent(_RGFW->display, &E);
6727 keyRepeat = RGFW_TRUE;
6728 }
6729 }
6730
6731 switch (E.type) {
6732 case KeyPress: {
6733 if (!(win->internal.enabledEvents & RGFW_keyPressedFlag)) return;
6734 RGFW_key value = (u8)RGFW_apiKeyToRGFW(E.xkey.keycode);
6735
6736 XkbStateRec state;
6737 XkbGetState(_RGFW->display, XkbUseCoreKbd, &state);
6738 RGFW_updateKeyMods(win, (state.locked_mods & LockMask), (state.locked_mods & Mod2Mask), (state.locked_mods & Mod3Mask));
6739
6740 if (win->src.ic && XFilterEvent(&E, None) == False) {
6741 char buffer[100];
6742 char* chars = buffer;
6743
6744 Status status;
6745 size_t count = (size_t)Xutf8LookupString(win->src.ic, &E.xkey, buffer, sizeof(buffer) - 1, NULL, &status);
6746
6747 if (status == XBufferOverflow) {
6748 chars = (char*)RGFW_ALLOC(count + 1);
6749 count = (size_t)Xutf8LookupString(win->src.ic, &E.xkey, chars, (int)count, NULL, &status);
6750 }
6751
6752 if (status == XLookupChars || status == XLookupBoth) {
6753 chars[count] = '\0';
6754 for (size_t index = 0; index < count;
6755 RGFW_keyCharCallback(win, RGFW_decodeUTF8(&chars[index], &index))
6756 );
6757 }
6758
6759 if (chars != buffer)
6760 RGFW_FREE(chars);
6761 } else {
6762 Window root = DefaultRootWindow(_RGFW->display);
6763 Window ret_root, ret_child;
6764 int root_x, root_y, win_x, win_y;
6765 unsigned int mask;
6766 XQueryPointer(_RGFW->display, root, &ret_root, &ret_child, &root_x, &root_y, &win_x, &win_y, &mask);
6767 KeySym sym = (KeySym)XkbKeycodeToKeysym(_RGFW->display, (KeyCode)E.xkey.keycode, 0, (KeyCode)mask & ShiftMask ? 1 : 0);
6768
6769 if ((mask & LockMask) && sym >= XK_a && sym <= XK_z)
6770 sym = (mask & ShiftMask) ? sym + 32 : sym - 32;
6771 if ((u8)sym != (u32)sym)
6772 sym = 0;
6773
6774 RGFW_keyCharCallback(win, (u8)sym);
6775 }
6776
6777 RGFW_keyCallback(win, value, win->internal.mod, keyRepeat, RGFW_TRUE);
6778 break;
6779 }
6780 case KeyRelease: {
6781 if (!(win->internal.enabledEvents & RGFW_keyReleasedFlag)) return;
6782
6783 RGFW_key value = (u8)RGFW_apiKeyToRGFW(E.xkey.keycode);
6784
6785 XkbStateRec state;
6786 XkbGetState(_RGFW->display, XkbUseCoreKbd, &state);
6787 RGFW_updateKeyMods(win, (state.locked_mods & LockMask), (state.locked_mods & Mod2Mask), (state.locked_mods & Mod3Mask));
6788
6789 RGFW_keyCallback(win, value, win->internal.mod, keyRepeat, RGFW_FALSE);
6790 break;
6791 }
6792 case ButtonPress: {
6793 RGFW_bool scroll = RGFW_FALSE;
6794 if (E.xbutton.button >= Button4 && E.xbutton.button <= 7) {
6795 scroll = RGFW_TRUE;
6796 }
6797
6798 float scrollX = 0.0f;
6799 float scrollY = 0.0f;
6800 RGFW_mouseButton value = 0;
6801
6802 switch (E.xbutton.button) {
6803 case Button1: value = RGFW_mouseLeft; break;
6804 case Button2: value = RGFW_mouseMiddle; break;
6805 case Button3: value = RGFW_mouseRight; break;
6806 case Button4: scrollY = 1.0; break;
6807 case Button5: scrollY = -1.0; break;
6808 case 6: scrollX = 1.0f; break;
6809 case 7: scrollX = -1.0f; break;
6810 default:
6811 value = (u8)E.xbutton.button - Button1 - 4;
6812 break;
6813 }
6814
6815 if (scroll) {
6816 RGFW_mouseScrollCallback(win, scrollX, scrollY);
6817 break;
6818 }
6819
6820 RGFW_mouseButtonCallback(win, value, RGFW_TRUE);
6821 break;
6822 }
6823 case ButtonRelease: {
6824 if (E.xbutton.button >= Button4 && E.xbutton.button <= 7) break;
6825
6826 RGFW_mouseButton value = 0;
6827 switch(E.xbutton.button) {
6828 case Button1: value = RGFW_mouseLeft; break;
6829 case Button2: value = RGFW_mouseMiddle; break;
6830 case Button3: value = RGFW_mouseRight; break;
6831 default:
6832 value = (u8)E.xbutton.button - Button1 - 4;
6833 break;
6834 }
6835
6836 RGFW_mouseButtonCallback(win, value, RGFW_FALSE);
6837 break;
6838 }
6839 case MotionNotify:
6840 RGFW_mousePosCallback(win, E.xmotion.x, E.xmotion.y, _RGFW->vectorX, _RGFW->vectorY);
6841 break;
6842
6843 case Expose: {
6844 RGFW_windowRefreshCallback(win);
6845
6846 #ifdef RGFW_ADVANCED_SMOOTH_RESIZE
6847 XSyncValue value;
6848 XSyncIntToValue(&value, (i32)win->src.counter_value);
6849 XSyncSetCounter(_RGFW->display, win->src.counter, value);
6850 #endif
6851 break;
6852 }
6853
6854 case PropertyNotify:
6855 if (E.xproperty.state != PropertyNewValue) break;
6856
6857 if (E.xproperty.atom == WM_STATE) {
6858 if (RGFW_window_isMinimized(win) && !(win->internal.flags & RGFW_windowMinimized)) {
6859 RGFW_windowMinimizedCallback(win);
6860 break;
6861 }
6862 } else if (E.xproperty.atom == _NET_WM_STATE) {
6863 if (RGFW_window_isMaximized(win) && !(win->internal.flags & RGFW_windowMaximize)) {
6864 RGFW_windowMaximizedCallback(win, win->x, win->y, win->w, win->h);
6865 break;
6866 }
6867 }
6868
6869 RGFW_window_checkMode(win);
6870 break;
6871 case MapNotify: case UnmapNotify: RGFW_window_checkMode(win); break;
6872 case ClientMessage: {
6873 RGFW_LOAD_ATOM(WM_DELETE_WINDOW);
6874 /* if the client closed the window */
6875 if (E.xclient.data.l[0] == (long)WM_DELETE_WINDOW) {
6876 RGFW_windowQuitCallback(win);
6877 break;
6878 }
6879 #ifdef RGFW_ADVANCED_SMOOTH_RESIZE
6880 if (E.xclient.message_type == WM_PROTOCOLS && (Atom)E.xclient.data.l[0] == _NET_WM_SYNC_REQUEST) {
6881 RGFW_windowRefreshCallback(win);
6882 win->src.counter_value = 0;
6883 win->src.counter_value |= E.xclient.data.l[2];
6884 win->src.counter_value |= (E.xclient.data.l[3] << 32);
6885
6886 XSyncValue value;
6887 XSyncIntToValue(&value, (i32)win->src.counter_value);
6888 XSyncSetCounter(_RGFW->display, win->src.counter, value);
6889 break;
6890 }
6891 #endif
6892 if ((win->internal.flags & RGFW_windowAllowDND) == 0)
6893 return;
6894
6895 i32 dragX = 0;
6896 i32 dragY = 0;
6897
6898 reply.xclient.window = source;
6899 reply.xclient.format = 32;
6900 reply.xclient.data.l[0] = (long)win->src.window;
6901 reply.xclient.data.l[1] = 0;
6902 reply.xclient.data.l[2] = None;
6903
6904 if (E.xclient.message_type == XdndEnter) {
6905 if (version > 5)
6906 break;
6907
6908 unsigned long count;
6909 Atom* formats;
6910 Atom real_formats[6];
6911 Bool list = E.xclient.data.l[1] & 1;
6912
6913 source = (unsigned long int)E.xclient.data.l[0];
6914 version = E.xclient.data.l[1] >> 24;
6915 format = None;
6916 if (list) {
6917 Atom actualType;
6918 i32 actualFormat;
6919 unsigned long bytesAfter;
6920
6921 XGetWindowProperty(
6922 _RGFW->display, source, XdndTypeList,
6923 0, LONG_MAX, False, 4,
6924 &actualType, &actualFormat, &count, &bytesAfter, (u8**)&formats
6925 );
6926 } else {
6927 count = 0;
6928
6929 size_t i;
6930 for (i = 2; i < 5; i++) {
6931 if (E.xclient.data.l[i] != None) {
6932 real_formats[count] = (unsigned long int)E.xclient.data.l[i];
6933 count += 1;
6934 }
6935 }
6936
6937 formats = real_formats;
6938 }
6939
6940 Atom XtextPlain = XInternAtom(_RGFW->display, "text/plain", False);
6941 Atom XtextUriList = XInternAtom(_RGFW->display, "text/uri-list", False);
6942
6943 size_t i;
6944 for (i = 0; i < count; i++) {
6945 if (formats[i] == XtextUriList || formats[i] == XtextPlain) {
6946 format = (int)formats[i];
6947 break;
6948 }
6949 }
6950
6951 if (list) {
6952 XFree(formats);
6953 }
6954
6955 break;
6956 }
6957
6958 if (E.xclient.message_type == XdndPosition) {
6959 const i32 xabs = (E.xclient.data.l[2] >> 16) & 0xffff;
6960 const i32 yabs = (E.xclient.data.l[2]) & 0xffff;
6961 Window dummy;
6962 i32 xpos, ypos;
6963
6964 if (version > 5)
6965 break;
6966
6967 XTranslateCoordinates(
6968 _RGFW->display, XDefaultRootWindow(_RGFW->display), win->src.window,
6969 xabs, yabs, &xpos, &ypos, &dummy
6970 );
6971
6972 dragX = xpos;
6973 dragY = ypos;
6974
6975 reply.xclient.window = source;
6976 reply.xclient.message_type = XdndStatus;
6977
6978 if (format) {
6979 reply.xclient.data.l[1] = 1;
6980 if (version >= 2)
6981 reply.xclient.data.l[4] = (long)XdndActionCopy;
6982 }
6983
6984 XSendEvent(_RGFW->display, source, False, NoEventMask, &reply);
6985 XFlush(_RGFW->display);
6986 break;
6987 }
6988 if (E.xclient.message_type != XdndDrop)
6989 break;
6990
6991 if (version > 5)
6992 break;
6993
6994 if (format) {
6995 Time time = (version >= 1)
6996 ? (Time)E.xclient.data.l[2]
6997 : CurrentTime;
6998
6999 XConvertSelection(
7000 _RGFW->display, XdndSelection, (Atom)format,
7001 XdndSelection, win->src.window, time
7002 );
7003 } else if (version >= 2) {
7004 XEvent new_reply = { ClientMessage };
7005
7006 XSendEvent(_RGFW->display, source, False, NoEventMask, &new_reply);
7007 XFlush(_RGFW->display);
7008 }
7009
7010 RGFW_dataDragCallback(win, dragX, dragY);
7011 } break;
7012 case SelectionNotify: {
7013 /* this is only for checking for xdnd drops */
7014 if (!(win->internal.enabledEvents & RGFW_dataDropFlag) || E.xselection.property != XdndSelection || !(win->internal.flags & RGFW_windowAllowDND))
7015 return;
7016 char* data;
7017 unsigned long result;
7018
7019 Atom actualType;
7020 i32 actualFormat;
7021 unsigned long bytesAfter;
7022
7023 XGetWindowProperty(_RGFW->display, E.xselection.requestor, E.xselection.property, 0, LONG_MAX, False, E.xselection.target, &actualType, &actualFormat, &result, &bytesAfter, (u8**) &data);
7024
7025 if (result == 0)
7026 break;
7027
7028 const char* prefix = (const char*)"file://";
7029
7030 char* line;
7031
7032 size_t count = 0;
7033 char** files = _RGFW->files;
7034
7035 while ((line = (char*)RGFW_strtok(data, "\r\n"))) {
7036 data = NULL;
7037
7038 if (line[0] == '#')
7039 continue;
7040
7041 char* l;
7042 for (l = line; 1; l++) {
7043 if ((l - line) > 7)
7044 break;
7045 else if (*l != prefix[(l - line)])
7046 break;
7047 else if (*l == '\0' && prefix[(l - line)] == '\0') {
7048 line += 7;
7049 while (*line != '/')
7050 line++;
7051 break;
7052 } else if (*l == '\0')
7053 break;
7054 }
7055
7056 count++;
7057
7058 size_t len = RGFW_unix_stringlen(line);
7059 char* path = (char*)RGFW_ALLOC(len + 1);
7060
7061 size_t index = 0;
7062 while (*line) {
7063 if (line[0] == '%' && line[1] && line[2]) {
7064 char digits[3] = {0};
7065 digits[0] = line[1];
7066 digits[1] = line[2];
7067 digits[2] = '\0';
7068 path[index] = (char) RGFW_STRTOL(digits, NULL, 16);
7069 line += 2;
7070 } else {
7071 if (index >= len) {
7072 break;
7073 }
7074
7075 path[index] = *line;
7076 }
7077
7078 index++;
7079 line++;
7080 }
7081
7082 path[len] = '\0';
7083 size_t cnt = RGFW_MIN(len + 1, RGFW_MAX_PATH);
7084 if (cnt == RGFW_MAX_PATH) {
7085 path[cnt] = '\0';
7086 }
7087
7088 RGFW_MEMCPY(files[count - 1], path, cnt);
7089 RGFW_FREE(path);
7090 }
7091
7092 RGFW_dataDropCallback(win, files, count);
7093 if (data)
7094 XFree(data);
7095
7096 if (version >= 2) {
7097 XEvent new_reply = { ClientMessage };
7098 new_reply.xclient.window = source;
7099 new_reply.xclient.message_type = XdndFinished;
7100 new_reply.xclient.format = 32;
7101 new_reply.xclient.data.l[1] = (long int)result;
7102 new_reply.xclient.data.l[2] = (long int)XdndActionCopy;
7103 XSendEvent(_RGFW->display, source, False, NoEventMask, &new_reply);
7104 XFlush(_RGFW->display);
7105 }
7106 break;
7107 }
7108 case FocusIn:
7109 if (win->src.ic) XSetICFocus(win->src.ic);
7110 RGFW_focusCallback(win, 1);
7111 break;
7112 case FocusOut:
7113 if (win->src.ic) XUnsetICFocus(win->src.ic);
7114 RGFW_focusCallback(win, 0);
7115 break;
7116 case EnterNotify: {
7117 RGFW_mouseNotifyCallback(win, E.xcrossing.x, E.xcrossing.y, RGFW_TRUE);
7118 break;
7119 }
7120
7121 case LeaveNotify: {
7122 RGFW_mouseNotifyCallback(win, win->internal.lastMouseX, win->internal.lastMouseY, RGFW_FALSE);
7123 break;
7124 }
7125 case ReparentNotify:
7126 win->src.parent = E.xreparent.parent;
7127 break;
7128 case ConfigureNotify: {
7129 /* detect resize */
7130 if (E.xconfigure.width != win->src.w || E.xconfigure.height != win->src.h) {
7131 RGFW_window_checkMode(win);
7132 win->src.w = E.xconfigure.width;
7133 win->src.h = E.xconfigure.height;
7134 RGFW_windowResizedCallback(win, E.xconfigure.width, E.xconfigure.height);
7135 }
7136
7137 i32 x = E.xconfigure.x;
7138 i32 y = E.xconfigure.y;
7139
7140 /*
7141 if the event came from the server and we're not a direct child of the root window then
7142 we're using local coords which need to be translated into screen coords
7143 */
7144 Window root = DefaultRootWindow(_RGFW->display);
7145 if (E.xany.send_event == 0 && win->src.parent != root) {
7146 Window dummy = 0;
7147 XTranslateCoordinates(_RGFW->display, win->src.parent, root, x, y, &x, &y, &dummy);
7148 }
7149
7150 /* detect move */
7151 if (E.xconfigure.x != win->src.x || E.xconfigure.y != win->src.y) {
7152 win->src.x = E.xconfigure.x;
7153 win->src.y = E.xconfigure.y;
7154 RGFW_windowMovedCallback(win, E.xconfigure.x, E.xconfigure.y);
7155 }
7156 return;
7157 }
7158 default:
7159 break;
7160 }
7161
7162 XFlush(_RGFW->display);
7163 }
7164
7165 void RGFW_FUNC(RGFW_pollEvents) (void) {
7166 RGFW_resetPrevState();
7167
7168 XPending(_RGFW->display);
7169 /* if there is no unread queued events, get a new one */
7170 while (QLength(_RGFW->display)) {
7171 RGFW_XHandleEvent();
7172 }
7173 }
7174
7175 void RGFW_FUNC(RGFW_window_move) (RGFW_window* win, i32 x, i32 y) {
7176 RGFW_ASSERT(win != NULL);
7177 win->x = x;
7178 win->y = y;
7179
7180 XMoveWindow(_RGFW->display, win->src.window, x, y);
7181 return;
7182 }
7183
7184
7185 void RGFW_FUNC(RGFW_window_resize) (RGFW_window* win, i32 w, i32 h) {
7186 RGFW_ASSERT(win != NULL);
7187 win->w = (i32)w;
7188 win->h = (i32)h;
7189
7190 XResizeWindow(_RGFW->display, win->src.window, (u32)w, (u32)h);
7191
7192 if ((win->internal.flags & RGFW_windowNoResize)) {
7193 XSizeHints sh;
7194 sh.flags = (1L << 4) | (1L << 5);
7195 sh.min_width = sh.max_width = (i32)w;
7196 sh.min_height = sh.max_height = (i32)h;
7197
7198 XSetWMSizeHints(_RGFW->display, (Drawable) win->src.window, &sh, XA_WM_NORMAL_HINTS);
7199 }
7200 return;
7201 }
7202
7203 void RGFW_FUNC(RGFW_window_setAspectRatio) (RGFW_window* win, i32 w, i32 h) {
7204 RGFW_ASSERT(win != NULL);
7205
7206
7207 if (w == 0 && h == 0)
7208 return;
7209 XSizeHints hints;
7210 long flags;
7211
7212 XGetWMNormalHints(_RGFW->display, win->src.window, &hints, &flags);
7213
7214 hints.flags |= PAspect;
7215
7216 hints.min_aspect.x = hints.max_aspect.x = (i32)w;
7217 hints.min_aspect.y = hints.max_aspect.y = (i32)h;
7218
7219 XSetWMNormalHints(_RGFW->display, win->src.window, &hints);
7220 return;
7221 }
7222
7223 void RGFW_FUNC(RGFW_window_setMinSize) (RGFW_window* win, i32 w, i32 h) {
7224 RGFW_ASSERT(win != NULL);
7225
7226 long flags;
7227 XSizeHints hints;
7228 RGFW_MEMSET(&hints, 0, sizeof(XSizeHints));
7229
7230 XGetWMNormalHints(_RGFW->display, win->src.window, &hints, &flags);
7231
7232 hints.flags |= PMinSize;
7233
7234 hints.min_width = (i32)w;
7235 hints.min_height = (i32)h;
7236
7237 XSetWMNormalHints(_RGFW->display, win->src.window, &hints);
7238 return;
7239 }
7240
7241 void RGFW_FUNC(RGFW_window_setMaxSize) (RGFW_window* win, i32 w, i32 h) {
7242 RGFW_ASSERT(win != NULL);
7243
7244 long flags;
7245 XSizeHints hints;
7246 RGFW_MEMSET(&hints, 0, sizeof(XSizeHints));
7247
7248 XGetWMNormalHints(_RGFW->display, win->src.window, &hints, &flags);
7249
7250 hints.flags |= PMaxSize;
7251
7252 hints.max_width = (i32)w;
7253 hints.max_height = (i32)h;
7254
7255 XSetWMNormalHints(_RGFW->display, win->src.window, &hints);
7256 return;
7257 }
7258
7259 void RGFW_toggleXMaximized(RGFW_window* win, RGFW_bool maximized);
7260 void RGFW_toggleXMaximized(RGFW_window* win, RGFW_bool maximized) {
7261 RGFW_ASSERT(win != NULL);
7262 RGFW_LOAD_ATOM(_NET_WM_STATE);
7263 RGFW_LOAD_ATOM(_NET_WM_STATE_MAXIMIZED_VERT);
7264 RGFW_LOAD_ATOM(_NET_WM_STATE_MAXIMIZED_HORZ);
7265
7266 XEvent xev = {0};
7267 xev.type = ClientMessage;
7268 xev.xclient.window = win->src.window;
7269 xev.xclient.message_type = _NET_WM_STATE;
7270 xev.xclient.format = 32;
7271 xev.xclient.data.l[0] = maximized;
7272 xev.xclient.data.l[1] = (long int)_NET_WM_STATE_MAXIMIZED_HORZ;
7273 xev.xclient.data.l[2] = (long int)_NET_WM_STATE_MAXIMIZED_VERT;
7274 xev.xclient.data.l[3] = 0;
7275 xev.xclient.data.l[4] = 0;
7276
7277 XSendEvent(_RGFW->display, DefaultRootWindow(_RGFW->display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
7278 }
7279
7280 void RGFW_FUNC(RGFW_window_maximize) (RGFW_window* win) {
7281 win->internal.oldX = win->x;
7282 win->internal.oldY = win->y;
7283 win->internal.oldW = win->w;
7284 win->internal.oldH = win->h;
7285
7286 RGFW_toggleXMaximized(win, 1);
7287 return;
7288 }
7289
7290 void RGFW_FUNC(RGFW_window_focus) (RGFW_window* win) {
7291 RGFW_ASSERT(win);
7292
7293 XWindowAttributes attr;
7294 XGetWindowAttributes(_RGFW->display, win->src.window, &attr);
7295 if (attr.map_state != IsViewable) return;
7296
7297 XSetInputFocus(_RGFW->display, win->src.window, RevertToPointerRoot, CurrentTime);
7298 XFlush(_RGFW->display);
7299 }
7300
7301 void RGFW_FUNC(RGFW_window_raise) (RGFW_window* win) {
7302 RGFW_ASSERT(win);
7303 XMapRaised(_RGFW->display, win->src.window);
7304 RGFW_window_setFullscreen(win, RGFW_window_isFullscreen(win));
7305 }
7306
7307 void RGFW_window_setXAtom(RGFW_window* win, Atom netAtom, RGFW_bool fullscreen);
7308 void RGFW_window_setXAtom(RGFW_window* win, Atom netAtom, RGFW_bool fullscreen) {
7309 RGFW_ASSERT(win != NULL);
7310 RGFW_LOAD_ATOM(_NET_WM_STATE);
7311
7312 XEvent xev = {0};
7313 xev.xclient.type = ClientMessage;
7314 xev.xclient.serial = 0;
7315 xev.xclient.send_event = True;
7316 xev.xclient.message_type = _NET_WM_STATE;
7317 xev.xclient.window = win->src.window;
7318 xev.xclient.format = 32;
7319 xev.xclient.data.l[0] = fullscreen;
7320 xev.xclient.data.l[1] = (long int)netAtom;
7321 xev.xclient.data.l[2] = 0;
7322
7323 XSendEvent(_RGFW->display, DefaultRootWindow(_RGFW->display), False, SubstructureNotifyMask | SubstructureRedirectMask, &xev);
7324 }
7325
7326 void RGFW_FUNC(RGFW_window_setFullscreen)(RGFW_window* win, RGFW_bool fullscreen) {
7327 RGFW_ASSERT(win != NULL);
7328
7329 if (fullscreen) {
7330 win->internal.flags |= RGFW_windowFullscreen;
7331 win->internal.oldX = win->x;
7332 win->internal.oldY = win->y;
7333 win->internal.oldW = win->w;
7334 win->internal.oldH = win->h;
7335 }
7336 else win->internal.flags &= ~(u32)RGFW_windowFullscreen;
7337
7338 XRaiseWindow(_RGFW->display, win->src.window);
7339
7340 RGFW_LOAD_ATOM(_NET_WM_STATE_FULLSCREEN);
7341 RGFW_window_setXAtom(win, _NET_WM_STATE_FULLSCREEN, fullscreen);
7342
7343 if (!(win->internal.flags & RGFW_windowTransparent)) {
7344 const unsigned char value = fullscreen;
7345 RGFW_LOAD_ATOM(_NET_WM_BYPASS_COMPOSITOR);
7346 XChangeProperty(
7347 _RGFW->display, win->src.window,
7348 _NET_WM_BYPASS_COMPOSITOR, XA_CARDINAL, 32,
7349 PropModeReplace, &value, 1);
7350 }
7351 }
7352
7353 void RGFW_FUNC(RGFW_window_setFloating)(RGFW_window* win, RGFW_bool floating) {
7354 RGFW_ASSERT(win != NULL);
7355 RGFW_LOAD_ATOM(_NET_WM_STATE_ABOVE);
7356 RGFW_window_setXAtom(win, _NET_WM_STATE_ABOVE, floating);
7357 }
7358
7359 void RGFW_FUNC(RGFW_window_setOpacity)(RGFW_window* win, u8 opacity) {
7360 RGFW_ASSERT(win != NULL);
7361 const u32 value = (u32) (0xffffffffu * (double) opacity);
7362 RGFW_LOAD_ATOM(NET_WM_WINDOW_OPACITY);
7363 XChangeProperty(_RGFW->display, win->src.window,
7364 NET_WM_WINDOW_OPACITY, XA_CARDINAL, 32, PropModeReplace, (unsigned char*) &value, 1);
7365 }
7366
7367 void RGFW_FUNC(RGFW_window_minimize)(RGFW_window* win) {
7368 RGFW_ASSERT(win != NULL);
7369
7370 if (RGFW_window_isMaximized(win)) return;
7371
7372 win->internal.oldX = win->x;
7373 win->internal.oldY = win->y;
7374 win->internal.oldW = win->w;
7375 win->internal.oldH = win->h;
7376 XIconifyWindow(_RGFW->display, win->src.window, DefaultScreen(_RGFW->display));
7377 XFlush(_RGFW->display);
7378 }
7379
7380 void RGFW_FUNC(RGFW_window_restore)(RGFW_window* win) {
7381 RGFW_ASSERT(win != NULL);
7382 RGFW_toggleXMaximized(win, RGFW_FALSE);
7383 RGFW_window_move(win, win->internal.oldX, win->internal.oldY);
7384 RGFW_window_resize(win, win->internal.oldW, win->internal.oldH);
7385
7386 RGFW_window_show(win);
7387 XFlush(_RGFW->display);
7388 }
7389
7390 RGFW_bool RGFW_FUNC(RGFW_window_isFloating)(RGFW_window* win) {
7391 RGFW_LOAD_ATOM(_NET_WM_STATE);
7392 RGFW_LOAD_ATOM(_NET_WM_STATE_ABOVE);
7393
7394 Atom actual_type;
7395 int actual_format;
7396 unsigned long nitems, bytes_after;
7397 Atom* prop_return = NULL;
7398
7399 int status = XGetWindowProperty(_RGFW->display, win->src.window, _NET_WM_STATE, 0, (~0L), False, XA_ATOM,
7400 &actual_type, &actual_format, &nitems, &bytes_after,
7401 (unsigned char **)&prop_return);
7402
7403 if (status != Success || actual_type != XA_ATOM)
7404 return RGFW_FALSE;
7405
7406 unsigned long i;
7407 for (i = 0; i < nitems; i++)
7408 if (prop_return[i] == _NET_WM_STATE_ABOVE) return RGFW_TRUE;
7409
7410 if (prop_return)
7411 XFree(prop_return);
7412 return RGFW_FALSE;
7413 }
7414
7415 void RGFW_FUNC(RGFW_window_setName)(RGFW_window* win, const char* name) {
7416 RGFW_ASSERT(win != NULL);
7417 if (name == NULL) name = "\0";
7418
7419 Xutf8SetWMProperties(_RGFW->display, win->src.window, name, name, NULL, 0, NULL, NULL, NULL);
7420 XStoreName(_RGFW->display, win->src.window, name);
7421
7422 RGFW_LOAD_ATOM(_NET_WM_NAME); RGFW_LOAD_ATOM(UTF8_STRING);
7423
7424 XChangeProperty(
7425 _RGFW->display, win->src.window, _NET_WM_NAME, UTF8_STRING,
7426 8, PropModeReplace, (u8*)name, (int)RGFW_unix_stringlen(name)
7427 );
7428 }
7429
7430 #ifndef RGFW_NO_PASSTHROUGH
7431 void RGFW_FUNC(RGFW_window_setMousePassthrough) (RGFW_window* win, RGFW_bool passthrough) {
7432 RGFW_ASSERT(win != NULL);
7433 if (passthrough) {
7434 Region region = XCreateRegion();
7435 XShapeCombineRegion(_RGFW->display, win->src.window, ShapeInput, 0, 0, region, ShapeSet);
7436 XDestroyRegion(region);
7437
7438 return;
7439 }
7440
7441 XShapeCombineMask(_RGFW->display, win->src.window, ShapeInput, 0, 0, None, ShapeSet);
7442 }
7443 #endif /* RGFW_NO_PASSTHROUGH */
7444
7445 RGFW_bool RGFW_FUNC(RGFW_window_setIconEx) (RGFW_window* win, u8* data_src, i32 w, i32 h, RGFW_format format, RGFW_icon type) {
7446 Atom _NET_WM_ICON = XInternAtom(_RGFW->display, "_NET_WM_ICON", False);
7447 RGFW_ASSERT(win != NULL);
7448 if (data_src == NULL) {
7449 RGFW_bool res = (RGFW_bool)XChangeProperty(
7450 _RGFW->display, win->src.window, _NET_WM_ICON, XA_CARDINAL, 32,
7451 PropModeReplace, (u8*)NULL, 0
7452 );
7453 return res;
7454 }
7455
7456 i32 count = (i32)(2 + (w * h));
7457
7458 unsigned long* data = (unsigned long*) RGFW_ALLOC((u32)count * sizeof(unsigned long));
7459 RGFW_ASSERT(data != NULL);
7460
7461 RGFW_MEMSET(data, 0, (u32)count * sizeof(unsigned long));
7462 data[0] = (unsigned long)w;
7463 data[1] = (unsigned long)h;
7464
7465 RGFW_copyImageData64((u8*)&data[2], w, h, RGFW_formatBGRA8, data_src, format, RGFW_TRUE, NULL);
7466 RGFW_bool res = RGFW_TRUE;
7467 if (type & RGFW_iconTaskbar) {
7468 res = (RGFW_bool)XChangeProperty(
7469 _RGFW->display, win->src.window, _NET_WM_ICON, XA_CARDINAL, 32,
7470 PropModeReplace, (u8*)data, count
7471 );
7472 }
7473
7474 RGFW_copyImageData64((u8*)&data[2], w, h, RGFW_formatBGRA8, data_src, format, RGFW_FALSE, NULL);
7475
7476 if (type & RGFW_iconWindow) {
7477 XWMHints wm_hints;
7478 wm_hints.flags = IconPixmapHint;
7479
7480 i32 depth = DefaultDepth(_RGFW->display, DefaultScreen(_RGFW->display));
7481 XImage *image = XCreateImage(_RGFW->display, DefaultVisual(_RGFW->display, DefaultScreen(_RGFW->display)),
7482 (u32)depth, ZPixmap, 0, (char *)&data[2], (u32)w, (u32)h, 32, 0);
7483
7484 wm_hints.icon_pixmap = XCreatePixmap(_RGFW->display, win->src.window, (u32)w, (u32)h, (u32)depth);
7485 XPutImage(_RGFW->display, wm_hints.icon_pixmap, DefaultGC(_RGFW->display, DefaultScreen(_RGFW->display)), image, 0, 0, 0, 0, (u32)w, (u32)h);
7486 image->data = NULL;
7487 XDestroyImage(image);
7488
7489 XSetWMHints(_RGFW->display, win->src.window, &wm_hints);
7490 }
7491
7492 RGFW_FREE(data);
7493 XFlush(_RGFW->display);
7494 return RGFW_BOOL(res);
7495 }
7496
7497 RGFW_mouse* RGFW_FUNC(RGFW_loadMouse) (u8* data, i32 w, i32 h, RGFW_format format) {
7498 RGFW_ASSERT(data);
7499 #ifndef RGFW_NO_X11_CURSOR
7500 RGFW_init();
7501 XcursorImage* native = XcursorImageCreate((i32)w, (i32)h);
7502 native->xhot = 0;
7503 native->yhot = 0;
7504 RGFW_MEMSET(native->pixels, 0, (u32)(w * h * 4));
7505 RGFW_copyImageData((u8*)native->pixels, w, h, RGFW_formatBGRA8, data, format, NULL);
7506
7507 Cursor cursor = XcursorImageLoadCursor(_RGFW->display, native);
7508 XcursorImageDestroy(native);
7509
7510 return (void*)cursor;
7511 #else
7512 RGFW_UNUSED(data); RGFW_UNUSED(w); RGFW_UNUSED(h); RGFW_UNUSED(format);
7513 return NULL;
7514 #endif
7515 }
7516
7517 void RGFW_FUNC(RGFW_window_setMouse)(RGFW_window* win, RGFW_mouse* mouse) {
7518 RGFW_ASSERT(win && mouse);
7519 XDefineCursor(_RGFW->display, win->src.window, (Cursor)mouse);
7520 }
7521
7522 void RGFW_FUNC(RGFW_freeMouse)(RGFW_mouse* mouse) {
7523 RGFW_ASSERT(mouse);
7524 XFreeCursor(_RGFW->display, (Cursor)mouse);
7525 }
7526
7527 void RGFW_FUNC(RGFW_window_moveMouse)(RGFW_window* win, i32 x, i32 y) {
7528 RGFW_ASSERT(win != NULL);
7529
7530 XEvent event;
7531 XQueryPointer(_RGFW->display, DefaultRootWindow(_RGFW->display),
7532 &event.xbutton.root, &event.xbutton.window,
7533 &event.xbutton.x_root, &event.xbutton.y_root,
7534 &event.xbutton.x, &event.xbutton.y,
7535 &event.xbutton.state);
7536
7537 win->internal.lastMouseX = x - win->x;
7538 win->internal.lastMouseY = y - win->y;
7539 if (event.xbutton.x == x && event.xbutton.y == y)
7540 return;
7541
7542 XWarpPointer(_RGFW->display, None, win->src.window, 0, 0, 0, 0, (int) x - win->x, (int) y - win->y);
7543 }
7544
7545 RGFW_bool RGFW_FUNC(RGFW_window_setMouseDefault) (RGFW_window* win) {
7546 return RGFW_window_setMouseStandard(win, RGFW_mouseArrow);
7547 }
7548
7549 RGFW_bool RGFW_FUNC(RGFW_window_setMouseStandard) (RGFW_window* win, u8 mouse) {
7550 RGFW_ASSERT(win != NULL);
7551
7552 u32 mouseIcon = 0;
7553
7554 switch (mouse) {
7555 case RGFW_mouseNormal: mouseIcon = XC_left_ptr; break;
7556 case RGFW_mouseArrow: mouseIcon = XC_left_ptr; break;
7557 case RGFW_mouseIbeam: mouseIcon = XC_xterm; break;
7558 case RGFW_mouseWait: mouseIcon = XC_watch; break;
7559 case RGFW_mouseCrosshair: mouseIcon = XC_tcross; break;
7560 case RGFW_mouseProgress: mouseIcon = XC_watch; break;
7561 case RGFW_mouseResizeNWSE: mouseIcon = XC_top_left_corner; break;
7562 case RGFW_mouseResizeNESW: mouseIcon = XC_top_right_corner; break;
7563 case RGFW_mouseResizeEW: mouseIcon = XC_sb_h_double_arrow; break;
7564 case RGFW_mouseResizeNS: mouseIcon = XC_sb_v_double_arrow; break;
7565 case RGFW_mouseResizeNW: mouseIcon = XC_top_left_corner; break;
7566 case RGFW_mouseResizeN: mouseIcon = XC_top_side; break;
7567 case RGFW_mouseResizeNE: mouseIcon = XC_top_right_corner; break;
7568 case RGFW_mouseResizeE: mouseIcon = XC_right_side; break;
7569 case RGFW_mouseResizeSE: mouseIcon = XC_bottom_right_corner; break;
7570 case RGFW_mouseResizeS: mouseIcon = XC_bottom_side; break;
7571 case RGFW_mouseResizeSW: mouseIcon = XC_bottom_left_corner; break;
7572 case RGFW_mouseResizeW: mouseIcon = XC_left_side; break;
7573 case RGFW_mouseResizeAll: mouseIcon = XC_fleur; break;
7574 case RGFW_mouseNotAllowed: mouseIcon = XC_pirate; break;
7575 case RGFW_mousePointingHand: mouseIcon = XC_hand2; break;
7576 default: return RGFW_FALSE;
7577 }
7578
7579 Cursor cursor = XCreateFontCursor(_RGFW->display, mouseIcon);
7580 XDefineCursor(_RGFW->display, win->src.window, (Cursor) cursor);
7581 XFreeCursor(_RGFW->display, (Cursor) cursor);
7582 return RGFW_TRUE;
7583 }
7584
7585 void RGFW_FUNC(RGFW_window_hide)(RGFW_window* win) {
7586 win->internal.flags |= (u32)RGFW_windowHide;
7587 XUnmapWindow(_RGFW->display, win->src.window);
7588
7589 XFlush(_RGFW->display);
7590 }
7591
7592 void RGFW_FUNC(RGFW_window_show) (RGFW_window* win) {
7593 win->internal.flags &= ~(u32)RGFW_windowHide;
7594 if (win->internal.flags & RGFW_windowFocusOnShow) RGFW_window_focus(win);
7595
7596 if (RGFW_window_isHidden(win) == RGFW_FALSE) {
7597 return;
7598 }
7599
7600 XMapWindow(_RGFW->display, win->src.window);
7601 RGFW_window_move(win, win->x, win->y);
7602
7603 RGFW_waitForShowEvent_X11(win);
7604 RGFW_window_setFullscreen(win, RGFW_window_isFullscreen(win));
7605 return;
7606 }
7607
7608 void RGFW_FUNC(RGFW_window_flash) (RGFW_window* win, RGFW_flashRequest request) {
7609 if (RGFW_window_isInFocus(win) && request) {
7610 return;
7611 }
7612
7613 XWMHints* wmhints = XGetWMHints(_RGFW->display, win->src.window);
7614 if (wmhints == NULL) return;
7615
7616 if (request) {
7617 wmhints->flags |= XUrgencyHint;
7618 if (request == RGFW_flashBriefly)
7619 win->src.flashEnd = RGFW_linux_getTimeNS() + (u64)1e+9;
7620 if (request == RGFW_flashUntilFocused)
7621 win->src.flashEnd = (u64)-1;
7622 } else {
7623 win->src.flashEnd = 0;
7624 wmhints->flags &= ~XUrgencyHint;
7625 }
7626
7627 XSetWMHints(_RGFW->display, win->src.window, wmhints);
7628 XFree(wmhints);
7629 }
7630
7631 RGFW_ssize_t RGFW_FUNC(RGFW_readClipboardPtr)(char* str, size_t strCapacity) {
7632 RGFW_init();
7633 RGFW_LOAD_ATOM(XSEL_DATA); RGFW_LOAD_ATOM(UTF8_STRING); RGFW_LOAD_ATOM(CLIPBOARD);
7634 if (XGetSelectionOwner(_RGFW->display, CLIPBOARD) == _RGFW->helperWindow) {
7635 if (str != NULL)
7636 RGFW_STRNCPY(str, _RGFW->clipboard, _RGFW->clipboard_len - 1);
7637 _RGFW->clipboard[_RGFW->clipboard_len - 1] = '\0';
7638 return (RGFW_ssize_t)_RGFW->clipboard_len - 1;
7639 }
7640
7641 XEvent event;
7642 int format;
7643 unsigned long N, sizeN;
7644 char* data;
7645 Atom target;
7646
7647 XConvertSelection(_RGFW->display, CLIPBOARD, UTF8_STRING, XSEL_DATA, _RGFW->helperWindow, CurrentTime);
7648 XSync(_RGFW->display, 0);
7649 while (1) {
7650 XNextEvent(_RGFW->display, &event);
7651 if (event.type != SelectionNotify) continue;
7652
7653 if (event.xselection.selection != CLIPBOARD || event.xselection.property == 0)
7654 return -1;
7655 break;
7656 }
7657
7658 XGetWindowProperty(event.xselection.display, event.xselection.requestor,
7659 event.xselection.property, 0L, (~0L), 0, AnyPropertyType, &target,
7660 &format, &sizeN, &N, (u8**) &data);
7661
7662 RGFW_ssize_t size;
7663 if (sizeN > strCapacity && str != NULL)
7664 size = -1;
7665
7666 if ((target == UTF8_STRING || target == XA_STRING) && str != NULL) {
7667 RGFW_MEMCPY(str, data, sizeN);
7668 str[sizeN] = '\0';
7669 XFree(data);
7670 } else if (str != NULL) size = -1;
7671
7672 XDeleteProperty(event.xselection.display, event.xselection.requestor, event.xselection.property);
7673 size = (RGFW_ssize_t)sizeN;
7674
7675 return size;
7676 }
7677
7678 i32 RGFW_XHandleClipboardSelectionHelper(void) {
7679 RGFW_LOAD_ATOM(SAVE_TARGETS);
7680
7681 XEvent event;
7682 XPending(_RGFW->display);
7683
7684 if (QLength(_RGFW->display) || XEventsQueued(_RGFW->display, QueuedAlready) + XEventsQueued(_RGFW->display, QueuedAfterReading))
7685 XNextEvent(_RGFW->display, &event);
7686 else
7687 return 0;
7688
7689 switch (event.type) {
7690 case SelectionRequest:
7691 RGFW_XHandleClipboardSelection(&event);
7692 return 0;
7693 case SelectionNotify:
7694 if (event.xselection.target == SAVE_TARGETS)
7695 return 0;
7696 break;
7697 default: break;
7698 }
7699
7700 return 0;
7701 }
7702
7703 void RGFW_FUNC(RGFW_writeClipboard)(const char* text, u32 textLen) {
7704 RGFW_LOAD_ATOM(SAVE_TARGETS); RGFW_LOAD_ATOM(CLIPBOARD);
7705 RGFW_init();
7706
7707 /* request ownership of the clipboard section and request to convert it, this means its our job to convert it */
7708 XSetSelectionOwner(_RGFW->display, CLIPBOARD, _RGFW->helperWindow, CurrentTime);
7709 if (XGetSelectionOwner(_RGFW->display, CLIPBOARD) != _RGFW->helperWindow) {
7710 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errClipboard, "X11 failed to become owner of clipboard selection");
7711 return;
7712 }
7713
7714 if (_RGFW->clipboard)
7715 RGFW_FREE(_RGFW->clipboard);
7716
7717 _RGFW->clipboard = (char*)RGFW_ALLOC(textLen);
7718 RGFW_ASSERT(_RGFW->clipboard != NULL);
7719
7720 RGFW_STRNCPY(_RGFW->clipboard, text, textLen - 1);
7721 _RGFW->clipboard[textLen - 1] = '\0';
7722 _RGFW->clipboard_len = textLen;
7723 return;
7724 }
7725
7726 RGFW_bool RGFW_FUNC(RGFW_window_isHidden)(RGFW_window* win) {
7727 RGFW_ASSERT(win != NULL);
7728 XWindowAttributes windowAttributes;
7729 XGetWindowAttributes(_RGFW->display, win->src.window, &windowAttributes);
7730
7731 return (windowAttributes.map_state != IsViewable);
7732 }
7733
7734 RGFW_bool RGFW_FUNC(RGFW_window_isMinimized)(RGFW_window* win) {
7735 RGFW_ASSERT(win != NULL);
7736 RGFW_LOAD_ATOM(WM_STATE);
7737
7738 Atom actual_type;
7739 i32 actual_format;
7740 unsigned long nitems, bytes_after;
7741 unsigned char* prop_data;
7742
7743 i32 status = XGetWindowProperty(_RGFW->display, win->src.window, WM_STATE, 0, 2, False,
7744 AnyPropertyType, &actual_type, &actual_format,
7745 &nitems, &bytes_after, &prop_data);
7746
7747 if (status == Success && nitems >= 1 && prop_data == (unsigned char*)IconicState) {
7748 XFree(prop_data);
7749 return RGFW_TRUE;
7750 }
7751
7752 if (prop_data != NULL)
7753 XFree(prop_data);
7754
7755 XWindowAttributes windowAttributes;
7756 XGetWindowAttributes(_RGFW->display, win->src.window, &windowAttributes);
7757 return windowAttributes.map_state != IsViewable;
7758 }
7759
7760 RGFW_bool RGFW_FUNC(RGFW_window_isMaximized)(RGFW_window* win) {
7761 RGFW_ASSERT(win != NULL);
7762 RGFW_LOAD_ATOM(_NET_WM_STATE);
7763 RGFW_LOAD_ATOM(_NET_WM_STATE_MAXIMIZED_VERT);
7764 RGFW_LOAD_ATOM(_NET_WM_STATE_MAXIMIZED_HORZ);
7765
7766 Atom actual_type;
7767 i32 actual_format;
7768 unsigned long nitems, bytes_after;
7769 unsigned char* prop_data;
7770
7771 i32 status = XGetWindowProperty(_RGFW->display, win->src.window, _NET_WM_STATE, 0, 1024, False,
7772 XA_ATOM, &actual_type, &actual_format,
7773 &nitems, &bytes_after, &prop_data);
7774
7775 if (status != Success) {
7776 if (prop_data != NULL)
7777 XFree(prop_data);
7778
7779 return RGFW_FALSE;
7780 }
7781
7782 u64 i;
7783 for (i = 0; i < nitems; i++) {
7784 if (prop_data[i] == _NET_WM_STATE_MAXIMIZED_VERT ||
7785 prop_data[i] == _NET_WM_STATE_MAXIMIZED_HORZ) {
7786 XFree(prop_data);
7787 return RGFW_TRUE;
7788 }
7789 }
7790
7791 if (prop_data != NULL)
7792 XFree(prop_data);
7793
7794 return RGFW_FALSE;
7795 }
7796
7797 RGFWDEF void RGFW_XGetSystemContentDPI(float* dpi);
7798 void RGFW_XGetSystemContentDPI(float* dpi) {
7799 if (dpi == NULL) return;
7800 float dpiOutput = 96.0f;
7801
7802 #ifndef RGFW_NO_XRANDR
7803 char* rms = XResourceManagerString(_RGFW->display);
7804 if (rms == NULL) return;
7805
7806 XrmDatabase db = XrmGetStringDatabase(rms);
7807 if (db == NULL) return;
7808
7809 XrmValue value;
7810 char* type = NULL;
7811
7812 if (XrmGetResource(db, "Xft.dpi", "Xft.Dpi", &type, &value) && type && RGFW_STRNCMP(type, "String", 7) == 0)
7813 dpiOutput = (float)RGFW_ATOF(value.addr);
7814 XrmDestroyDatabase(db);
7815 #endif
7816
7817 if (dpi) *dpi = dpiOutput;
7818 }
7819
7820 RGFWDEF XRRModeInfo* RGFW_XGetMode(XRRCrtcInfo* ci, XRRScreenResources* res, RRMode mode, RGFW_monitorMode* foundMode);
7821 XRRModeInfo* RGFW_XGetMode(XRRCrtcInfo* ci, XRRScreenResources* res, RRMode mode, RGFW_monitorMode* foundMode) {
7822 XRRModeInfo* mi = None;
7823 for (i32 j = 0; j < res->nmode; j++) {
7824 if (res->modes[j].id == mode)
7825 mi = &res->modes[j];
7826 }
7827
7828 if (mi == None) return NULL;
7829
7830 if ((mi->modeFlags & RR_Interlace) != 0) return NULL;
7831
7832 foundMode->w = (i32)mi->width;
7833 foundMode->h = (i32)mi->height;
7834 if (ci->rotation == RR_Rotate_90 || ci->rotation == RR_Rotate_270) {
7835 foundMode->w = (i32)mi->height;
7836 foundMode->h = (i32)mi->width;
7837 } else {
7838 foundMode->w = (i32)mi->width;
7839 foundMode->h = (i32)mi->height;
7840 }
7841
7842 RGFW_splitBPP((u32)DefaultDepth(_RGFW->display, DefaultScreen(_RGFW->display)), foundMode);
7843
7844 foundMode->src = (void*)mode;
7845
7846 foundMode->refreshRate = 0;
7847 if (mi->hTotal == 0 || mi->vTotal == 0)
7848 return mi;
7849
7850 u32 vTotal = mi->vTotal;
7851
7852 if (mi->modeFlags & RR_DoubleScan) {
7853 vTotal *= 2;
7854 }
7855
7856 if (mi->modeFlags & RR_Interlace) {
7857 vTotal /= 2;
7858 }
7859
7860 i32 numerator = (i32)mi->dotClock;
7861 i32 denominator = (i32)(mi->hTotal * vTotal);
7862 float refreshRate = 0;
7863
7864 if (denominator <= 0) {
7865 denominator = 1;
7866 }
7867
7868 refreshRate = ((float)numerator / (float)denominator);
7869
7870 foundMode->refreshRate = RGFW_ROUNDF((refreshRate * 100)) / 100.0f;
7871 return mi;
7872 }
7873
7874 void RGFW_FUNC(RGFW_pollMonitors) (void) {
7875 RGFW_init();
7876
7877 Window root = XDefaultRootWindow(_RGFW->display);
7878 XRRScreenResources* res = XRRGetScreenResourcesCurrent(_RGFW->display, root);
7879 if (res == 0) {
7880 return;
7881 }
7882
7883 RROutput primary = XRRGetOutputPrimary(_RGFW->display, root);
7884
7885 for (RGFW_monitorNode* node = _RGFW->monitors.list.head; node; node = node->next) {
7886 node->disconnected = RGFW_TRUE;
7887 }
7888
7889 for (i32 i = 0; i < res->noutput; i++) {
7890 RGFW_monitorNode* node = NULL;
7891 for (node = _RGFW->monitors.list.head; node; node = node->next) {
7892 if (node->rrOutput == res->outputs[i]) {
7893 break;
7894 }
7895 }
7896
7897 if (node) {
7898 node->disconnected = RGFW_FALSE;
7899 if (node->rrOutput == primary) {
7900 _RGFW->monitors.primary = node;
7901 }
7902 continue;
7903 }
7904
7905 RGFW_monitor monitor;
7906
7907 XRROutputInfo* info = XRRGetOutputInfo(_RGFW->display, res, res->outputs[i]);
7908 if (info == NULL || info->connection != RR_Connected || info->crtc == None) {
7909 continue;
7910 }
7911
7912 XRRCrtcInfo* ci = XRRGetCrtcInfo(_RGFW->display, res, info->crtc);
7913
7914 if (ci == NULL) {
7915 continue;
7916 }
7917
7918 float physW = (float)info->mm_width / 25.4f;
7919 float physH = (float)info->mm_height / 25.4f;
7920
7921 RGFW_STRNCPY(monitor.name, info->name, sizeof(monitor.name) - 1);
7922 monitor.name[sizeof(monitor.name) - 1] = '\0';
7923
7924 if (physW > 0.0f && physH > 0.0f) {
7925 monitor.physW = physW;
7926 monitor.physH = physH;
7927 } else {
7928 monitor.physW = (float) ((float)ci->width / 96.f);
7929 monitor.physH = (float) ((float)ci->height / 96.f);
7930 }
7931
7932 monitor.x = ci->x;
7933 monitor.y = ci->y;
7934
7935 float dpi = 96.0f;
7936 RGFW_XGetSystemContentDPI(&dpi);
7937
7938 monitor.scaleX = dpi / 96.0f;
7939 monitor.scaleY = dpi / 96.0f;
7940
7941 monitor.pixelRatio = dpi >= 192.0f ? 2.0f : 1.0f;
7942
7943 XRRModeInfo* mi = RGFW_XGetMode(ci, res, ci->mode, &monitor.mode);
7944
7945 if (mi == NULL) {
7946 break;
7947 }
7948
7949 XRRFreeCrtcInfo(ci);
7950
7951 node = RGFW_monitors_add(&monitor);
7952 if (node == NULL) break;
7953
7954 node->rrOutput = res->outputs[i];
7955 node->crtc = info->crtc;
7956
7957 if (node->rrOutput == primary) {
7958 _RGFW->monitors.primary = node;
7959 }
7960
7961 XRRFreeOutputInfo(info);
7962 info = NULL;
7963
7964 RGFW_monitorCallback(_RGFW->root, &node->mon, RGFW_TRUE);
7965 }
7966
7967 XRRFreeScreenResources(res);
7968
7969 RGFW_monitors_refresh();
7970 }
7971
7972 RGFW_bool RGFW_FUNC(RGFW_monitor_getWorkarea) (RGFW_monitor* monitor, i32* x, i32* y, i32* width, i32* height) {
7973 RGFW_LOAD_ATOM(_NET_WORKAREA);
7974 RGFW_LOAD_ATOM(_NET_CURRENT_DESKTOP);
7975
7976 Window root = DefaultRootWindow(_RGFW->display);
7977
7978 i32 areaX = monitor->x;
7979 i32 areaY = monitor->y;
7980 i32 areaW = monitor->mode.w;
7981 i32 areaH = monitor->mode.h;
7982
7983 if (_NET_WORKAREA && _NET_CURRENT_DESKTOP) {
7984 Atom* extents = NULL;
7985 Atom* desktop = NULL;
7986
7987 Atom actualType = 0;
7988 int actualFormat = 0;
7989 unsigned long extentCount = 0, bytesAfter = 0;
7990 XGetWindowProperty(_RGFW->display, root, _NET_WORKAREA, 0, LONG_MAX, False, XA_CARDINAL, &actualType, &actualFormat, &extentCount, &bytesAfter, (u8**) &extents);
7991
7992 unsigned long count;
7993 XGetWindowProperty(_RGFW->display, root, _NET_CURRENT_DESKTOP, 0, LONG_MAX, False, XA_CARDINAL, &actualType, &actualFormat, &count, &bytesAfter, (u8**) &desktop);
7994
7995 if (count) {
7996 if (extentCount >= 4 && *desktop < extentCount / 4) {
7997 i32 globalX = (i32)extents[*desktop * 4 + 0];
7998 i32 globalY = (i32)extents[*desktop * 4 + 1];
7999 i32 globalW = (i32)extents[*desktop * 4 + 2];
8000 i32 globalH = (i32)extents[*desktop * 4 + 3];
8001
8002 if (areaX < globalX) {
8003 areaW -= globalX - areaX;
8004 areaX = globalX;
8005 }
8006
8007 if (areaY < globalY) {
8008 areaH -= globalY - areaY;
8009 areaY = globalY;
8010 }
8011
8012 if (areaX + areaW > globalX + globalW)
8013 areaW = globalX - areaX + globalW;
8014 if (areaY + areaH > globalY + globalH)
8015 areaH = globalY - areaY + globalH;
8016 }
8017 }
8018
8019 if (extents)
8020 XFree(extents);
8021 if (desktop)
8022 XFree(desktop);
8023 }
8024
8025 if (x) *x = areaX;
8026 if (y) *y = areaY;
8027 if (width) *width = areaW;
8028 if (height) *height = areaH;
8029
8030 return RGFW_TRUE;
8031 }
8032
8033 size_t RGFW_FUNC(RGFW_monitor_getModesPtr) (RGFW_monitor* monitor, RGFW_monitorMode** modes) {
8034 size_t count = 0;
8035
8036 XRRScreenResources* res = XRRGetScreenResourcesCurrent(_RGFW->display, DefaultRootWindow(_RGFW->display));
8037 if (res == NULL) return 0;
8038
8039 XRRCrtcInfo* ci = XRRGetCrtcInfo(_RGFW->display, res, monitor->node->crtc);
8040 XRROutputInfo* oi = XRRGetOutputInfo(_RGFW->display, res, monitor->node->rrOutput);
8041 count = (size_t)oi->nmode;
8042
8043 int i;
8044 for (i = 0; modes && i < oi->nmode; i++) {
8045 XRRModeInfo* mi = RGFW_XGetMode(ci, res, oi->modes[i], &((*modes)[i]));
8046 RGFW_UNUSED(mi);
8047 }
8048
8049 XRRFreeOutputInfo(oi);
8050 XRRFreeCrtcInfo(ci);
8051 XRRFreeScreenResources(res);
8052
8053 return count;
8054 }
8055
8056 size_t RGFW_FUNC(RGFW_monitor_getGammaRampPtr) (RGFW_monitor* monitor, RGFW_gammaRamp* ramp) {
8057 RGFW_UNUSED(monitor); RGFW_UNUSED(ramp);
8058 #ifndef RGFW_NO_XRANDR
8059 size_t size = (size_t)XRRGetCrtcGammaSize(_RGFW->display, monitor->node->crtc);
8060 XRRCrtcGamma* gamma = XRRGetCrtcGamma(_RGFW->display, monitor->node->crtc);
8061
8062 if (ramp) {
8063 RGFW_MEMCPY(ramp->red, gamma->red, size * sizeof(unsigned short));
8064 RGFW_MEMCPY(ramp->green, gamma->green, size * sizeof(unsigned short));
8065 RGFW_MEMCPY(ramp->blue, gamma->blue, size * sizeof(unsigned short));
8066 }
8067
8068 XRRFreeGamma(gamma);
8069 return size;
8070 #endif
8071
8072 return 0;
8073 }
8074
8075 RGFW_bool RGFW_FUNC(RGFW_monitor_setGammaRamp) (RGFW_monitor* monitor, RGFW_gammaRamp* ramp) {
8076 RGFW_UNUSED(monitor); RGFW_UNUSED(ramp);
8077
8078 #ifndef RGFW_NO_XRANDR
8079 size_t size = (size_t)XRRGetCrtcGammaSize(_RGFW->display, monitor->node->crtc);
8080 if (size != ramp->count) {
8081 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errX11, "X11: Gamma ramp size must match current ramp size");
8082 return RGFW_FALSE;
8083 }
8084
8085 XRRCrtcGamma* gamma = XRRAllocGamma((int)ramp->count);
8086
8087 memcpy(gamma->red, ramp->red, ramp->count * sizeof(unsigned short));
8088 memcpy(gamma->green, ramp->green, ramp->count * sizeof(unsigned short));
8089 memcpy(gamma->blue, ramp->blue, ramp->count * sizeof(unsigned short));
8090
8091 XRRSetCrtcGamma(_RGFW->display, monitor->node->crtc, gamma);
8092 XRRFreeGamma(gamma);
8093
8094 return RGFW_TRUE;
8095 #endif
8096 return RGFW_FALSE;
8097 }
8098
8099 RGFW_bool RGFW_FUNC(RGFW_monitor_setMode)(RGFW_monitor* mon, RGFW_monitorMode* mode) {
8100 RGFW_bool out = RGFW_FALSE;
8101
8102 XRRScreenResources* res = XRRGetScreenResourcesCurrent(_RGFW->display, DefaultRootWindow(_RGFW->display));
8103 XRRCrtcInfo* ci = XRRGetCrtcInfo(_RGFW->display, res, mon->node->crtc);
8104
8105 if (XRRSetCrtcConfig(_RGFW->display, res, mon->node->crtc, CurrentTime, ci->x, ci->y, (RRMode)mode->src, ci->rotation, ci->outputs, ci->noutput) == True) {
8106 out = RGFW_TRUE;
8107 }
8108
8109 XRRFreeCrtcInfo(ci);
8110 XRRFreeScreenResources(res);
8111 return out;
8112 }
8113
8114 RGFW_bool RGFW_FUNC(RGFW_monitor_requestMode)(RGFW_monitor* mon, RGFW_monitorMode* mode, RGFW_modeRequest request) {
8115 #ifndef RGFW_NO_XRANDR
8116 RGFW_init();
8117
8118 RGFW_bool output = RGFW_FALSE;
8119
8120 XRRScreenResources* res = XRRGetScreenResourcesCurrent(_RGFW->display, DefaultRootWindow(_RGFW->display));
8121 if (res == NULL) return RGFW_FALSE;
8122
8123 XRRCrtcInfo* ci = XRRGetCrtcInfo(_RGFW->display, res, mon->node->crtc);
8124 XRROutputInfo* oi = XRRGetOutputInfo(_RGFW->display, res, mon->node->rrOutput);
8125
8126 RRMode native = None;
8127
8128 int i;
8129 for (i = 0; i < oi->nmode; i++) {
8130 RGFW_monitorMode foundMode;
8131 XRRModeInfo* mi = RGFW_XGetMode(ci, res, oi->modes[i], &foundMode);
8132 if (mi == NULL) {
8133 continue;
8134 }
8135
8136 if (RGFW_monitorModeCompare(mode, &foundMode, request)) {
8137 native = mi->id;
8138 output = RGFW_TRUE;
8139 mon->mode = foundMode;
8140 break;
8141 }
8142 }
8143
8144 if (native) {
8145 XRRSetCrtcConfig(_RGFW->display, res, mon->node->crtc, CurrentTime, ci->x, ci->y, native, ci->rotation, ci->outputs, ci->noutput);
8146 }
8147
8148 XRRFreeOutputInfo(oi);
8149 XRRFreeCrtcInfo(ci);
8150 XRRFreeScreenResources(res);
8151 return output;
8152 #endif
8153 return RGFW_FALSE;
8154 }
8155
8156 RGFW_monitor* RGFW_FUNC(RGFW_window_getMonitor) (RGFW_window* win) {
8157 RGFW_ASSERT(win != NULL);
8158
8159 XWindowAttributes attrs;
8160 if (!XGetWindowAttributes(_RGFW->display, win->src.window, &attrs)) {
8161 return NULL;
8162 }
8163
8164 for (RGFW_monitorNode* node = _RGFW->monitors.list.head; node; node = node->next) {
8165 if ((attrs.x < node->mon.x + node->mon.mode.w) && (attrs.x + attrs.width > node->mon.x) && (attrs.y < node->mon.y + node->mon.mode.h) && (attrs.y + attrs.height > node->mon.y))
8166 return &node->mon;
8167 }
8168
8169
8170 return &_RGFW->monitors.list.head->mon;
8171 }
8172
8173 #ifdef RGFW_OPENGL
8174 RGFW_bool RGFW_FUNC(RGFW_window_createContextPtr_OpenGL) (RGFW_window* win, RGFW_glContext* context, RGFW_glHints* hints) {
8175 /* for checking extensions later */
8176 const char sRGBARBstr[] = "GLX_ARB_framebuffer_sRGB";
8177 const char sRGBEXTstr[] = "GLX_EXT_framebuffer_sRGB";
8178 const char noErorrStr[] = "GLX_ARB_create_context_no_error";
8179 const char flushStr[] = "GLX_ARB_context_flush_control";
8180 const char robustStr[] = "GLX_ARB_create_context_robustness";
8181
8182 /* basic RGFW int */
8183 win->src.ctx.native = context;
8184 win->src.gfxType = RGFW_gfxNativeOpenGL;
8185
8186 /* This is required so that way the user can create their own OpenGL context after RGFW_createWindow is used */
8187 RGFW_bool showWindow = RGFW_FALSE;
8188 if (win->src.window) {
8189 showWindow = (RGFW_window_isMinimized(win) == RGFW_FALSE);
8190 RGFW_window_closePlatform(win);
8191 }
8192
8193 RGFW_bool transparent = (win->internal.flags & RGFW_windowTransparent);
8194
8195 /* start by creating a GLX config / X11 Viusal */
8196 XVisualInfo visual;
8197 GLXFBConfig bestFbc;
8198
8199 i32 visual_attribs[40];
8200 RGFW_attribStack stack;
8201 RGFW_attribStack_init(&stack, visual_attribs, 40);
8202 RGFW_attribStack_pushAttribs(&stack, GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR);
8203 RGFW_attribStack_pushAttribs(&stack, GLX_X_RENDERABLE, 1);
8204 RGFW_attribStack_pushAttribs(&stack, GLX_RENDER_TYPE, GLX_RGBA_BIT);
8205 RGFW_attribStack_pushAttribs(&stack, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT);
8206 RGFW_attribStack_pushAttribs(&stack, GLX_DOUBLEBUFFER, 1);
8207 RGFW_attribStack_pushAttribs(&stack, GLX_ALPHA_SIZE, hints->alpha);
8208 RGFW_attribStack_pushAttribs(&stack, GLX_DEPTH_SIZE, hints->depth);
8209 RGFW_attribStack_pushAttribs(&stack, GLX_STENCIL_SIZE, hints->stencil);
8210 RGFW_attribStack_pushAttribs(&stack, GLX_STEREO, hints->stereo);
8211 RGFW_attribStack_pushAttribs(&stack, GLX_AUX_BUFFERS, hints->auxBuffers);
8212 RGFW_attribStack_pushAttribs(&stack, GLX_RED_SIZE, hints->red);
8213 RGFW_attribStack_pushAttribs(&stack, GLX_GREEN_SIZE, hints->green);
8214 RGFW_attribStack_pushAttribs(&stack, GLX_BLUE_SIZE, hints->blue);
8215 RGFW_attribStack_pushAttribs(&stack, GLX_ACCUM_RED_SIZE, hints->accumRed);
8216 RGFW_attribStack_pushAttribs(&stack, GLX_ACCUM_GREEN_SIZE, hints->accumGreen);
8217 RGFW_attribStack_pushAttribs(&stack, GLX_ACCUM_BLUE_SIZE, hints->accumBlue);
8218 RGFW_attribStack_pushAttribs(&stack, GLX_ACCUM_ALPHA_SIZE, hints->accumAlpha);
8219
8220 if (hints->sRGB) {
8221 if (RGFW_extensionSupportedPlatform_OpenGL(sRGBARBstr, sizeof(sRGBARBstr)))
8222 RGFW_attribStack_pushAttribs(&stack, GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB, hints->sRGB);
8223 if (RGFW_extensionSupportedPlatform_OpenGL(sRGBEXTstr, sizeof(sRGBEXTstr)))
8224 RGFW_attribStack_pushAttribs(&stack, GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, hints->sRGB);
8225 }
8226
8227 RGFW_attribStack_pushAttribs(&stack, 0, 0);
8228
8229 /* find the configs */
8230 i32 fbcount;
8231 GLXFBConfig* fbc = glXChooseFBConfig(_RGFW->display, DefaultScreen(_RGFW->display), visual_attribs, &fbcount);
8232
8233 i32 best_fbc = -1;
8234 i32 best_depth = 0;
8235 i32 best_samples = 0;
8236
8237 if (fbcount == 0) {
8238 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errOpenGLContext, "Failed to find any valid GLX visual configs.");
8239 return 0;
8240 }
8241
8242 /* search through all found configs to find the best match */
8243 i32 i;
8244 for (i = 0; i < fbcount; i++) {
8245 XVisualInfo* vi = glXGetVisualFromFBConfig(_RGFW->display, fbc[i]);
8246 if (vi == NULL)
8247 continue;
8248
8249 i32 samp_buf, samples;
8250 glXGetFBConfigAttrib(_RGFW->display, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf);
8251 glXGetFBConfigAttrib(_RGFW->display, fbc[i], GLX_SAMPLES, &samples);
8252
8253 if (best_fbc == -1) best_fbc = i;
8254 if ((!(transparent) || vi->depth == 32) && best_depth == 0) {
8255 best_fbc = i;
8256 best_depth = vi->depth;
8257 }
8258 if ((!(transparent) || vi->depth == 32) && samples <= hints->samples && samples > best_samples) {
8259 best_fbc = i;
8260 best_depth = vi->depth;
8261 best_samples = samples;
8262 }
8263 XFree(vi);
8264 }
8265
8266 if (best_fbc == -1) {
8267 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errOpenGLContext, "Failed to get a valid GLX visual.");
8268 return 0;
8269 }
8270
8271 /* we found a config */
8272 bestFbc = fbc[best_fbc];
8273 XVisualInfo* vi = glXGetVisualFromFBConfig(_RGFW->display, bestFbc);
8274 if (vi->depth != 32 && transparent)
8275 RGFW_sendDebugInfo(RGFW_typeWarning, RGFW_warningOpenGL, "Failed to to find a matching visual with a 32-bit depth.");
8276
8277 if (best_samples < hints->samples)
8278 RGFW_sendDebugInfo(RGFW_typeWarning, RGFW_warningOpenGL, "Failed to load a matching sample count.");
8279
8280 XFree(fbc);
8281 visual = *vi;
8282 XFree(vi);
8283
8284 /* use the visual to create a new window */
8285 RGFW_XCreateWindow(visual, "", win->internal.flags, win);
8286
8287 if (showWindow) {
8288 RGFW_window_show(win);
8289 }
8290
8291 /* create the actual OpenGL context */
8292 i32 context_attribs[40];
8293 RGFW_attribStack_init(&stack, context_attribs, 40);
8294
8295 i32 mask = 0;
8296 switch (hints->profile) {
8297 case RGFW_glES: mask |= GLX_CONTEXT_ES_PROFILE_BIT_EXT; break;
8298 case RGFW_glForwardCompatibility: mask |= GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; break;
8299 case RGFW_glCompatibility: mask |= GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; break;
8300 case RGFW_glCore: mask |= GLX_CONTEXT_CORE_PROFILE_BIT_ARB; break;
8301 default: mask |= GLX_CONTEXT_CORE_PROFILE_BIT_ARB; break;
8302 }
8303
8304 RGFW_attribStack_pushAttribs(&stack, GLX_CONTEXT_PROFILE_MASK_ARB, mask);
8305
8306 if (hints->minor || hints->major) {
8307 RGFW_attribStack_pushAttribs(&stack, GLX_CONTEXT_MAJOR_VERSION_ARB, hints->major);
8308 RGFW_attribStack_pushAttribs(&stack, GLX_CONTEXT_MINOR_VERSION_ARB, hints->minor);
8309 }
8310
8311
8312 if (RGFW_extensionSupportedPlatform_OpenGL(flushStr, sizeof(flushStr))) {
8313 if (hints->releaseBehavior == RGFW_glReleaseFlush) {
8314 RGFW_attribStack_pushAttribs(&stack, GLX_CONTEXT_RELEASE_BEHAVIOR_ARB, GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB);
8315 } else if (hints->releaseBehavior == RGFW_glReleaseNone) {
8316 RGFW_attribStack_pushAttribs(&stack, GLX_CONTEXT_RELEASE_BEHAVIOR_ARB, GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB);
8317 }
8318 }
8319
8320 i32 flags = 0;
8321 if (hints->debug) flags |= GLX_CONTEXT_DEBUG_BIT_ARB;
8322 if (hints->robustness && RGFW_extensionSupportedPlatform_OpenGL(robustStr, sizeof(robustStr))) flags |= GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB;
8323 if (flags) {
8324 RGFW_attribStack_pushAttribs(&stack, GLX_CONTEXT_FLAGS_ARB, flags);
8325 }
8326
8327 if (RGFW_extensionSupportedPlatform_OpenGL(noErorrStr, sizeof(noErorrStr))) {
8328 RGFW_attribStack_pushAttribs(&stack, GLX_CONTEXT_OPENGL_NO_ERROR_ARB, hints->noError);
8329 }
8330
8331 RGFW_attribStack_pushAttribs(&stack, 0, 0);
8332
8333 /* create the context */
8334 glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
8335 char str[] = "glXCreateContextAttribsARB";
8336 glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB((u8*) str);
8337
8338 GLXContext ctx = NULL;
8339 if (hints->share) {
8340 ctx = hints->share->ctx;
8341 }
8342
8343 if (glXCreateContextAttribsARB == NULL) {
8344 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errOpenGLContext, "Failed to load proc address 'glXCreateContextAttribsARB', loading a generic OpenGL context.");
8345 win->src.ctx.native->ctx = glXCreateContext(_RGFW->display, &visual, ctx, True);
8346 } else {
8347 _RGFW->x11Error = NULL;
8348 win->src.ctx.native->ctx = glXCreateContextAttribsARB(_RGFW->display, bestFbc, ctx, True, context_attribs);
8349 if (_RGFW->x11Error || win->src.ctx.native->ctx == NULL) {
8350 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errOpenGLContext, "Failed to create an OpenGL context with AttribsARB, loading a generic OpenGL context.");
8351 win->src.ctx.native->ctx = glXCreateContext(_RGFW->display, &visual, ctx, True);
8352 }
8353 }
8354
8355 #ifndef RGFW_NO_GLXWINDOW
8356 win->src.ctx.native->window = glXCreateWindow(_RGFW->display, bestFbc, win->src.window, NULL);
8357 #else
8358 win->src.ctx.native->window = win->src.window;
8359 #endif
8360
8361 glXMakeCurrent(_RGFW->display, (Drawable)win->src.ctx.native->window, (GLXContext)win->src.ctx.native->ctx);
8362 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoOpenGL, "OpenGL context initalized.");
8363
8364 RGFW_window_swapInterval_OpenGL(win, 0);
8365
8366 return RGFW_TRUE;
8367 }
8368
8369 void RGFW_FUNC(RGFW_window_deleteContextPtr_OpenGL) (RGFW_window* win, RGFW_glContext* ctx) {
8370 #ifndef RGFW_NO_GLXWINDOW
8371 if (win->src.ctx.native->window != win->src.window) {
8372 glXDestroyWindow(_RGFW->display, win->src.ctx.native->window);
8373 }
8374 #endif
8375
8376 glXDestroyContext(_RGFW->display, ctx->ctx);
8377 win->src.ctx.native = NULL;
8378 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoOpenGL, "OpenGL context freed.");
8379 }
8380
8381 RGFW_bool RGFW_FUNC(RGFW_extensionSupportedPlatform_OpenGL)(const char * extension, size_t len) {
8382 RGFW_init();
8383 const char* extensions = glXQueryExtensionsString(_RGFW->display, XDefaultScreen(_RGFW->display));
8384 return (extensions != NULL) && RGFW_extensionSupportedStr(extensions, extension, len);
8385 }
8386
8387 RGFW_proc RGFW_FUNC(RGFW_getProcAddress_OpenGL)(const char* procname) { return glXGetProcAddress((u8*) procname); }
8388
8389 void RGFW_FUNC(RGFW_window_makeCurrentContext_OpenGL) (RGFW_window* win) { if (win) RGFW_ASSERT(win->src.ctx.native);
8390 if (win == NULL)
8391 glXMakeCurrent(NULL, (Drawable)NULL, (GLXContext) NULL);
8392 else
8393 glXMakeCurrent(_RGFW->display, (Drawable)win->src.ctx.native->window, (GLXContext) win->src.ctx.native->ctx);
8394 return;
8395 }
8396 void* RGFW_FUNC(RGFW_getCurrentContext_OpenGL) (void) { return glXGetCurrentContext(); }
8397 void RGFW_FUNC(RGFW_window_swapBuffers_OpenGL) (RGFW_window* win) { RGFW_ASSERT(win->src.ctx.native); glXSwapBuffers(_RGFW->display, win->src.ctx.native->window); }
8398
8399 void RGFW_FUNC(RGFW_window_swapInterval_OpenGL) (RGFW_window* win, i32 swapInterval) {
8400 RGFW_ASSERT(win != NULL);
8401 /* cached pfn to avoid calling glXGetProcAddress more than once */
8402 static PFNGLXSWAPINTERVALEXTPROC pfn = NULL;
8403 static int (*pfn2)(int) = NULL;
8404
8405 if (pfn == NULL) {
8406 u8 str[] = "glXSwapIntervalEXT";
8407 pfn = (PFNGLXSWAPINTERVALEXTPROC)glXGetProcAddress(str);
8408 if (pfn == NULL) {
8409 pfn = (PFNGLXSWAPINTERVALEXTPROC)1;
8410 const char* array[] = {"GLX_MESA_swap_control", "GLX_SGI_swap_control"};
8411
8412 size_t i;
8413 for (i = 0; i < sizeof(array) / sizeof(char*) && pfn2 == NULL; i++) {
8414 pfn2 = (int(*)(int))glXGetProcAddress((u8*)array[i]);
8415 }
8416
8417 if (pfn2 != NULL) {
8418 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errOpenGLContext, "Failed to load swap interval function, fallingback to the native swapinterval function");
8419 } else {
8420 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errOpenGLContext, "Failed to load swap interval function");
8421 }
8422 }
8423 }
8424
8425 if (pfn != (PFNGLXSWAPINTERVALEXTPROC)1) {
8426 pfn(_RGFW->display, win->src.ctx.native->window, swapInterval);
8427 }
8428 else if (pfn2 != NULL) {
8429 pfn2(swapInterval);
8430 }
8431 }
8432 #endif /* RGFW_OPENGL */
8433
8434 i32 RGFW_initPlatform_X11(void) {
8435 #ifdef RGFW_USE_XDL
8436 XDL_init();
8437 #endif
8438
8439 #if !defined(RGFW_NO_X11_CURSOR) && !defined(RGFW_NO_X11_CURSOR_PRELOAD)
8440 #if defined(__CYGWIN__)
8441 RGFW_LOAD_LIBRARY(X11Cursorhandle, "libXcursor-1.so");
8442 #elif defined(__OpenBSD__) || defined(__NetBSD__)
8443 RGFW_LOAD_LIBRARY(X11Cursorhandle, "libXcursor.so");
8444 #else
8445 RGFW_LOAD_LIBRARY(X11Cursorhandle, "libXcursor.so.1");
8446 #endif
8447 RGFW_PROC_DEF(X11Cursorhandle, XcursorImageCreate);
8448 RGFW_PROC_DEF(X11Cursorhandle, XcursorImageDestroy);
8449 RGFW_PROC_DEF(X11Cursorhandle, XcursorImageLoadCursor);
8450 #endif
8451
8452 #if !defined(RGFW_NO_X11_XI_PRELOAD)
8453 #if defined(__CYGWIN__)
8454 RGFW_LOAD_LIBRARY(X11Xihandle, "libXi-6.so");
8455 #elif defined(__OpenBSD__) || defined(__NetBSD__)
8456 RGFW_LOAD_LIBRARY(X11Xihandle, "libXi.so");
8457 #else
8458 RGFW_LOAD_LIBRARY(X11Xihandle, "libXi.so.6");
8459 #endif
8460 RGFW_PROC_DEF(X11Xihandle, XISelectEvents);
8461 #endif
8462
8463 #if !defined(RGFW_NO_X11_EXT_PRELOAD)
8464 #if defined(__CYGWIN__)
8465 RGFW_LOAD_LIBRARY(X11XEXThandle, "libXext-6.so");
8466 #elif defined(__OpenBSD__) || defined(__NetBSD__)
8467 RGFW_LOAD_LIBRARY(X11XEXThandle, "libXext.so");
8468 #else
8469 RGFW_LOAD_LIBRARY(X11XEXThandle, "libXext.so.6");
8470 #endif
8471 RGFW_PROC_DEF(X11XEXThandle, XSyncCreateCounter);
8472 RGFW_PROC_DEF(X11XEXThandle, XSyncIntToValue);
8473 RGFW_PROC_DEF(X11XEXThandle, XSyncSetCounter);
8474 RGFW_PROC_DEF(X11XEXThandle, XShapeCombineRegion);
8475 RGFW_PROC_DEF(X11XEXThandle, XShapeCombineMask);
8476 #endif
8477
8478 XInitThreads(); /*!< init X11 threading */
8479 _RGFW->display = XOpenDisplay(0);
8480 _RGFW->context = XUniqueContext();
8481
8482 XSetWindowAttributes wa;
8483 RGFW_MEMSET(&wa, 0, sizeof(wa));
8484 wa.event_mask = PropertyChangeMask;
8485 _RGFW->helperWindow = XCreateWindow(_RGFW->display, XDefaultRootWindow(_RGFW->display), 0, 0, 1, 1, 0, 0,
8486 InputOnly, DefaultVisual(_RGFW->display, DefaultScreen(_RGFW->display)), CWEventMask, &wa);
8487
8488 u8 RGFW_blk[] = { 0, 0, 0, 0 };
8489 _RGFW->hiddenMouse = RGFW_loadMouse(RGFW_blk, 1, 1, RGFW_formatRGBA8);
8490 _RGFW->clipboard = NULL;
8491
8492 XkbComponentNamesRec rec;
8493 XkbDescPtr desc = XkbGetMap(_RGFW->display, 0, XkbUseCoreKbd);
8494 XkbDescPtr evdesc;
8495 XSetErrorHandler(RGFW_XErrorHandler);
8496 u8 old[256];
8497
8498 XkbGetNames(_RGFW->display, XkbKeyNamesMask, desc);
8499
8500 RGFW_MEMSET(&rec, 0, sizeof(rec));
8501 char evdev[] = "evdev";
8502 rec.keycodes = evdev;
8503 evdesc = XkbGetKeyboardByName(_RGFW->display, XkbUseCoreKbd, &rec, XkbGBN_KeyNamesMask, XkbGBN_KeyNamesMask, False);
8504 /* memo: RGFW_keycodes[x11 keycode] = rgfw keycode */
8505 if(evdesc != NULL && desc != NULL) {
8506 int i, j;
8507 for(i = 0; i < (int)sizeof(old); i++){
8508 old[i] = _RGFW->keycodes[i];
8509 _RGFW->keycodes[i] = 0;
8510 }
8511 for(i = evdesc->min_key_code; i <= evdesc->max_key_code; i++){
8512 for(j = desc->min_key_code; j <= desc->max_key_code; j++){
8513 if(RGFW_STRNCMP(evdesc->names->keys[i].name, desc->names->keys[j].name, XkbKeyNameLength) == 0){
8514 _RGFW->keycodes[j] = old[i];
8515 break;
8516 }
8517 }
8518 }
8519 XkbFreeKeyboard(desc, 0, True);
8520 XkbFreeKeyboard(evdesc, 0, True);
8521 }
8522
8523 XSetLocaleModifiers("");
8524 XRegisterIMInstantiateCallback(_RGFW->display, NULL, NULL, NULL, RGFW_x11_imInitCallback, NULL);
8525
8526 unsigned char mask[XIMaskLen(XI_RawMotion)];
8527 RGFW_MEMSET(mask, 0, sizeof(mask));
8528 XISetMask(mask, XI_RawMotion);
8529
8530 XIEventMask em;
8531 em.deviceid = XIAllMasterDevices;
8532 em.mask_len = sizeof(mask);
8533 em.mask = mask;
8534
8535 XISelectEvents(_RGFW->display, XDefaultRootWindow(_RGFW->display), &em, 1);
8536
8537 #ifndef RGFW_NO_XRANDR
8538 i32 errorBase;
8539 if (XRRQueryExtension(_RGFW->display, &_RGFW->xrandrEventBase, &errorBase)) {
8540 XRRSelectInput(_RGFW->display, RootWindow(_RGFW->display, DefaultScreen(_RGFW->display)), RROutputChangeNotifyMask);
8541 }
8542 #endif
8543
8544 return 0;
8545 }
8546
8547 void RGFW_deinitPlatform_X11(void) {
8548 #define RGFW_FREE_LIBRARY(x) if (x != NULL) dlclose(x); x = NULL;
8549 /* to save the clipboard on the x server after the window is closed */
8550 RGFW_LOAD_ATOM(CLIPBOARD_MANAGER); RGFW_LOAD_ATOM(CLIPBOARD);
8551 RGFW_LOAD_ATOM(SAVE_TARGETS);
8552 if (XGetSelectionOwner(_RGFW->display, CLIPBOARD) == _RGFW->helperWindow) {
8553 XConvertSelection(_RGFW->display, CLIPBOARD_MANAGER, SAVE_TARGETS, None, _RGFW->helperWindow, CurrentTime);
8554 while (RGFW_XHandleClipboardSelectionHelper());
8555 }
8556
8557 XUnregisterIMInstantiateCallback(_RGFW->display, NULL, NULL, NULL, RGFW_x11_imInitCallback, NULL);
8558
8559 if (_RGFW->im) {
8560 XCloseIM(_RGFW->im);
8561 _RGFW->im = NULL;
8562 }
8563
8564 if (_RGFW->clipboard) {
8565 RGFW_FREE(_RGFW->clipboard);
8566 _RGFW->clipboard = NULL;
8567 }
8568
8569 if (_RGFW->hiddenMouse) {
8570 RGFW_freeMouse(_RGFW->hiddenMouse);
8571 _RGFW->hiddenMouse = NULL;
8572 }
8573
8574 XDestroyWindow(_RGFW->display, (Drawable) _RGFW->helperWindow); /*!< close the window */
8575 XCloseDisplay(_RGFW->display); /*!< kill connection to the x server */
8576
8577 #if !defined(RGFW_NO_X11_CURSOR_PRELOAD) && !defined(RGFW_NO_X11_CURSOR)
8578 RGFW_FREE_LIBRARY(X11Cursorhandle);
8579 #endif
8580 #if !defined(RGFW_NO_X11_XI_PRELOAD)
8581 RGFW_FREE_LIBRARY(X11Xihandle);
8582 #endif
8583
8584 #ifdef RGFW_USE_XDL
8585 XDL_close();
8586 #endif
8587
8588 #if !defined(RGFW_NO_X11_EXT_PRELOAD)
8589 RGFW_FREE_LIBRARY(X11XEXThandle);
8590 #endif
8591 }
8592
8593 void RGFW_FUNC(RGFW_window_closePlatform)(RGFW_window* win) {
8594 if (win->src.ic) {
8595 XDestroyIC(win->src.ic);
8596 win->src.ic = NULL;
8597 }
8598
8599 XFreeGC(_RGFW->display, win->src.gc);
8600 XDeleteContext(_RGFW->display, win->src.window, _RGFW->context);
8601 XDestroyWindow(_RGFW->display, (Drawable) win->src.window); /*!< close the window */
8602 return;
8603 }
8604
8605 #ifdef RGFW_WEBGPU
8606 WGPUSurface RGFW_FUNC(RGFW_window_createSurface_WebGPU) (RGFW_window* window, WGPUInstance instance) {
8607 WGPUSurfaceDescriptor surfaceDesc = {0};
8608 WGPUSurfaceSourceXlibWindow fromXlib = {0};
8609 fromXlib.chain.sType = WGPUSType_SurfaceSourceXlibWindow;
8610 fromXlib.display = _RGFW->display;
8611 fromXlib.window = window->src.window;
8612
8613 surfaceDesc.nextInChain = (WGPUChainedStruct*)&fromXlib.chain;
8614 return wgpuInstanceCreateSurface(instance, &surfaceDesc);
8615 }
8616 #endif
8617
8618 #endif
8619 /*
8620 End of X11 linux / wayland / unix defines
8621 */
8622
8623 /*
8624
8625 Start of Wayland defayland
8626 */
8627
8628 #ifdef RGFW_WAYLAND
8629 #ifdef RGFW_X11
8630 #undef RGFW_FUNC /* remove previous define */
8631 #define RGFW_FUNC(func) func##_Wayland
8632 #else
8633 #define RGFW_FUNC(func) func
8634 #endif
8635
8636 /*
8637 Wayland TODO: (out of date)
8638 - fix RGFW_keyPressed lock state
8639
8640 RGFW_windowMoved, the window was moved (by the user)
8641 RGFW_windowRefresh The window content needs to be refreshed
8642
8643 RGFW_dataDrop a file has been dropped into the window
8644 RGFW_dataDrag
8645
8646 - window args:
8647 #define RGFW_windowNoResize the window cannot be resized by the user
8648 #define RGFW_windowAllowDND the window supports drag and drop
8649 #define RGFW_scaleToMonitor scale the window to the screen
8650
8651 - other missing functions functions ("TODO wayland") (~30 functions)
8652 - fix buffer rendering weird behavior
8653 */
8654 #include <errno.h>
8655 #include <unistd.h>
8656 #include <sys/mman.h>
8657 #include <xkbcommon/xkbcommon.h>
8658 #include <xkbcommon/xkbcommon-keysyms.h>
8659 #include <xkbcommon/xkbcommon-compose.h>
8660 #include <dirent.h>
8661 #include <linux/kd.h>
8662 #include <wayland-cursor.h>
8663 #include <fcntl.h>
8664
8665 struct wl_display* RGFW_getDisplay_Wayland(void) { return _RGFW->wl_display; }
8666 struct wl_surface* RGFW_window_getWindow_Wayland(RGFW_window* win) { return win->src.surface; }
8667
8668
8669 /* wayland global garbage (wayland bad, X11 is fine (ish) (not really)) */
8670 #include "xdg-shell-client-protocol.h"
8671 #include "xdg-toplevel-icon-v1-client-protocol.h"
8672 #include "xdg-decoration-unstable-v1-client-protocol.h"
8673 #include "relative-pointer-unstable-v1-client-protocol.h"
8674 #include "pointer-constraints-unstable-v1-client-protocol.h"
8675 #include "xdg-output-unstable-v1-client-protocol.h"
8676 #include "pointer-warp-v1-client-protocol.h"
8677
8678 void RGFW_toggleWaylandMaximized(RGFW_window* win, RGFW_bool maximized);
8679
8680 static void RGFW_wl_setOpaque(RGFW_window* win) {
8681 struct wl_region* wl_region = wl_compositor_create_region(_RGFW->compositor);
8682
8683 if (!wl_region) return; /* return if no region was created */
8684
8685 wl_region_add(wl_region, 0, 0, win->w, win->h);
8686 wl_surface_set_opaque_region(win->src.surface, wl_region);
8687 wl_region_destroy(wl_region);
8688
8689 }
8690
8691 static void RGFW_wl_xdg_wm_base_ping_handler(void* data, struct xdg_wm_base* wm_base,
8692 u32 serial) {
8693 RGFW_UNUSED(data);
8694 xdg_wm_base_pong(wm_base, serial);
8695 }
8696 static void RGFW_wl_xdg_surface_configure_handler(void* data, struct xdg_surface* xdg_surface,
8697 u32 serial) {
8698
8699 xdg_surface_ack_configure(xdg_surface, serial);
8700
8701 RGFW_window* win = (RGFW_window*)data;
8702
8703 if (win == NULL) {
8704 win = _RGFW->kbOwner;
8705 if (win == NULL)
8706 return;
8707 }
8708
8709 /* useful for libdecor */
8710 if (win->src.activated != win->src.pending_activated) {
8711 win->src.activated = win->src.pending_activated;
8712 }
8713
8714 if (win->src.maximized != win->src.pending_maximized) {
8715 RGFW_toggleWaylandMaximized(win, win->src.pending_maximized);
8716
8717 RGFW_window_checkMode(win);
8718 }
8719
8720
8721 if (win->src.resizing) {
8722
8723 RGFW_windowResizedCallback(win, win->w, win->h);
8724 RGFW_window_resize(win, win->w, win->h);
8725 if (!(win->internal.flags & RGFW_windowTransparent)) {
8726 RGFW_wl_setOpaque(win);
8727 }
8728 }
8729
8730 win->src.configured = RGFW_TRUE;
8731 }
8732
8733 static void RGFW_wl_xdg_toplevel_configure_handler(void* data, struct xdg_toplevel* toplevel,
8734 i32 width, i32 height, struct wl_array* states) {
8735
8736 RGFW_UNUSED(toplevel);
8737 RGFW_window* win = (RGFW_window*)data;
8738
8739
8740 win->src.pending_activated = RGFW_FALSE;
8741 win->src.pending_maximized = RGFW_FALSE;
8742 win->src.resizing = RGFW_FALSE;
8743
8744
8745 enum xdg_toplevel_state* state;
8746 wl_array_for_each(state, states) {
8747 switch (*state) {
8748 case XDG_TOPLEVEL_STATE_ACTIVATED:
8749 win->src.pending_activated = RGFW_TRUE;
8750 break;
8751 case XDG_TOPLEVEL_STATE_MAXIMIZED:
8752 win->src.pending_maximized = RGFW_TRUE;
8753 break;
8754 default:
8755 break;
8756 }
8757
8758 }
8759 /* if width and height are not zero and are not the same as the window */
8760 /* the window is resizing so update the values */
8761 if ((width && height) && (win->w != width || win->h != height)) {
8762 win->src.resizing = RGFW_TRUE;
8763 win->src.w = win->w = width;
8764 win->src.h = win->h = height;
8765 }
8766 }
8767
8768 static void RGFW_wl_xdg_toplevel_close_handler(void* data, struct xdg_toplevel *toplevel) {
8769 RGFW_UNUSED(toplevel);
8770 RGFW_window* win = (RGFW_window*)data;
8771
8772 if (!win->internal.shouldClose) {
8773 RGFW_windowQuitCallback(win);
8774 }
8775 }
8776
8777 static void RGFW_wl_xdg_decoration_configure_handler(void* data,
8778 struct zxdg_toplevel_decoration_v1* zxdg_toplevel_decoration_v1, u32 mode) {
8779 RGFW_window* win = (RGFW_window*)data; RGFW_UNUSED(zxdg_toplevel_decoration_v1);
8780
8781 /* this is expected to run once */
8782 /* set the decoration mode set by earlier request */
8783 if (mode != win->src.decoration_mode) {
8784 win->src.decoration_mode = mode;
8785 }
8786 }
8787
8788 static void RGFW_wl_shm_format_handler(void* data, struct wl_shm *shm, u32 format) {
8789 RGFW_UNUSED(data); RGFW_UNUSED(shm); RGFW_UNUSED(format);
8790 }
8791
8792 static void RGFW_wl_relative_pointer_motion(void *data, struct zwp_relative_pointer_v1 *zwp_relative_pointer_v1,
8793 u32 time_hi, u32 time_lo, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t dx_unaccel, wl_fixed_t dy_unaccel) {
8794
8795 RGFW_UNUSED(zwp_relative_pointer_v1); RGFW_UNUSED(time_hi); RGFW_UNUSED(time_lo);
8796 RGFW_UNUSED(dx_unaccel); RGFW_UNUSED(dy_unaccel);
8797
8798 RGFW_info* RGFW = (RGFW_info*)data;
8799
8800 RGFW_ASSERT(RGFW->mouseOwner != NULL);
8801 RGFW_window* win = RGFW->mouseOwner;
8802
8803 RGFW_ASSERT(win);
8804
8805 float vecX = (float)wl_fixed_to_double(dx);
8806 float vecY = (float)wl_fixed_to_double(dy);
8807 RGFW_mousePosCallback(win, win->internal.lastMouseX, win->internal.lastMouseY, vecX, vecY);
8808 }
8809
8810 static void RGFW_wl_pointer_locked(void *data, struct zwp_locked_pointer_v1 *zwp_locked_pointer_v1) {
8811 RGFW_UNUSED(zwp_locked_pointer_v1);
8812 RGFW_info* RGFW = (RGFW_info*)data;
8813 wl_pointer_set_cursor(RGFW->wl_pointer, RGFW->mouse_enter_serial, NULL, 0, 0); /* draw no cursor */
8814 }
8815
8816 static void RGFW_wl_pointer_enter(void* data, struct wl_pointer* pointer, u32 serial,
8817 struct wl_surface *surface, wl_fixed_t surface_x, wl_fixed_t surface_y) {
8818 RGFW_info* RGFW = (RGFW_info*)data;
8819 RGFW_window* win = (RGFW_window*)wl_surface_get_user_data(surface);
8820
8821 /* save when the pointer is locked or using default cursor */
8822 RGFW->mouse_enter_serial = serial;
8823 win->internal.mouseInside = RGFW_TRUE;
8824 RGFW->windowState.mouseEnter = RGFW_TRUE;
8825
8826 RGFW->mouseOwner = win;
8827
8828 /* set the cursor */
8829 if (win->src.using_custom_cursor) {
8830 wl_pointer_set_cursor(pointer, serial, win->src.custom_cursor_surface, 0, 0);
8831 }
8832 else {
8833 RGFW_window_setMouseDefault(win);
8834 }
8835
8836 i32 x = (i32)wl_fixed_to_double(surface_x);
8837 i32 y = (i32)wl_fixed_to_double(surface_y);
8838 RGFW_mouseNotifyCallback(win, x, y, RGFW_TRUE);
8839 }
8840
8841 static void RGFW_wl_pointer_leave(void* data, struct wl_pointer *pointer, u32 serial, struct wl_surface *surface) {
8842 RGFW_UNUSED(pointer); RGFW_UNUSED(serial);
8843 RGFW_window* win = (RGFW_window*)wl_surface_get_user_data(surface);
8844 RGFW_info* RGFW = (RGFW_info*)data;
8845 if (RGFW->mouseOwner == win)
8846 RGFW->mouseOwner = NULL;
8847
8848 RGFW_mouseNotifyCallback(win, win->internal.lastMouseX, win->internal.lastMouseY, RGFW_FALSE);
8849 }
8850
8851 static void RGFW_wl_pointer_motion(void* data, struct wl_pointer *pointer, u32 time, wl_fixed_t x, wl_fixed_t y) {
8852 RGFW_UNUSED(pointer); RGFW_UNUSED(time);
8853
8854 RGFW_info* RGFW = (RGFW_info*)data;
8855 RGFW_ASSERT(RGFW->mouseOwner != NULL);
8856
8857 RGFW_window* win = RGFW->mouseOwner;
8858
8859 i32 convertedX = (i32)wl_fixed_to_double(x);
8860 i32 convertedY = (i32)wl_fixed_to_double(y);
8861 float newVecX = (float)(convertedX - win->internal.lastMouseX);
8862 float newVecY = (float)(convertedY - win->internal.lastMouseY);
8863
8864 RGFW_mousePosCallback(win, convertedX, convertedY, newVecX, newVecY);
8865 }
8866
8867 static void RGFW_wl_pointer_button(void* data, struct wl_pointer *pointer, u32 serial, u32 time, u32 button, u32 state) {
8868 RGFW_UNUSED(pointer); RGFW_UNUSED(time); RGFW_UNUSED(serial);
8869 RGFW_info* RGFW = (RGFW_info*)data;
8870
8871 RGFW_ASSERT(RGFW->mouseOwner != NULL);
8872 RGFW_window* win = RGFW->mouseOwner;
8873
8874 u32 b = (button - 0x110);
8875
8876 /* flip right and middle button codes */
8877 if (b == 1) b = 2;
8878 else if (b == 2) b = 1;
8879
8880 RGFW_mouseButtonCallback(win, (u8)b, RGFW_BOOL(state));
8881 }
8882
8883 static void RGFW_wl_pointer_axis(void* data, struct wl_pointer *pointer, u32 time, u32 axis, wl_fixed_t value) {
8884 RGFW_UNUSED(pointer); RGFW_UNUSED(time); RGFW_UNUSED(axis);
8885
8886 RGFW_info* RGFW = (RGFW_info*)data;
8887 RGFW_ASSERT(RGFW->mouseOwner != NULL);
8888 RGFW_window* win = RGFW->mouseOwner;
8889
8890 float scrollX = 0.0;
8891 float scrollY = 0.0;
8892
8893 if (!(win->internal.enabledEvents & (RGFW_BIT(RGFW_mouseScroll)))) return;
8894
8895 if (axis == WL_POINTER_AXIS_HORIZONTAL_SCROLL)
8896 scrollX = (float)(-wl_fixed_to_double(value) / 10.0);
8897 else if (axis == WL_POINTER_AXIS_VERTICAL_SCROLL)
8898 scrollY = (float)(-wl_fixed_to_double(value) / 10.0);
8899
8900 RGFW_mouseScrollCallback(win, scrollX, scrollY);
8901 }
8902
8903
8904 static void RGFW_doNothing(void) { }
8905
8906 static void RGFW_wl_keyboard_keymap(void* data, struct wl_keyboard *keyboard, u32 format, i32 fd, u32 size) {
8907 RGFW_UNUSED(keyboard); RGFW_UNUSED(format);
8908 RGFW_info* RGFW = (RGFW_info*)data;
8909
8910 char *keymap_string = mmap (NULL, size, PROT_READ, MAP_SHARED, fd, 0);
8911 xkb_keymap_unref(RGFW->keymap);
8912 RGFW->keymap = xkb_keymap_new_from_string(RGFW->xkb_context, keymap_string, XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS);
8913
8914 munmap(keymap_string, size);
8915 close(fd);
8916 xkb_state_unref(RGFW->xkb_state);
8917 RGFW->xkb_state = xkb_state_new(RGFW->keymap);
8918
8919 const char* locale = getenv("LC_ALL");
8920 if (!locale)
8921 locale = getenv("LC_CTYPE");
8922 if (!locale)
8923 locale = getenv("LANG");
8924 if (!locale)
8925 locale = "C";
8926
8927 struct xkb_compose_table* composeTable = xkb_compose_table_new_from_locale(RGFW->xkb_context, locale, XKB_COMPOSE_COMPILE_NO_FLAGS);
8928 if (composeTable) {
8929 RGFW->composeState = xkb_compose_state_new(composeTable, XKB_COMPOSE_STATE_NO_FLAGS);
8930 xkb_compose_table_unref(composeTable);
8931 }
8932 }
8933
8934 static void RGFW_wl_keyboard_enter(void* data, struct wl_keyboard *keyboard, u32 serial, struct wl_surface *surface, struct wl_array *keys) {
8935 RGFW_UNUSED(keyboard); RGFW_UNUSED(keys);
8936
8937 RGFW_info* RGFW = (RGFW_info*)data;
8938 RGFW_window* win = (RGFW_window*)wl_surface_get_user_data(surface);
8939 RGFW->kbOwner = win;
8940
8941
8942 // this is to prevent race conditions
8943 if (RGFW->data_device != NULL && win->src.data_source != NULL) {
8944 wl_data_device_set_selection(RGFW->data_device, win->src.data_source, serial);
8945 }
8946 /* is set when RGFW_window_minimize is called; if the minimize button is */
8947 /* pressed this flag is not set since there is no event to listen for */
8948 if (win->src.minimized == RGFW_TRUE) win->src.minimized = RGFW_FALSE;
8949
8950 RGFW_focusCallback(win, RGFW_TRUE);
8951 }
8952
8953 static void RGFW_wl_keyboard_leave(void* data, struct wl_keyboard *keyboard, u32 serial, struct wl_surface *surface) {
8954 RGFW_UNUSED(keyboard); RGFW_UNUSED(serial);
8955
8956 RGFW_info* RGFW = (RGFW_info*)data;
8957 RGFW_window* win = (RGFW_window*)wl_surface_get_user_data(surface);
8958 if (RGFW->kbOwner == win)
8959 RGFW->kbOwner = NULL;
8960
8961 RGFW_focusCallback(win, RGFW_FALSE);
8962 }
8963
8964 static xkb_keysym_t RGFW_wl_composeSymbol(RGFW_info* RGFW, xkb_keysym_t sym) {
8965 if (sym == XKB_KEY_NoSymbol || !RGFW->composeState)
8966 return sym;
8967 if (xkb_compose_state_feed(RGFW->composeState, sym) != XKB_COMPOSE_FEED_ACCEPTED)
8968 return sym;
8969 switch (xkb_compose_state_get_status(RGFW->composeState)) {
8970 case XKB_COMPOSE_COMPOSED:
8971 return xkb_compose_state_get_one_sym(RGFW->composeState);
8972 case XKB_COMPOSE_COMPOSING:
8973 case XKB_COMPOSE_CANCELLED:
8974 return XKB_KEY_NoSymbol;
8975 case XKB_COMPOSE_NOTHING:
8976 default:
8977 return sym;
8978 }
8979 }
8980
8981 static void RGFW_wl_keyboard_key(void* data, struct wl_keyboard *keyboard, u32 serial, u32 time, u32 key, u32 state) {
8982 RGFW_UNUSED(keyboard); RGFW_UNUSED(serial); RGFW_UNUSED(time);
8983
8984 RGFW_info* RGFW = (RGFW_info*)data;
8985 if (RGFW->kbOwner == NULL) return;
8986
8987 RGFW_window *RGFW_key_win = RGFW->kbOwner;
8988 RGFW_key RGFWkey = RGFW_apiKeyToRGFW(key + 8);
8989
8990 RGFW_updateKeyMods(RGFW_key_win, RGFW_BOOL(xkb_keymap_mod_get_index(RGFW->keymap, "Lock")), RGFW_BOOL(xkb_keymap_mod_get_index(RGFW->keymap, "Mod2")), RGFW_BOOL(xkb_keymap_mod_get_index(RGFW->keymap, "ScrollLock")));
8991 RGFW_keyCallback(RGFW_key_win, (u8)RGFWkey, RGFW_key_win->internal.mod, RGFW_window_isKeyDown(RGFW_key_win, (u8)RGFWkey), RGFW_BOOL(state));
8992
8993 const xkb_keysym_t* keysyms;
8994 if (xkb_state_key_get_syms(RGFW->xkb_state, key + 8, &keysyms) == 1) {
8995 xkb_keysym_t keysym = RGFW_wl_composeSymbol(RGFW, keysyms[0]);
8996 u32 codepoint = xkb_keysym_to_utf32(keysym);
8997 if (codepoint != 0) {
8998 RGFW_keyCharCallback(RGFW_key_win, codepoint);
8999 }
9000 }
9001 }
9002
9003 static void RGFW_wl_keyboard_modifiers(void* data, struct wl_keyboard *keyboard, u32 serial, u32 mods_depressed, u32 mods_latched, u32 mods_locked, u32 group) {
9004 RGFW_UNUSED(keyboard); RGFW_UNUSED(serial); RGFW_UNUSED(time);
9005 RGFW_info* RGFW = (RGFW_info*)data;
9006 xkb_state_update_mask(RGFW->xkb_state, mods_depressed, mods_latched, mods_locked, 0, 0, group);
9007 }
9008
9009 static void RGFW_wl_seat_capabilities(void* data, struct wl_seat *seat, u32 capabilities) {
9010 RGFW_info* RGFW = (RGFW_info*)data;
9011 static struct wl_pointer_listener pointer_listener;
9012 RGFW_MEMSET(&pointer_listener, 0, sizeof(pointer_listener));
9013 pointer_listener.enter = &RGFW_wl_pointer_enter;
9014 pointer_listener.leave = &RGFW_wl_pointer_leave;
9015 pointer_listener.motion = &RGFW_wl_pointer_motion;
9016 pointer_listener.button = &RGFW_wl_pointer_button;
9017 pointer_listener.axis = &RGFW_wl_pointer_axis;
9018
9019 static struct wl_keyboard_listener keyboard_listener;
9020 RGFW_MEMSET(&keyboard_listener, 0, sizeof(keyboard_listener));
9021 keyboard_listener.keymap = &RGFW_wl_keyboard_keymap;
9022 keyboard_listener.enter = &RGFW_wl_keyboard_enter;
9023 keyboard_listener.leave = &RGFW_wl_keyboard_leave;
9024 keyboard_listener.key = &RGFW_wl_keyboard_key;
9025 keyboard_listener.modifiers = &RGFW_wl_keyboard_modifiers;
9026
9027 if ((capabilities & WL_SEAT_CAPABILITY_POINTER) && !RGFW->wl_pointer) {
9028 RGFW->wl_pointer = wl_seat_get_pointer(seat);
9029 wl_pointer_add_listener(RGFW->wl_pointer, &pointer_listener, RGFW);
9030 }
9031 if ((capabilities & WL_SEAT_CAPABILITY_KEYBOARD) && !RGFW->wl_keyboard) {
9032 RGFW->wl_keyboard = wl_seat_get_keyboard(seat);
9033 wl_keyboard_add_listener(RGFW->wl_keyboard, &keyboard_listener, RGFW);
9034 }
9035
9036 if (!(capabilities & WL_SEAT_CAPABILITY_POINTER) && RGFW->wl_pointer) {
9037 wl_pointer_destroy(RGFW->wl_pointer);
9038 }
9039 if (!(capabilities & WL_SEAT_CAPABILITY_KEYBOARD) && RGFW->wl_keyboard) {
9040 wl_keyboard_destroy(RGFW->wl_keyboard);
9041 }
9042 }
9043
9044 static void RGFW_wl_output_set_geometry(void *data, struct wl_output *wl_output,
9045 i32 x, i32 y, i32 physical_width, i32 physical_height,
9046 i32 subpixel, const char *make, const char *model, i32 transform) {
9047
9048 RGFW_monitor* monitor = &((RGFW_monitorNode*)data)->mon;
9049 monitor->x = x;
9050 monitor->y = y;
9051
9052 monitor->physW = (float)physical_width / 25.4f;
9053 monitor->physH = (float)physical_height / 25.4f;
9054
9055 RGFW_UNUSED(wl_output);
9056 RGFW_UNUSED(subpixel);
9057 RGFW_UNUSED(make);
9058 RGFW_UNUSED(model);
9059 RGFW_UNUSED(transform);
9060 }
9061
9062 static void RGFW_wl_output_handle_mode(void *data, struct wl_output *wl_output, u32 flags,
9063 i32 width, i32 height, i32 refresh) {
9064
9065 RGFW_monitor* monitor = &((RGFW_monitorNode*)data)->mon;
9066
9067 RGFW_monitorMode mode;
9068 mode.w = width;
9069 mode.h = height;
9070 mode.refreshRate = (float)refresh / 1000.0f;
9071 mode.src = wl_output;
9072
9073 monitor->node->modeCount += 1;
9074
9075 RGFW_monitorMode* modes = (RGFW_monitorMode*)RGFW_ALLOC(monitor->node->modeCount * sizeof(RGFW_monitorMode));
9076
9077 if (monitor->node->modeCount > 1) {
9078 RGFW_monitor_getModesPtr(monitor, &modes);
9079 RGFW_FREE(monitor->node->modes);
9080 }
9081
9082 modes[monitor->node->modeCount - 1] = mode;
9083 monitor->node->modes = modes;
9084
9085 if (flags & WL_OUTPUT_MODE_CURRENT) {
9086 monitor->mode = mode;
9087 } else {
9088 }
9089 }
9090
9091 static void RGFW_wl_output_set_scale(void *data, struct wl_output *wl_output, i32 factor) {
9092 RGFW_UNUSED(wl_output);
9093 RGFW_monitor* mon = &((RGFW_monitorNode*)data)->mon;
9094
9095 mon->scaleX = (float)factor;
9096 mon->scaleY = (float)factor;
9097 }
9098
9099 static void RGFW_wl_output_set_name(void *data, struct wl_output *wl_output, const char *name) {
9100 RGFW_monitor* monitor = &((RGFW_monitorNode*)data)->mon;
9101
9102 RGFW_STRNCPY(monitor->name, name, sizeof(monitor->name) - 1);
9103 monitor->name[sizeof(monitor->name) - 1] = '\0';
9104
9105 RGFW_UNUSED(wl_output);
9106
9107 }
9108
9109 static void RGFW_xdg_output_logical_pos(void *data, struct zxdg_output_v1 *zxdg_output_v1, i32 x, i32 y) {
9110 RGFW_monitor* monitor = &((RGFW_monitorNode*)data)->mon;
9111 monitor->x = x;
9112 monitor->y = y;
9113 RGFW_UNUSED(zxdg_output_v1);
9114 }
9115
9116 static void RGFW_xdg_output_logical_size(void *data, struct zxdg_output_v1 *zxdg_output_v1, i32 width, i32 height) {
9117 RGFW_monitor* monitor = &((RGFW_monitorNode*)data)->mon;
9118
9119 float mon_float_width = (float) monitor->mode.w;
9120 float mon_float_height = (float) monitor->mode.h;
9121
9122 float scaleX = (mon_float_width / (float) width);
9123 float scaleY = (mon_float_height / (float) height);
9124 RGFW_UNUSED(scaleY);
9125
9126 float dpi = scaleX * 96.0f;
9127
9128 monitor->pixelRatio = dpi >= 192.0f ? 2.0f : 1.0f;
9129
9130 /* under xwayland the monitor changes w & h when compositor scales it */
9131 monitor->mode.w = width;
9132 monitor->mode.h = height;
9133 RGFW_UNUSED(zxdg_output_v1);
9134 }
9135
9136
9137 static void RGFW_wl_output_handle_done(void* data, struct wl_output* output) {
9138 RGFW_UNUSED(output);
9139
9140 RGFW_monitor* monitor = &((RGFW_monitorNode*)data)->mon;
9141
9142 if (monitor->physW <= 0 || monitor->physH <= 0) {
9143 monitor->physW = (i32) ((float)monitor->mode.w / 96.0f);
9144 monitor->physH = (i32) ((float)monitor->mode.h / 96.0f);
9145 }
9146
9147 if (((RGFW_monitorNode*)data)->disconnected == RGFW_FALSE) {
9148 return;
9149 }
9150
9151 ((RGFW_monitorNode*)data)->disconnected = RGFW_TRUE;
9152
9153 RGFW_monitorCallback(_RGFW->root, monitor, RGFW_TRUE);
9154 }
9155
9156 static void RGFW_wl_create_outputs(struct wl_registry *const registry, u32 id) {
9157 struct wl_output *output = wl_registry_bind(registry, id, &wl_output_interface, wl_display_get_version(_RGFW->wl_display) < 4 ? 3 : 4);
9158 RGFW_monitorNode* node;
9159 RGFW_monitor mon;
9160
9161 if (!output) return;
9162
9163 char RGFW_mon_default_name[10];
9164
9165 RGFW_SNPRINTF(RGFW_mon_default_name, sizeof(RGFW_mon_default_name), "monitor-%li", _RGFW->monitors.count);
9166 RGFW_STRNCPY(mon.name, RGFW_mon_default_name, sizeof(mon.name) - 1);
9167 mon.name[sizeof(mon.name) - 1] = '\0';
9168
9169 /* set in case compositor does not send one */
9170 /* or no xdg_output support */
9171 mon.scaleY = mon.scaleX = mon.pixelRatio = 1.0f;
9172
9173 node = RGFW_monitors_add(&mon);
9174 if (node == NULL) return;
9175
9176 node->modeCount = 0;
9177 node->disconnected = RGFW_TRUE;
9178 node->id = id;
9179 node->output = output;
9180
9181 static const struct wl_output_listener wl_output_listener = {
9182 .geometry = RGFW_wl_output_set_geometry,
9183 .mode = RGFW_wl_output_handle_mode,
9184 .done = RGFW_wl_output_handle_done,
9185 .scale = RGFW_wl_output_set_scale,
9186 .name = RGFW_wl_output_set_name,
9187 .description = (void (*)(void *, struct wl_output *, const char *))&RGFW_doNothing
9188 };
9189
9190 /* the wl_output will have a reference to the node */
9191 wl_output_set_user_data(output, node);
9192
9193 /* pass the monitor so we can access it in the callback functions */
9194 wl_output_add_listener(output, &wl_output_listener, node);
9195
9196 if (!_RGFW->xdg_output_manager)
9197 return; /* compositor does not support it */
9198
9199 static const struct zxdg_output_v1_listener xdg_output_listener = {
9200 .name = (void (*)(void *,struct zxdg_output_v1 *, const char *))&RGFW_doNothing,
9201 .done = (void (*)(void *,struct zxdg_output_v1 *))&RGFW_doNothing,
9202 .description = (void (*)(void *,struct zxdg_output_v1 *, const char *))&RGFW_doNothing,
9203 .logical_position = RGFW_xdg_output_logical_pos,
9204 .logical_size = RGFW_xdg_output_logical_size
9205 };
9206
9207 node->xdg_output = zxdg_output_manager_v1_get_xdg_output(_RGFW->xdg_output_manager, node->output);
9208 zxdg_output_v1_add_listener(node->xdg_output, &xdg_output_listener, node);
9209 }
9210
9211 static void RGFW_wl_surface_enter(void *data, struct wl_surface *wl_surface, struct wl_output *output) {
9212 RGFW_UNUSED(wl_surface);
9213
9214 RGFW_window* win = (RGFW_window*)data;
9215 RGFW_monitorNode* node = wl_output_get_user_data(output);
9216 if (node == NULL) return;
9217
9218 win->src.active_monitor = node;
9219
9220 if (win->internal.flags & RGFW_windowScaleToMonitor)
9221 RGFW_window_scaleToMonitor(win);
9222 }
9223
9224 static void RGFW_wl_data_source_send(void *data, struct wl_data_source *wl_data_source, const char *mime_type, i32 fd) {
9225 RGFW_UNUSED(data); RGFW_UNUSED(wl_data_source);
9226
9227 // a client can accept our clipboard
9228 if (RGFW_STRNCMP(mime_type, "text/plain;charset=utf-8", 25) == 0) {
9229 // do not write \0
9230 write(fd, _RGFW->clipboard, _RGFW->clipboard_len - 1);
9231 }
9232
9233 close(fd);
9234 }
9235
9236 static void RGFW_wl_data_source_cancelled(void *data, struct wl_data_source *wl_data_source) {
9237
9238 RGFW_info* RGFW = (RGFW_info*)data;
9239
9240 if (RGFW->kbOwner->src.data_source == wl_data_source) {
9241 RGFW->kbOwner->src.data_source = NULL;
9242 }
9243
9244 wl_data_source_destroy(wl_data_source);
9245
9246 }
9247
9248 static void RGFW_wl_data_device_data_offer(void *data, struct wl_data_device *wl_data_device, struct wl_data_offer *wl_data_offer) {
9249
9250 RGFW_UNUSED(data); RGFW_UNUSED(wl_data_device);
9251 static const struct wl_data_offer_listener wl_data_offer_listener = {
9252 .offer = (void (*)(void *data, struct wl_data_offer *wl_data_offer, const char *))RGFW_doNothing,
9253 .source_actions = (void (*)(void *data, struct wl_data_offer *wl_data_offer, u32 dnd_action))RGFW_doNothing,
9254 .action = (void (*)(void *data, struct wl_data_offer *wl_data_offer, u32 dnd_action))RGFW_doNothing
9255 };
9256 wl_data_offer_add_listener(wl_data_offer, &wl_data_offer_listener, NULL);
9257 }
9258
9259 static void RGFW_wl_data_device_selection(void *data, struct wl_data_device *wl_data_device, struct wl_data_offer *wl_data_offer) {
9260 RGFW_UNUSED(data); RGFW_UNUSED(wl_data_device);
9261 /* Clipboard is empty */
9262 if (wl_data_offer == NULL) {
9263 return;
9264 }
9265
9266 int pfds[2];
9267 pipe(pfds);
9268
9269 wl_data_offer_receive(wl_data_offer, "text/plain;charset=utf-8", pfds[1]);
9270 close(pfds[1]);
9271
9272 wl_display_roundtrip(_RGFW->wl_display);
9273
9274 char buf[1024];
9275
9276 ssize_t n = read(pfds[0], buf, sizeof(buf));
9277
9278 _RGFW->clipboard = (char*)RGFW_ALLOC((size_t)n);
9279 RGFW_ASSERT(_RGFW->clipboard != NULL);
9280 RGFW_STRNCPY(_RGFW->clipboard, buf, (size_t)n);
9281
9282 _RGFW->clipboard_len = (size_t)n + 1;
9283
9284 close(pfds[0]);
9285
9286 wl_data_offer_destroy(wl_data_offer);
9287
9288 }
9289
9290 static void RGFW_wl_global_registry_handler(void* data, struct wl_registry *registry, u32 id, const char *interface, u32 version) {
9291
9292 static struct wl_seat_listener seat_listener = {&RGFW_wl_seat_capabilities, (void (*)(void *, struct wl_seat *, const char *))&RGFW_doNothing};
9293 static const struct wl_shm_listener shm_listener = { .format = RGFW_wl_shm_format_handler };
9294
9295 RGFW_info* RGFW = (RGFW_info*)data;
9296 RGFW_UNUSED(version);
9297
9298 if (RGFW_STRNCMP(interface, "wl_compositor", 16) == 0) {
9299 RGFW->compositor = wl_registry_bind(registry, id, &wl_compositor_interface, 4);
9300 } else if (RGFW_STRNCMP(interface, "xdg_wm_base", 12) == 0) {
9301 RGFW->xdg_wm_base = wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
9302 } else if (RGFW_STRNCMP(interface, zxdg_decoration_manager_v1_interface.name, 255) == 0) {
9303 RGFW->decoration_manager = wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
9304 } else if (RGFW_STRNCMP(interface, zwp_pointer_constraints_v1_interface.name, 255) == 0) {
9305 RGFW->constraint_manager = wl_registry_bind(registry, id, &zwp_pointer_constraints_v1_interface, 1);
9306 } else if (RGFW_STRNCMP(interface, zwp_relative_pointer_manager_v1_interface.name, 255) == 0) {
9307 RGFW->relative_pointer_manager = wl_registry_bind(registry, id, &zwp_relative_pointer_manager_v1_interface, 1);
9308 } else if (RGFW_STRNCMP(interface, xdg_toplevel_icon_manager_v1_interface.name, 255) == 0) {
9309 RGFW->icon_manager = wl_registry_bind(registry, id, &xdg_toplevel_icon_manager_v1_interface, 1);
9310 } else if (RGFW_STRNCMP(interface, "wl_shm", 7) == 0) {
9311 RGFW->shm = wl_registry_bind(registry, id, &wl_shm_interface, 1);
9312 wl_shm_add_listener(RGFW->shm, &shm_listener, RGFW);
9313 } else if (RGFW_STRNCMP(interface,"wl_seat", 8) == 0) {
9314 RGFW->seat = wl_registry_bind(registry, id, &wl_seat_interface, 1);
9315 wl_seat_add_listener(RGFW->seat, &seat_listener, RGFW);
9316 } else if (RGFW_STRNCMP(interface, zxdg_output_manager_v1_interface.name, 255) == 0) {
9317 RGFW->xdg_output_manager = wl_registry_bind(registry, id, &zxdg_output_manager_v1_interface, 1);
9318 } else if (RGFW_STRNCMP(interface,"wl_output", 10) == 0) {
9319 RGFW_wl_create_outputs(registry, id);
9320 } else if (RGFW_STRNCMP(interface, wp_pointer_warp_v1_interface.name, 255) == 0) {
9321 RGFW->wp_pointer_warp = wl_registry_bind(registry, id, &wp_pointer_warp_v1_interface, 1);
9322 } else if (RGFW_STRNCMP(interface,"wl_data_device_manager", 23) == 0) {
9323 RGFW->data_device_manager = wl_registry_bind(registry, id, &wl_data_device_manager_interface, 1);
9324 }
9325 }
9326
9327 static void RGFW_wl_global_registry_remove(void* data, struct wl_registry *registry, u32 id) {
9328 RGFW_UNUSED(data); RGFW_UNUSED(registry);
9329 RGFW_info* RGFW = (RGFW_info*)data;
9330 RGFW_monitorNode* prev = RGFW->monitors.list.head;
9331 RGFW_monitorNode* node = NULL;
9332 if (prev == NULL) return;
9333
9334 if (prev->id != id) {
9335 /* find the first node that has a matching id */
9336 while(prev->next != NULL && prev->next->id != id) {
9337 prev = prev->next;
9338 }
9339
9340 if (prev->next == NULL) return;
9341 node = prev->next;
9342 } else {
9343 node = prev;
9344 }
9345
9346 if (node->output) {
9347 wl_output_destroy(node->output);
9348 }
9349
9350 if (node->xdg_output) {
9351 zxdg_output_v1_destroy(node->xdg_output);
9352 }
9353
9354 if (node->modeCount) {
9355 RGFW_FREE(node->modes);
9356 node->modeCount = 0;
9357 }
9358
9359 RGFW_monitorCallback(_RGFW->root, &node->mon, RGFW_FALSE);
9360 RGFW_monitors_remove(node, prev);
9361 }
9362
9363 static void RGFW_wl_randname(char *buf) {
9364 struct timespec ts;
9365 clock_gettime(CLOCK_REALTIME, &ts);
9366 long r = ts.tv_nsec;
9367
9368 int i;
9369 for (i = 0; i < 6; i++) {
9370 buf[i] = (char)('A'+(r&15)+(r&16)*2);
9371 r >>= 5;
9372 }
9373 }
9374
9375 static int RGFW_wl_anonymous_shm_open(void) {
9376 char name[] = "/RGFW-wayland-XXXXXX";
9377 int retries = 100;
9378
9379 do {
9380 RGFW_wl_randname(name + RGFW_unix_stringlen(name) - 6);
9381
9382 --retries;
9383 /* shm_open guarantees that O_CLOEXEC is set */
9384 int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
9385 if (fd >= 0) {
9386 shm_unlink(name);
9387 return fd;
9388 }
9389 } while (retries > 0 && errno == EEXIST);
9390
9391 return -1;
9392 }
9393
9394 static int RGFW_wl_create_shm_file(off_t size) {
9395 int fd = RGFW_wl_anonymous_shm_open();
9396 if (fd < 0) {
9397 return fd;
9398 }
9399
9400 if (ftruncate(fd, size) < 0) {
9401 close(fd);
9402 return -1;
9403 }
9404
9405 return fd;
9406 }
9407
9408 i32 RGFW_initPlatform_Wayland(void) {
9409 _RGFW->wl_display = wl_display_connect(NULL);
9410 if (_RGFW->wl_display == NULL) {
9411 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errWayland, "Failed to load Wayland display");
9412 return -1;
9413 }
9414
9415 _RGFW->compositor = NULL;
9416 static const struct wl_registry_listener registry_listener = {
9417 .global = RGFW_wl_global_registry_handler,
9418 .global_remove = RGFW_wl_global_registry_remove,
9419 };
9420
9421 _RGFW->registry = wl_display_get_registry(_RGFW->wl_display);
9422 wl_registry_add_listener(_RGFW->registry, &registry_listener, _RGFW);
9423
9424 wl_display_roundtrip(_RGFW->wl_display); /* bind to globals */
9425
9426 if (_RGFW->compositor == NULL) {
9427 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errWayland, "Can't find compositor.");
9428 return 1;
9429 }
9430
9431 if (_RGFW->wl_cursor_theme == NULL) {
9432 _RGFW->wl_cursor_theme = wl_cursor_theme_load(NULL, 24, _RGFW->shm);
9433 _RGFW->cursor_surface = wl_compositor_create_surface(_RGFW->compositor);
9434 }
9435
9436 u8 RGFW_blk[] = { 0, 0, 0, 0 };
9437 _RGFW->hiddenMouse = RGFW_loadMouse(RGFW_blk, 1, 1, RGFW_formatRGBA8);
9438
9439 static const struct xdg_wm_base_listener xdg_wm_base_listener = {
9440 .ping = RGFW_wl_xdg_wm_base_ping_handler,
9441 };
9442
9443 xdg_wm_base_add_listener(_RGFW->xdg_wm_base, &xdg_wm_base_listener, NULL);
9444
9445 _RGFW->xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
9446
9447 static const struct wl_data_device_listener wl_data_device_listener = {
9448 .data_offer = RGFW_wl_data_device_data_offer,
9449 .enter = (void (*)(void *, struct wl_data_device *, u32, struct wl_surface*, wl_fixed_t, wl_fixed_t, struct wl_data_offer *))&RGFW_doNothing,
9450 .leave = (void (*)(void *, struct wl_data_device *))&RGFW_doNothing,
9451 .motion = (void (*)(void *, struct wl_data_device *, u32, wl_fixed_t, wl_fixed_t))&RGFW_doNothing,
9452 .drop = (void (*)(void *, struct wl_data_device *))&RGFW_doNothing,
9453 .selection = RGFW_wl_data_device_selection
9454 };
9455
9456 if (_RGFW->seat && _RGFW->data_device_manager) {
9457 _RGFW->data_device = wl_data_device_manager_get_data_device(_RGFW->data_device_manager, _RGFW->seat);
9458 wl_data_device_add_listener(_RGFW->data_device, &wl_data_device_listener, NULL);
9459 }
9460
9461 return 0;
9462 }
9463
9464 void RGFW_deinitPlatform_Wayland(void) {
9465 if (_RGFW->clipboard) {
9466 RGFW_FREE(_RGFW->clipboard);
9467 _RGFW->clipboard = NULL;
9468 }
9469
9470 if (_RGFW->wl_pointer) {
9471 wl_pointer_destroy(_RGFW->wl_pointer);
9472 }
9473 if (_RGFW->wl_keyboard) {
9474 wl_keyboard_destroy(_RGFW->wl_keyboard);
9475 }
9476
9477 wl_registry_destroy(_RGFW->registry);
9478 if (_RGFW->decoration_manager != NULL)
9479 zxdg_decoration_manager_v1_destroy(_RGFW->decoration_manager);
9480 if (_RGFW->relative_pointer_manager != NULL) {
9481 zwp_relative_pointer_manager_v1_destroy(_RGFW->relative_pointer_manager);
9482 }
9483
9484 if (_RGFW->relative_pointer) {
9485 zwp_relative_pointer_v1_destroy(_RGFW->relative_pointer);
9486 }
9487
9488 if (_RGFW->constraint_manager != NULL) {
9489 zwp_pointer_constraints_v1_destroy(_RGFW->constraint_manager);
9490 }
9491
9492 if (_RGFW->xdg_output_manager != NULL)
9493 if (_RGFW->icon_manager != NULL) {
9494 xdg_toplevel_icon_manager_v1_destroy(_RGFW->icon_manager);
9495 }
9496
9497 if (_RGFW->xdg_output_manager) {
9498 zxdg_output_manager_v1_destroy(_RGFW->xdg_output_manager);
9499 }
9500
9501 if (_RGFW->data_device_manager) {
9502 wl_data_device_manager_destroy(_RGFW->data_device_manager);
9503 }
9504
9505 if (_RGFW->data_device) {
9506 wl_data_device_destroy(_RGFW->data_device);
9507 }
9508
9509 if (_RGFW->wl_cursor_theme != NULL) {
9510 wl_cursor_theme_destroy(_RGFW->wl_cursor_theme);
9511 }
9512
9513 if (_RGFW->wp_pointer_warp != NULL) {
9514 wp_pointer_warp_v1_destroy(_RGFW->wp_pointer_warp);
9515 }
9516
9517 RGFW_freeMouse(_RGFW->hiddenMouse);
9518
9519 RGFW_monitorNode* node = _RGFW->monitors.list.head;
9520
9521 while (node != NULL) {
9522 if (node->output) {
9523 wl_output_destroy(node->output);
9524 }
9525
9526 if (node->xdg_output) {
9527 zxdg_output_v1_destroy(node->xdg_output);
9528 }
9529
9530 _RGFW->monitors.count -= 1;
9531 node = node->next;
9532
9533 }
9534
9535 wl_surface_destroy(_RGFW->cursor_surface);
9536 wl_shm_destroy(_RGFW->shm);
9537 wl_seat_release(_RGFW->seat);
9538 xdg_wm_base_destroy(_RGFW->xdg_wm_base);
9539 wl_compositor_destroy(_RGFW->compositor);
9540 wl_display_disconnect(_RGFW->wl_display);
9541 }
9542
9543 RGFW_format RGFW_FUNC(RGFW_nativeFormat)(void) { return RGFW_formatBGRA8; }
9544
9545 RGFW_bool RGFW_FUNC(RGFW_createSurfacePtr) (u8* data, i32 w, i32 h, RGFW_format format, RGFW_surface* surface) {
9546 RGFW_ASSERT(surface != NULL);
9547 surface->data = data;
9548 surface->w = w;
9549 surface->h = h;
9550 surface->format = format;
9551 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoBuffer, "Creating a 4 channel buffer");
9552
9553 u32 size = (u32)(surface->w * surface->h * 4);
9554 int fd = RGFW_wl_create_shm_file(size);
9555 if (fd < 0) {
9556 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errBuffer, "Failed to create a buffer.");
9557 return RGFW_FALSE;
9558 }
9559
9560 surface->native.pool = wl_shm_create_pool(_RGFW->shm, fd, (i32)size);
9561
9562 surface->native.buffer = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
9563 if (surface->native.buffer == MAP_FAILED) {
9564 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errBuffer, "mmap failed.");
9565 return RGFW_FALSE;
9566 }
9567
9568 surface->native.fd = fd;
9569 surface->native.format = RGFW_formatBGRA8;
9570 return RGFW_TRUE;
9571 }
9572
9573 void RGFW_FUNC(RGFW_window_blitSurface) (RGFW_window* win, RGFW_surface* surface) {
9574 RGFW_ASSERT(surface != NULL);
9575
9576 surface->native.wl_buffer = wl_shm_pool_create_buffer(surface->native.pool, 0, RGFW_MIN(win->w, surface->w), RGFW_MIN(win->h, surface->h), (i32)surface->w * 4, WL_SHM_FORMAT_ARGB8888);
9577 RGFW_copyImageData(surface->native.buffer, surface->w, RGFW_MIN(win->h, surface->h), surface->native.format, surface->data, surface->format, surface->convertFunc);
9578
9579 wl_surface_attach(win->src.surface, surface->native.wl_buffer, 0, 0);
9580 wl_surface_damage(win->src.surface, 0, 0, RGFW_MIN(win->w, surface->w), RGFW_MIN(win->h, surface->h));
9581 wl_surface_commit(win->src.surface);
9582
9583 wl_buffer_destroy(surface->native.wl_buffer);
9584 }
9585
9586 void RGFW_FUNC(RGFW_surface_freePtr) (RGFW_surface* surface) {
9587 RGFW_ASSERT(surface != NULL);
9588
9589 wl_shm_pool_destroy(surface->native.pool);
9590 close(surface->native.fd);
9591
9592 munmap(surface->native.buffer, (size_t)(surface->w * surface->h * 4));
9593 }
9594
9595 void RGFW_FUNC(RGFW_window_setBorder) (RGFW_window* win, RGFW_bool border) {
9596 RGFW_setBit(&win->internal.flags, RGFW_windowNoBorder, !border);
9597
9598 /* for now just toggle between SSD & CSD depending on the bool */
9599 if (_RGFW->decoration_manager != NULL) {
9600 zxdg_toplevel_decoration_v1_set_mode(win->src.decoration, (border ? ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE : ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE));
9601 }
9602 }
9603
9604 void RGFW_FUNC(RGFW_window_setRawMouseModePlatform) (RGFW_window* win, RGFW_bool state) {
9605 RGFW_ASSERT(win);
9606 if (_RGFW->relative_pointer_manager == NULL) return;
9607
9608 if (state == RGFW_FALSE) {
9609 if (_RGFW->relative_pointer != NULL)
9610 zwp_relative_pointer_v1_destroy(_RGFW->relative_pointer);
9611 _RGFW->relative_pointer = NULL;
9612 return;
9613 }
9614
9615 if (_RGFW->relative_pointer != NULL) return;
9616
9617 _RGFW->relative_pointer = zwp_relative_pointer_manager_v1_get_relative_pointer(_RGFW->relative_pointer_manager, _RGFW->wl_pointer);
9618
9619 static const struct zwp_relative_pointer_v1_listener relative_motion_listener = {
9620 .relative_motion = RGFW_wl_relative_pointer_motion
9621 };
9622
9623 zwp_relative_pointer_v1_add_listener(_RGFW->relative_pointer, &relative_motion_listener, _RGFW);
9624 }
9625
9626 void RGFW_FUNC(RGFW_window_captureMousePlatform) (RGFW_window* win, RGFW_bool state) {
9627 RGFW_ASSERT(win);
9628
9629 /* compositor has no support or window already is locked do nothing */
9630 if (_RGFW->constraint_manager == NULL) return;
9631
9632 if (state == RGFW_FALSE) {
9633 if (win->src.locked_pointer != NULL)
9634 zwp_locked_pointer_v1_destroy(win->src.locked_pointer);
9635 win->src.locked_pointer = NULL;
9636 return;
9637 }
9638
9639
9640 if (win->src.locked_pointer != NULL) return;
9641 win->src.locked_pointer = zwp_pointer_constraints_v1_lock_pointer(_RGFW->constraint_manager, win->src.surface, _RGFW->wl_pointer, NULL, ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT);
9642
9643 static const struct zwp_locked_pointer_v1_listener locked_listener = {
9644 .locked = RGFW_wl_pointer_locked,
9645 .unlocked = (void (*)(void *, struct zwp_locked_pointer_v1 *))RGFW_doNothing
9646 };
9647
9648 zwp_locked_pointer_v1_add_listener(win->src.locked_pointer, &locked_listener, _RGFW);
9649 }
9650
9651 RGFW_window* RGFW_FUNC(RGFW_createWindowPlatform) (const char* name, RGFW_windowFlags flags, RGFW_window* win) {
9652 RGFW_sendDebugInfo(RGFW_typeWarning, RGFW_warningWayland, "RGFW Wayland support is experimental");
9653
9654 static const struct xdg_surface_listener xdg_surface_listener = {
9655 .configure = RGFW_wl_xdg_surface_configure_handler,
9656 };
9657
9658 static const struct wl_surface_listener wl_surface_listener = {
9659 .enter = RGFW_wl_surface_enter,
9660 .leave = (void (*)(void *, struct wl_surface *, struct wl_output *))&RGFW_doNothing,
9661 .preferred_buffer_scale = (void (*)(void *, struct wl_surface *, i32))&RGFW_doNothing,
9662 .preferred_buffer_transform = (void (*)(void *, struct wl_surface *, u32))&RGFW_doNothing
9663 };
9664
9665 win->src.surface = wl_compositor_create_surface(_RGFW->compositor);
9666 wl_surface_add_listener(win->src.surface, &wl_surface_listener, win);
9667
9668 /* create a surface for a custom cursor */
9669 win->src.custom_cursor_surface = wl_compositor_create_surface(_RGFW->compositor);
9670
9671 win->src.xdg_surface = xdg_wm_base_get_xdg_surface(_RGFW->xdg_wm_base, win->src.surface);
9672 xdg_surface_add_listener(win->src.xdg_surface, &xdg_surface_listener, win);
9673
9674 xdg_wm_base_set_user_data(_RGFW->xdg_wm_base, win);
9675
9676 win->src.xdg_toplevel = xdg_surface_get_toplevel(win->src.xdg_surface);
9677
9678 if (_RGFW->className == NULL)
9679 _RGFW->className = (char*)name;
9680
9681 xdg_toplevel_set_app_id(win->src.xdg_toplevel, name);
9682
9683 xdg_surface_set_window_geometry(win->src.xdg_surface, 0, 0, win->w, win->h);
9684
9685 if (!(win->internal.flags & RGFW_windowTransparent)) { /* no transparency */
9686 RGFW_wl_setOpaque(win);
9687 }
9688
9689 static const struct xdg_toplevel_listener xdg_toplevel_listener = {
9690 .configure = RGFW_wl_xdg_toplevel_configure_handler,
9691 .close = RGFW_wl_xdg_toplevel_close_handler,
9692 };
9693
9694 xdg_toplevel_add_listener(win->src.xdg_toplevel, &xdg_toplevel_listener, win);
9695
9696 /* compositor supports both SSD & CSD
9697 So choose accordingly
9698 */
9699 if (_RGFW->decoration_manager) {
9700 u32 decoration_mode = ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE;
9701 win->src.decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(
9702 _RGFW->decoration_manager, win->src.xdg_toplevel);
9703
9704 static const struct zxdg_toplevel_decoration_v1_listener xdg_decoration_listener = {
9705 .configure = RGFW_wl_xdg_decoration_configure_handler
9706 };
9707
9708 zxdg_toplevel_decoration_v1_add_listener(win->src.decoration, &xdg_decoration_listener, win);
9709
9710 /* we want no decorations */
9711 if ((flags & RGFW_windowNoBorder)) {
9712 decoration_mode = ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE;
9713 }
9714
9715 zxdg_toplevel_decoration_v1_set_mode(win->src.decoration, decoration_mode);
9716
9717 /* no xdg_decoration support */
9718 } else if (!(flags & RGFW_windowNoBorder)) {
9719 /* TODO, some fallback */
9720 #ifdef RGFW_LIBDECOR
9721 static struct libdecor_interface interface = {
9722 .error = NULL,
9723 };
9724
9725 static struct libdecor_frame_interface frameInterface = {0}; /*= {
9726 RGFW_wl_handle_configure,
9727 RGFW_wl_handle_close,
9728 RGFW_wl_handle_commit,
9729 RGFW_wl_handle_dismiss_popup,
9730 };*/
9731
9732 win->src.decorContext = libdecor_new(_RGFW->wl_display, &interface);
9733 if (win->src.decorContext) {
9734 struct libdecor_frame *frame = libdecor_decorate(win->src.decorContext, win->src.surface, &frameInterface, win);
9735 if (!frame) {
9736 libdecor_unref(win->src.decorContext);
9737 win->src.decorContext = NULL;
9738 } else {
9739 libdecor_frame_set_app_id(frame, "my-libdecor-app");
9740 libdecor_frame_set_title(frame, "My Libdecor Window");
9741 }
9742 }
9743 #endif
9744 }
9745
9746 if (_RGFW->icon_manager != NULL) {
9747 /* set the default wayland icon */
9748 xdg_toplevel_icon_manager_v1_set_icon(_RGFW->icon_manager, win->src.xdg_toplevel, NULL);
9749 }
9750
9751 wl_surface_commit(win->src.surface);
9752
9753 while (win->src.configured == RGFW_FALSE) {
9754 wl_display_dispatch(_RGFW->wl_display);
9755 }
9756
9757 RGFW_UNUSED(name);
9758
9759 return win;
9760 }
9761
9762 RGFW_bool RGFW_FUNC(RGFW_getGlobalMouse) (i32* x, i32* y) {
9763 RGFW_init();
9764 if (x) *x = 0;
9765 if (y) *y = 0;
9766 return RGFW_FALSE;
9767 }
9768
9769 RGFW_key RGFW_FUNC(RGFW_physicalToMappedKey)(RGFW_key key) {
9770 u32 keycode = RGFW_rgfwToApiKey(key);
9771 xkb_keycode_t kc = keycode + 8;
9772 xkb_keysym_t sym = xkb_state_key_get_one_sym(_RGFW->xkb_state, kc);
9773 if (sym < 256) {
9774 return (RGFW_key)sym;
9775 }
9776
9777 switch (sym) {
9778 case XKB_KEY_F1: return RGFW_F1;
9779 case XKB_KEY_F2: return RGFW_F2;
9780 case XKB_KEY_F3: return RGFW_F3;
9781 case XKB_KEY_F4: return RGFW_F4;
9782 case XKB_KEY_F5: return RGFW_F5;
9783 case XKB_KEY_F6: return RGFW_F6;
9784 case XKB_KEY_F7: return RGFW_F7;
9785 case XKB_KEY_F8: return RGFW_F8;
9786 case XKB_KEY_F9: return RGFW_F9;
9787 case XKB_KEY_F10: return RGFW_F10;
9788 case XKB_KEY_F11: return RGFW_F11;
9789 case XKB_KEY_F12: return RGFW_F12;
9790 case XKB_KEY_F13: return RGFW_F13;
9791 case XKB_KEY_F14: return RGFW_F14;
9792 case XKB_KEY_F15: return RGFW_F15;
9793 case XKB_KEY_F16: return RGFW_F16;
9794 case XKB_KEY_F17: return RGFW_F17;
9795 case XKB_KEY_F18: return RGFW_F18;
9796 case XKB_KEY_F19: return RGFW_F19;
9797 case XKB_KEY_F20: return RGFW_F20;
9798 case XKB_KEY_F21: return RGFW_F21;
9799 case XKB_KEY_F22: return RGFW_F22;
9800 case XKB_KEY_F23: return RGFW_F23;
9801 case XKB_KEY_F24: return RGFW_F24;
9802 case XKB_KEY_F25: return RGFW_F25;
9803 case XKB_KEY_Shift_L: return RGFW_shiftL;
9804 case XKB_KEY_Shift_R: return RGFW_shiftR;
9805 case XKB_KEY_Control_L: return RGFW_controlL;
9806 case XKB_KEY_Control_R: return RGFW_controlR;
9807 case XKB_KEY_Alt_L: return RGFW_altL;
9808 case XKB_KEY_Alt_R: return RGFW_altR;
9809 case XKB_KEY_Super_L: return RGFW_superL;
9810 case XKB_KEY_Super_R: return RGFW_superR;
9811 case XKB_KEY_Caps_Lock: return RGFW_capsLock;
9812 case XKB_KEY_Num_Lock: return RGFW_numLock;
9813 case XKB_KEY_Scroll_Lock:return RGFW_scrollLock;
9814 case XKB_KEY_Up: return RGFW_up;
9815 case XKB_KEY_Down: return RGFW_down;
9816 case XKB_KEY_Left: return RGFW_left;
9817 case XKB_KEY_Right: return RGFW_right;
9818 case XKB_KEY_Home: return RGFW_home;
9819 case XKB_KEY_End: return RGFW_end;
9820 case XKB_KEY_Page_Up: return RGFW_pageUp;
9821 case XKB_KEY_Page_Down: return RGFW_pageDown;
9822 case XKB_KEY_Insert: return RGFW_insert;
9823 case XKB_KEY_Menu: return RGFW_menu;
9824 case XKB_KEY_KP_Add: return RGFW_kpPlus;
9825 case XKB_KEY_KP_Subtract: return RGFW_kpMinus;
9826 case XKB_KEY_KP_Multiply: return RGFW_kpMultiply;
9827 case XKB_KEY_KP_Divide: return RGFW_kpSlash;
9828 case XKB_KEY_KP_Equal: return RGFW_kpEqual;
9829 case XKB_KEY_KP_Enter: return RGFW_kpReturn;
9830 case XKB_KEY_KP_Decimal: return RGFW_kpPeriod;
9831 case XKB_KEY_KP_0: return RGFW_kp0;
9832 case XKB_KEY_KP_1: return RGFW_kp1;
9833 case XKB_KEY_KP_2: return RGFW_kp2;
9834 case XKB_KEY_KP_3: return RGFW_kp3;
9835 case XKB_KEY_KP_4: return RGFW_kp4;
9836 case XKB_KEY_KP_5: return RGFW_kp5;
9837 case XKB_KEY_KP_6: return RGFW_kp6;
9838 case XKB_KEY_KP_7: return RGFW_kp7;
9839 case XKB_KEY_KP_8: return RGFW_kp8;
9840 case XKB_KEY_KP_9: return RGFW_kp9;
9841 case XKB_KEY_Print: return RGFW_printScreen;
9842 case XKB_KEY_Pause: return RGFW_pause;
9843 default: break;
9844 }
9845
9846 return RGFW_keyNULL;
9847 }
9848
9849 void RGFW_FUNC(RGFW_pollEvents) (void) {
9850 RGFW_resetPrevState();
9851
9852 /* send buffered requests to compositor */
9853 while (wl_display_flush(_RGFW->wl_display) == -1) {
9854 /* compositor not responding to new requests */
9855 /* so let's dispatch some events so the compositor responds */
9856 if (errno == EAGAIN) {
9857 if (wl_display_dispatch_pending(_RGFW->wl_display) == -1) {
9858 return;
9859 }
9860 } else {
9861 return;
9862 }
9863 }
9864
9865 /* read the events; if empty this reads from the */
9866 /* wayland file descriptor */
9867 if (wl_display_dispatch(_RGFW->wl_display) == -1) {
9868 return;
9869 }
9870
9871 }
9872
9873 void RGFW_FUNC(RGFW_window_move) (RGFW_window* win, i32 x, i32 y) {
9874 RGFW_ASSERT(win != NULL);
9875 win->x = x;
9876 win->y = y;
9877 }
9878
9879
9880 void RGFW_FUNC(RGFW_window_resize) (RGFW_window* win, i32 w, i32 h) {
9881 RGFW_ASSERT(win != NULL);
9882 win->w = w;
9883 win->h = h;
9884 if (_RGFW->compositor) {
9885 xdg_surface_set_window_geometry(win->src.xdg_surface, 0, 0, win->w, win->h);
9886 #ifdef RGFW_OPENGL
9887 if (win->src.ctx.egl)
9888 wl_egl_window_resize(win->src.ctx.egl->eglWindow, (i32)w, (i32)h, 0, 0);
9889 #endif
9890 }
9891 }
9892
9893 void RGFW_FUNC(RGFW_window_setAspectRatio) (RGFW_window* win, i32 w, i32 h) {
9894 RGFW_ASSERT(win != NULL);
9895
9896 if (w == 0 && h == 0)
9897 return;
9898 xdg_toplevel_set_max_size(win->src.xdg_toplevel, (i32)w, (i32)h);
9899 }
9900
9901 void RGFW_FUNC(RGFW_window_setMinSize) (RGFW_window* win, i32 w, i32 h) {
9902 RGFW_ASSERT(win != NULL);
9903 xdg_toplevel_set_min_size(win->src.xdg_toplevel, w, h);
9904 }
9905
9906 void RGFW_FUNC(RGFW_window_setMaxSize) (RGFW_window* win, i32 w, i32 h) {
9907 RGFW_ASSERT(win != NULL);
9908 xdg_toplevel_set_max_size(win->src.xdg_toplevel, w, h);
9909 }
9910
9911 void RGFW_toggleWaylandMaximized(RGFW_window* win, RGFW_bool maximized) {
9912 win->src.maximized = maximized;
9913 if (maximized) {
9914 xdg_toplevel_set_maximized(win->src.xdg_toplevel);
9915 } else {
9916 xdg_toplevel_unset_maximized(win->src.xdg_toplevel);
9917 }
9918 }
9919
9920 void RGFW_FUNC(RGFW_window_maximize) (RGFW_window* win) {
9921 win->internal.oldX = win->x;
9922 win->internal.oldY = win->y;
9923 win->internal.oldW = win->w;
9924 win->internal.oldH = win->h;
9925 RGFW_toggleWaylandMaximized(win, 1);
9926 return;
9927 }
9928
9929 void RGFW_FUNC(RGFW_window_focus)(RGFW_window* win) {
9930 RGFW_ASSERT(win);
9931 }
9932
9933 void RGFW_FUNC(RGFW_window_raise)(RGFW_window* win) {
9934 RGFW_ASSERT(win);
9935 }
9936
9937 void RGFW_FUNC(RGFW_window_setFullscreen)(RGFW_window* win, RGFW_bool fullscreen) {
9938 RGFW_ASSERT(win != NULL);
9939 if (fullscreen) {
9940
9941 win->internal.flags |= RGFW_windowFullscreen;
9942 win->internal.oldX = win->x;
9943 win->internal.oldY = win->y;
9944 win->internal.oldW = win->w;
9945 win->internal.oldH = win->h;
9946 xdg_toplevel_set_fullscreen(win->src.xdg_toplevel, NULL); /* let the compositor decide */
9947 } else {
9948 win->internal.flags &= ~(u32)RGFW_windowFullscreen;
9949 xdg_toplevel_unset_fullscreen(win->src.xdg_toplevel);
9950 }
9951
9952 }
9953
9954 void RGFW_FUNC(RGFW_window_setFloating) (RGFW_window* win, RGFW_bool floating) {
9955 RGFW_ASSERT(win != NULL);
9956 RGFW_UNUSED(floating);
9957 }
9958
9959 void RGFW_FUNC(RGFW_window_setOpacity) (RGFW_window* win, u8 opacity) {
9960 RGFW_ASSERT(win != NULL);
9961 RGFW_UNUSED(opacity);
9962 }
9963
9964 void RGFW_FUNC(RGFW_window_minimize)(RGFW_window* win) {
9965 RGFW_ASSERT(win != NULL);
9966 if (RGFW_window_isMaximized(win)) return;
9967 win->internal.oldX = win->x;
9968 win->internal.oldY = win->y;
9969 win->internal.oldW = win->w;
9970 win->internal.oldH = win->h;
9971 win->src.minimized = RGFW_TRUE;
9972 xdg_toplevel_set_minimized(win->src.xdg_toplevel);
9973 }
9974
9975 void RGFW_FUNC(RGFW_window_restore)(RGFW_window* win) {
9976 RGFW_ASSERT(win != NULL);
9977 RGFW_toggleWaylandMaximized(win, RGFW_FALSE);
9978
9979 RGFW_window_move(win, win->internal.oldX, win->internal.oldY);
9980 RGFW_window_resize(win, win->internal.oldW, win->internal.oldH);
9981
9982 RGFW_window_show(win);
9983 RGFW_window_move(win, win->internal.oldX, win->internal.oldY);
9984 RGFW_window_resize(win, win->internal.oldW, win->internal.oldH);
9985
9986 RGFW_window_show(win);
9987 }
9988
9989 RGFW_bool RGFW_FUNC(RGFW_window_isFloating)(RGFW_window* win) {
9990 return (!RGFW_window_isFullscreen(win) && !RGFW_window_isMaximized(win));
9991 }
9992
9993 void RGFW_FUNC(RGFW_window_setName) (RGFW_window* win, const char* name) {
9994 RGFW_ASSERT(win != NULL);
9995 if (name == NULL) name = "\0";
9996
9997 if (_RGFW->compositor)
9998 xdg_toplevel_set_title(win->src.xdg_toplevel, name);
9999 }
10000
10001 #ifndef RGFW_NO_PASSTHROUGH
10002 void RGFW_FUNC(RGFW_window_setMousePassthrough) (RGFW_window* win, RGFW_bool passthrough) {
10003 RGFW_ASSERT(win != NULL);
10004 RGFW_UNUSED(passthrough);
10005 }
10006 #endif /* RGFW_NO_PASSTHROUGH */
10007
10008 RGFW_bool RGFW_FUNC(RGFW_window_setIconEx) (RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format, RGFW_icon type) {
10009 RGFW_ASSERT(win != NULL);
10010 RGFW_UNUSED(type);
10011
10012 if (_RGFW->icon_manager == NULL || w != h) return RGFW_FALSE;
10013
10014 if (win->src.icon) {
10015 xdg_toplevel_icon_v1_destroy(win->src.icon);
10016 win->src.icon= NULL;
10017 }
10018
10019 RGFW_surface* surface = RGFW_createSurface(data, w, h, format);
10020
10021 if (surface == NULL) return RGFW_FALSE;
10022
10023 RGFW_copyImageData(surface->native.buffer, RGFW_MIN(w, surface->w), RGFW_MIN(h, surface->h), surface->native.format, surface->data, surface->format, NULL);
10024
10025 win->src.icon = xdg_toplevel_icon_manager_v1_create_icon(_RGFW->icon_manager);
10026 xdg_toplevel_icon_v1_add_buffer(win->src.icon, surface->native.wl_buffer, 1);
10027 xdg_toplevel_icon_manager_v1_set_icon(_RGFW->icon_manager, win->src.xdg_toplevel, win->src.icon);
10028
10029 RGFW_surface_free(surface);
10030 return RGFW_TRUE;
10031 }
10032
10033 RGFW_mouse* RGFW_FUNC(RGFW_loadMouse)(u8* data, i32 w, i32 h, RGFW_format format) {
10034
10035 RGFW_surface *mouse_surface = RGFW_createSurface(data, w, h, format);
10036
10037 if (mouse_surface == NULL) return NULL;
10038
10039 RGFW_copyImageData(mouse_surface->native.buffer, RGFW_MIN(w, mouse_surface->w), RGFW_MIN(h, mouse_surface->h), mouse_surface->native.format, mouse_surface->data, mouse_surface->format, NULL);
10040
10041 return (void*) mouse_surface;
10042 }
10043
10044 void RGFW_FUNC(RGFW_window_setMouse)(RGFW_window* win, RGFW_mouse* mouse) {
10045 RGFW_ASSERT(win); RGFW_ASSERT(mouse);
10046 RGFW_surface *mouse_surface = (RGFW_surface*)mouse;
10047
10048 win->src.using_custom_cursor = RGFW_TRUE;
10049
10050 struct wl_buffer *mouse_buffer = mouse_surface->native.wl_buffer;
10051
10052 wl_surface_attach(win->src.custom_cursor_surface, mouse_buffer, 0, 0);
10053 wl_surface_damage(win->src.custom_cursor_surface, 0, 0, mouse_surface->w, mouse_surface->h);
10054 wl_surface_commit(win->src.custom_cursor_surface);
10055
10056 }
10057
10058 void RGFW_FUNC(RGFW_freeMouse)(RGFW_mouse* mouse) {
10059 if (mouse != NULL) {
10060 RGFW_surface_free((RGFW_surface*)mouse);
10061 }
10062 }
10063
10064 void RGFW_FUNC(RGFW_window_moveMouse)(RGFW_window* win, i32 x, i32 y) {
10065 if (_RGFW->wp_pointer_warp != NULL) {
10066 wp_pointer_warp_v1_warp_pointer(_RGFW->wp_pointer_warp, win->src.surface, _RGFW->wl_pointer, wl_fixed_from_int(x), wl_fixed_from_int(y), _RGFW->mouse_enter_serial);
10067 }
10068 }
10069
10070 RGFW_bool RGFW_FUNC(RGFW_window_setMouseDefault)(RGFW_window* win) {
10071 return RGFW_window_setMouseStandard(win, RGFW_mouseArrow);
10072 }
10073
10074 RGFW_bool RGFW_FUNC(RGFW_window_setMouseStandard)(RGFW_window* win, u8 mouse) {
10075 RGFW_ASSERT(win != NULL);
10076
10077 char* cursorName = NULL;
10078 switch (mouse) {
10079 case RGFW_mouseNormal: cursorName = (char*)"left_ptr"; break;
10080 case RGFW_mouseArrow: cursorName = (char*)"left_ptr"; break;
10081 case RGFW_mouseIbeam: cursorName = (char*)"xterm"; break;
10082 case RGFW_mouseCrosshair: cursorName = (char*)"crosshair"; break;
10083 case RGFW_mousePointingHand: cursorName = (char*)"hand2"; break;
10084 case RGFW_mouseResizeEW: cursorName = (char*)"sb_h_double_arrow"; break;
10085 case RGFW_mouseResizeNS: cursorName = (char*)"sb_v_double_arrow"; break;
10086 case RGFW_mouseResizeNWSE: cursorName = (char*)"top_left_corner"; break; /* or fd_double_arrow */
10087 case RGFW_mouseResizeNESW: cursorName = (char*)"top_right_corner"; break; /* or bd_double_arrow */
10088 case RGFW_mouseResizeNW: cursorName = (char*)"top_left_corner"; break;
10089 case RGFW_mouseResizeN: cursorName = (char*)"top_side"; break;
10090 case RGFW_mouseResizeNE: cursorName = (char*)"top_right_corner"; break;
10091 case RGFW_mouseResizeE: cursorName = (char*)"right_side"; break;
10092 case RGFW_mouseResizeSE: cursorName = (char*)"bottom_right_corner"; break;
10093 case RGFW_mouseResizeS: cursorName = (char*)"bottom_side"; break;
10094 case RGFW_mouseResizeSW: cursorName = (char*)"bottom_left_corner"; break;
10095 case RGFW_mouseResizeW: cursorName = (char*)"left_side"; break;
10096 case RGFW_mouseResizeAll: cursorName = (char*)"fleur"; break;
10097 case RGFW_mouseNotAllowed: cursorName = (char*)"not-allowed"; break;
10098 case RGFW_mouseWait: cursorName = (char*)"watch"; break;
10099 case RGFW_mouseProgress: cursorName = (char*)"watch"; break;
10100 default: return RGFW_FALSE;
10101 }
10102
10103 win->src.using_custom_cursor = RGFW_FALSE;
10104
10105 struct wl_cursor* wlcursor = wl_cursor_theme_get_cursor(_RGFW->wl_cursor_theme, cursorName);
10106 if (wlcursor == NULL)
10107 return RGFW_FALSE;
10108 struct wl_cursor_image* cursor_image = wlcursor->images[0];
10109 struct wl_buffer* cursor_buffer = wl_cursor_image_get_buffer(cursor_image);
10110 wl_pointer_set_cursor(_RGFW->wl_pointer, _RGFW->mouse_enter_serial, _RGFW->cursor_surface, (i32)cursor_image->hotspot_x, (i32)cursor_image->hotspot_y);
10111 wl_surface_attach(_RGFW->cursor_surface, cursor_buffer, 0, 0);
10112 wl_surface_damage(_RGFW->cursor_surface, 0, 0, (i32)cursor_image->width, (i32)cursor_image->height);
10113 wl_surface_commit(_RGFW->cursor_surface);
10114 return RGFW_TRUE;
10115 }
10116
10117 void RGFW_FUNC(RGFW_window_hide) (RGFW_window* win) {
10118 wl_surface_attach(win->src.surface, NULL, 0, 0);
10119 wl_surface_commit(win->src.surface);
10120 win->internal.flags |= RGFW_windowHide;
10121 }
10122
10123 void RGFW_FUNC(RGFW_window_show) (RGFW_window* win) {
10124 win->internal.flags &= ~(u32)RGFW_windowHide;
10125 if (win->internal.flags & RGFW_windowFocusOnShow) RGFW_window_focus(win);
10126 /* wl_surface_attach(win->src.surface, win->x, win->y, win->w, win->h, 0, 0); */
10127 wl_surface_commit(win->src.surface);
10128 }
10129
10130 void RGFW_FUNC(RGFW_window_flash) (RGFW_window* win, RGFW_flashRequest request) {
10131 if (RGFW_window_isInFocus(win) && request) {
10132 return;
10133 }
10134 }
10135
10136 RGFW_ssize_t RGFW_FUNC(RGFW_readClipboardPtr) (char* str, size_t strCapacity) {
10137 RGFW_UNUSED(strCapacity);
10138
10139 if (str != NULL)
10140 RGFW_STRNCPY(str, _RGFW->clipboard, _RGFW->clipboard_len - 1);
10141 _RGFW->clipboard[_RGFW->clipboard_len - 1] = '\0';
10142 return (RGFW_ssize_t)_RGFW->clipboard_len - 1;
10143 }
10144
10145 void RGFW_FUNC(RGFW_writeClipboard) (const char* text, u32 textLen) {
10146
10147 // compositor does not support wl_data_device_manager
10148 // clients cannot read rgfw's clipboard
10149 if (_RGFW->data_device_manager == NULL) return;
10150 // clear the clipboard
10151 if (_RGFW->clipboard)
10152 RGFW_FREE(_RGFW->clipboard);
10153
10154 // set the contents
10155 _RGFW->clipboard = (char*)RGFW_ALLOC(textLen);
10156 RGFW_ASSERT(_RGFW->clipboard != NULL);
10157 RGFW_STRNCPY(_RGFW->clipboard, text, textLen - 1);
10158 _RGFW->clipboard[textLen - 1] = '\0';
10159 _RGFW->clipboard_len = textLen;
10160
10161 // means we already wrote to the clipboard
10162 // so destroy it to create a new one
10163 RGFW_window* win = _RGFW->kbOwner;
10164
10165 if (win->src.data_source != NULL) {
10166 wl_data_source_destroy(win->src.data_source);
10167 win->src.data_source = NULL;
10168 }
10169
10170 // advertise to other clients that we offer text
10171 win->src.data_source = wl_data_device_manager_create_data_source(_RGFW->data_device_manager);
10172
10173 // basic error checking
10174 if (win->src.data_source == NULL) {
10175 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errClipboard, "Could not create clipboard data source");
10176 return;
10177 }
10178 wl_data_source_offer(win->src.data_source , "text/plain;charset=utf-8");
10179
10180 // needed RGFW_doNothing because wayland will call the functions
10181 // if not set they are random data that lead to a crash
10182 static const struct wl_data_source_listener data_source_listener = {
10183 .target = (void (*)(void *, struct wl_data_source *, const char *))&RGFW_doNothing,
10184 .action = (void (*)(void *, struct wl_data_source *, u32))&RGFW_doNothing,
10185 .dnd_drop_performed = (void (*)(void *, struct wl_data_source *))&RGFW_doNothing,
10186 .dnd_finished = (void (*)(void *, struct wl_data_source *))&RGFW_doNothing,
10187 .send = RGFW_wl_data_source_send,
10188 .cancelled = RGFW_wl_data_source_cancelled
10189 };
10190
10191 wl_data_source_add_listener(win->src.data_source, &data_source_listener, _RGFW);
10192
10193 }
10194
10195 RGFW_bool RGFW_FUNC(RGFW_window_isHidden) (RGFW_window* win) {
10196 RGFW_ASSERT(win != NULL);
10197 return RGFW_FALSE;
10198 }
10199
10200 RGFW_bool RGFW_FUNC(RGFW_window_isMinimized) (RGFW_window* win) {
10201 RGFW_ASSERT(win != NULL);
10202 return win->src.minimized;
10203 }
10204
10205 RGFW_bool RGFW_FUNC(RGFW_window_isMaximized) (RGFW_window* win) {
10206 RGFW_ASSERT(win != NULL);
10207 return win->src.maximized;
10208 }
10209
10210 void RGFW_FUNC(RGFW_pollMonitors) (void) {
10211 _RGFW->monitors.primary = _RGFW->monitors.list.head;
10212 }
10213
10214
10215 RGFW_bool RGFW_FUNC(RGFW_monitor_getWorkarea) (RGFW_monitor* monitor, i32* x, i32* y, i32* width, i32* height) {
10216 /* NOTE: Wayland has no way to get the actual workarea as far as I'm aware :( */
10217 if (x) *x = monitor->x;
10218 if (y) *y = monitor->y;
10219 if (width) *width = monitor->mode.w;
10220 if (height) *height = monitor->mode.h;
10221 return RGFW_TRUE;
10222 }
10223
10224 size_t RGFW_FUNC(RGFW_monitor_getModesPtr) (RGFW_monitor* monitor, RGFW_monitorMode** modes) {
10225 if (modes) {
10226 RGFW_MEMCPY((*modes), monitor->node->modes, monitor->node->modeCount * sizeof(RGFW_monitorMode));
10227 }
10228
10229 return monitor->node->modeCount;
10230 }
10231
10232 size_t RGFW_FUNC(RGFW_monitor_getGammaRampPtr) (RGFW_monitor* monitor, RGFW_gammaRamp* ramp) {
10233 RGFW_UNUSED(monitor); RGFW_UNUSED(ramp);
10234 return 0;
10235 }
10236
10237 RGFW_bool RGFW_FUNC(RGFW_monitor_setGammaRamp) (RGFW_monitor* monitor, RGFW_gammaRamp* ramp) {
10238 RGFW_UNUSED(monitor); RGFW_UNUSED(ramp);
10239 return RGFW_FALSE;
10240 }
10241
10242 RGFW_bool RGFW_FUNC(RGFW_monitor_requestMode) (RGFW_monitor* mon, RGFW_monitorMode* mode, RGFW_modeRequest request) {
10243 for (size_t i = 0; i < mon->node->modeCount; i++) {
10244 if (RGFW_monitorModeCompare(mode, &mon->node->modes[i], request) == RGFW_FALSE) {
10245 continue;
10246 }
10247
10248 RGFW_monitor_setMode(mon, &mon->node->modes[i]);
10249 return RGFW_TRUE;
10250 }
10251
10252 return RGFW_FALSE;
10253 }
10254
10255 RGFW_bool RGFW_FUNC(RGFW_monitor_setMode) (RGFW_monitor* mon, RGFW_monitorMode* mode) {
10256 RGFW_UNUSED(mon); RGFW_UNUSED(mode);
10257 return RGFW_FALSE;
10258 }
10259
10260 RGFW_monitor* RGFW_FUNC(RGFW_window_getMonitor) (RGFW_window* win) {
10261 RGFW_ASSERT(win);
10262 if (win->src.active_monitor == NULL) {
10263 /* TODO: fix race condition [probably a problem with wayland] */
10264 return RGFW_getPrimaryMonitor();
10265 }
10266
10267 return &win->src.active_monitor->mon;
10268 }
10269
10270 #ifdef RGFW_OPENGL
10271 RGFW_bool RGFW_FUNC(RGFW_extensionSupportedPlatform_OpenGL) (const char * extension, size_t len) { return RGFW_extensionSupportedPlatform_EGL(extension, len); }
10272 RGFW_proc RGFW_FUNC(RGFW_getProcAddress_OpenGL) (const char* procname) { return RGFW_getProcAddress_EGL(procname); }
10273
10274
10275 RGFW_bool RGFW_FUNC(RGFW_window_createContextPtr_OpenGL)(RGFW_window* win, RGFW_glContext* ctx, RGFW_glHints* hints) {
10276 RGFW_bool out = RGFW_window_createContextPtr_EGL(win, &ctx->egl, hints);
10277 win->src.gfxType = RGFW_gfxNativeOpenGL;
10278
10279 RGFW_window_swapInterval_OpenGL(win, 0);
10280 return out;
10281 }
10282 void RGFW_FUNC(RGFW_window_deleteContextPtr_OpenGL) (RGFW_window* win, RGFW_glContext* ctx) { RGFW_window_deleteContextPtr_EGL(win, &ctx->egl); win->src.ctx.native = NULL; }
10283
10284 void RGFW_FUNC(RGFW_window_makeCurrentContext_OpenGL) (RGFW_window* win) { RGFW_window_makeCurrentContext_EGL(win); }
10285 void* RGFW_FUNC(RGFW_getCurrentContext_OpenGL) (void) { return RGFW_getCurrentContext_EGL(); }
10286 void RGFW_FUNC(RGFW_window_swapBuffers_OpenGL) (RGFW_window* win) { RGFW_window_swapBuffers_EGL(win); }
10287 void RGFW_FUNC(RGFW_window_swapInterval_OpenGL) (RGFW_window* win, i32 swapInterval) { RGFW_window_swapInterval_EGL(win, swapInterval); }
10288 #endif /* RGFW_OPENGL */
10289
10290 void RGFW_FUNC(RGFW_window_closePlatform)(RGFW_window* win) {
10291 RGFW_ASSERT(win != NULL);
10292 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoWindow, "a window was freed");
10293 #ifdef RGFW_LIBDECOR
10294 if (win->src.decorContext)
10295 libdecor_unref(win->src.decorContext);
10296 #endif
10297
10298 if (win->src.decoration) {
10299 zxdg_toplevel_decoration_v1_destroy(win->src.decoration);
10300 }
10301
10302 if (win->src.xdg_toplevel) {
10303 xdg_toplevel_destroy(win->src.xdg_toplevel);
10304 }
10305
10306 wl_surface_destroy(win->src.custom_cursor_surface);
10307
10308 if (win->src.locked_pointer) {
10309 zwp_locked_pointer_v1_destroy(win->src.locked_pointer);
10310 }
10311
10312 if (win->src.icon) {
10313 xdg_toplevel_icon_v1_destroy(win->src.icon);
10314 }
10315
10316 xdg_surface_destroy(win->src.xdg_surface);
10317 wl_surface_destroy(win->src.surface);
10318 }
10319
10320 #ifdef RGFW_WEBGPU
10321 WGPUSurface RGFW_FUNC(RGFW_window_createSurface_WebGPU) (RGFW_window* window, WGPUInstance instance) {
10322 WGPUSurfaceDescriptor surfaceDesc = {0};
10323 WGPUSurfaceSourceWaylandSurface fromWl = {0};
10324 fromWl.chain.sType = WGPUSType_SurfaceSourceWaylandSurface;
10325 fromWl.display = _RGFW->wl_display;
10326 fromWl.surface = window->src.surface;
10327
10328 surfaceDesc.nextInChain = (WGPUChainedStruct*)&fromWl.chain;
10329 return wgpuInstanceCreateSurface(instance, &surfaceDesc);
10330 }
10331 #endif
10332
10333
10334
10335 #endif /* RGFW_WAYLAND */
10336 /*
10337 End of Wayland defines
10338 */
10339
10340 /*
10341
10342 Start of Windows defines
10343
10344
10345 */
10346
10347 #ifdef RGFW_WINDOWS
10348 #ifndef WIN32_LEAN_AND_MEAN
10349 #define WIN32_LEAN_AND_MEAN
10350 #endif
10351
10352 #ifndef OEMRESOURCE
10353 #define OEMRESOURCE
10354 #endif
10355
10356 #include <windows.h>
10357
10358 #ifndef OCR_NORMAL
10359 #define OCR_NORMAL 32512
10360 #define OCR_IBEAM 32513
10361 #define OCR_WAIT 32514
10362 #define OCR_CROSS 32515
10363 #define OCR_UP 32516
10364 #define OCR_SIZENWSE 32642
10365 #define OCR_SIZENESW 32643
10366 #define OCR_SIZEWE 32644
10367 #define OCR_SIZENS 32645
10368 #define OCR_SIZEALL 32646
10369 #define OCR_NO 32648
10370 #define OCR_HAND 32649
10371 #define OCR_APPSTARTING 32650
10372 #endif
10373
10374 #include <windowsx.h>
10375 #include <shellapi.h>
10376 #include <shellscalingapi.h>
10377 #include <wchar.h>
10378 #include <locale.h>
10379 #include <winuser.h>
10380
10381 #ifndef WM_DPICHANGED
10382 #define WM_DPICHANGED 0x02E0
10383 #endif
10384
10385 RGFWDEF DWORD RGFW_winapi_window_getStyle(RGFW_window* win, RGFW_windowFlags flags);
10386 DWORD RGFW_winapi_window_getStyle(RGFW_window* win, RGFW_windowFlags flags) {
10387 RGFW_UNUSED(win);
10388 DWORD style = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
10389
10390 if ((flags & RGFW_windowFullscreen)) {
10391 style |= WS_POPUP;
10392 } else {
10393 style |= WS_SYSMENU | WS_MINIMIZEBOX;
10394
10395 if (!(flags & RGFW_windowNoBorder)) {
10396 style |= WS_CAPTION;
10397
10398 if (!(flags & RGFW_windowNoResize))
10399 style |= WS_MAXIMIZEBOX | WS_THICKFRAME;
10400 }
10401 else
10402 style |= WS_POPUP;
10403 }
10404
10405 return style;
10406 }
10407
10408 RGFWDEF DWORD RGFW_winapi_window_getExStyle(RGFW_window* win, RGFW_windowFlags flags);
10409 DWORD RGFW_winapi_window_getExStyle(RGFW_window* win, RGFW_windowFlags flags) {
10410 DWORD style = WS_EX_APPWINDOW;
10411 if (flags & RGFW_windowFullscreen || (flags & RGFW_windowFloating || RGFW_window_isFloating(win))) {
10412 style |= WS_EX_TOPMOST;
10413 }
10414
10415 return style;
10416 }
10417
10418 RGFW_bool RGFW_createUTF8FromWideStringWin32(const WCHAR* source, char* out, size_t max);
10419
10420 #define GL_FRONT 0x0404
10421 #define GL_BACK 0x0405
10422 #define GL_LEFT 0x0406
10423 #define GL_RIGHT 0x0407
10424
10425 typedef int (*PFN_wglGetSwapIntervalEXT)(void);
10426 PFN_wglGetSwapIntervalEXT wglGetSwapIntervalEXTSrc = NULL;
10427 #define wglGetSwapIntervalEXT wglGetSwapIntervalEXTSrc
10428
10429 /* these two wgl functions need to be preloaded */
10430 typedef HGLRC (WINAPI *PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC hdc, HGLRC hglrc, const int *attribList);
10431 PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL;
10432
10433 HMODULE RGFW_wgl_dll = NULL;
10434
10435 #ifndef RGFW_NO_LOAD_WGL
10436 typedef HGLRC(WINAPI* PFN_wglCreateContext)(HDC);
10437 typedef BOOL(WINAPI* PFN_wglDeleteContext)(HGLRC);
10438 typedef PROC(WINAPI* PFN_wglGetProcAddress)(LPCSTR);
10439 typedef BOOL(WINAPI* PFN_wglMakeCurrent)(HDC, HGLRC);
10440 typedef HDC(WINAPI* PFN_wglGetCurrentDC)(void);
10441 typedef HGLRC(WINAPI* PFN_wglGetCurrentContext)(void);
10442 typedef BOOL(WINAPI* PFN_wglShareLists)(HGLRC, HGLRC);
10443
10444 PFN_wglCreateContext wglCreateContextSRC;
10445 PFN_wglDeleteContext wglDeleteContextSRC;
10446 PFN_wglGetProcAddress wglGetProcAddressSRC;
10447 PFN_wglMakeCurrent wglMakeCurrentSRC;
10448 PFN_wglGetCurrentDC wglGetCurrentDCSRC;
10449 PFN_wglGetCurrentContext wglGetCurrentContextSRC;
10450 PFN_wglShareLists wglShareListsSRC;
10451
10452 #define wglCreateContext wglCreateContextSRC
10453 #define wglDeleteContext wglDeleteContextSRC
10454 #define wglGetProcAddress wglGetProcAddressSRC
10455 #define wglMakeCurrent wglMakeCurrentSRC
10456 #define wglGetCurrentDC wglGetCurrentDCSRC
10457 #define wglGetCurrentContext wglGetCurrentContextSRC
10458 #define wglShareLists wglShareListsSRC
10459 #endif
10460
10461 void* RGFW_window_getHWND(RGFW_window* win) { return win->src.window; }
10462 void* RGFW_window_getHDC(RGFW_window* win) { return win->src.hdc; }
10463
10464 #ifdef RGFW_OPENGL
10465 RGFWDEF void RGFW_win32_loadOpenGLFuncs(HWND dummyWin);
10466
10467 typedef HRESULT (APIENTRY* PFNWGLCHOOSEPIXELFORMATARBPROC)(HDC hdc, const int* piAttribIList, const FLOAT* pfAttribFList, UINT nMaxFormats, int* piFormats, UINT* nNumFormats);
10468 PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = NULL;
10469
10470 typedef BOOL(APIENTRY* PFNWGLSWAPINTERVALEXTPROC)(int interval);
10471 PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL;
10472 #endif
10473
10474 #ifndef RGFW_NO_DWM
10475 HMODULE RGFW_dwm_dll = NULL;
10476 #ifndef _DWMAPI_H_
10477 typedef struct { DWORD dwFlags; int fEnable; HRGN hRgnBlur; int fTransitionOnMaximized;} DWM_BLURBEHIND;
10478 #endif
10479 typedef HRESULT (WINAPI * PFN_DwmEnableBlurBehindWindow)(HWND, const DWM_BLURBEHIND*);
10480 PFN_DwmEnableBlurBehindWindow DwmEnableBlurBehindWindowSRC = NULL;
10481
10482 typedef HRESULT (WINAPI * PFN_DwmSetWindowAttribute)(HWND, DWORD, LPCVOID, DWORD);
10483 PFN_DwmSetWindowAttribute DwmSetWindowAttributeSRC = NULL;
10484 #endif
10485 void RGFW_win32_makeWindowTransparent(RGFW_window* win);
10486 void RGFW_win32_makeWindowTransparent(RGFW_window* win) {
10487 if (!(win->internal.flags & RGFW_windowTransparent)) return;
10488
10489 #ifndef RGFW_NO_DWM
10490 if (DwmEnableBlurBehindWindowSRC != NULL) {
10491 DWM_BLURBEHIND bb = {0, 0, 0, 0};
10492 bb.dwFlags = 0x1;
10493 bb.fEnable = TRUE;
10494 bb.hRgnBlur = NULL;
10495 DwmEnableBlurBehindWindowSRC(win->src.window, &bb);
10496
10497 } else
10498 #endif
10499 {
10500 SetWindowLong(win->src.window, GWL_EXSTYLE, WS_EX_LAYERED);
10501 SetLayeredWindowAttributes(win->src.window, 0, 128, LWA_ALPHA);
10502 }
10503 }
10504
10505 RGFWDEF RGFW_bool RGFW_win32_getDarkModeState(void);
10506 RGFW_bool RGFW_win32_getDarkModeState(void) {
10507 u32 lightMode = 1;
10508 DWORD len = sizeof(lightMode);
10509
10510 RegGetValueW(
10511 HKEY_CURRENT_USER,
10512 L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
10513 L"AppsUseLightTheme", RRF_RT_REG_DWORD, NULL, &lightMode, &len
10514 );
10515
10516 return (lightMode == 0);
10517 }
10518
10519 RGFWDEF void RGFW_win32_makeWindowDarkMode(RGFW_window* win, RGFW_bool state);
10520 void RGFW_win32_makeWindowDarkMode(RGFW_window* win, RGFW_bool state) {
10521 BOOL value = (state == RGFW_TRUE) ? TRUE : FALSE;
10522 DwmSetWindowAttributeSRC(win->src.window, 20 /* DWMWA_USE_IMMERSIVE_DARK_MODE */, &value, sizeof(value));
10523 }
10524
10525 LRESULT CALLBACK WndProcW(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
10526 LRESULT CALLBACK WndProcW(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
10527 RGFW_window* win = (RGFW_window*)GetPropW(hWnd, L"RGFW");
10528 if (win == NULL) return DefWindowProcW(hWnd, message, wParam, lParam);
10529
10530 static BYTE keyboardState[256];
10531 GetKeyboardState(keyboardState);
10532
10533 RECT frame;
10534 ZeroMemory(&frame, sizeof(frame));
10535 DWORD style = RGFW_winapi_window_getStyle(win, win->internal.flags);
10536 DWORD exStyle = RGFW_winapi_window_getExStyle(win, win->internal.flags);
10537 AdjustWindowRectEx(&frame, style, FALSE, exStyle);
10538
10539 switch (message) {
10540 case WM_DISPLAYCHANGE:
10541 RGFW_pollMonitors();
10542 break;
10543 case WM_CLOSE:
10544 case WM_QUIT:
10545 RGFW_windowQuitCallback(win);
10546 return 0;
10547 case WM_ACTIVATE: {
10548 RGFW_bool inFocus = RGFW_BOOL(LOWORD(wParam) != WA_INACTIVE);
10549 RGFW_focusCallback(win, inFocus);
10550
10551 return DefWindowProcW(hWnd, message, wParam, lParam);
10552 }
10553 case WM_MOVE:
10554 if (win->internal.captureMouse) {
10555 RGFW_window_captureMousePlatform(win, RGFW_TRUE);
10556 }
10557
10558 RGFW_windowMovedCallback(win, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
10559 return DefWindowProcW(hWnd, message, wParam, lParam);
10560 case WM_SIZE: {
10561 if (win->internal.captureMouse) {
10562 RGFW_window_captureMousePlatform(win, RGFW_TRUE);
10563 }
10564
10565 RGFW_windowResizedCallback(win, LOWORD(lParam), HIWORD(lParam));
10566 RGFW_window_checkMode(win);
10567 return DefWindowProcW(hWnd, message, wParam, lParam);
10568 }
10569 case WM_MOUSEACTIVATE: {
10570 if (HIWORD(lParam) == WM_LBUTTONDOWN) {
10571 if (LOWORD(lParam) != HTCLIENT)
10572 win->src.actionFrame = RGFW_TRUE;
10573 }
10574
10575 break;
10576 }
10577 case WM_CAPTURECHANGED: {
10578 if (lParam == 0 && win->src.actionFrame) {
10579 RGFW_window_captureMousePlatform(win, win->internal.captureMouse);
10580 win->src.actionFrame = RGFW_FALSE;
10581 }
10582
10583 break;
10584 }
10585 #ifndef RGFW_NO_DPI
10586 case WM_DPICHANGED: {
10587 const float scaleX = HIWORD(wParam) / (float) 96;
10588 const float scaleY = LOWORD(wParam) / (float) 96;
10589
10590 RGFW_scaleUpdatedCallback(win, scaleX, scaleY);
10591 return DefWindowProcW(hWnd, message, wParam, lParam);
10592 }
10593 #endif
10594 case WM_SIZING: {
10595 if (win->src.aspectRatioW == 0 && win->src.aspectRatioH == 0) {
10596 break;
10597 }
10598
10599 RECT* area = (RECT*)lParam;
10600 i32 edge = (i32)wParam;
10601
10602 double ratio = (double)win->src.aspectRatioW / (double) win->src.aspectRatioH;
10603
10604 if (edge == WMSZ_LEFT || edge == WMSZ_BOTTOMLEFT || edge == WMSZ_RIGHT || edge == WMSZ_BOTTOMRIGHT) {
10605 area->bottom = area->top + (frame.bottom - frame.top) + (i32) (((area->right - area->left) - (frame.right - frame.left)) / ratio);
10606 } else if (edge == WMSZ_TOPLEFT || edge == WMSZ_TOPRIGHT) {
10607 area->top = area->bottom - (frame.bottom - frame.top) - (i32) (((area->right - area->left) - (frame.right - frame.left)) / ratio);
10608 } else if (edge == WMSZ_TOP || edge == WMSZ_BOTTOM) {
10609 area->right = area->left + (frame.right - frame.left) + (i32) (((area->bottom - area->top) - (frame.bottom - frame.top)) * ratio);
10610 }
10611
10612 return TRUE;
10613 }
10614 case WM_GETMINMAXINFO: {
10615 MINMAXINFO* mmi = (MINMAXINFO*) lParam;
10616 RGFW_bool resize = ((win->src.minSizeW == win->src.maxSizeW) && (win->src.minSizeH == win->src.maxSizeH));
10617 RGFW_setBit(&win->internal.flags, RGFW_windowNoResize, resize);
10618
10619 mmi->ptMinTrackSize.x = (LONG)(win->src.minSizeW + (frame.right - frame.left));
10620 mmi->ptMinTrackSize.y = (LONG)(win->src.minSizeH + (frame.bottom - frame.top));
10621 if (win->src.maxSizeW == 0 && win->src.maxSizeH == 0)
10622 return DefWindowProcW(hWnd, message, wParam, lParam);
10623
10624 mmi->ptMaxTrackSize.x = (LONG)(win->src.maxSizeW + (frame.right - frame.left));
10625 mmi->ptMaxTrackSize.y = (LONG)(win->src.maxSizeH + (frame.bottom - frame.top));
10626 return DefWindowProcW(hWnd, message, wParam, lParam);
10627 }
10628 case WM_PAINT: {
10629 PAINTSTRUCT ps;
10630 BeginPaint(hWnd, &ps);
10631 RGFW_windowRefreshCallback(win);
10632 EndPaint(hWnd, &ps);
10633
10634 return DefWindowProcW(hWnd, message, wParam, lParam);
10635 }
10636 #if(_WIN32_WINNT >= 0x0600)
10637 case WM_DWMCOMPOSITIONCHANGED:
10638 case WM_DWMCOLORIZATIONCOLORCHANGED:
10639 RGFW_win32_makeWindowTransparent(win);
10640 break;
10641 #endif
10642
10643 case WM_ENTERSIZEMOVE: {
10644 if (win->src.actionFrame)
10645 RGFW_window_captureMousePlatform(win, win->internal.captureMouse);
10646
10647 #ifdef RGFW_ADVANCED_SMOOTH_RESIZE
10648 SetTimer(win->src.window, 1, USER_TIMER_MINIMUM, NULL); break;
10649 #endif
10650 break;
10651 }
10652 case WM_EXITSIZEMOVE: {
10653 if (win->src.actionFrame)
10654 RGFW_window_captureMousePlatform(win, win->internal.captureMouse);
10655
10656 #ifdef RGFW_ADVANCED_SMOOTH_RESIZE
10657 KillTimer(win->src.window, 1); break;
10658 #endif
10659 break;
10660 }
10661 case WM_TIMER:
10662 RGFW_windowRefreshCallback(win);
10663 break;
10664
10665 case WM_NCLBUTTONDOWN: {
10666 /* workaround for half-second pause when starting to move window
10667 see: https://gamedev.net/forums/topic/672094-keeping-things-moving-during-win32-moveresize-events/5254386/
10668 */
10669 POINT point = { 0, 0 };
10670 if (SendMessage(win->src.window, WM_NCHITTEST, wParam, lParam) != HTCAPTION || GetCursorPos(&point) == FALSE)
10671 break;
10672
10673 ScreenToClient(win->src.window, &point);
10674 PostMessage(win->src.window, WM_MOUSEMOVE, 0, (u32)(point.x)|((u32)(point.y) << 16));
10675 break;
10676 }
10677 case WM_MOUSELEAVE:
10678 RGFW_mouseNotifyCallback(win, win->internal.lastMouseX, win->internal.lastMouseY, RGFW_FALSE);
10679 break;
10680
10681 case WM_CHAR:
10682 case WM_SYSCHAR: {
10683 if (wParam >= 0xd800 && wParam <= 0xdbff)
10684 win->src.highSurrogate = (WCHAR) wParam;
10685 else {
10686 u32 codepoint = 0;
10687
10688 if (wParam >= 0xdc00 && wParam <= 0xdfff) {
10689 if (win->src.highSurrogate) {
10690 codepoint += (u32)((win->src.highSurrogate - 0xd800) << 10);
10691 codepoint += (u32)((WCHAR) wParam - 0xdc00);
10692 codepoint += 0x10000;
10693 }
10694 }
10695 else
10696 codepoint = (WCHAR) wParam;
10697
10698 win->src.highSurrogate = 0;
10699 RGFW_keyCharCallback(win, (u32)codepoint);
10700 }
10701
10702 return 0;
10703 }
10704
10705 case WM_UNICHAR: {
10706 if (wParam == UNICODE_NOCHAR) {
10707 return TRUE;
10708 }
10709
10710 RGFW_keyCharCallback(win, (u32)wParam);
10711 return 0;
10712 }
10713 case WM_SYSKEYUP: case WM_KEYUP: {
10714 if (!(win->internal.enabledEvents & RGFW_keyReleasedFlag)) return DefWindowProcW(hWnd, message, wParam, lParam);
10715 i32 scancode = (HIWORD(lParam) & (KF_EXTENDED | 0xff));
10716 if (scancode == 0)
10717 scancode = (i32)MapVirtualKeyW((UINT)wParam, MAPVK_VK_TO_VSC);
10718
10719 switch (scancode) {
10720 case 0x54: scancode = 0x137; break; /* Alt+PrtS */
10721 case 0x146: scancode = 0x45; break; /* Ctrl+Pause */
10722 case 0x136: scancode = 0x36; break; /* CJK IME sets the extended bit for right Shift */
10723 default: break;
10724 }
10725
10726 RGFW_key value = (u8)RGFW_apiKeyToRGFW((u32) scancode);
10727
10728 if (wParam == VK_CONTROL) {
10729 if (HIWORD(lParam) & KF_EXTENDED)
10730 value = RGFW_controlR;
10731 else value = RGFW_controlL;
10732 }
10733
10734 RGFW_bool repeat = ((lParam & 0x40000000) != 0) || RGFW_window_isKeyDown(win, value);
10735
10736 RGFW_updateKeyMods(win, (GetKeyState(VK_CAPITAL) & 0x0001), (GetKeyState(VK_NUMLOCK) & 0x0001), (GetKeyState(VK_SCROLL) & 0x0001));
10737 RGFW_keyCallback(win, value, win->internal.mod, repeat, RGFW_FALSE);
10738 break;
10739 }
10740 case WM_SYSKEYDOWN: case WM_KEYDOWN: {
10741 if (!(win->internal.enabledEvents & RGFW_keyPressedFlag)) return DefWindowProcW(hWnd, message, wParam, lParam);
10742 i32 scancode = (HIWORD(lParam) & (KF_EXTENDED | 0xff));
10743 if (scancode == 0)
10744 scancode = (i32)MapVirtualKeyW((u32)wParam, MAPVK_VK_TO_VSC);
10745
10746 switch (scancode) {
10747 case 0x54: scancode = 0x137; break; /* Alt+PrtS */
10748 case 0x146: scancode = 0x45; break; /* Ctrl+Pause */
10749 case 0x136: scancode = 0x36; break; /* CJK IME sets the extended bit for right Shift */
10750 default: break;
10751 }
10752
10753 RGFW_key value = (u8)RGFW_apiKeyToRGFW((u32) scancode);
10754 if (wParam == VK_CONTROL) {
10755 if (HIWORD(lParam) & KF_EXTENDED)
10756 value = RGFW_controlR;
10757 else value = RGFW_controlL;
10758 }
10759
10760 RGFW_bool repeat = ((lParam & 0x40000000) != 0) || RGFW_window_isKeyDown(win, value);
10761
10762 RGFW_updateKeyMods(win, (GetKeyState(VK_CAPITAL) & 0x0001), (GetKeyState(VK_NUMLOCK) & 0x0001), (GetKeyState(VK_SCROLL) & 0x0001));
10763 RGFW_keyCallback(win, value, win->internal.mod, repeat, 1);
10764 break;
10765 }
10766 case WM_MOUSEMOVE: {
10767 if (win->internal.mouseInside == RGFW_FALSE) {
10768 RGFW_mouseNotifyCallback(win, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), RGFW_TRUE);
10769 }
10770
10771 if ((win->internal.rawMouse) || _RGFW->rawMouse) {
10772 return DefWindowProcW(hWnd, message, wParam, lParam);
10773 }
10774
10775 RGFW_mousePosCallback(win, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), _RGFW->vectorX, _RGFW->vectorY);
10776 break;
10777 }
10778 case WM_INPUT: {
10779 if (!(win->internal.rawMouse || _RGFW->rawMouse)) return DefWindowProcW(hWnd, message, wParam, lParam);
10780 unsigned size = sizeof(RAWINPUT);
10781 static RAWINPUT raw;
10782
10783 GetRawInputData((HRAWINPUT)lParam, RID_INPUT, &raw, &size, sizeof(RAWINPUTHEADER));
10784
10785 if (raw.header.dwType != RIM_TYPEMOUSE || (raw.data.mouse.lLastX == 0 && raw.data.mouse.lLastY == 0) )
10786 break;
10787
10788 float vecX = 0.0f;
10789 float vecY = 0.0f;
10790
10791 if (raw.data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE) {
10792 POINT pos = {0, 0};
10793 int width, height;
10794
10795 if (raw.data.mouse.usFlags & MOUSE_VIRTUAL_DESKTOP) {
10796 pos.x += GetSystemMetrics(SM_XVIRTUALSCREEN);
10797 pos.y += GetSystemMetrics(SM_YVIRTUALSCREEN);
10798 width = GetSystemMetrics(SM_CXVIRTUALSCREEN);
10799 height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
10800 }
10801 else {
10802 width = GetSystemMetrics(SM_CXSCREEN);
10803 height = GetSystemMetrics(SM_CYSCREEN);
10804 }
10805
10806 pos.x += (int) (((float)raw.data.mouse.lLastX / 65535.f) * (float)width);
10807 pos.y += (int) (((float)raw.data.mouse.lLastY / 65535.f) * (float)height);
10808 ScreenToClient(win->src.window, &pos);
10809
10810 vecX = (float)(pos.x - win->internal.lastMouseX);
10811 vecY = (float)(pos.y - win->internal.lastMouseY);
10812 } else {
10813 vecX = (float)(raw.data.mouse.lLastX);
10814 vecY = (float)(raw.data.mouse.lLastY);
10815 }
10816
10817 RGFW_mousePosCallback(win, win->internal.lastMouseX, win->internal.lastMouseY, vecX, vecY);
10818 break;
10819 }
10820 case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: case WM_XBUTTONDOWN: {
10821 RGFW_mouseButton value = 0;
10822 if (message == WM_XBUTTONDOWN)
10823 value = RGFW_mouseMisc1 + (GET_XBUTTON_WPARAM(wParam) == XBUTTON2);
10824 else value = (message == WM_LBUTTONDOWN) ? (u8)RGFW_mouseLeft :
10825 (message == WM_RBUTTONDOWN) ? (u8)RGFW_mouseRight : (u8)RGFW_mouseMiddle;
10826
10827 RGFW_mouseButtonCallback(win, value, 1);
10828 break;
10829 }
10830 case WM_LBUTTONUP: case WM_RBUTTONUP: case WM_MBUTTONUP: case WM_XBUTTONUP: {
10831 RGFW_mouseButton value = 0;
10832 if (message == WM_XBUTTONUP)
10833 value = RGFW_mouseMisc1 + (GET_XBUTTON_WPARAM(wParam) == XBUTTON2);
10834 else value = (message == WM_LBUTTONUP) ? (u8)RGFW_mouseLeft :
10835 (message == WM_RBUTTONUP) ? (u8)RGFW_mouseRight : (u8)RGFW_mouseMiddle;
10836
10837 RGFW_mouseButtonCallback(win, value, 0);
10838 break;
10839 }
10840 case WM_MOUSEWHEEL: {
10841 float scrollY = (float)((i16) HIWORD(wParam) / (double) WHEEL_DELTA);
10842 RGFW_mouseScrollCallback(win, 0.0f, scrollY);
10843 break;
10844 }
10845 case 0x020E: {/* WM_MOUSEHWHEEL */
10846 float scrollX = -(float)((i16) HIWORD(wParam) / (double) WHEEL_DELTA);
10847 RGFW_mouseScrollCallback(win, scrollX, 0.0f);
10848 break;
10849 }
10850 case WM_DROPFILES: {
10851 HDROP drop = (HDROP) wParam;
10852 POINT pt;
10853
10854 /* Move the mouse to the position of the drop */
10855 DragQueryPoint(drop, &pt);
10856 RGFW_dataDragCallback(win, pt.x, pt.y);
10857
10858 if (!(win->internal.enabledEvents & RGFW_dataDrop)) return DefWindowProcW(hWnd, message, wParam, lParam);
10859 char** files = _RGFW->files;
10860 size_t count = DragQueryFileW(drop, 0xffffffff, NULL, 0);
10861
10862 u32 i;
10863 for (i = 0; i < count; i++) {
10864 UINT length = DragQueryFileW(drop, i, NULL, 0);
10865 if (length == 0)
10866 continue;
10867
10868 WCHAR buffer[RGFW_MAX_PATH * 2];
10869 if (length > (RGFW_MAX_PATH * 2) - 1)
10870 length = RGFW_MAX_PATH * 2;
10871
10872 DragQueryFileW(drop, i, buffer, length + 1);
10873
10874 RGFW_createUTF8FromWideStringWin32(buffer, files[i], RGFW_MAX_PATH);
10875
10876 files[i][RGFW_MAX_PATH - 1] = '\0';
10877 }
10878
10879 DragFinish(drop);
10880
10881 RGFW_dataDropCallback(win, files, count);
10882 break;
10883 }
10884 default: break;
10885 }
10886
10887 return DefWindowProcW(hWnd, message, wParam, lParam);
10888 }
10889
10890 #ifndef RGFW_NO_DPI
10891 HMODULE RGFW_Shcore_dll = NULL;
10892 typedef HRESULT (WINAPI *PFN_GetDpiForMonitor)(HMONITOR,MONITOR_DPI_TYPE,UINT*,UINT*);
10893 PFN_GetDpiForMonitor GetDpiForMonitorSRC = NULL;
10894 #define GetDpiForMonitor GetDpiForMonitorSRC
10895 #endif
10896
10897 #if !defined(RGFW_NO_LOAD_WINMM) && !defined(RGFW_NO_WINMM)
10898 HMODULE RGFW_winmm_dll = NULL;
10899 typedef u32 (WINAPI * PFN_timeBeginPeriod)(u32);
10900 typedef PFN_timeBeginPeriod PFN_timeEndPeriod;
10901 PFN_timeBeginPeriod timeBeginPeriodSRC, timeEndPeriodSRC;
10902 #define timeBeginPeriod timeBeginPeriodSRC
10903 #define timeEndPeriod timeEndPeriodSRC
10904 #elif !defined(RGFW_NO_WINMM)
10905 __declspec(dllimport) u32 __stdcall timeBeginPeriod(u32 uPeriod);
10906 __declspec(dllimport) u32 __stdcall timeEndPeriod(u32 uPeriod);
10907 #endif
10908 #define RGFW_PROC_DEF(proc, name) if (name##SRC == NULL && proc != NULL) { \
10909 name##SRC = (PFN_##name)(RGFW_proc)GetProcAddress((proc), (#name)); \
10910 RGFW_ASSERT(name##SRC != NULL); \
10911 }
10912
10913 RGFW_format RGFW_nativeFormat(void) { return RGFW_formatBGRA8; }
10914
10915 RGFW_bool RGFW_createSurfacePtr(u8* data, i32 w, i32 h, RGFW_format format, RGFW_surface* surface) {
10916 RGFW_ASSERT(surface != NULL);
10917 surface->data = data;
10918 surface->w = w;
10919 surface->h = h;
10920 surface->format = format;
10921
10922 BITMAPV5HEADER bi;
10923 ZeroMemory(&bi, sizeof(bi));
10924 bi.bV5Size = sizeof(bi);
10925 bi.bV5Width = (i32)w;
10926 bi.bV5Height = -((LONG) h);
10927 bi.bV5Planes = 1;
10928 bi.bV5BitCount = (format >= RGFW_formatRGBA8) ? 32 : 24;
10929 bi.bV5Compression = BI_RGB;
10930
10931 surface->native.bitmap = CreateDIBSection(_RGFW->root->src.hdc,
10932 (BITMAPINFO*) &bi, DIB_RGB_COLORS,
10933 (void**) &surface->native.bitmapBits,
10934 NULL, (DWORD) 0);
10935
10936 surface->native.format = (format >= RGFW_formatRGBA8) ? RGFW_formatBGRA8 : RGFW_formatBGR8;
10937
10938 if (surface->native.bitmap == NULL) {
10939 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errBuffer, "Failed to create DIB section.");
10940 return RGFW_FALSE;
10941 }
10942
10943 surface->native.hdcMem = CreateCompatibleDC(_RGFW->root->src.hdc);
10944 SelectObject(surface->native.hdcMem, surface->native.bitmap);
10945
10946 return RGFW_TRUE;
10947 }
10948
10949 void RGFW_surface_freePtr(RGFW_surface* surface) {
10950 RGFW_ASSERT(surface != NULL);
10951
10952 DeleteDC(surface->native.hdcMem);
10953 DeleteObject(surface->native.bitmap);
10954 }
10955
10956 void RGFW_window_blitSurface(RGFW_window* win, RGFW_surface* surface) {
10957 RGFW_copyImageData(surface->native.bitmapBits, surface->w, RGFW_MIN(win->h, surface->h), surface->native.format, surface->data, surface->format, surface->convertFunc);
10958 BitBlt(win->src.hdc, 0, 0, RGFW_MIN(win->w, surface->w), RGFW_MIN(win->h, surface->h), surface->native.hdcMem, 0, 0, SRCCOPY);
10959 }
10960
10961 void RGFW_window_setRawMouseModePlatform(RGFW_window* win, RGFW_bool state) {
10962 RGFW_UNUSED(win);
10963 RAWINPUTDEVICE id = { 0x01, 0x02, 0, win->src.window };
10964 id.dwFlags = (state == RGFW_TRUE) ? 0 : RIDEV_REMOVE;
10965
10966 RegisterRawInputDevices(&id, 1, sizeof(id));
10967 }
10968
10969 void RGFW_window_captureMousePlatform(RGFW_window* win, RGFW_bool state) {
10970 if (state == RGFW_FALSE) {
10971 ClipCursor(NULL);
10972 return;
10973 }
10974
10975 RECT clipRect;
10976 GetClientRect(win->src.window, &clipRect);
10977 ClientToScreen(win->src.window, (POINT*) &clipRect.left);
10978 ClientToScreen(win->src.window, (POINT*) &clipRect.right);
10979 ClipCursor(&clipRect);
10980 }
10981
10982 #define RGFW_LOAD_LIBRARY(x, lib) if (x == NULL) { x = LoadLibraryA(lib); RGFW_ASSERT(x != NULL); }
10983
10984 #ifdef RGFW_DIRECTX
10985 int RGFW_window_createSwapChain_DirectX(RGFW_window* win, IDXGIFactory* pFactory, IUnknown* pDevice, IDXGISwapChain** swapchain) {
10986 RGFW_ASSERT(win && pFactory && pDevice && swapchain);
10987
10988 static DXGI_SWAP_CHAIN_DESC swapChainDesc;
10989 RGFW_MEMSET(&swapChainDesc, 0, sizeof(swapChainDesc));
10990 swapChainDesc.BufferCount = 2;
10991 swapChainDesc.BufferDesc.Width = win->w;
10992 swapChainDesc.BufferDesc.Height = win->h;
10993 swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
10994 swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
10995 swapChainDesc.OutputWindow = (HWND)win->src.window;
10996 swapChainDesc.SampleDesc.Count = 1;
10997 swapChainDesc.SampleDesc.Quality = 0;
10998 swapChainDesc.Windowed = TRUE;
10999 swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
11000
11001 HRESULT hr = pFactory->lpVtbl->CreateSwapChain(pFactory, (IUnknown*)pDevice, &swapChainDesc, swapchain);
11002 if (FAILED(hr)) {
11003 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errDirectXContext, "Failed to create DirectX swap chain!");
11004 return -2;
11005 }
11006
11007 return 0;
11008 }
11009 #endif
11010
11011 /* we're doing it with magic numbers because some keys are missing */
11012 void RGFW_initKeycodesPlatform(void) {
11013 _RGFW->keycodes[0x00B] = RGFW_0;
11014 _RGFW->keycodes[0x002] = RGFW_1;
11015 _RGFW->keycodes[0x003] = RGFW_2;
11016 _RGFW->keycodes[0x004] = RGFW_3;
11017 _RGFW->keycodes[0x005] = RGFW_4;
11018 _RGFW->keycodes[0x006] = RGFW_5;
11019 _RGFW->keycodes[0x007] = RGFW_6;
11020 _RGFW->keycodes[0x008] = RGFW_7;
11021 _RGFW->keycodes[0x009] = RGFW_8;
11022 _RGFW->keycodes[0x00A] = RGFW_9;
11023 _RGFW->keycodes[0x01E] = RGFW_a;
11024 _RGFW->keycodes[0x030] = RGFW_b;
11025 _RGFW->keycodes[0x02E] = RGFW_c;
11026 _RGFW->keycodes[0x020] = RGFW_d;
11027 _RGFW->keycodes[0x012] = RGFW_e;
11028 _RGFW->keycodes[0x021] = RGFW_f;
11029 _RGFW->keycodes[0x022] = RGFW_g;
11030 _RGFW->keycodes[0x023] = RGFW_h;
11031 _RGFW->keycodes[0x017] = RGFW_i;
11032 _RGFW->keycodes[0x024] = RGFW_j;
11033 _RGFW->keycodes[0x025] = RGFW_k;
11034 _RGFW->keycodes[0x026] = RGFW_l;
11035 _RGFW->keycodes[0x032] = RGFW_m;
11036 _RGFW->keycodes[0x031] = RGFW_n;
11037 _RGFW->keycodes[0x018] = RGFW_o;
11038 _RGFW->keycodes[0x019] = RGFW_p;
11039 _RGFW->keycodes[0x010] = RGFW_q;
11040 _RGFW->keycodes[0x013] = RGFW_r;
11041 _RGFW->keycodes[0x01F] = RGFW_s;
11042 _RGFW->keycodes[0x014] = RGFW_t;
11043 _RGFW->keycodes[0x016] = RGFW_u;
11044 _RGFW->keycodes[0x02F] = RGFW_v;
11045 _RGFW->keycodes[0x011] = RGFW_w;
11046 _RGFW->keycodes[0x02D] = RGFW_x;
11047 _RGFW->keycodes[0x015] = RGFW_y;
11048 _RGFW->keycodes[0x02C] = RGFW_z;
11049 _RGFW->keycodes[0x028] = RGFW_apostrophe;
11050 _RGFW->keycodes[0x02B] = RGFW_backSlash;
11051 _RGFW->keycodes[0x033] = RGFW_comma;
11052 _RGFW->keycodes[0x00D] = RGFW_equals;
11053 _RGFW->keycodes[0x029] = RGFW_backtick;
11054 _RGFW->keycodes[0x01A] = RGFW_bracket;
11055 _RGFW->keycodes[0x00C] = RGFW_minus;
11056 _RGFW->keycodes[0x034] = RGFW_period;
11057 _RGFW->keycodes[0x01B] = RGFW_closeBracket;
11058 _RGFW->keycodes[0x027] = RGFW_semicolon;
11059 _RGFW->keycodes[0x035] = RGFW_slash;
11060 _RGFW->keycodes[0x056] = RGFW_world2;
11061 _RGFW->keycodes[0x00E] = RGFW_backSpace;
11062 _RGFW->keycodes[0x153] = RGFW_delete;
11063 _RGFW->keycodes[0x14F] = RGFW_end;
11064 _RGFW->keycodes[0x01C] = RGFW_enter;
11065 _RGFW->keycodes[0x001] = RGFW_escape;
11066 _RGFW->keycodes[0x147] = RGFW_home;
11067 _RGFW->keycodes[0x152] = RGFW_insert;
11068 _RGFW->keycodes[0x15D] = RGFW_menu;
11069 _RGFW->keycodes[0x151] = RGFW_pageDown;
11070 _RGFW->keycodes[0x149] = RGFW_pageUp;
11071 _RGFW->keycodes[0x045] = RGFW_pause;
11072 _RGFW->keycodes[0x039] = RGFW_space;
11073 _RGFW->keycodes[0x00F] = RGFW_tab;
11074 _RGFW->keycodes[0x03A] = RGFW_capsLock;
11075 _RGFW->keycodes[0x145] = RGFW_numLock;
11076 _RGFW->keycodes[0x046] = RGFW_scrollLock;
11077 _RGFW->keycodes[0x03B] = RGFW_F1;
11078 _RGFW->keycodes[0x03C] = RGFW_F2;
11079 _RGFW->keycodes[0x03D] = RGFW_F3;
11080 _RGFW->keycodes[0x03E] = RGFW_F4;
11081 _RGFW->keycodes[0x03F] = RGFW_F5;
11082 _RGFW->keycodes[0x040] = RGFW_F6;
11083 _RGFW->keycodes[0x041] = RGFW_F7;
11084 _RGFW->keycodes[0x042] = RGFW_F8;
11085 _RGFW->keycodes[0x043] = RGFW_F9;
11086 _RGFW->keycodes[0x044] = RGFW_F10;
11087 _RGFW->keycodes[0x057] = RGFW_F11;
11088 _RGFW->keycodes[0x058] = RGFW_F12;
11089 _RGFW->keycodes[0x064] = RGFW_F13;
11090 _RGFW->keycodes[0x065] = RGFW_F14;
11091 _RGFW->keycodes[0x066] = RGFW_F15;
11092 _RGFW->keycodes[0x067] = RGFW_F16;
11093 _RGFW->keycodes[0x068] = RGFW_F17;
11094 _RGFW->keycodes[0x069] = RGFW_F18;
11095 _RGFW->keycodes[0x06A] = RGFW_F19;
11096 _RGFW->keycodes[0x06B] = RGFW_F20;
11097 _RGFW->keycodes[0x06C] = RGFW_F21;
11098 _RGFW->keycodes[0x06D] = RGFW_F22;
11099 _RGFW->keycodes[0x06E] = RGFW_F23;
11100 _RGFW->keycodes[0x076] = RGFW_F24;
11101 _RGFW->keycodes[0x038] = RGFW_altL;
11102 _RGFW->keycodes[0x01D] = RGFW_controlL;
11103 _RGFW->keycodes[0x02A] = RGFW_shiftL;
11104 _RGFW->keycodes[0x15B] = RGFW_superL;
11105 _RGFW->keycodes[0x137] = RGFW_printScreen;
11106 _RGFW->keycodes[0x138] = RGFW_altR;
11107 _RGFW->keycodes[0x11D] = RGFW_controlR;
11108 _RGFW->keycodes[0x036] = RGFW_shiftR;
11109 _RGFW->keycodes[0x15C] = RGFW_superR;
11110 _RGFW->keycodes[0x150] = RGFW_down;
11111 _RGFW->keycodes[0x14B] = RGFW_left;
11112 _RGFW->keycodes[0x14D] = RGFW_right;
11113 _RGFW->keycodes[0x148] = RGFW_up;
11114 _RGFW->keycodes[0x052] = RGFW_kp0;
11115 _RGFW->keycodes[0x04F] = RGFW_kp1;
11116 _RGFW->keycodes[0x050] = RGFW_kp2;
11117 _RGFW->keycodes[0x051] = RGFW_kp3;
11118 _RGFW->keycodes[0x04B] = RGFW_kp4;
11119 _RGFW->keycodes[0x04C] = RGFW_kp5;
11120 _RGFW->keycodes[0x04D] = RGFW_kp6;
11121 _RGFW->keycodes[0x047] = RGFW_kp7;
11122 _RGFW->keycodes[0x048] = RGFW_kp8;
11123 _RGFW->keycodes[0x049] = RGFW_kp9;
11124 _RGFW->keycodes[0x04E] = RGFW_kpPlus;
11125 _RGFW->keycodes[0x053] = RGFW_kpPeriod;
11126 _RGFW->keycodes[0x135] = RGFW_kpSlash;
11127 _RGFW->keycodes[0x11C] = RGFW_kpReturn;
11128 _RGFW->keycodes[0x059] = RGFW_kpEqual;
11129 _RGFW->keycodes[0x037] = RGFW_kpMultiply;
11130 _RGFW->keycodes[0x04A] = RGFW_kpMinus;
11131 }
11132
11133
11134 i32 RGFW_initPlatform(void) {
11135 #ifndef RGFW_NO_DPI
11136 #if (_WIN32_WINNT >= 0x0600)
11137 SetProcessDPIAware();
11138 #endif
11139 #endif
11140
11141 #ifndef RGFW_NO_WINMM
11142 #ifndef RGFW_NO_LOAD_WINMM
11143 RGFW_LOAD_LIBRARY(RGFW_winmm_dll, "winmm.dll");
11144 RGFW_PROC_DEF(RGFW_winmm_dll, timeBeginPeriod);
11145 RGFW_PROC_DEF(RGFW_winmm_dll, timeEndPeriod);
11146 #endif
11147 timeBeginPeriod(1);
11148 #endif
11149
11150 #ifndef RGFW_NO_DWM
11151 RGFW_LOAD_LIBRARY(RGFW_dwm_dll, "dwmapi.dll");
11152 RGFW_PROC_DEF(RGFW_dwm_dll, DwmEnableBlurBehindWindow);
11153 RGFW_PROC_DEF(RGFW_dwm_dll, DwmSetWindowAttribute);
11154 #endif
11155
11156 RGFW_LOAD_LIBRARY(RGFW_wgl_dll, "opengl32.dll");
11157 #ifndef RGFW_NO_LOAD_WGL
11158 RGFW_PROC_DEF(RGFW_wgl_dll, wglCreateContext);
11159 RGFW_PROC_DEF(RGFW_wgl_dll, wglDeleteContext);
11160 RGFW_PROC_DEF(RGFW_wgl_dll, wglGetProcAddress);
11161 RGFW_PROC_DEF(RGFW_wgl_dll, wglMakeCurrent);
11162 RGFW_PROC_DEF(RGFW_wgl_dll, wglGetCurrentDC);
11163 RGFW_PROC_DEF(RGFW_wgl_dll, wglGetCurrentContext);
11164 RGFW_PROC_DEF(RGFW_wgl_dll, wglShareLists);
11165 #endif
11166
11167 u8 RGFW_blk[] = { 0, 0, 0, 0 };
11168 _RGFW->hiddenMouse = RGFW_loadMouse(RGFW_blk, 1, 1, RGFW_formatRGBA8);
11169 return 1;
11170 }
11171
11172 RGFW_window* RGFW_createWindowPlatform(const char* name, RGFW_windowFlags flags, RGFW_window* win) {
11173 if (name[0] == 0) name = (char*) " ";
11174 win->src.hIconSmall = win->src.hIconBig = NULL;
11175 win->src.maxSizeW = 0;
11176 win->src.maxSizeH = 0;
11177 win->src.minSizeW = 0;
11178 win->src.minSizeH = 0;
11179 win->src.aspectRatioW = 0;
11180 win->src.aspectRatioH = 0;
11181
11182 HINSTANCE inh = GetModuleHandleA(NULL);
11183
11184 #ifndef __cplusplus
11185 WNDCLASSW Class = {0}; /*!< Setup the Window class. */
11186 #else
11187 WNDCLASSW Class = {};
11188 #endif
11189
11190 if (_RGFW->className == NULL)
11191 _RGFW->className = (char*)name;
11192
11193 wchar_t wide_class[256];
11194 MultiByteToWideChar(CP_UTF8, 0, _RGFW->className, -1, wide_class, 255);
11195
11196 Class.lpszClassName = wide_class;
11197 Class.hInstance = inh;
11198 Class.hCursor = LoadCursor(NULL, IDC_ARROW);
11199 Class.lpfnWndProc = WndProcW;
11200 Class.cbClsExtra = sizeof(RGFW_window*);
11201
11202 Class.hIcon = (HICON)LoadImageA(GetModuleHandleW(NULL), "RGFW_ICON", IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_SHARED);
11203 if (Class.hIcon == NULL)
11204 Class.hIcon = (HICON)LoadImageA(NULL, (LPCSTR)IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_SHARED);
11205
11206 RegisterClassW(&Class);
11207
11208 DWORD window_style = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
11209
11210 RECT windowRect, clientRect;
11211
11212 if (!(flags & RGFW_windowNoBorder)) {
11213 window_style |= WS_CAPTION | WS_SYSMENU | WS_BORDER | WS_MINIMIZEBOX;
11214
11215 if (!(flags & RGFW_windowNoResize))
11216 window_style |= WS_SIZEBOX | WS_MAXIMIZEBOX;
11217 } else
11218 window_style |= WS_POPUP | WS_VISIBLE | WS_SYSMENU;
11219
11220 wchar_t wide_name[256];
11221 MultiByteToWideChar(CP_UTF8, 0, name, -1, wide_name, 255);
11222 HWND dummyWin = CreateWindowW(Class.lpszClassName, (wchar_t*)wide_name, window_style, win->x, win->y, win->w, win->h, 0, 0, inh, 0);
11223
11224 GetWindowRect(dummyWin, &windowRect);
11225 GetClientRect(dummyWin, &clientRect);
11226
11227 #ifdef RGFW_OPENGL
11228 RGFW_win32_loadOpenGLFuncs(dummyWin);
11229 #endif
11230
11231 DestroyWindow(dummyWin);
11232
11233 RECT rect = { 0, 0, win->w, win->h};
11234 DWORD style = RGFW_winapi_window_getStyle(win, flags);
11235 DWORD exStyle = RGFW_winapi_window_getExStyle(win, flags);
11236 AdjustWindowRectEx(&rect, style, FALSE, exStyle);
11237
11238 win->src.window = CreateWindowW(Class.lpszClassName, (wchar_t*)wide_name, window_style, win->x + rect.left, win->y + rect.top, rect.right - rect.left, rect.bottom - rect.top, 0, 0, inh, 0);
11239 SetPropW(win->src.window, L"RGFW", win);
11240 RGFW_window_resize(win, win->w, win->h); /* so WM_GETMINMAXINFO gets called again */
11241
11242 if (flags & RGFW_windowAllowDND) {
11243 win->internal.flags |= RGFW_windowAllowDND;
11244 RGFW_window_setDND(win, 1);
11245 }
11246 win->src.hdc = GetDC(win->src.window);
11247
11248 RGFW_win32_makeWindowDarkMode(win, RGFW_win32_getDarkModeState());
11249 RGFW_win32_makeWindowTransparent(win);
11250 return win;
11251 }
11252
11253 void RGFW_window_setBorder(RGFW_window* win, RGFW_bool border) {
11254 RGFW_setBit(&win->internal.flags, RGFW_windowNoBorder, !border);
11255 LONG style = GetWindowLong(win->src.window, GWL_STYLE);
11256
11257 if (border == 0) {
11258 SetWindowLong(win->src.window, GWL_STYLE, style & ~WS_OVERLAPPEDWINDOW);
11259 SetWindowPos(
11260 win->src.window, HWND_TOP, 0, 0, 0, 0,
11261 SWP_NOZORDER | SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE
11262 );
11263 }
11264 else {
11265 if (win->internal.flags & RGFW_windowNoResize) style &= ~WS_MAXIMIZEBOX;
11266 SetWindowLong(win->src.window, GWL_STYLE, style | WS_OVERLAPPEDWINDOW);
11267 SetWindowPos(
11268 win->src.window, HWND_TOP, 0, 0, 0, 0,
11269 SWP_NOZORDER | SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE
11270 );
11271 }
11272 }
11273
11274 void RGFW_window_setDND(RGFW_window* win, RGFW_bool allow) {
11275 RGFW_setBit(&win->internal.flags, RGFW_windowAllowDND, allow);
11276 DragAcceptFiles(win->src.window, allow);
11277 }
11278
11279 RGFW_bool RGFW_getGlobalMouse(i32* x, i32* y) {
11280 POINT p;
11281 GetCursorPos(&p);
11282 if (x) *x = p.x;
11283 if (y) *y = p.y;
11284 return RGFW_TRUE;
11285 }
11286
11287 void RGFW_window_setAspectRatio(RGFW_window* win, i32 w, i32 h) {
11288 RGFW_ASSERT(win != NULL);
11289 win->src.aspectRatioW = w;
11290 win->src.aspectRatioH = h;
11291 }
11292
11293 void RGFW_window_setMinSize(RGFW_window* win, i32 w, i32 h) {
11294 RGFW_ASSERT(win != NULL);
11295 win->src.minSizeW = w;
11296 win->src.minSizeH = h;
11297 }
11298
11299 void RGFW_window_setMaxSize(RGFW_window* win, i32 w, i32 h) {
11300 RGFW_ASSERT(win != NULL);
11301 win->src.maxSizeW = w;
11302 win->src.maxSizeH = h;
11303 }
11304
11305 void RGFW_window_focus(RGFW_window* win) {
11306 RGFW_ASSERT(win);
11307 SetForegroundWindow(win->src.window);
11308 SetFocus(win->src.window);
11309 }
11310
11311 void RGFW_window_raise(RGFW_window* win) {
11312 RGFW_ASSERT(win);
11313 BringWindowToTop(win->src.window);
11314 SetWindowPos(win->src.window, HWND_TOP, win->x, win->y, win->w, win->h, SWP_NOSIZE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
11315 }
11316
11317 void RGFW_window_setFullscreen(RGFW_window* win, RGFW_bool fullscreen) {
11318 RGFW_ASSERT(win != NULL);
11319
11320 if (fullscreen == RGFW_FALSE) {
11321 RGFW_window_setBorder(win, 1);
11322
11323 RECT rect = { 0, 0, win->internal.oldW, win->internal.oldH};
11324 DWORD style = RGFW_winapi_window_getStyle(win, win->internal.flags);
11325 DWORD exStyle = RGFW_winapi_window_getExStyle(win, win->internal.flags);
11326 AdjustWindowRectEx(&rect, style, FALSE, exStyle);
11327 SetWindowPos(win->src.window, HWND_TOP, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_NOZORDER);
11328
11329
11330 win->internal.flags &= ~(u32)RGFW_windowFullscreen;
11331 win->x = win->internal.oldX;
11332 win->y = win->internal.oldY;
11333 win->w = win->internal.oldW;
11334 win->h = win->internal.oldH;
11335 return;
11336 }
11337
11338 win->internal.oldX = win->x;
11339 win->internal.oldY = win->y;
11340 win->internal.oldW = win->w;
11341 win->internal.oldH = win->h;
11342 win->internal.flags |= RGFW_windowFullscreen;
11343
11344 RGFW_monitor* mon = RGFW_window_getMonitor(win);
11345
11346 RGFW_window_setBorder(win, 0);
11347 RGFW_monitor_scaleToWindow(mon, win);
11348
11349 SetWindowPos(win->src.window, HWND_TOPMOST, (i32)mon->x, (i32)mon->y, (i32)mon->mode.w, (i32)mon->mode.h, SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_SHOWWINDOW);
11350
11351 win->x = mon->x;
11352 win->y = mon->y;
11353 win->w = mon->mode.w;
11354 win->h = mon->mode.h;
11355 }
11356
11357 void RGFW_window_maximize(RGFW_window* win) {
11358 RGFW_ASSERT(win != NULL);
11359 RGFW_window_hide(win);
11360 ShowWindow(win->src.window, SW_MAXIMIZE);
11361 }
11362
11363 void RGFW_window_minimize(RGFW_window* win) {
11364 RGFW_ASSERT(win != NULL);
11365 ShowWindow(win->src.window, SW_MINIMIZE);
11366 }
11367
11368 void RGFW_window_setFloating(RGFW_window* win, RGFW_bool floating) {
11369 RGFW_ASSERT(win != NULL);
11370 if (floating) SetWindowPos(win->src.window, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
11371 else SetWindowPos(win->src.window, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
11372 }
11373
11374 void RGFW_window_setOpacity(RGFW_window* win, u8 opacity) {
11375 SetWindowLong(win->src.window, GWL_EXSTYLE, WS_EX_LAYERED);
11376 SetLayeredWindowAttributes(win->src.window, 0, opacity, LWA_ALPHA);
11377 }
11378
11379 void RGFW_window_restore(RGFW_window* win) { RGFW_window_show(win); }
11380
11381 RGFW_bool RGFW_window_isFloating(RGFW_window* win) {
11382 return (GetWindowLongPtr(win->src.window, GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
11383 }
11384
11385 void RGFW_stopCheckEvents(void) {
11386 PostMessageW(_RGFW->root->src.window, WM_NULL, 0, 0);
11387 }
11388
11389 void RGFW_waitForEvent(i32 waitMS) {
11390 MsgWaitForMultipleObjects(0, NULL, FALSE, (DWORD)waitMS, QS_ALLINPUT);
11391 }
11392
11393 RGFW_key RGFW_physicalToMappedKey(RGFW_key key) {
11394 UINT vsc = RGFW_rgfwToApiKey(key);
11395 BYTE keyboardState[256] = {0};
11396
11397 if (!GetKeyboardState(keyboardState))
11398 return key;
11399
11400 UINT vk = MapVirtualKeyW(vsc, MAPVK_VSC_TO_VK);
11401 HKL layout = GetKeyboardLayout(0);
11402
11403 wchar_t charBuffer[4] = {0};
11404 int result = ToUnicodeEx(vk, vsc, keyboardState, charBuffer, 1, 0, layout);
11405
11406 if (result == 1 && charBuffer[0] < 256) {
11407 return (RGFW_key)charBuffer[0];
11408 }
11409
11410 switch (vk) {
11411 case VK_F1: return RGFW_F1;
11412 case VK_F2: return RGFW_F2;
11413 case VK_F3: return RGFW_F3;
11414 case VK_F4: return RGFW_F4;
11415 case VK_F5: return RGFW_F5;
11416 case VK_F6: return RGFW_F6;
11417 case VK_F7: return RGFW_F7;
11418 case VK_F8: return RGFW_F8;
11419 case VK_F9: return RGFW_F9;
11420 case VK_F10: return RGFW_F10;
11421 case VK_F11: return RGFW_F11;
11422 case VK_F12: return RGFW_F12;
11423 case VK_F13: return RGFW_F13;
11424 case VK_F14: return RGFW_F14;
11425 case VK_F15: return RGFW_F15;
11426 case VK_F16: return RGFW_F16;
11427 case VK_F17: return RGFW_F17;
11428 case VK_F18: return RGFW_F18;
11429 case VK_F19: return RGFW_F19;
11430 case VK_F20: return RGFW_F20;
11431 case VK_F21: return RGFW_F21;
11432 case VK_F22: return RGFW_F22;
11433 case VK_F23: return RGFW_F23;
11434 case VK_F24: return RGFW_F24;
11435 case VK_LSHIFT: return RGFW_shiftL;
11436 case VK_RSHIFT: return RGFW_shiftR;
11437 case VK_LCONTROL: return RGFW_controlL;
11438 case VK_RCONTROL: return RGFW_controlR;
11439 case VK_LMENU: return RGFW_altL;
11440 case VK_RMENU: return RGFW_altR;
11441 case VK_LWIN: return RGFW_superL;
11442 case VK_RWIN: return RGFW_superR;
11443 case VK_CAPITAL: return RGFW_capsLock;
11444 case VK_NUMLOCK: return RGFW_numLock;
11445 case VK_SCROLL: return RGFW_scrollLock;
11446 case VK_UP: return RGFW_up;
11447 case VK_DOWN: return RGFW_down;
11448 case VK_LEFT: return RGFW_left;
11449 case VK_RIGHT: return RGFW_right;
11450 case VK_HOME: return RGFW_home;
11451 case VK_END: return RGFW_end;
11452 case VK_PRIOR: return RGFW_pageUp;
11453 case VK_NEXT: return RGFW_pageDown;
11454 case VK_INSERT: return RGFW_insert;
11455 case VK_APPS: return RGFW_menu;
11456 case VK_ADD: return RGFW_kpPlus;
11457 case VK_SUBTRACT: return RGFW_kpMinus;
11458 case VK_MULTIPLY: return RGFW_kpMultiply;
11459 case VK_DIVIDE: return RGFW_kpSlash;
11460 case VK_RETURN: return RGFW_kpReturn;
11461 case VK_DECIMAL: return RGFW_kpPeriod;
11462 case VK_NUMPAD0: return RGFW_kp0;
11463 case VK_NUMPAD1: return RGFW_kp1;
11464 case VK_NUMPAD2: return RGFW_kp2;
11465 case VK_NUMPAD3: return RGFW_kp3;
11466 case VK_NUMPAD4: return RGFW_kp4;
11467 case VK_NUMPAD5: return RGFW_kp5;
11468 case VK_NUMPAD6: return RGFW_kp6;
11469 case VK_NUMPAD7: return RGFW_kp7;
11470 case VK_NUMPAD8: return RGFW_kp8;
11471 case VK_NUMPAD9: return RGFW_kp9;
11472 case VK_SNAPSHOT: return RGFW_printScreen;
11473 case VK_PAUSE: return RGFW_pause;
11474 default: return RGFW_keyNULL;
11475 }
11476
11477 return RGFW_keyNULL;
11478 }
11479
11480 void RGFW_pollEvents(void) {
11481 RGFW_resetPrevState();
11482 MSG msg;
11483 while (PeekMessageA(&msg, NULL, 0u, 0u, PM_REMOVE)) {
11484 TranslateMessage(&msg);
11485 DispatchMessageA(&msg);
11486 }
11487 }
11488
11489 RGFW_bool RGFW_window_isHidden(RGFW_window* win) {
11490 RGFW_ASSERT(win != NULL);
11491 return IsWindowVisible(win->src.window) == 0 && !RGFW_window_isMinimized(win);
11492 }
11493
11494 RGFW_bool RGFW_window_isMinimized(RGFW_window* win) {
11495 RGFW_ASSERT(win != NULL);
11496
11497 #ifndef __cplusplus
11498 WINDOWPLACEMENT placement = {0};
11499 #else
11500 WINDOWPLACEMENT placement = {};
11501 #endif
11502 GetWindowPlacement(win->src.window, &placement);
11503 return placement.showCmd == SW_SHOWMINIMIZED;
11504 }
11505
11506 RGFW_bool RGFW_window_isMaximized(RGFW_window* win) {
11507 RGFW_ASSERT(win != NULL);
11508
11509 #ifndef __cplusplus
11510 WINDOWPLACEMENT placement = {0};
11511 #else
11512 WINDOWPLACEMENT placement = {};
11513 #endif
11514 GetWindowPlacement(win->src.window, &placement);
11515 return placement.showCmd == SW_SHOWMAXIMIZED || IsZoomed(win->src.window);
11516 }
11517
11518 RGFW_bool RGFW_monitor_getWorkarea(RGFW_monitor* monitor, i32* x, i32* y, i32* width, i32* height) {
11519 MONITORINFOEX mi;
11520 mi.cbSize = sizeof(MONITORINFOEX);
11521 GetMonitorInfoA(monitor->node->hMonitor, (LPMONITORINFO)&mi);
11522
11523 if (x) *x = mi.rcWork.left;
11524 if (y) *y = mi.rcWork.top;
11525 if (width) *width = mi.rcWork.right - mi.rcWork.left;
11526 if (height) *height = mi.rcWork.bottom - mi.rcWork.top;
11527
11528 return RGFW_TRUE;
11529 }
11530
11531 size_t RGFW_monitor_getGammaRampPtr(RGFW_monitor* monitor, RGFW_gammaRamp* ramp) {
11532 WORD values[3][256];
11533
11534 HDC dc = CreateDCW(L"DISPLAY", monitor->node->adapterName, NULL, NULL);
11535 GetDeviceGammaRamp(dc, values);
11536 DeleteDC(dc);
11537
11538 if (ramp) {
11539 memcpy(ramp->red, values[0], sizeof(values[0]));
11540 memcpy(ramp->green, values[1], sizeof(values[1]));
11541 memcpy(ramp->blue, values[2], sizeof(values[2]));
11542 }
11543
11544 return sizeof(values[0]) / sizeof(WORD);
11545 }
11546
11547 RGFW_bool RGFW_monitor_setGammaRamp(RGFW_monitor* monitor, RGFW_gammaRamp* ramp) {
11548 WORD values[3][256];
11549 if (ramp->count != 256) {
11550 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errX11, "Win32: Gamma ramp size must be 256");
11551 return RGFW_FALSE;
11552 }
11553
11554 memcpy(values[0], ramp->red, sizeof(values[0]));
11555 memcpy(values[1], ramp->green, sizeof(values[1]));
11556 memcpy(values[2], ramp->blue, sizeof(values[2]));
11557
11558 HDC dc = CreateDCW(L"DISPLAY", monitor->node->adapterName, NULL, NULL);
11559 SetDeviceGammaRamp(dc, values);
11560 DeleteDC(dc);
11561 return RGFW_TRUE;
11562 }
11563
11564 BOOL CALLBACK RGFW_win32_getMonitorHandle(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData);
11565 BOOL CALLBACK RGFW_win32_getMonitorHandle(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
11566 RGFW_UNUSED(hMonitor);
11567 RGFW_UNUSED(hdcMonitor);
11568 RGFW_UNUSED(lprcMonitor);
11569 RGFW_UNUSED(dwData);
11570
11571 MONITORINFOEXW mi;
11572 ZeroMemory(&mi, sizeof(mi));
11573 mi.cbSize = sizeof(mi);
11574
11575 if (GetMonitorInfoW(hMonitor, (MONITORINFO*) &mi)) {
11576 RGFW_monitorNode* node = (RGFW_monitorNode*)dwData;
11577 if (wcscmp(mi.szDevice, node->adapterName) == 0) {
11578 node->hMonitor = hMonitor;
11579 }
11580 }
11581
11582 return TRUE;
11583 }
11584
11585 RGFWDEF void RGFW_win32_getMode(DEVMODEW* dm, RGFW_monitorMode* mode);
11586 void RGFW_win32_getMode(DEVMODEW* dm, RGFW_monitorMode* mode) {
11587 mode->w = (i32)dm->dmPelsWidth;
11588 mode->h = (i32)dm->dmPelsHeight;
11589 RGFW_splitBPP(dm->dmBitsPerPel, mode);
11590
11591 switch (dm->dmDisplayFrequency) {
11592 case 119:
11593 case 59:
11594 case 29:
11595 mode->refreshRate = ((float)(dm->dmDisplayFrequency + 1) * 1000.0f) / 1001.f;
11596 break;
11597 default:
11598 mode->refreshRate = (float)dm->dmDisplayFrequency;
11599 break;
11600 }
11601 }
11602
11603 size_t RGFW_monitor_getModesPtr(RGFW_monitor* monitor, RGFW_monitorMode** modes){
11604 size_t count = 0;
11605 DWORD modeIndex = 0;
11606
11607 for (;;) {
11608 DEVMODEW dm;
11609 ZeroMemory(&dm, sizeof(dm));
11610 dm.dmSize = sizeof(dm);
11611
11612 if (!EnumDisplaySettingsW(monitor->node->adapterName, modeIndex, &dm))
11613 break;
11614
11615 modeIndex++;
11616
11617 if (dm.dmBitsPerPel < 15)
11618 continue;
11619
11620 if (modes) {
11621 RGFW_monitorMode mode;
11622 RGFW_win32_getMode(&dm, &mode);
11623
11624 size_t i;
11625 for (i = 0; i < count; i++) {
11626 if (RGFW_monitorModeCompare(&(*modes)[i], &mode, RGFW_monitorAll) == RGFW_TRUE) {
11627 break;
11628 }
11629 }
11630
11631 if (i < count) {
11632 continue;
11633 }
11634
11635 (*modes)[count] = mode;
11636 }
11637
11638 count += 1;
11639 }
11640
11641 return count;
11642 }
11643
11644 RGFWDEF void RGFW_win32_createMonitor(DISPLAY_DEVICEW* adapter, DISPLAY_DEVICEW* dd);
11645 void RGFW_win32_createMonitor(DISPLAY_DEVICEW* adapter, DISPLAY_DEVICEW* dd) {
11646 DEVMODEW dm;
11647 ZeroMemory(&dm, sizeof(dm));
11648 dm.dmSize = sizeof(dm);
11649
11650 if (!EnumDisplaySettingsW(adapter->DeviceName, ENUM_CURRENT_SETTINGS, &dm)) {
11651 return;
11652 }
11653
11654 RGFW_monitorNode* node = RGFW_monitors_add(NULL);
11655
11656 wcscpy(node->adapterName, adapter->DeviceName);
11657 wcscpy(node->deviceName, dd->DeviceName);
11658
11659 RGFW_createUTF8FromWideStringWin32(dd->DeviceString, node->mon.name, sizeof(node->mon.name));
11660 node->mon.name[sizeof(node->mon.name) - 1] = '\0';
11661
11662 RECT rect;
11663 rect.left = (LONG)dm.dmPosition.x;
11664 rect.top = (LONG)dm.dmPosition.y;
11665 rect.right = (LONG)((LONG)dm.dmPosition.x + (LONG)dm.dmPelsWidth);
11666 rect.bottom = (LONG)((long)dm.dmPosition.y + (LONG)dm.dmPelsHeight);
11667 EnumDisplayMonitors(NULL, &rect, RGFW_win32_getMonitorHandle, (LPARAM)node);
11668
11669 RGFW_win32_getMode(&dm, &node->mon.mode);
11670
11671 MONITORINFOEXW monitorInfo;
11672 monitorInfo.cbSize = sizeof(MONITORINFOEXW);
11673 GetMonitorInfoW(node->hMonitor, (LPMONITORINFO)&monitorInfo);
11674
11675 node->mon.x = monitorInfo.rcMonitor.left;
11676 node->mon.y = monitorInfo.rcMonitor.top;
11677
11678 HDC hdc = CreateDCW(monitorInfo.szDevice, NULL, NULL, NULL);
11679 /* get pixels per inch */
11680 float dpiX = (float)GetDeviceCaps(hdc, LOGPIXELSX);
11681 float dpiY = (float)GetDeviceCaps(hdc, LOGPIXELSX);
11682
11683 node->mon.scaleX = dpiX / 96.0f;
11684 node->mon.scaleY = dpiY / 96.0f;
11685 node->mon.pixelRatio = dpiX >= 192.0f ? 2.0f : 1.0f;
11686
11687 node->mon.physW = (float)GetDeviceCaps(hdc, HORZSIZE) / 25.4f;
11688 node->mon.physH = (float)GetDeviceCaps(hdc, VERTSIZE) / 25.4f;
11689 DeleteDC(hdc);
11690
11691 #ifndef RGFW_NO_DPI
11692 RGFW_LOAD_LIBRARY(RGFW_Shcore_dll, "shcore.dll");
11693 RGFW_PROC_DEF(RGFW_Shcore_dll, GetDpiForMonitor);
11694
11695 if (GetDpiForMonitor != NULL) {
11696 u32 x, y;
11697 GetDpiForMonitor(node->hMonitor, MDT_EFFECTIVE_DPI, &x, &y);
11698 node->mon.scaleX = (float) (x) / (float) 96.0f;
11699 node->mon.scaleY = (float) (y) / (float) 96.0f;
11700 node->mon.pixelRatio = dpiX >= 192.0f ? 2.0f : 1.0f;
11701 }
11702 #endif
11703
11704 if (monitorInfo.dwFlags & MONITORINFOF_PRIMARY) {
11705 _RGFW->monitors.primary = node;
11706 }
11707
11708 RGFW_monitorCallback(_RGFW->root, &node->mon, RGFW_TRUE);
11709 }
11710
11711 void RGFW_pollMonitors(void) {
11712 for (RGFW_monitorNode* node = _RGFW->monitors.list.head; node; node = node->next) {
11713 node->disconnected = RGFW_TRUE;
11714 }
11715
11716 /* loop through display adapters (GPU) */
11717 DISPLAY_DEVICEW adapter;
11718 DWORD adapterNum;
11719 for (adapterNum = 0; ; adapterNum++) {
11720 ZeroMemory(&adapter, sizeof(adapter));
11721 adapter.cb = sizeof(adapter);
11722
11723 if (!EnumDisplayDevicesW(NULL, adapterNum, &adapter, 0))
11724 break;
11725
11726 if (!(adapter.StateFlags & DISPLAY_DEVICE_ACTIVE))
11727 continue;
11728
11729 DISPLAY_DEVICEW dd;
11730 dd.cb = sizeof(dd);
11731
11732 /* loop through display devices (monitors) */
11733 DWORD deviceNum;
11734 for (deviceNum = 0; ; deviceNum++) {
11735 ZeroMemory(&dd, sizeof(dd));
11736 dd.cb = sizeof(dd);
11737
11738 if (!EnumDisplayDevicesW(adapter.DeviceName, deviceNum, &dd, 0))
11739 break;
11740
11741 if (!(dd.StateFlags & DISPLAY_DEVICE_ACTIVE))
11742 continue;
11743
11744 RGFW_monitorNode* node;
11745 for (node = _RGFW->monitors.list.head; node; node = node->next) {
11746 if (node->disconnected == RGFW_TRUE && wcscmp(node->deviceName, dd.DeviceName) == 0) {
11747 node->disconnected = RGFW_FALSE;
11748 EnumDisplayMonitors(NULL, NULL, RGFW_win32_getMonitorHandle, (LPARAM) &node->mon);
11749 break;
11750 }
11751 }
11752
11753 if (node) {
11754 continue;
11755 }
11756
11757 RGFW_win32_createMonitor(&adapter, &dd);
11758 }
11759
11760 /* if there are no display devices, just use the monitor directly (hack borrowed from GLFW (I'm not giving it back)) */
11761 if (deviceNum == 0) {
11762 RGFW_monitorNode* node;
11763 for (node = _RGFW->monitors.list.head; node; node = node->next) {
11764 if (node->disconnected == RGFW_TRUE && wcscmp(node->adapterName, adapter.DeviceName) == 0) {
11765 node->disconnected = RGFW_FALSE;
11766 break;
11767 }
11768 }
11769
11770 if (node) {
11771 continue;
11772 }
11773
11774 RGFW_win32_createMonitor(&adapter, NULL);
11775 }
11776 }
11777
11778 RGFW_monitors_refresh();
11779 }
11780
11781 RGFW_monitor* RGFW_window_getMonitor(RGFW_window* win) {
11782 HMONITOR src = MonitorFromWindow(win->src.window, MONITOR_DEFAULTTOPRIMARY);
11783 RGFW_monitorNode* node = _RGFW->monitors.list.head;
11784
11785 for (node = _RGFW->monitors.list.head; node; node = node->next) {
11786 if (node->hMonitor == src) {
11787 return &node->mon;
11788 }
11789 }
11790
11791 return RGFW_getPrimaryMonitor();
11792 }
11793
11794 RGFW_bool RGFW_monitor_setMode(RGFW_monitor* mon, RGFW_monitorMode* mode) {
11795 DEVMODEW dm;
11796 ZeroMemory(&dm, sizeof(dm));
11797 dm.dmSize = sizeof(dm);
11798
11799 dm.dmFields |= DM_PELSWIDTH | DM_PELSHEIGHT;
11800 dm.dmPelsWidth = (u32)mode->w;
11801 dm.dmPelsHeight = (u32)mode->h;
11802
11803 dm.dmFields |= DM_DISPLAYFREQUENCY;
11804 dm.dmDisplayFrequency = (DWORD)mode->refreshRate;
11805
11806 dm.dmFields |= DM_BITSPERPEL;
11807 dm.dmBitsPerPel = (DWORD)(mode->red + mode->green + mode->blue);
11808
11809 if (ChangeDisplaySettingsExW(mon->node->adapterName, &dm, NULL, CDS_TEST, NULL) == DISP_CHANGE_SUCCESSFUL) {
11810 if (ChangeDisplaySettingsExW(mon->node->adapterName, &dm, NULL, CDS_UPDATEREGISTRY, NULL) == DISP_CHANGE_SUCCESSFUL)
11811 return RGFW_TRUE;
11812 return RGFW_FALSE;
11813 } else return RGFW_FALSE;
11814 }
11815
11816 RGFW_bool RGFW_monitor_requestMode(RGFW_monitor* mon, RGFW_monitorMode* mode, RGFW_modeRequest request) {
11817 HMONITOR src = mon->node->hMonitor;
11818
11819 MONITORINFOEX monitorInfo;
11820 monitorInfo.cbSize = sizeof(MONITORINFOEX);
11821 GetMonitorInfoA(src, (LPMONITORINFO)&monitorInfo);
11822
11823 DEVMODEW dm;
11824 ZeroMemory(&dm, sizeof(dm));
11825 dm.dmSize = sizeof(dm);
11826
11827 if (EnumDisplaySettingsW(mon->node->adapterName, ENUM_CURRENT_SETTINGS, &dm)) {
11828 if (request & RGFW_monitorScale) {
11829 dm.dmFields |= DM_PELSWIDTH | DM_PELSHEIGHT;
11830 dm.dmPelsWidth = (u32)mode->w;
11831 dm.dmPelsHeight = (u32)mode->h;
11832 }
11833
11834 if (request & RGFW_monitorRefresh) {
11835 dm.dmFields |= DM_DISPLAYFREQUENCY;
11836 dm.dmDisplayFrequency = (DWORD)mode->refreshRate;
11837 }
11838
11839 if (request & RGFW_monitorRGB) {
11840 dm.dmFields |= DM_BITSPERPEL;
11841 dm.dmBitsPerPel = (DWORD)(mode->red + mode->green + mode->blue);
11842 }
11843
11844 if (ChangeDisplaySettingsExW(mon->node->adapterName, &dm, NULL, CDS_TEST, NULL) == DISP_CHANGE_SUCCESSFUL) {
11845 if (ChangeDisplaySettingsExW(mon->node->adapterName, &dm, NULL, CDS_UPDATEREGISTRY, NULL) == DISP_CHANGE_SUCCESSFUL) {
11846 RGFW_win32_getMode(&dm, &mon->mode);
11847 return RGFW_TRUE;
11848 }
11849 return RGFW_FALSE;
11850 } else return RGFW_FALSE;
11851 }
11852
11853 return RGFW_FALSE;
11854 }
11855
11856 HICON RGFW_loadHandleImage(u8* data, i32 w, i32 h, RGFW_format format, BOOL icon);
11857 HICON RGFW_loadHandleImage(u8* data, i32 w, i32 h, RGFW_format format, BOOL icon) {
11858 BITMAPV5HEADER bi;
11859 ZeroMemory(&bi, sizeof(bi));
11860 bi.bV5Size = sizeof(bi);
11861 bi.bV5Width = (i32)w;
11862 bi.bV5Height = -((LONG) h);
11863 bi.bV5Planes = 1;
11864 bi.bV5BitCount = (WORD)32;
11865 bi.bV5Compression = BI_RGB;
11866 HDC dc = GetDC(NULL);
11867 u8* target = NULL;
11868
11869 HBITMAP color = CreateDIBSection(dc,
11870 (BITMAPINFO*) &bi, DIB_RGB_COLORS, (void**) &target,
11871 NULL, (DWORD) 0);
11872
11873 RGFW_copyImageData(target, w, h, RGFW_formatBGRA8, data, format, NULL);
11874 ReleaseDC(NULL, dc);
11875
11876 HBITMAP mask = CreateBitmap((i32)w, (i32)h, 1, 1, NULL);
11877
11878 ICONINFO ii;
11879 ZeroMemory(&ii, sizeof(ii));
11880 ii.fIcon = icon;
11881 ii.xHotspot = (u32)w / 2;
11882 ii.yHotspot = (u32)h / 2;
11883 ii.hbmMask = mask;
11884 ii.hbmColor = color;
11885
11886 HICON handle = CreateIconIndirect(&ii);
11887
11888 DeleteObject(color);
11889 DeleteObject(mask);
11890
11891 return handle;
11892 }
11893 RGFW_mouse* RGFW_loadMouse(u8* data, i32 w, i32 h, RGFW_format format) {
11894 HCURSOR cursor = (HCURSOR) RGFW_loadHandleImage(data, w, h, format, FALSE);
11895 return cursor;
11896 }
11897
11898 void RGFW_window_setMouse(RGFW_window* win, RGFW_mouse* mouse) {
11899 RGFW_ASSERT(win && mouse);
11900 SetClassLongPtrA(win->src.window, GCLP_HCURSOR, (LPARAM) mouse);
11901 SetCursor((HCURSOR)mouse);
11902 }
11903
11904 void RGFW_freeMouse(RGFW_mouse* mouse) {
11905 RGFW_ASSERT(mouse);
11906 DestroyCursor((HCURSOR)mouse);
11907 }
11908
11909 RGFW_bool RGFW_window_setMouseDefault(RGFW_window* win) {
11910 return RGFW_window_setMouseStandard(win, RGFW_mouseArrow);
11911 }
11912
11913 RGFW_bool RGFW_window_setMouseStandard(RGFW_window* win, u8 mouse) {
11914 RGFW_ASSERT(win != NULL);
11915
11916 u32 mouseIcon = 0;
11917
11918 switch (mouse) {
11919 case RGFW_mouseNormal: mouseIcon = OCR_NORMAL; break;
11920 case RGFW_mouseArrow: mouseIcon = OCR_NORMAL; break;
11921 case RGFW_mouseIbeam: mouseIcon = OCR_IBEAM; break;
11922 case RGFW_mouseWait: mouseIcon = OCR_WAIT; break;
11923 case RGFW_mouseCrosshair: mouseIcon = OCR_CROSS; break;
11924 case RGFW_mouseProgress: mouseIcon = OCR_APPSTARTING; break;
11925 case RGFW_mouseResizeNWSE: mouseIcon = OCR_SIZENWSE; break;
11926 case RGFW_mouseResizeNESW: mouseIcon = OCR_SIZENESW; break;
11927 case RGFW_mouseResizeEW: mouseIcon = OCR_SIZEWE; break;
11928 case RGFW_mouseResizeNS: mouseIcon = OCR_SIZENS; break;
11929 case RGFW_mouseResizeAll: mouseIcon = OCR_SIZEALL; break;
11930 case RGFW_mouseNotAllowed: mouseIcon = OCR_NO; break;
11931 case RGFW_mousePointingHand: mouseIcon = OCR_HAND; break;
11932 case RGFW_mouseResizeNW: mouseIcon = OCR_SIZENWSE; break;
11933 case RGFW_mouseResizeN: mouseIcon = OCR_SIZENS; break;
11934 case RGFW_mouseResizeNE: mouseIcon = OCR_SIZENESW; break;
11935 case RGFW_mouseResizeE: mouseIcon = OCR_SIZEWE; break;
11936 case RGFW_mouseResizeSE: mouseIcon = OCR_SIZENWSE; break;
11937 case RGFW_mouseResizeS: mouseIcon = OCR_SIZENS; break;
11938 case RGFW_mouseResizeSW: mouseIcon = OCR_SIZENESW; break;
11939 case RGFW_mouseResizeW: mouseIcon = OCR_SIZEWE; break;
11940 default: return RGFW_FALSE;
11941 }
11942
11943 char* icon = MAKEINTRESOURCEA(mouseIcon);
11944
11945 SetClassLongPtrA(win->src.window, GCLP_HCURSOR, (LPARAM) LoadCursorA(NULL, icon));
11946 SetCursor(LoadCursorA(NULL, icon));
11947 return RGFW_TRUE;
11948 }
11949
11950 void RGFW_window_hide(RGFW_window* win) {
11951 ShowWindow(win->src.window, SW_HIDE);
11952 }
11953
11954 void RGFW_window_show(RGFW_window* win) {
11955 if (win->internal.flags & RGFW_windowFocusOnShow) RGFW_window_focus(win);
11956 ShowWindow(win->src.window, SW_RESTORE);
11957 }
11958
11959 void RGFW_window_flash(RGFW_window* win, RGFW_flashRequest request) {
11960 if (RGFW_window_isInFocus(win) && request) {
11961 return;
11962 }
11963
11964 FLASHWINFO desc;
11965 RGFW_MEMSET(&desc, 0, sizeof(desc));
11966
11967 desc.cbSize = sizeof(desc);
11968 desc.hwnd = win->src.window;
11969
11970 switch (request) {
11971 case RGFW_flashCancel:
11972 desc.dwFlags = FLASHW_STOP;
11973 break;
11974 case RGFW_flashBriefly:
11975 desc.dwFlags = FLASHW_TRAY;
11976 desc.uCount = 1;
11977 break;
11978 case RGFW_flashUntilFocused:
11979 desc.dwFlags = (FLASHW_TRAY | FLASHW_TIMERNOFG);
11980 break;
11981 default: break;
11982 }
11983
11984 FlashWindowEx(&desc);
11985 }
11986
11987 #define RGFW_FREE_LIBRARY(x) if (x != NULL) FreeLibrary(x); x = NULL;
11988 void RGFW_deinitPlatform(void) {
11989 #ifndef RGFW_NO_DPI
11990 RGFW_FREE_LIBRARY(RGFW_Shcore_dll);
11991 #endif
11992
11993 #ifndef RGFW_NO_WINMM
11994 timeEndPeriod(1);
11995 #ifndef RGFW_NO_LOAD_WINMM
11996 RGFW_FREE_LIBRARY(RGFW_winmm_dll);
11997 #endif
11998 #endif
11999
12000 RGFW_FREE_LIBRARY(RGFW_wgl_dll);
12001
12002 RGFW_freeMouse(_RGFW->hiddenMouse);
12003 }
12004
12005
12006 void RGFW_window_closePlatform(RGFW_window* win) {
12007 RemovePropW(win->src.window, L"RGFW");
12008 ReleaseDC(win->src.window, win->src.hdc); /*!< delete device context */
12009 DestroyWindow(win->src.window); /*!< delete window */
12010
12011 if (win->src.hIconSmall) DestroyIcon(win->src.hIconSmall);
12012 if (win->src.hIconBig) DestroyIcon(win->src.hIconBig);
12013 }
12014
12015 void RGFW_window_move(RGFW_window* win, i32 x, i32 y) {
12016 RGFW_ASSERT(win != NULL);
12017
12018 win->x = x;
12019 win->y = y;
12020 SetWindowPos(win->src.window, HWND_TOP, win->x, win->y, 0, 0, SWP_NOSIZE);
12021 }
12022
12023 void RGFW_window_resize(RGFW_window* win, i32 w, i32 h) {
12024 RGFW_ASSERT(win != NULL);
12025
12026 win->w = w;
12027 win->h = h;
12028
12029 RECT rect = { 0, 0, w, h};
12030 DWORD style = RGFW_winapi_window_getStyle(win, win->internal.flags);
12031 DWORD exStyle = RGFW_winapi_window_getExStyle(win, win->internal.flags);
12032 AdjustWindowRectEx(&rect, style, FALSE, exStyle);
12033
12034 SetWindowPos(win->src.window, HWND_TOP, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_NOZORDER);
12035 }
12036
12037 void RGFW_window_setName(RGFW_window* win, const char* name) {
12038 RGFW_ASSERT(win != NULL);
12039 if (name == NULL) name = "\0";
12040
12041 wchar_t wide_name[256];
12042 MultiByteToWideChar(CP_UTF8, 0, name, -1, wide_name, 256);
12043 SetWindowTextW(win->src.window, wide_name);
12044 }
12045
12046 #ifndef RGFW_NO_PASSTHROUGH
12047 void RGFW_window_setMousePassthrough(RGFW_window* win, RGFW_bool passthrough) {
12048 RGFW_ASSERT(win != NULL);
12049 COLORREF key = 0;
12050 BYTE alpha = 0;
12051 DWORD flags = 0;
12052 i32 exStyle = GetWindowLongW(win->src.window, GWL_EXSTYLE);
12053
12054 if (exStyle & WS_EX_LAYERED)
12055 GetLayeredWindowAttributes(win->src.window, &key, &alpha, &flags);
12056
12057 if (passthrough)
12058 exStyle |= (WS_EX_TRANSPARENT | WS_EX_LAYERED);
12059 else {
12060 exStyle &= ~WS_EX_TRANSPARENT;
12061 if (exStyle & WS_EX_LAYERED && !(flags & LWA_ALPHA))
12062 exStyle &= ~WS_EX_LAYERED;
12063 }
12064
12065 SetWindowLongW(win->src.window, GWL_EXSTYLE, exStyle);
12066
12067 if (passthrough)
12068 SetLayeredWindowAttributes(win->src.window, key, alpha, flags);
12069 }
12070 #endif
12071
12072 RGFW_bool RGFW_window_setIconEx(RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format, RGFW_icon type) {
12073 RGFW_ASSERT(win != NULL);
12074 #ifndef RGFW_WIN95
12075 if (win->src.hIconSmall && (type & RGFW_iconWindow)) DestroyIcon(win->src.hIconSmall);
12076 if (win->src.hIconBig && (type & RGFW_iconTaskbar)) DestroyIcon(win->src.hIconBig);
12077
12078 if (data == NULL) {
12079 HICON defaultIcon = LoadIcon(NULL, IDI_APPLICATION);
12080 if (type & RGFW_iconWindow)
12081 SendMessage(win->src.window, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)defaultIcon);
12082 if (type & RGFW_iconTaskbar)
12083 SendMessage(win->src.window, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)defaultIcon);
12084 return RGFW_TRUE;
12085 }
12086
12087 if (type & RGFW_iconWindow) {
12088 win->src.hIconSmall = RGFW_loadHandleImage(data, w, h, format, TRUE);
12089 SendMessage(win->src.window, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)win->src.hIconSmall);
12090 }
12091 if (type & RGFW_iconTaskbar) {
12092 win->src.hIconBig = RGFW_loadHandleImage(data, w, h, format, TRUE);
12093 SendMessage(win->src.window, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)win->src.hIconBig);
12094 }
12095 return RGFW_TRUE;
12096 #else
12097 RGFW_UNUSED(img);
12098 RGFW_UNUSED(type);
12099 return RGFW_FALSE;
12100 #endif
12101 }
12102
12103 RGFW_ssize_t RGFW_readClipboardPtr(char* str, size_t strCapacity) {
12104 /* Open the clipboard */
12105 if (OpenClipboard(NULL) == 0)
12106 return -1;
12107
12108 /* Get the clipboard data as a Unicode string */
12109 HANDLE hData = GetClipboardData(CF_UNICODETEXT);
12110 if (hData == NULL) {
12111 CloseClipboard();
12112 return -1;
12113 }
12114
12115 wchar_t* wstr = (wchar_t*) GlobalLock(hData);
12116
12117 RGFW_ssize_t textLen = 0;
12118
12119 {
12120 setlocale(LC_ALL, "en_US.UTF-8");
12121
12122 textLen = (RGFW_ssize_t)wcstombs(NULL, wstr, 0) + 1;
12123 if (str != NULL && (RGFW_ssize_t)strCapacity <= textLen - 1)
12124 textLen = 0;
12125
12126 if (str != NULL && textLen) {
12127 if (textLen > 1)
12128 wcstombs(str, wstr, (size_t)(textLen));
12129
12130 str[textLen - 1] = '\0';
12131 }
12132 }
12133
12134 /* Release the clipboard data */
12135 GlobalUnlock(hData);
12136 CloseClipboard();
12137
12138 return textLen;
12139 }
12140
12141 void RGFW_writeClipboard(const char* text, u32 textLen) {
12142 HANDLE object;
12143 WCHAR* buffer;
12144
12145 object = GlobalAlloc(GMEM_MOVEABLE, (1 + textLen) * sizeof(WCHAR));
12146 if (!object)
12147 return;
12148
12149 buffer = (WCHAR*) GlobalLock(object);
12150 if (!buffer) {
12151 GlobalFree(object);
12152 return;
12153 }
12154
12155 MultiByteToWideChar(CP_UTF8, 0, text, -1, buffer, (i32)textLen);
12156 GlobalUnlock(object);
12157
12158 if (!OpenClipboard(_RGFW->root->src.window)) {
12159 GlobalFree(object);
12160 return;
12161 }
12162
12163 EmptyClipboard();
12164 SetClipboardData(CF_UNICODETEXT, object);
12165 CloseClipboard();
12166 }
12167
12168 void RGFW_window_moveMouse(RGFW_window* win, i32 x, i32 y) {
12169 RGFW_ASSERT(win != NULL);
12170 win->internal.lastMouseX = x - win->x;
12171 win->internal.lastMouseY = y - win->y;
12172 SetCursorPos(x, y);
12173 }
12174
12175 #ifdef RGFW_OPENGL
12176 RGFW_bool RGFW_extensionSupportedPlatform_OpenGL(const char * extension, size_t len) {
12177 const char* extensions = NULL;
12178
12179 RGFW_proc proc = RGFW_getProcAddress_OpenGL("wglGetExtensionsStringARB");
12180 RGFW_proc proc2 = RGFW_getProcAddress_OpenGL("wglGetExtensionsStringEXT");
12181
12182 if (proc)
12183 extensions = ((const char* (*)(HDC))proc)(wglGetCurrentDC());
12184 else if (proc2)
12185 extensions = ((const char*(*)(void))proc2)();
12186 return extensions != NULL && RGFW_extensionSupportedStr(extensions, extension, len);
12187 }
12188
12189 RGFW_proc RGFW_getProcAddress_OpenGL(const char* procname) {
12190 RGFW_proc proc = (RGFW_proc)wglGetProcAddress(procname);
12191 if (proc)
12192 return proc;
12193
12194 return (RGFW_proc) GetProcAddress(RGFW_wgl_dll, procname);
12195 }
12196
12197 void RGFW_win32_loadOpenGLFuncs(HWND dummyWin) {
12198 if (wglSwapIntervalEXT != NULL && wglChoosePixelFormatARB != NULL && wglChoosePixelFormatARB != NULL)
12199 return;
12200
12201 HDC dummy_dc = GetDC(dummyWin);
12202 u32 pfd_flags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
12203
12204 PIXELFORMATDESCRIPTOR pfd = {sizeof(pfd), 1, pfd_flags, PFD_TYPE_RGBA, 32, 8, PFD_MAIN_PLANE, 32, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 32, 8, 0, PFD_MAIN_PLANE, 0, 0, 0, 0};
12205
12206 int dummy_pixel_format = ChoosePixelFormat(dummy_dc, &pfd);
12207 SetPixelFormat(dummy_dc, dummy_pixel_format, &pfd);
12208
12209 HGLRC dummy_context = wglCreateContext(dummy_dc);
12210
12211 HGLRC cur = wglGetCurrentContext();
12212 wglMakeCurrent(dummy_dc, dummy_context);
12213
12214 wglCreateContextAttribsARB = ((PFNWGLCREATECONTEXTATTRIBSARBPROC(WINAPI *)(const char*)) wglGetProcAddress)("wglCreateContextAttribsARB");
12215 wglChoosePixelFormatARB = ((PFNWGLCHOOSEPIXELFORMATARBPROC(WINAPI *)(const char*)) wglGetProcAddress)("wglChoosePixelFormatARB");
12216
12217 wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)(RGFW_proc)wglGetProcAddress("wglSwapIntervalEXT");
12218 if (wglSwapIntervalEXT == NULL) {
12219 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errOpenGLContext, "Failed to load swap interval function");
12220 }
12221
12222 wglMakeCurrent(dummy_dc, cur);
12223 wglDeleteContext(dummy_context);
12224 ReleaseDC(dummyWin, dummy_dc);
12225 }
12226
12227 #define WGL_ACCELERATION_ARB 0x2003
12228 #define WGL_FULL_ACCELERATION_ARB 0x2027
12229 #define WGL_DRAW_TO_WINDOW_ARB 0x2001
12230 #define WGL_PIXEL_TYPE_ARB 0x2013
12231 #define WGL_TYPE_RGBA_ARB 0x202b
12232 #define WGL_SUPPORT_OPENGL_ARB 0x2010
12233 #define WGL_COLOR_BITS_ARB 0x2014
12234 #define WGL_DOUBLE_BUFFER_ARB 0x2011
12235 #define WGL_ALPHA_BITS_ARB 0x201b
12236 #define WGL_DEPTH_BITS_ARB 0x2022
12237 #define WGL_STENCIL_BITS_ARB 0x2023
12238 #define WGL_STEREO_ARB 0x2012
12239 #define WGL_AUX_BUFFERS_ARB 0x2024
12240 #define WGL_RED_BITS_ARB 0x2015
12241 #define WGL_GREEN_BITS_ARB 0x2017
12242 #define WGL_BLUE_BITS_ARB 0x2019
12243 #define WGL_ACCUM_RED_BITS_ARB 0x201e
12244 #define WGL_ACCUM_GREEN_BITS_ARB 0x201f
12245 #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
12246 #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
12247 #define WGL_COLORSPACE_SRGB_EXT 0x3089
12248 #define WGL_CONTEXT_OPENGL_NO_ERROR_ARB 0x31b3
12249 #define WGL_CONTEXT_RELEASE_BEHAVIOR_ARB 0x2097
12250 #define WGL_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB 0x0000
12251 #define WGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB 0x2098
12252 #define WGL_CONTEXT_FLAGS_ARB 0x2094
12253 #define WGL_ACCESS_READ_WRITE_NV 0x00000001
12254 #define WGL_COVERAGE_SAMPLES_NV 0x2042
12255 #define WGL_CONTEXT_ES_PROFILE_BIT_EXT 0x00000004
12256 #define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
12257 #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
12258 #define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
12259 #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
12260 #define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
12261 #define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
12262 #define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20A9
12263 #define WGL_CONTEXT_RELEASE_BEHAVIOR_ARB 0x2097
12264 #define WGL_CONTEXT_DEBUG_BIT_ARB 0x00000001
12265 #define WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004
12266
12267 RGFW_bool RGFW_window_createContextPtr_OpenGL(RGFW_window* win, RGFW_glContext* ctx, RGFW_glHints* hints) {
12268 const char flushControl[] = "WGL_ARB_context_flush_control";
12269 const char noError[] = "WGL_ARB_create_context_no_error";
12270 const char robustness[] = "WGL_ARB_create_context_robustness";
12271
12272 win->src.ctx.native = ctx;
12273 win->src.gfxType = RGFW_gfxNativeOpenGL;
12274
12275 PIXELFORMATDESCRIPTOR pfd;
12276 pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
12277 pfd.nVersion = 1;
12278 pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
12279 pfd.iPixelType = PFD_TYPE_RGBA;
12280 pfd.iLayerType = PFD_MAIN_PLANE;
12281 pfd.cColorBits = 32;
12282 pfd.cAlphaBits = 8;
12283 pfd.cDepthBits = 24;
12284 pfd.cStencilBits = (BYTE)hints->stencil;
12285 pfd.cAuxBuffers = (BYTE)hints->auxBuffers;
12286 if (hints->stereo) pfd.dwFlags |= PFD_STEREO;
12287
12288 /* try to create the pixel format we want for OpenGL and then try to create an OpenGL context for the specified version */
12289 if (hints->renderer == RGFW_glSoftware)
12290 pfd.dwFlags |= PFD_GENERIC_FORMAT | PFD_GENERIC_ACCELERATED;
12291
12292 /* get pixel format, default to a basic pixel format */
12293 int pixel_format = ChoosePixelFormat(win->src.hdc, &pfd);
12294 if (wglChoosePixelFormatARB != NULL) {
12295 i32 pixel_format_attribs[50];
12296 RGFW_attribStack stack;
12297 RGFW_attribStack_init(&stack, pixel_format_attribs, 50);
12298
12299 RGFW_attribStack_pushAttribs(&stack, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB);
12300 RGFW_attribStack_pushAttribs(&stack, WGL_DRAW_TO_WINDOW_ARB, 1);
12301 RGFW_attribStack_pushAttribs(&stack, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB);
12302 RGFW_attribStack_pushAttribs(&stack, WGL_SUPPORT_OPENGL_ARB, 1);
12303 RGFW_attribStack_pushAttribs(&stack, WGL_COLOR_BITS_ARB, 32);
12304 RGFW_attribStack_pushAttribs(&stack, WGL_DOUBLE_BUFFER_ARB, 1);
12305 RGFW_attribStack_pushAttribs(&stack, WGL_ALPHA_BITS_ARB, hints->alpha);
12306 RGFW_attribStack_pushAttribs(&stack, WGL_DEPTH_BITS_ARB, hints->depth);
12307 RGFW_attribStack_pushAttribs(&stack, WGL_STENCIL_BITS_ARB, hints->stencil);
12308 RGFW_attribStack_pushAttribs(&stack, WGL_STEREO_ARB, hints->stereo);
12309 RGFW_attribStack_pushAttribs(&stack, WGL_AUX_BUFFERS_ARB, hints->auxBuffers);
12310 RGFW_attribStack_pushAttribs(&stack, WGL_RED_BITS_ARB, hints->red);
12311 RGFW_attribStack_pushAttribs(&stack, WGL_GREEN_BITS_ARB, hints->blue);
12312 RGFW_attribStack_pushAttribs(&stack, WGL_BLUE_BITS_ARB, hints->green);
12313 RGFW_attribStack_pushAttribs(&stack, WGL_ACCUM_RED_BITS_ARB, hints->accumRed);
12314 RGFW_attribStack_pushAttribs(&stack, WGL_ACCUM_GREEN_BITS_ARB, hints->accumGreen);
12315 RGFW_attribStack_pushAttribs(&stack, WGL_ACCUM_BLUE_BITS_ARB, hints->accumBlue);
12316 RGFW_attribStack_pushAttribs(&stack, WGL_ACCUM_ALPHA_BITS_ARB, hints->accumAlpha);
12317
12318 if(hints->sRGB) {
12319 if (hints->profile != RGFW_glES)
12320 RGFW_attribStack_pushAttribs(&stack, WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, 1);
12321 else
12322 RGFW_attribStack_pushAttribs(&stack, WGL_COLORSPACE_SRGB_EXT, hints->sRGB);
12323 }
12324
12325 RGFW_attribStack_pushAttribs(&stack, WGL_COVERAGE_SAMPLES_NV, hints->samples);
12326
12327 RGFW_attribStack_pushAttribs(&stack, 0, 0);
12328
12329 int new_pixel_format;
12330 UINT num_formats;
12331 wglChoosePixelFormatARB(win->src.hdc, pixel_format_attribs, 0, 1, &new_pixel_format, &num_formats);
12332 if (!num_formats)
12333 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errOpenGLContext, "Failed to create a pixel format for WGL");
12334 else pixel_format = new_pixel_format;
12335 }
12336
12337 PIXELFORMATDESCRIPTOR suggested;
12338 if (!DescribePixelFormat(win->src.hdc, pixel_format, sizeof(suggested), &suggested) ||
12339 !SetPixelFormat(win->src.hdc, pixel_format, &pfd))
12340 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errOpenGLContext, "Failed to set the WGL pixel format");
12341
12342 if (wglCreateContextAttribsARB != NULL) {
12343 /* create OpenGL/WGL context for the specified version */
12344 i32 attribs[40];
12345 RGFW_attribStack stack;
12346 RGFW_attribStack_init(&stack, attribs, 50);
12347
12348
12349 i32 mask = 0;
12350 switch (hints->profile) {
12351 case RGFW_glES: mask |= WGL_CONTEXT_ES_PROFILE_BIT_EXT; break;
12352 case RGFW_glCompatibility: mask |= WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; break;
12353 case RGFW_glForwardCompatibility: mask |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; break;
12354 case RGFW_glCore: mask |= WGL_CONTEXT_CORE_PROFILE_BIT_ARB; break;
12355 default: mask |= WGL_CONTEXT_CORE_PROFILE_BIT_ARB; break;
12356 }
12357
12358 RGFW_attribStack_pushAttribs(&stack, WGL_CONTEXT_PROFILE_MASK_ARB, mask);
12359
12360 if (hints->minor || hints->major) {
12361 RGFW_attribStack_pushAttribs(&stack, WGL_CONTEXT_MAJOR_VERSION_ARB, hints->major);
12362 RGFW_attribStack_pushAttribs(&stack, WGL_CONTEXT_MINOR_VERSION_ARB, hints->minor);
12363 }
12364
12365 if (RGFW_extensionSupportedPlatform_OpenGL(noError, sizeof(noError)))
12366 RGFW_attribStack_pushAttribs(&stack, WGL_CONTEXT_OPENGL_NO_ERROR_ARB, hints->noError);
12367
12368 if (RGFW_extensionSupportedPlatform_OpenGL(flushControl, sizeof(flushControl))) {
12369 if (hints->releaseBehavior == RGFW_glReleaseFlush) {
12370 RGFW_attribStack_pushAttribs(&stack, WGL_CONTEXT_RELEASE_BEHAVIOR_ARB, WGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB); /* WGL_CONTEXT_RELEASE_BEHAVIOR_ARB */
12371 } else if (hints->releaseBehavior == RGFW_glReleaseNone) {
12372 RGFW_attribStack_pushAttribs(&stack, WGL_CONTEXT_RELEASE_BEHAVIOR_ARB, WGL_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB);
12373 }
12374 }
12375
12376 i32 flags = 0;
12377 if (hints->debug) flags |= WGL_CONTEXT_DEBUG_BIT_ARB;
12378 if (hints->robustness && RGFW_extensionSupportedPlatform_OpenGL(robustness, sizeof(robustness))) flags |= WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB;
12379 if (flags) {
12380 RGFW_attribStack_pushAttribs(&stack, WGL_CONTEXT_FLAGS_ARB, flags);
12381 }
12382
12383
12384 RGFW_attribStack_pushAttribs(&stack, 0, 0);
12385
12386 win->src.ctx.native->ctx = (HGLRC)wglCreateContextAttribsARB(win->src.hdc, NULL, attribs);
12387 }
12388
12389 if (wglCreateContextAttribsARB == NULL || win->src.ctx.native->ctx == NULL) { /* fall back to a default context (probably OpenGL 2 or something) */
12390 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errOpenGLContext, "Failed to create an accelerated OpenGL Context.");
12391 win->src.ctx.native->ctx = wglCreateContext(win->src.hdc);
12392 }
12393
12394 ReleaseDC(win->src.window, win->src.hdc);
12395 win->src.hdc = GetDC(win->src.window);
12396
12397 if (hints->share) {
12398 wglShareLists((HGLRC)RGFW_getCurrentContext_OpenGL(), hints->share->ctx);
12399 }
12400
12401 wglMakeCurrent(win->src.hdc, win->src.ctx.native->ctx);
12402 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoOpenGL, "OpenGL context initalized.");
12403 return RGFW_TRUE;
12404 }
12405
12406 void RGFW_window_deleteContextPtr_OpenGL(RGFW_window* win, RGFW_glContext* ctx) {
12407 wglDeleteContext((HGLRC) ctx->ctx); /*!< delete OpenGL context */
12408 win->src.ctx.native->ctx = NULL;
12409 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoOpenGL, "OpenGL context freed.");
12410 }
12411
12412 void RGFW_window_makeCurrentContext_OpenGL(RGFW_window* win) {
12413 if (win == NULL)
12414 wglMakeCurrent(NULL, NULL);
12415 else
12416 wglMakeCurrent(win->src.hdc, (HGLRC) win->src.ctx.native->ctx);
12417 }
12418 void* RGFW_getCurrentContext_OpenGL(void) {
12419 return wglGetCurrentContext();
12420 }
12421 void RGFW_window_swapBuffers_OpenGL(RGFW_window* win) {
12422 RGFW_ASSERT(win->src.ctx.native);
12423 SwapBuffers(win->src.hdc);
12424 }
12425
12426 void RGFW_window_swapInterval_OpenGL(RGFW_window* win, i32 swapInterval) {
12427 RGFW_ASSERT(win != NULL);
12428 if (wglSwapIntervalEXT == NULL || wglSwapIntervalEXT(swapInterval) == FALSE)
12429 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errOpenGLContext, "Failed to set swap interval");
12430 }
12431 #endif
12432
12433 RGFW_bool RGFW_createUTF8FromWideStringWin32(const WCHAR* source, char* output, size_t max) {
12434 i32 size = 0;
12435 if (source == NULL) {
12436 return RGFW_FALSE;
12437 }
12438 size = WideCharToMultiByte(CP_UTF8, 0, source, -1, NULL, 0, NULL, NULL);
12439 if (!size) {
12440 return RGFW_FALSE;
12441 }
12442
12443 if (size > (i32)max)
12444 size = (i32)max;
12445
12446 if (!WideCharToMultiByte(CP_UTF8, 0, source, -1, output, size, NULL, NULL)) {
12447 return RGFW_FALSE;
12448 }
12449
12450 output[size] = 0;
12451 return RGFW_TRUE;
12452 }
12453
12454 #ifdef RGFW_WEBGPU
12455 WGPUSurface RGFW_window_createSurface_WebGPU(RGFW_window* window, WGPUInstance instance) {
12456 WGPUSurfaceDescriptor surfaceDesc = {0};
12457 WGPUSurfaceSourceWindowsHWND fromHwnd = {0};
12458 fromHwnd.chain.sType = WGPUSType_SurfaceSourceWindowsHWND;
12459 fromHwnd.hwnd = window->src.window;
12460
12461 fromHwnd.hinstance = GetModuleHandle(NULL);
12462
12463 surfaceDesc.nextInChain = (WGPUChainedStruct*)&fromHwnd.chain;
12464 return wgpuInstanceCreateSurface(instance, &surfaceDesc);
12465 }
12466 #endif
12467
12468 #endif /* RGFW_WINDOWS */
12469
12470 /*
12471 End of Windows defines
12472 */
12473
12474
12475
12476 /*
12477
12478 Start of MacOS defines
12479
12480
12481 */
12482
12483 #if defined(RGFW_MACOS)
12484 /*
12485 based on silicon.h
12486 start of cocoa wrapper
12487 */
12488
12489 #include <CoreGraphics/CoreGraphics.h>
12490 #include <ApplicationServices/ApplicationServices.h>
12491 #include <objc/runtime.h>
12492 #include <objc/message.h>
12493 #include <mach/mach_time.h>
12494
12495 #include <Carbon/Carbon.h>
12496
12497 typedef TISInputSourceRef (*PFN_TISCopyCurrentKeyboardLayoutInputSource)(void);
12498 PFN_TISCopyCurrentKeyboardLayoutInputSource TISCopyCurrentKeyboardLayoutInputSourceSrc;
12499 #define TISCopyCurrentKeyboardLayoutInputSource TISCopyCurrentKeyboardLayoutInputSourceSrc
12500
12501 typedef CFDataRef (*PFN_TISGetInputSourceProperty)(TISInputSourceRef, CFStringRef);
12502 PFN_TISGetInputSourceProperty TISGetInputSourcePropertySrc;
12503 #define TISGetInputSourceProperty TISGetInputSourcePropertySrc
12504
12505 typedef u8 (*PFN_LMGetKbdType)(void);
12506 PFN_LMGetKbdType LMGetKbdTypeSrc;
12507 #define LMGetKbdType LMGetKbdTypeSrc
12508
12509 CFStringRef kTISPropertyUnicodeKeyLayoutDataSrc;
12510
12511 #ifndef __OBJC__
12512 typedef CGRect NSRect;
12513 typedef CGPoint NSPoint;
12514 typedef CGSize NSSize;
12515
12516 typedef const char* NSPasteboardType;
12517 typedef unsigned long NSUInteger;
12518 typedef long NSInteger;
12519 typedef NSInteger NSModalResponse;
12520
12521 typedef enum NSRequestUserAttentionType {
12522 NSCriticalRequest = 0,
12523 NSInformationalRequest = 10
12524 } NSRequestUserAttentionType;
12525
12526 typedef enum NSApplicationActivationPolicy {
12527 NSApplicationActivationPolicyRegular,
12528 NSApplicationActivationPolicyAccessory,
12529 NSApplicationActivationPolicyProhibited
12530 } NSApplicationActivationPolicy;
12531
12532 typedef RGFW_ENUM(u32, NSBackingStoreType) {
12533 NSBackingStoreRetained = 0,
12534 NSBackingStoreNonretained = 1,
12535 NSBackingStoreBuffered = 2
12536 };
12537
12538 typedef RGFW_ENUM(u32, NSWindowStyleMask) {
12539 NSWindowStyleMaskBorderless = 0,
12540 NSWindowStyleMaskTitled = 1 << 0,
12541 NSWindowStyleMaskClosable = 1 << 1,
12542 NSWindowStyleMaskMiniaturizable = 1 << 2,
12543 NSWindowStyleMaskResizable = 1 << 3,
12544 NSWindowStyleMaskTexturedBackground = 1 << 8, /* deprecated */
12545 NSWindowStyleMaskUnifiedTitleAndToolbar = 1 << 12,
12546 NSWindowStyleMaskFullScreen = 1 << 14,
12547 NSWindowStyleMaskFullSizeContentView = 1 << 15,
12548 NSWindowStyleMaskUtilityWindow = 1 << 4,
12549 NSWindowStyleMaskDocModalWindow = 1 << 6,
12550 NSWindowStyleMaskNonactivatingpanel = 1 << 7,
12551 NSWindowStyleMaskHUDWindow = 1 << 13
12552 };
12553
12554 #define NSPasteboardTypeString "public.utf8-plain-text"
12555
12556 typedef RGFW_ENUM(i32, NSDragOperation) {
12557 NSDragOperationNone = 0,
12558 NSDragOperationCopy = 1,
12559 NSDragOperationLink = 2,
12560 NSDragOperationGeneric = 4,
12561 NSDragOperationPrivate = 8,
12562 NSDragOperationMove = 16,
12563 NSDragOperationDelete = 32,
12564 NSDragOperationEvery = (int)ULONG_MAX
12565 };
12566
12567 typedef RGFW_ENUM(NSInteger, NSOpenGLContextParameter) {
12568 NSOpenGLContextParameterSwapInterval = 222, /* 1 param. 0 -> Don't sync, 1 -> Sync to vertical retrace */
12569 NSOpenGLContextParametectxaceOrder = 235, /* 1 param. 1 -> Above Window (default), -1 -> Below Window */
12570 NSOpenGLContextParametectxaceOpacity = 236, /* 1 param. 1-> Surface is opaque (default), 0 -> non-opaque */
12571 NSOpenGLContextParametectxaceBackingSize = 304, /* 2 params. Width/height of surface backing size */
12572 NSOpenGLContextParameterReclaimResources = 308, /* 0 params. */
12573 NSOpenGLContextParameterCurrentRendererID = 309, /* 1 param. Retrieves the current renderer ID */
12574 NSOpenGLContextParameterGPUVertexProcessing = 310, /* 1 param. Currently processing vertices with GPU (get) */
12575 NSOpenGLContextParameterGPUFragmentProcessing = 311, /* 1 param. Currently processing fragments with GPU (get) */
12576 NSOpenGLContextParameterHasDrawable = 314, /* 1 param. Boolean returned if drawable is attached */
12577 NSOpenGLContextParameterMPSwapsInFlight = 315, /* 1 param. Max number of swaps queued by the MP GL engine */
12578
12579 NSOpenGLContextParameterSwapRectangle API_DEPRECATED("", macos(10.0, 10.14)) = 200, /* 4 params. Set or get the swap rectangle {x, y, w, h} */
12580 NSOpenGLContextParameterSwapRectangleEnable API_DEPRECATED("", macos(10.0, 10.14)) = 201, /* Enable or disable the swap rectangle */
12581 NSOpenGLContextParameterRasterizationEnable API_DEPRECATED("", macos(10.0, 10.14)) = 221, /* Enable or disable all rasterization */
12582 NSOpenGLContextParameterStateValidation API_DEPRECATED("", macos(10.0, 10.14)) = 301, /* Validate state for multi-screen functionality */
12583 NSOpenGLContextParametectxaceSurfaceVolatile API_DEPRECATED("", macos(10.0, 10.14)) = 306, /* 1 param. Surface volatile state */
12584 };
12585
12586 typedef RGFW_ENUM(NSInteger, NSWindowButton) {
12587 NSWindowCloseButton = 0,
12588 NSWindowMiniaturizeButton = 1,
12589 NSWindowZoomButton = 2,
12590 NSWindowToolbarButton = 3,
12591 NSWindowDocumentIconButton = 4,
12592 NSWindowDocumentVersionsButton = 6,
12593 NSWindowFullScreenButton = 7,
12594 };
12595
12596 #define NSPasteboardTypeURL "public.url"
12597 #define NSPasteboardTypeFileURL "public.file-url"
12598 #define NSTrackingMouseEnteredAndExited 0x01
12599 #define NSTrackingMouseMoved 0x02
12600 #define NSTrackingCursorUpdate 0x04
12601 #define NSTrackingActiveWhenFirstResponder 0x10
12602 #define NSTrackingActiveInKeyWindow 0x20
12603 #define NSTrackingActiveInActiveApp 0x40
12604 #define NSTrackingActiveAlways 0x80
12605 #define NSTrackingAssumeInside 0x100
12606 #define NSTrackingInVisibleRect 0x200
12607 #define NSTrackingEnabledDuringMouseDrag 0x400
12608 enum {
12609 NSOpenGLPFAAllRenderers = 1, /* choose from all available renderers */
12610 NSOpenGLPFATripleBuffer = 3, /* choose a triple buffered pixel format */
12611 NSOpenGLPFADoubleBuffer = 5, /* choose a double buffered pixel format */
12612 NSOpenGLPFAAuxBuffers = 7, /* number of aux buffers */
12613 NSOpenGLPFAColorSize = 8, /* number of color buffer bits */
12614 NSOpenGLPFAAlphaSize = 11, /* number of alpha component bits */
12615 NSOpenGLPFADepthSize = 12, /* number of depth buffer bits */
12616 NSOpenGLPFAStencilSize = 13, /* number of stencil buffer bits */
12617 NSOpenGLPFAAccumSize = 14, /* number of accum buffer bits */
12618 NSOpenGLPFAMinimumPolicy = 51, /* never choose smaller buffers than requested */
12619 NSOpenGLPFAMaximumPolicy = 52, /* choose largest buffers of type requested */
12620 NSOpenGLPFASampleBuffers = 55, /* number of multi sample buffers */
12621 NSOpenGLPFASamples = 56, /* number of samples per multi sample buffer */
12622 NSOpenGLPFAAuxDepthStencil = 57, /* each aux buffer has its own depth stencil */
12623 NSOpenGLPFAColorFloat = 58, /* color buffers store floating point pixels */
12624 NSOpenGLPFAMultisample = 59, /* choose multisampling */
12625 NSOpenGLPFASupersample = 60, /* choose supersampling */
12626 NSOpenGLPFASampleAlpha = 61, /* request alpha filtering */
12627 NSOpenGLPFARendererID = 70, /* request renderer by ID */
12628 NSOpenGLPFANoRecovery = 72, /* disable all failure recovery systems */
12629 NSOpenGLPFAAccelerated = 73, /* choose a hardware accelerated renderer */
12630 NSOpenGLPFAClosestPolicy = 74, /* choose the closest color buffer to request */
12631 NSOpenGLPFABackingStore = 76, /* back buffer contents are valid after swap */
12632 NSOpenGLPFAScreenMask = 84, /* bit mask of supported physical screens */
12633 NSOpenGLPFAAllowOfflineRenderers = 96, /* allow use of offline renderers */
12634 NSOpenGLPFAAcceleratedCompute = 97, /* choose a hardware accelerated compute device */
12635 NSOpenGLPFAOpenGLProfile = 99, /* specify an OpenGL Profile to use */
12636 NSOpenGLProfileVersionLegacy = 0x1000, /* The requested profile is a legacy (pre-OpenGL 3.0) profile. */
12637 NSOpenGLProfileVersion3_2Core = 0x3200, /* The 3.2 Profile of OpenGL */
12638 NSOpenGLProfileVersion4_1Core = 0x3200, /* The 4.1 profile of OpenGL */
12639 NSOpenGLPFAVirtualScreenCount = 128, /* number of virtual screens in this format */
12640 NSOpenGLPFAStereo = 6,
12641 NSOpenGLPFAOffScreen = 53,
12642 NSOpenGLPFAFullScreen = 54,
12643 NSOpenGLPFASingleRenderer = 71,
12644 NSOpenGLPFARobust = 75,
12645 NSOpenGLPFAMPSafe = 78,
12646 NSOpenGLPFAWindow = 80,
12647 NSOpenGLPFAMultiScreen = 81,
12648 NSOpenGLPFACompliant = 83,
12649 NSOpenGLPFAPixelBuffer = 90,
12650 NSOpenGLPFARemotePixelBuffer = 91,
12651 };
12652
12653 typedef RGFW_ENUM(u32, NSEventType) { /* various types of events */
12654 NSEventTypeApplicationDefined = 15,
12655 };
12656 typedef unsigned long long NSEventMask;
12657
12658 typedef enum NSEventModifierFlags {
12659 NSEventModifierFlagCapsLock = 1 << 16,
12660 NSEventModifierFlagShift = 1 << 17,
12661 NSEventModifierFlagControl = 1 << 18,
12662 NSEventModifierFlagOption = 1 << 19,
12663 NSEventModifierFlagCommand = 1 << 20,
12664 NSEventModifierFlagNumericPad = 1 << 21
12665 } NSEventModifierFlags;
12666
12667 typedef RGFW_ENUM(NSUInteger, NSBitmapFormat) {
12668 NSBitmapFormatAlphaFirst = 1 << 0, /* 0 means is alpha last (RGBA, CMYKA, etc.) */
12669 NSBitmapFormatAlphaNonpremultiplied = 1 << 1, /* 0 means is premultiplied */
12670 NSBitmapFormatFloatingpointSamples = 1 << 2, /* 0 is integer */
12671
12672 NSBitmapFormatSixteenBitLittleEndian = (1 << 8),
12673 NSBitmapFormatThirtyTwoBitLittleEndian = (1 << 9),
12674 NSBitmapFormatSixteenBitBigEndian = (1 << 10),
12675 NSBitmapFormatThirtyTwoBitBigEndian = (1 << 11)
12676 };
12677
12678 #else
12679 #import <AppKit/AppKit.h>
12680 #include <Foundation/Foundation.h>
12681 #endif /* notdef __OBJC__ */
12682
12683 #ifdef __arm64__
12684 /* ARM just uses objc_msgSend */
12685 #define abi_objc_msgSend_stret objc_msgSend
12686 #define abi_objc_msgSend_fpret objc_msgSend
12687 #else /* __i386__ */
12688 /* x86 just uses abi_objc_msgSend_fpret and (NSColor *)objc_msgSend_id respectively */
12689 #define abi_objc_msgSend_stret objc_msgSend_stret
12690 #define abi_objc_msgSend_fpret objc_msgSend_fpret
12691 #endif
12692
12693 #define NSAlloc(nsclass) objc_msgSend_id((id)nsclass, sel_registerName("alloc"))
12694 #define objc_msgSend_bool(x, y) ((BOOL (*)(id, SEL))objc_msgSend) ((id)(x), (SEL)y)
12695 #define objc_msgSend_void(x, y) ((void (*)(id, SEL))objc_msgSend) ((id)(x), (SEL)y)
12696 #define objc_msgSend_void_id(x, y, z) ((void (*)(id, SEL, id))objc_msgSend) ((id)x, (SEL)y, (id)z)
12697 #define objc_msgSend_uint(x, y) ((NSUInteger (*)(id, SEL))objc_msgSend) ((id)(x), (SEL)y)
12698 #define objc_msgSend_void_bool(x, y, z) ((void (*)(id, SEL, BOOL))objc_msgSend) ((id)(x), (SEL)y, (BOOL)z)
12699 #define objc_msgSend_bool_void(x, y) ((BOOL (*)(id, SEL))objc_msgSend) ((id)(x), (SEL)y)
12700 #define objc_msgSend_void_SEL(x, y, z) ((void (*)(id, SEL, SEL))objc_msgSend) ((id)(x), (SEL)y, (SEL)z)
12701 #define objc_msgSend_id(x, y) ((id (*)(id, SEL))objc_msgSend) ((id)(x), (SEL)y)
12702 #define objc_msgSend_id_id(x, y, z) ((id (*)(id, SEL, id))objc_msgSend) ((id)(x), (SEL)y, (id)z)
12703 #define objc_msgSend_id_bool(x, y, z) ((BOOL (*)(id, SEL, id))objc_msgSend) ((id)(x), (SEL)y, (id)z)
12704 #define objc_msgSend_int(x, y, z) ((id (*)(id, SEL, int))objc_msgSend) ((id)(x), (SEL)y, (int)z)
12705 #define objc_msgSend_arr(x, y, z) ((id (*)(id, SEL, int))objc_msgSend) ((id)(x), (SEL)y, (int)z)
12706 #define objc_msgSend_ptr(x, y, z) ((id (*)(id, SEL, void*))objc_msgSend) ((id)(x), (SEL)y, (void*)z)
12707 #define objc_msgSend_class(x, y) ((id (*)(Class, SEL))objc_msgSend) ((Class)(x), (SEL)y)
12708 #define objc_msgSend_class_char(x, y, z) ((id (*)(Class, SEL, char*))objc_msgSend) ((Class)(x), (SEL)y, (char*)z)
12709
12710 #define NSRelease(obj) objc_msgSend_void((id)obj, sel_registerName("release"))
12711 RGFWDEF id NSString_stringWithUTF8String(const char* str);
12712 id NSString_stringWithUTF8String(const char* str) {
12713 return ((id(*)(id, SEL, const char*))objc_msgSend) ((id)objc_getClass("NSString"), sel_registerName("stringWithUTF8String:"), str);
12714 }
12715
12716 RGFWDEF float RGFW_cocoaYTransform(float y);
12717 float RGFW_cocoaYTransform(float y) { return (float)(CGDisplayBounds(CGMainDisplayID()).size.height - (double)y - (double)1.0f); }
12718
12719 const char* NSString_to_char(id str);
12720 const char* NSString_to_char(id str) {
12721 return ((const char* (*)(id, SEL)) objc_msgSend) ((id)(id)str, sel_registerName("UTF8String"));
12722 }
12723
12724 unsigned char* NSBitmapImageRep_bitmapData(id imageRep);
12725 unsigned char* NSBitmapImageRep_bitmapData(id imageRep) {
12726 return ((unsigned char* (*)(id, SEL))objc_msgSend) ((id)imageRep, sel_registerName("bitmapData"));
12727 }
12728
12729 id NSBitmapImageRep_initWithBitmapData(unsigned char** planes, NSInteger width, NSInteger height, NSInteger bps, NSInteger spp, bool alpha, bool isPlanar, const char* colorSpaceName, NSBitmapFormat bitmapFormat, NSInteger rowBytes, NSInteger pixelBits);
12730 id NSBitmapImageRep_initWithBitmapData(unsigned char** planes, NSInteger width, NSInteger height, NSInteger bps, NSInteger spp, bool alpha, bool isPlanar, const char* colorSpaceName, NSBitmapFormat bitmapFormat, NSInteger rowBytes, NSInteger pixelBits) {
12731 SEL func = sel_registerName("initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bitmapFormat:bytesPerRow:bitsPerPixel:");
12732
12733 return (id) ((id(*)(id, SEL, unsigned char**, NSInteger, NSInteger, NSInteger, NSInteger, bool, bool, id, NSBitmapFormat, NSInteger, NSInteger))objc_msgSend)
12734 (NSAlloc((id)objc_getClass("NSBitmapImageRep")), func, planes, width, height, bps, spp, alpha, isPlanar, NSString_stringWithUTF8String(colorSpaceName), bitmapFormat, rowBytes, pixelBits);
12735 }
12736
12737 id NSColor_colorWithSRGB(CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha);
12738 id NSColor_colorWithSRGB(CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha) {
12739 Class nsclass = objc_getClass("NSColor");
12740 SEL func = sel_registerName("colorWithSRGBRed:green:blue:alpha:");
12741 return ((id(*)(id, SEL, CGFloat, CGFloat, CGFloat, CGFloat))objc_msgSend)
12742 ((id)nsclass, func, red, green, blue, alpha);
12743 }
12744
12745 id NSPasteboard_generalPasteboard(void);
12746 id NSPasteboard_generalPasteboard(void) {
12747 return (id) objc_msgSend_id((id)objc_getClass("NSPasteboard"), sel_registerName("generalPasteboard"));
12748 }
12749
12750 id* cstrToNSStringArray(char** strs, size_t len);
12751 id* cstrToNSStringArray(char** strs, size_t len) {
12752 static id nstrs[6];
12753 size_t i;
12754 for (i = 0; i < len; i++)
12755 nstrs[i] = NSString_stringWithUTF8String(strs[i]);
12756
12757 return nstrs;
12758 }
12759
12760 const char* NSPasteboard_stringForType(id pasteboard, NSPasteboardType dataType, size_t* len);
12761 const char* NSPasteboard_stringForType(id pasteboard, NSPasteboardType dataType, size_t* len) {
12762 SEL func = sel_registerName("stringForType:");
12763 id nsstr = NSString_stringWithUTF8String((const char*)dataType);
12764 id nsString = ((id(*)(id, SEL, id))objc_msgSend)(pasteboard, func, nsstr);
12765 const char* str = NSString_to_char(nsString);
12766 if (len != NULL)
12767 *len = (size_t)((NSUInteger(*)(id, SEL, int))objc_msgSend)(nsString, sel_registerName("maximumLengthOfBytesUsingEncoding:"), 4);
12768 return str;
12769 }
12770
12771 id c_array_to_NSArray(void* array, size_t len);
12772 id c_array_to_NSArray(void* array, size_t len) {
12773 return ((id (*)(id, SEL, void*, NSUInteger))objc_msgSend) (NSAlloc(objc_getClass("NSArray")), sel_registerName("initWithObjects:count:"), array, len);
12774 }
12775
12776
12777 void NSregisterForDraggedTypes(id view, NSPasteboardType* newTypes, size_t len);
12778 void NSregisterForDraggedTypes(id view, NSPasteboardType* newTypes, size_t len) {
12779 id* ntypes = cstrToNSStringArray((char**)newTypes, len);
12780
12781 id array = c_array_to_NSArray(ntypes, len);
12782 objc_msgSend_void_id(view, sel_registerName("registerForDraggedTypes:"), array);
12783 NSRelease(array);
12784 }
12785
12786 NSInteger NSPasteBoard_declareTypes(id pasteboard, NSPasteboardType* newTypes, size_t len, void* owner);
12787 NSInteger NSPasteBoard_declareTypes(id pasteboard, NSPasteboardType* newTypes, size_t len, void* owner) {
12788 id* ntypes = cstrToNSStringArray((char**)newTypes, len);
12789
12790 SEL func = sel_registerName("declareTypes:owner:");
12791
12792 id array = c_array_to_NSArray(ntypes, len);
12793
12794 NSInteger output = ((NSInteger(*)(id, SEL, id, void*))objc_msgSend)
12795 (pasteboard, func, array, owner);
12796 NSRelease(array);
12797
12798 return output;
12799 }
12800
12801 #define NSRetain(obj) objc_msgSend_void((id)obj, sel_registerName("retain"))
12802
12803 /*
12804 End of cocoa wrapper
12805 */
12806
12807 static id RGFW__osxCustomInitWithRGFWWindow(id self, SEL _cmd, RGFW_window* win) {
12808 RGFW_UNUSED(_cmd);
12809 struct objc_super s = { self, class_getSuperclass(object_getClass(self)) };
12810 self = ((id (*)(struct objc_super*, SEL))objc_msgSendSuper)(&s, sel_registerName("init"));
12811
12812 if (self != nil) {
12813 object_setInstanceVariable(self, "RGFW_window", win);
12814 object_setInstanceVariable(self, "trackingArea", nil);
12815
12816 object_setInstanceVariable(
12817 self, "markedText",
12818 ((id (*)(id, SEL))objc_msgSend)(
12819 ((id (*)(Class, SEL))objc_msgSend)(objc_getClass("NSMutableAttributedString"), sel_registerName("alloc")),
12820 sel_registerName("init")
12821 )
12822 );
12823
12824 ((void (*)(id, SEL))objc_msgSend)(self, sel_registerName("updateTrackingAreas"));
12825
12826 ((void (*)(id, SEL, id))objc_msgSend)(
12827 self, sel_registerName("registerForDraggedTypes:"),
12828 ((id (*)(Class, SEL, id))objc_msgSend)(
12829 objc_getClass("NSArray"),
12830 sel_registerName("arrayWithObject:"),
12831 ((id (*)(Class, SEL, const char*))objc_msgSend)(
12832 objc_getClass("NSString"),
12833 sel_registerName("stringWithUTF8String:"),
12834 "public.url"
12835 )
12836 )
12837 );
12838 }
12839
12840 return self;
12841 }
12842
12843 static u32 RGFW_OnClose(id self) {
12844 RGFW_window* win = NULL;
12845 object_getInstanceVariable(self, (const char*)"RGFW_window", (void**)&win);
12846 if (win == NULL) return true;
12847
12848 RGFW_windowQuitCallback(win);
12849 return false;
12850 }
12851
12852 /* NOTE(EimaMei): Fixes the constant clicking when the app is running under a terminal. */
12853 static bool RGFW__osxAcceptsFirstResponder(void) { return true; }
12854 static bool RGFW__osxPerformKeyEquivalent(id event) { RGFW_UNUSED(event); return true; }
12855
12856 static NSDragOperation RGFW__osxDraggingEntered(id self, SEL sel, id sender) {
12857 RGFW_UNUSED(sender); RGFW_UNUSED(self); RGFW_UNUSED(sel);
12858
12859 return NSDragOperationCopy;
12860 }
12861 static NSDragOperation RGFW__osxDraggingUpdated(id self, SEL sel, id sender) {
12862 RGFW_UNUSED(sel);
12863
12864 RGFW_window* win = NULL;
12865
12866 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
12867 if (win == NULL)
12868 return 0;
12869 if (!(win->internal.enabledEvents & RGFW_dataDragFlag)) return NSDragOperationCopy;
12870
12871 NSPoint p = ((NSPoint(*)(id, SEL)) objc_msgSend)(sender, sel_registerName("draggingLocation"));
12872 RGFW_dataDragCallback(win, (i32) p.x, (i32) (win->h - p.y));
12873 return NSDragOperationCopy;
12874 }
12875 static bool RGFW__osxPrepareForDragOperation(id self) {
12876 RGFW_window* win = NULL;
12877 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
12878 if (win == NULL || (!(win->internal.enabledEvents & RGFW_dataDropFlag)))
12879 return true;
12880
12881 if (!(win->internal.flags & RGFW_windowAllowDND)) {
12882 return false;
12883 }
12884
12885 return true;
12886 }
12887
12888 void RGFW__osxDraggingEnded(id self, SEL sel, id sender);
12889 void RGFW__osxDraggingEnded(id self, SEL sel, id sender) { RGFW_UNUSED(sender); RGFW_UNUSED(self); RGFW_UNUSED(sel); return; }
12890
12891 static bool RGFW__osxPerformDragOperation(id self, SEL sel, id sender) {
12892 RGFW_UNUSED(sender); RGFW_UNUSED(self); RGFW_UNUSED(sel);
12893
12894 RGFW_window* win = NULL;
12895 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
12896 if (win == NULL || (!(win->internal.enabledEvents & RGFW_dataDropFlag)))
12897 return false;
12898
12899 /* id pasteBoard = objc_msgSend_id(sender, sel_registerName("draggingPasteboard")); */
12900
12901 id pasteBoard = objc_msgSend_id(sender, sel_registerName("draggingPasteboard"));
12902
12903 /* Get the types of data available on the pasteboard */
12904 id types = objc_msgSend_id(pasteBoard, sel_registerName("types"));
12905
12906 /* Get the string type for file URLs */
12907 id fileURLsType = objc_msgSend_class_char(objc_getClass("NSString"), sel_registerName("stringWithUTF8String:"), "NSFilenamesPboardType");
12908
12909 /* Check if the pasteboard contains file URLs */
12910 if (objc_msgSend_id_bool(types, sel_registerName("containsObject:"), fileURLsType) == 0) {
12911 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errClipboard, "No files found on the pasteboard.");
12912 return 0;
12913 }
12914
12915 id fileURLs = objc_msgSend_id_id(pasteBoard, sel_registerName("propertyListForType:"), fileURLsType);
12916 int count = ((int (*)(id, SEL))objc_msgSend)(fileURLs, sel_registerName("count"));
12917
12918 if (count == 0)
12919 return 0;
12920
12921 char** files = (char**)(void*)_RGFW->files;
12922
12923 u32 i;
12924 for (i = 0; i < (u32)count; i++) {
12925 id fileURL = objc_msgSend_arr(fileURLs, sel_registerName("objectAtIndex:"), i);
12926 const char *filePath = ((const char* (*)(id, SEL))objc_msgSend)(fileURL, sel_registerName("UTF8String"));
12927 RGFW_STRNCPY(files[i], filePath, RGFW_MAX_PATH - 1);
12928 files[i][RGFW_MAX_PATH - 1] = '\0';
12929 }
12930
12931 RGFW_dataDropCallback(win, files, (size_t)count);
12932
12933 return false;
12934 }
12935
12936 #ifndef RGFW_NO_IOKIT
12937 #include <IOKit/IOKitLib.h>
12938
12939 float RGFW_osx_getFallbackRefreshRate(CGDirectDisplayID displayID);
12940 float RGFW_osx_getFallbackRefreshRate(CGDirectDisplayID displayID) {
12941 float refreshRate = 0;
12942 io_iterator_t it;
12943 io_service_t service;
12944 CFNumberRef indexRef, clockRef, countRef;
12945 u32 clock, count;
12946
12947 #ifdef kIOMainPortDefault
12948 if (IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOFramebuffer"), &it) != 0)
12949 #elif defined(kIOMasterPortDefault)
12950 if (IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOFramebuffer"), &it) != 0)
12951 #endif
12952 return RGFW_FALSE;
12953
12954 while ((service = IOIteratorNext(it)) != 0) {
12955 u32 index;
12956 indexRef = (CFNumberRef)IORegistryEntryCreateCFProperty(service, CFSTR("IOFramebufferOpenGLIndex"), kCFAllocatorDefault, kNilOptions);
12957 if (indexRef == 0) continue;
12958
12959 if (CFNumberGetValue(indexRef, kCFNumberIntType, &index) && CGOpenGLDisplayMaskToDisplayID(1 << index) == displayID) {
12960 CFRelease(indexRef);
12961 break;
12962 }
12963
12964 CFRelease(indexRef);
12965 }
12966
12967 if (service) {
12968 clockRef = (CFNumberRef)IORegistryEntryCreateCFProperty(service, CFSTR("IOFBCurrentPixelClock"), kCFAllocatorDefault, kNilOptions);
12969 if (clockRef) {
12970 if (CFNumberGetValue(clockRef, kCFNumberIntType, &clock) && clock) {
12971 countRef = (CFNumberRef)IORegistryEntryCreateCFProperty(service, CFSTR("IOFBCurrentPixelCount"), kCFAllocatorDefault, kNilOptions);
12972 if (countRef && CFNumberGetValue(countRef, kCFNumberIntType, &count) && count) {
12973 refreshRate = (float)((double)clock / (double) count);
12974 CFRelease(countRef);
12975 }
12976 }
12977 CFRelease(clockRef);
12978 }
12979 }
12980
12981 IOObjectRelease(it);
12982 return refreshRate;
12983 }
12984 #endif
12985
12986 void RGFW_moveToMacOSResourceDir(void) {
12987 char resourcesPath[256];
12988
12989 CFBundleRef bundle = CFBundleGetMainBundle();
12990 if (!bundle)
12991 return;
12992
12993 CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(bundle);
12994 CFStringRef last = CFURLCopyLastPathComponent(resourcesURL);
12995
12996 if (
12997 CFStringCompare(CFSTR("Resources"), last, 0) != kCFCompareEqualTo ||
12998 CFURLGetFileSystemRepresentation(resourcesURL, true, (u8*) resourcesPath, 255) == 0
12999 ) {
13000 CFRelease(last);
13001 CFRelease(resourcesURL);
13002 return;
13003 }
13004
13005 CFRelease(last);
13006 CFRelease(resourcesURL);
13007
13008 chdir(resourcesPath);
13009 }
13010
13011 static void RGFW__osxDidChangeScreenParameters(id self, SEL _cmd, id notification) {
13012 RGFW_UNUSED(self); RGFW_UNUSED(_cmd); RGFW_UNUSED(notification);
13013 RGFW_pollMonitors();
13014 }
13015
13016 static void RGFW__osxWindowDeminiaturize(id self, SEL sel) {
13017 RGFW_UNUSED(sel);
13018 RGFW_window* win = NULL;
13019 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13020 if (win == NULL) return;
13021
13022 RGFW_windowRestoredCallback(win, win->x, win->y, win->w, win->h);
13023
13024 }
13025 static void RGFW__osxWindowMiniaturize(id self, SEL sel) {
13026 RGFW_UNUSED(sel);
13027 RGFW_window* win = NULL;
13028 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13029 if (win == NULL) return;
13030
13031 RGFW_windowMinimizedCallback(win);
13032
13033 }
13034
13035 static void RGFW__osxWindowBecameKey(id self, SEL sel) {
13036 RGFW_UNUSED(sel);
13037 RGFW_window* win = NULL;
13038 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13039 if (win == NULL) return;
13040
13041 RGFW_focusCallback(win, RGFW_TRUE);
13042 }
13043
13044 static void RGFW__osxWindowResignKey(id self, SEL sel) {
13045 RGFW_UNUSED(sel);
13046 RGFW_window* win = NULL;
13047 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13048 if (win == NULL) return;
13049
13050 RGFW_focusCallback(win, RGFW_FALSE);
13051 }
13052
13053 static void RGFW__osxDidWindowResize(id self, SEL _cmd, id notification) {
13054 RGFW_UNUSED(_cmd); RGFW_UNUSED(notification);
13055 RGFW_window* win = NULL;
13056 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13057 if (win == NULL) return;
13058
13059 NSRect frame;
13060 if (win->src.view) frame = ((NSRect(*)(id, SEL))abi_objc_msgSend_stret)((id)win->src.view, sel_registerName("frame"));
13061 else return;
13062
13063 if (frame.size.width == 0 || frame.size.height == 0) return;
13064 win->w = (i32)frame.size.width;
13065 win->h = (i32)frame.size.height;
13066
13067 RGFW_monitor* mon = RGFW_window_getMonitor(win);
13068 if (mon == NULL) return;
13069
13070 if ((i32)mon->mode.w == win->w && (i32)mon->mode.h - 102 <= win->h) {
13071 RGFW_windowMaximizedCallback(win, 0, 0, win->w, win->h);
13072 } else if (win->internal.flags & RGFW_windowMaximize) {
13073 RGFW_windowRestoredCallback(win, win->x, win->y, win->w, win->h);
13074 }
13075
13076 RGFW_windowResizedCallback(win, win->w, win->h);
13077 }
13078
13079 static void RGFW__osxWindowMove(id self, SEL sel) {
13080 RGFW_UNUSED(sel);
13081 RGFW_window* win = NULL;
13082 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13083 if (win == NULL) return;
13084
13085 NSRect frame = ((NSRect(*)(id, SEL))abi_objc_msgSend_stret)((id)win->src.window, sel_registerName("frame"));
13086 NSRect content = ((NSRect(*)(id, SEL, NSRect))abi_objc_msgSend_stret)((id)win->src.window, sel_registerName("contentRectForFrameRect:"), frame);
13087
13088 float y = RGFW_cocoaYTransform((float)(content.origin.y + content.size.height - 1));
13089
13090 RGFW_windowMovedCallback(win, (i32)content.origin.x, (i32)y);
13091 }
13092
13093 static void RGFW__osxViewDidChangeBackingProperties(id self, SEL _cmd) {
13094 RGFW_UNUSED(_cmd);
13095 RGFW_window* win = NULL;
13096 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13097 if (win == NULL) return;
13098
13099 RGFW_monitor* mon = RGFW_window_getMonitor(win);
13100 if (mon == NULL) return;
13101
13102 RGFW_scaleUpdatedCallback(win, mon->scaleX, mon->scaleY);
13103 }
13104
13105 static BOOL RGFW__osxWantsUpdateLayer(id self, SEL _cmd) { RGFW_UNUSED(self); RGFW_UNUSED(_cmd); return YES; }
13106
13107 static void RGFW__osxUpdateLayer(id self, SEL _cmd) {
13108 RGFW_UNUSED(self); RGFW_UNUSED(_cmd);
13109 RGFW_window* win = NULL;
13110 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13111 if (win == NULL) return;
13112 RGFW_windowRefreshCallback(win);
13113 }
13114
13115 static void RGFW__osxDrawRect(id self, SEL _cmd, CGRect rect) {
13116 RGFW_UNUSED(rect); RGFW_UNUSED(_cmd);
13117 RGFW_window* win = NULL;
13118 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13119 if (win == NULL) return;
13120
13121 RGFW_windowRefreshCallback(win);
13122 }
13123
13124 static void RGFW__osxMouseEntered(id self, SEL _cmd, id event) {
13125 RGFW_UNUSED(_cmd);
13126 RGFW_window* win = NULL;
13127 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13128 if (win == NULL) return;
13129
13130 NSPoint p = ((NSPoint(*)(id, SEL))objc_msgSend)(event, sel_registerName("locationInWindow"));
13131 RGFW_mouseNotifyCallback(win, (i32)p.x, (i32)(win->h - p.y), 1);
13132 }
13133
13134 static void RGFW__osxMouseExited(id self, SEL _cmd, id event) {
13135 RGFW_UNUSED(_cmd); RGFW_UNUSED(event);
13136 RGFW_window* win = NULL;
13137 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13138 if (win == NULL) return;
13139
13140 RGFW_mouseNotifyCallback(win, win->internal.lastMouseX, win->internal.lastMouseY, RGFW_FALSE);
13141 }
13142
13143 static void RGFW__osxKeyDown(id self, SEL _cmd, id event) {
13144 RGFW_UNUSED(_cmd);
13145 RGFW_window* win = NULL;
13146 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13147 if (win == NULL || !(win->internal.enabledEvents & RGFW_keyPressedFlag)) return;
13148
13149 u32 key = (u16)((u32(*)(id, SEL))objc_msgSend)(event, sel_registerName("keyCode"));
13150
13151 RGFW_key value = (u8)RGFW_apiKeyToRGFW(key);
13152 RGFW_bool repeat = RGFW_window_isKeyPressed(win, value);
13153
13154 RGFW_keyCallback(win, value, win->internal.mod, repeat, 1);
13155
13156 id nsstring = ((id(*)(id, SEL))objc_msgSend)(event, sel_registerName("charactersIgnoringModifiers"));
13157 const char* string = NSString_to_char(nsstring);
13158 size_t count = (size_t)((int (*)(id, SEL))objc_msgSend)(nsstring, sel_registerName("length"));
13159
13160 for (size_t index = 0; index < count;
13161 RGFW_keyCharCallback(win, RGFW_decodeUTF8(&string[index], &index))
13162 );
13163 }
13164
13165 static void RGFW__osxKeyUp(id self, SEL _cmd, id event) {
13166 RGFW_UNUSED(_cmd);
13167 RGFW_window* win = NULL;
13168 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13169 if (win == NULL || !(win->internal.enabledEvents & RGFW_keyReleasedFlag)) return;
13170
13171 u32 key = (u16)((u32(*)(id, SEL))objc_msgSend)(event, sel_registerName("keyCode"));
13172
13173 RGFW_key value = (u8)RGFW_apiKeyToRGFW(key);
13174 RGFW_bool repeat = RGFW_window_isKeyDown(win, (u8)value);
13175
13176 RGFW_keyCallback(win, value, win->internal.mod, repeat, 0);
13177 }
13178
13179 static void RGFW__osxFlagsChanged(id self, SEL _cmd, id event) {
13180 RGFW_UNUSED(_cmd);
13181 RGFW_window* win = NULL;
13182 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13183 if (win == NULL) return;
13184
13185 RGFW_key value = 0;
13186 RGFW_bool pressed = RGFW_FALSE;
13187
13188 u32 flags = (u32)((u32(*)(id, SEL))objc_msgSend)(event, sel_registerName("modifierFlags"));
13189 RGFW_updateKeyModsEx(win,
13190 ((u32)(flags & NSEventModifierFlagCapsLock) % 255),
13191 ((flags & NSEventModifierFlagNumericPad) % 255),
13192 ((flags & NSEventModifierFlagControl) % 255),
13193 ((flags & NSEventModifierFlagOption) % 255),
13194 ((flags & NSEventModifierFlagShift) % 255),
13195 ((flags & NSEventModifierFlagCommand) % 255), 0);
13196 u8 i;
13197 for (i = 0; i < 9; i++)
13198 _RGFW->keyboard[i + RGFW_capsLock].prev = _RGFW->keyboard[i + RGFW_capsLock].current;
13199
13200 for (i = 0; i < 5; i++) {
13201 u32 shift = (1 << (i + 16));
13202 RGFW_key key = i + RGFW_capsLock;
13203 if ((flags & shift) && !RGFW_window_isKeyDown(win, (u8)key)) {
13204 pressed = RGFW_TRUE;
13205 value = (u8)key;
13206 break;
13207 }
13208 if (!(flags & shift) && RGFW_window_isKeyDown(win, (u8)key)) {
13209 pressed = RGFW_FALSE;
13210 value = (u8)key;
13211 break;
13212 }
13213 }
13214
13215 RGFW_bool repeat = RGFW_window_isKeyDown(win, (u8)value);
13216 RGFW_keyCallback(win, value, win->internal.mod, repeat, pressed);
13217
13218 if (value != RGFW_capsLock) {
13219 RGFW_keyCallback(win, value + 4, win->internal.mod, repeat, pressed);
13220 }
13221
13222 }
13223
13224 static void RGFW__osxMouseMoved(id self, SEL _cmd, id event) {
13225 RGFW_UNUSED(_cmd);
13226 RGFW_window* win = NULL;
13227 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13228 if (win == NULL) return;
13229
13230 NSPoint p = ((NSPoint(*)(id, SEL))objc_msgSend)(event, sel_registerName("locationInWindow"));
13231
13232 CGFloat vecX = ((CGFloat(*)(id, SEL))abi_objc_msgSend_fpret)(event, sel_registerName("deltaX"));
13233 CGFloat vecY = ((CGFloat(*)(id, SEL))abi_objc_msgSend_fpret)(event, sel_registerName("deltaY"));
13234
13235 RGFW_mousePosCallback(win, (i32)p.x, (i32)(win->h - p.y), (float)vecX, (float)vecY);
13236 }
13237
13238 static void RGFW__osxMouseDown(id self, SEL _cmd, id event) {
13239 RGFW_UNUSED(_cmd);
13240 RGFW_window* win = NULL;
13241 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13242 if (win == NULL) return;
13243
13244 u32 buttonNumber = (u32)((u32(*)(id, SEL))objc_msgSend)(event, sel_registerName("buttonNumber"));
13245
13246 RGFW_mouseButton value = 0;
13247 switch (buttonNumber) {
13248 case 0: value = RGFW_mouseLeft; break;
13249 case 1: value = RGFW_mouseRight; break;
13250 case 2: value = RGFW_mouseMiddle; break;
13251 default: value = (u8)buttonNumber;
13252 }
13253
13254 RGFW_mouseButtonCallback(win, value, 1);
13255 }
13256
13257 static void RGFW__osxMouseUp(id self, SEL _cmd, id event) {
13258 RGFW_UNUSED(_cmd);
13259 RGFW_window* win = NULL;
13260 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13261 if (win == NULL) return;
13262
13263 u32 buttonNumber = (u32)((u32(*)(id, SEL))objc_msgSend)(event, sel_registerName("buttonNumber"));
13264
13265 RGFW_mouseButton value = 0;
13266 switch (buttonNumber) {
13267 case 0: value = RGFW_mouseLeft; break;
13268 case 1: value = RGFW_mouseRight; break;
13269 case 2: value = RGFW_mouseMiddle; break;
13270 default: value = (u8)buttonNumber;
13271 }
13272
13273 RGFW_mouseButtonCallback(win, value, 0);
13274 }
13275
13276 static void RGFW__osxScrollWheel(id self, SEL _cmd, id event) {
13277 RGFW_UNUSED(_cmd);
13278 RGFW_window* win = NULL;
13279 object_getInstanceVariable(self, "RGFW_window", (void**)&win);
13280 if (win == NULL) return;
13281
13282 float deltaX = (float)((CGFloat(*)(id, SEL))abi_objc_msgSend_fpret)(event, sel_registerName("deltaX"));
13283 float deltaY = (float)((CGFloat(*)(id, SEL))abi_objc_msgSend_fpret)(event, sel_registerName("deltaY"));
13284
13285 RGFW_mouseScrollCallback(win, deltaX, deltaY);
13286 }
13287
13288 RGFW_format RGFW_nativeFormat(void) { return RGFW_formatRGBA8; }
13289
13290 RGFW_bool RGFW_createSurfacePtr(u8* data, i32 w, i32 h, RGFW_format format, RGFW_surface* surface) {
13291 surface->data = data;
13292 surface->w = w;
13293 surface->h = h;
13294 surface->format = format;
13295 surface->native.format = RGFW_formatRGBA8;
13296
13297 surface->native.buffer = (u8*)RGFW_ALLOC((size_t)(w * h * 4));
13298 return RGFW_TRUE;
13299 }
13300
13301 void RGFW_surface_freePtr(RGFW_surface* surface) {
13302 RGFW_FREE(surface->native.buffer);
13303 }
13304
13305 void RGFW_window_blitSurface(RGFW_window* win, RGFW_surface* surface) {
13306 id pool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
13307 pool = objc_msgSend_id(pool, sel_registerName("init"));
13308
13309 int minW = RGFW_MIN(win->w, surface->w);
13310 int minH = RGFW_MIN(win->h, surface->h);
13311
13312 RGFW_monitor* mon = RGFW_window_getMonitor(win);
13313 if (mon == NULL) return;
13314
13315 minW = (i32)((float)minW * mon->pixelRatio);
13316 minH = (i32)((float)minH * mon->pixelRatio);
13317
13318 surface->native.rep = (void*)NSBitmapImageRep_initWithBitmapData(&surface->native.buffer, minW, minH, 8, 4, true, false, "NSDeviceRGBColorSpace", 1 << 1, (u32)surface->w * 4, 32);
13319
13320 id image = ((id (*)(Class, SEL))objc_msgSend)(objc_getClass("NSImage"), sel_getUid("alloc"));
13321 NSSize size = (NSSize){(double)minW, (double)minH};
13322 image = ((id (*)(id, SEL, NSSize))objc_msgSend)((id)image, sel_getUid("initWithSize:"), size);
13323
13324 RGFW_copyImageData(NSBitmapImageRep_bitmapData((id)surface->native.rep), surface->w, minH, RGFW_formatRGBA8, surface->data, surface->native.format, surface->convertFunc);
13325 ((void (*)(id, SEL, id))objc_msgSend)((id)image, sel_getUid("addRepresentation:"), (id)surface->native.rep);
13326
13327 id layer = ((id (*)(id, SEL))objc_msgSend)((id)win->src.view, sel_getUid("layer"));
13328 ((void (*)(id, SEL, id))objc_msgSend)(layer, sel_getUid("setContents:"), (id)image);
13329
13330 NSRelease(image);
13331 NSRelease(surface->native.rep);
13332
13333 objc_msgSend_bool_void(pool, sel_registerName("drain"));
13334 }
13335
13336 void* RGFW_window_getView_OSX(RGFW_window* win) { return win->src.view; }
13337
13338 void RGFW_window_setLayer_OSX(RGFW_window* win, void* layer) {
13339 objc_msgSend_void_id((id)win->src.view, sel_registerName("setLayer:"), (id)layer);
13340 }
13341
13342 void* RGFW_getLayer_OSX(void) {
13343 return objc_msgSend_class((id)objc_getClass("CAMetalLayer"), (SEL)sel_registerName("layer"));
13344 }
13345 void* RGFW_window_getWindow_OSX(RGFW_window* win) { return win->src.window; }
13346
13347 void RGFW_initKeycodesPlatform(void) {
13348 _RGFW->keycodes[0x1D] = RGFW_0;
13349 _RGFW->keycodes[0x12] = RGFW_1;
13350 _RGFW->keycodes[0x13] = RGFW_2;
13351 _RGFW->keycodes[0x14] = RGFW_3;
13352 _RGFW->keycodes[0x15] = RGFW_4;
13353 _RGFW->keycodes[0x17] = RGFW_5;
13354 _RGFW->keycodes[0x16] = RGFW_6;
13355 _RGFW->keycodes[0x1A] = RGFW_7;
13356 _RGFW->keycodes[0x1C] = RGFW_8;
13357 _RGFW->keycodes[0x19] = RGFW_9;
13358 _RGFW->keycodes[0x00] = RGFW_a;
13359 _RGFW->keycodes[0x0B] = RGFW_b;
13360 _RGFW->keycodes[0x08] = RGFW_c;
13361 _RGFW->keycodes[0x02] = RGFW_d;
13362 _RGFW->keycodes[0x0E] = RGFW_e;
13363 _RGFW->keycodes[0x03] = RGFW_f;
13364 _RGFW->keycodes[0x05] = RGFW_g;
13365 _RGFW->keycodes[0x04] = RGFW_h;
13366 _RGFW->keycodes[0x22] = RGFW_i;
13367 _RGFW->keycodes[0x26] = RGFW_j;
13368 _RGFW->keycodes[0x28] = RGFW_k;
13369 _RGFW->keycodes[0x25] = RGFW_l;
13370 _RGFW->keycodes[0x2E] = RGFW_m;
13371 _RGFW->keycodes[0x2D] = RGFW_n;
13372 _RGFW->keycodes[0x1F] = RGFW_o;
13373 _RGFW->keycodes[0x23] = RGFW_p;
13374 _RGFW->keycodes[0x0C] = RGFW_q;
13375 _RGFW->keycodes[0x0F] = RGFW_r;
13376 _RGFW->keycodes[0x01] = RGFW_s;
13377 _RGFW->keycodes[0x11] = RGFW_t;
13378 _RGFW->keycodes[0x20] = RGFW_u;
13379 _RGFW->keycodes[0x09] = RGFW_v;
13380 _RGFW->keycodes[0x0D] = RGFW_w;
13381 _RGFW->keycodes[0x07] = RGFW_x;
13382 _RGFW->keycodes[0x10] = RGFW_y;
13383 _RGFW->keycodes[0x06] = RGFW_z;
13384 _RGFW->keycodes[0x27] = RGFW_apostrophe;
13385 _RGFW->keycodes[0x2A] = RGFW_backSlash;
13386 _RGFW->keycodes[0x2B] = RGFW_comma;
13387 _RGFW->keycodes[0x18] = RGFW_equals;
13388 _RGFW->keycodes[0x32] = RGFW_backtick;
13389 _RGFW->keycodes[0x21] = RGFW_bracket;
13390 _RGFW->keycodes[0x1B] = RGFW_minus;
13391 _RGFW->keycodes[0x2F] = RGFW_period;
13392 _RGFW->keycodes[0x1E] = RGFW_closeBracket;
13393 _RGFW->keycodes[0x29] = RGFW_semicolon;
13394 _RGFW->keycodes[0x2C] = RGFW_slash;
13395 _RGFW->keycodes[0x0A] = RGFW_world1;
13396 _RGFW->keycodes[0x33] = RGFW_backSpace;
13397 _RGFW->keycodes[0x39] = RGFW_capsLock;
13398 _RGFW->keycodes[0x75] = RGFW_delete;
13399 _RGFW->keycodes[0x7D] = RGFW_down;
13400 _RGFW->keycodes[0x77] = RGFW_end;
13401 _RGFW->keycodes[0x24] = RGFW_enter;
13402 _RGFW->keycodes[0x35] = RGFW_escape;
13403 _RGFW->keycodes[0x7A] = RGFW_F1;
13404 _RGFW->keycodes[0x78] = RGFW_F2;
13405 _RGFW->keycodes[0x63] = RGFW_F3;
13406 _RGFW->keycodes[0x76] = RGFW_F4;
13407 _RGFW->keycodes[0x60] = RGFW_F5;
13408 _RGFW->keycodes[0x61] = RGFW_F6;
13409 _RGFW->keycodes[0x62] = RGFW_F7;
13410 _RGFW->keycodes[0x64] = RGFW_F8;
13411 _RGFW->keycodes[0x65] = RGFW_F9;
13412 _RGFW->keycodes[0x6D] = RGFW_F10;
13413 _RGFW->keycodes[0x67] = RGFW_F11;
13414 _RGFW->keycodes[0x6F] = RGFW_F12;
13415 _RGFW->keycodes[0x69] = RGFW_printScreen;
13416 _RGFW->keycodes[0x6B] = RGFW_F14;
13417 _RGFW->keycodes[0x71] = RGFW_F15;
13418 _RGFW->keycodes[0x6A] = RGFW_F16;
13419 _RGFW->keycodes[0x40] = RGFW_F17;
13420 _RGFW->keycodes[0x4F] = RGFW_F18;
13421 _RGFW->keycodes[0x50] = RGFW_F19;
13422 _RGFW->keycodes[0x5A] = RGFW_F20;
13423 _RGFW->keycodes[0x73] = RGFW_home;
13424 _RGFW->keycodes[0x72] = RGFW_insert;
13425 _RGFW->keycodes[0x7B] = RGFW_left;
13426 _RGFW->keycodes[0x3A] = RGFW_altL;
13427 _RGFW->keycodes[0x3B] = RGFW_controlL;
13428 _RGFW->keycodes[0x38] = RGFW_shiftL;
13429 _RGFW->keycodes[0x37] = RGFW_superL;
13430 _RGFW->keycodes[0x6E] = RGFW_menu;
13431 _RGFW->keycodes[0x47] = RGFW_numLock;
13432 _RGFW->keycodes[0x79] = RGFW_pageDown;
13433 _RGFW->keycodes[0x74] = RGFW_pageUp;
13434 _RGFW->keycodes[0x7C] = RGFW_right;
13435 _RGFW->keycodes[0x3D] = RGFW_altR;
13436 _RGFW->keycodes[0x3E] = RGFW_controlR;
13437 _RGFW->keycodes[0x3C] = RGFW_shiftR;
13438 _RGFW->keycodes[0x36] = RGFW_superR;
13439 _RGFW->keycodes[0x31] = RGFW_space;
13440 _RGFW->keycodes[0x30] = RGFW_tab;
13441 _RGFW->keycodes[0x7E] = RGFW_up;
13442 _RGFW->keycodes[0x52] = RGFW_kp0;
13443 _RGFW->keycodes[0x53] = RGFW_kp1;
13444 _RGFW->keycodes[0x54] = RGFW_kp2;
13445 _RGFW->keycodes[0x55] = RGFW_kp3;
13446 _RGFW->keycodes[0x56] = RGFW_kp4;
13447 _RGFW->keycodes[0x57] = RGFW_kp5;
13448 _RGFW->keycodes[0x58] = RGFW_kp6;
13449 _RGFW->keycodes[0x59] = RGFW_kp7;
13450 _RGFW->keycodes[0x5B] = RGFW_kp8;
13451 _RGFW->keycodes[0x5C] = RGFW_kp9;
13452 _RGFW->keycodes[0x45] = RGFW_kpSlash;
13453 _RGFW->keycodes[0x41] = RGFW_kpPeriod;
13454 _RGFW->keycodes[0x4B] = RGFW_kpSlash;
13455 _RGFW->keycodes[0x4C] = RGFW_kpReturn;
13456 _RGFW->keycodes[0x51] = RGFW_kpEqual;
13457 _RGFW->keycodes[0x43] = RGFW_kpMultiply;
13458 _RGFW->keycodes[0x4E] = RGFW_kpMinus;
13459 }
13460
13461 i32 RGFW_initPlatform(void) {
13462 _RGFW->tisBundle = (void*)CFBundleGetBundleWithIdentifier(CFSTR("com.apple.HIToolbox"));
13463
13464 TISGetInputSourcePropertySrc = (PFN_TISGetInputSourceProperty)CFBundleGetFunctionPointerForName((CFBundleRef)_RGFW->tisBundle, CFSTR("TISGetInputSourceProperty"));
13465 TISCopyCurrentKeyboardLayoutInputSourceSrc = (PFN_TISCopyCurrentKeyboardLayoutInputSource)CFBundleGetFunctionPointerForName((CFBundleRef)_RGFW->tisBundle, CFSTR("TISCopyCurrentKeyboardLayoutInputSource"));
13466 LMGetKbdTypeSrc = (PFN_LMGetKbdType)CFBundleGetFunctionPointerForName((CFBundleRef)_RGFW->tisBundle, CFSTR("LMGetKbdType"));
13467
13468 CFStringRef* cfStr = (CFStringRef*)CFBundleGetDataPointerForName((CFBundleRef)_RGFW->tisBundle, CFSTR("kTISPropertyUnicodeKeyLayoutData"));;
13469 if (cfStr) kTISPropertyUnicodeKeyLayoutDataSrc = *cfStr;
13470
13471 class_addMethod(objc_getClass("NSObject"), sel_registerName("windowShouldClose:"), (IMP)(void*)RGFW_OnClose, 0);
13472
13473 /* NOTE(EimaMei): Fixes the 'Boop' sfx from constantly playing each time you click a key. Only a problem when running in the terminal. */
13474 class_addMethod(objc_getClass("NSWindowClass"), sel_registerName("acceptsFirstResponder:"), (IMP)(void*)RGFW__osxAcceptsFirstResponder, 0);
13475 class_addMethod(objc_getClass("NSWindowClass"), sel_registerName("performKeyEquivalent:"), (IMP)(void*)RGFW__osxPerformKeyEquivalent, 0);
13476
13477 _RGFW->NSApp = objc_msgSend_id(objc_getClass("NSApplication"), sel_registerName("sharedApplication"));
13478
13479 NSRetain(_RGFW->NSApp);
13480
13481 _RGFW->customNSAppDelegateClass = objc_allocateClassPair(objc_getClass("NSObject"), "RGFWNSAppDelegate", 0);
13482 class_addMethod((Class)_RGFW->customNSAppDelegateClass, sel_registerName("applicationDidChangeScreenParameters:"), (IMP)RGFW__osxDidChangeScreenParameters, "v@:@");
13483 objc_registerClassPair((Class)_RGFW->customNSAppDelegateClass);
13484 _RGFW->customNSAppDelegate = objc_msgSend_id(NSAlloc(_RGFW->customNSAppDelegateClass), sel_registerName("init"));
13485
13486 objc_msgSend_void_id(_RGFW->NSApp, sel_registerName("setDelegate:"), _RGFW->customNSAppDelegate);
13487
13488 ((void (*)(id, SEL, NSUInteger))objc_msgSend) ((id)_RGFW->NSApp, sel_registerName("setActivationPolicy:"), NSApplicationActivationPolicyRegular);
13489
13490 _RGFW->customViewClasses[0] = objc_allocateClassPair(objc_getClass("NSView"), "RGFWCustomView", 0);
13491 _RGFW->customViewClasses[1] = objc_allocateClassPair(objc_getClass("NSOpenGLView"), "RGFWOpenGLCustomView", 0);
13492 for (size_t i = 0; i < 2; i++) {
13493 class_addIvar((Class)_RGFW->customViewClasses[i], "RGFW_window", sizeof(RGFW_window*), sizeof(RGFW_window*), "L");
13494 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("drawRect:"), (IMP)RGFW__osxDrawRect, "v@:{CGRect=ffff}");
13495 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("viewDidChangeBackingProperties"), (IMP)RGFW__osxViewDidChangeBackingProperties, "v@:");
13496 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("mouseDown:"), (IMP)RGFW__osxMouseDown, "v@:@");
13497 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("rightMouseDown:"), (IMP)RGFW__osxMouseDown, "v@:@");
13498 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("otherMouseDown:"), (IMP)RGFW__osxMouseDown, "v@:@");
13499 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("mouseUp:"), (IMP)RGFW__osxMouseUp, "v@:@");
13500 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("rightMouseUp:"), (IMP)RGFW__osxMouseUp, "v@:@");
13501 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("otherMouseUp:"), (IMP)RGFW__osxMouseUp, "v@:@");
13502 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("scrollWheel:"), (IMP)RGFW__osxScrollWheel, "v@:@");
13503 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("mouseDragged:"), (IMP)RGFW__osxMouseMoved, "v@:@");
13504 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("rightMouseDragged:"), (IMP)RGFW__osxMouseMoved, "v@:@");
13505 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("otherMouseDragged:"), (IMP)RGFW__osxMouseMoved, "v@:@");
13506 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("keyDown:"), (IMP)RGFW__osxKeyDown, "v@:@");
13507 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("keyUp:"), (IMP)RGFW__osxKeyUp, "v@:@");
13508 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("mouseMoved:"), (IMP)RGFW__osxMouseMoved, "v@:@");
13509 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("mouseEntered:"), (IMP)RGFW__osxMouseEntered, "v@:@");
13510 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("mouseExited:"), (IMP)RGFW__osxMouseExited, "v@:@");
13511 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("flagsChanged:"), (IMP)RGFW__osxFlagsChanged, "v@:@");
13512 class_addMethod((Class)_RGFW->customViewClasses[i], sel_getUid("acceptsFirstResponder"), (IMP)RGFW__osxAcceptsFirstResponder, "B@:");
13513 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("initWithRGFWWindow:"), (IMP)RGFW__osxCustomInitWithRGFWWindow, "@@:{CGRect={CGPoint=dd}{CGSize=dd}}");
13514 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("wantsUpdateLayer"), (IMP)RGFW__osxWantsUpdateLayer, "B@:");
13515 class_addMethod((Class)_RGFW->customViewClasses[i], sel_registerName("updateLayer"), (IMP)RGFW__osxUpdateLayer, "v@:");
13516 objc_registerClassPair((Class)_RGFW->customViewClasses[i]);
13517 }
13518
13519 _RGFW->customWindowDelegateClass = objc_allocateClassPair(objc_getClass("NSObject"), "RGFWWindowDelegate", 0);
13520 class_addIvar((Class)_RGFW->customWindowDelegateClass, "RGFW_window", sizeof(RGFW_window*), sizeof(RGFW_window*), "L");
13521 class_addMethod((Class)_RGFW->customWindowDelegateClass, sel_registerName("windowDidResize:"), (IMP)RGFW__osxDidWindowResize, "v@:@");
13522 class_addMethod((Class)_RGFW->customWindowDelegateClass, sel_registerName("windowDidMove:"), (IMP) RGFW__osxWindowMove, "");
13523 class_addMethod((Class)_RGFW->customWindowDelegateClass, sel_registerName("windowDidMiniaturize:"), (IMP) RGFW__osxWindowMiniaturize, "");
13524 class_addMethod((Class)_RGFW->customWindowDelegateClass, sel_registerName("windowDidDeminiaturize:"), (IMP) RGFW__osxWindowDeminiaturize, "");
13525 class_addMethod((Class)_RGFW->customWindowDelegateClass, sel_registerName("windowDidBecomeKey:"), (IMP) RGFW__osxWindowBecameKey, "");
13526 class_addMethod((Class)_RGFW->customWindowDelegateClass, sel_registerName("windowDidResignKey:"), (IMP) RGFW__osxWindowResignKey, "");
13527 class_addMethod((Class)_RGFW->customWindowDelegateClass, sel_registerName("draggingEntered:"), (IMP)RGFW__osxDraggingEntered, "l@:@");
13528 class_addMethod((Class)_RGFW->customWindowDelegateClass, sel_registerName("draggingUpdated:"), (IMP)RGFW__osxDraggingUpdated, "l@:@");
13529 class_addMethod((Class)_RGFW->customWindowDelegateClass, sel_registerName("draggingExited:"), (IMP)RGFW__osxDraggingEnded, "v@:@");
13530 class_addMethod((Class)_RGFW->customWindowDelegateClass, sel_registerName("draggingEnded:"), (IMP)RGFW__osxDraggingEnded, "v@:@");
13531 class_addMethod((Class)_RGFW->customWindowDelegateClass, sel_registerName("prepareForDragOperation:"), (IMP)RGFW__osxPrepareForDragOperation, "B@:@");
13532 class_addMethod((Class)_RGFW->customWindowDelegateClass, sel_registerName("performDragOperation:"), (IMP)RGFW__osxPerformDragOperation, "B@:@");
13533 objc_registerClassPair((Class)_RGFW->customWindowDelegateClass);
13534 return 0;
13535 }
13536
13537 void RGFW_osx_initView(RGFW_window* win) {
13538 NSRect contentRect;
13539 contentRect.origin.x = 0;
13540 contentRect.origin.y = 0;
13541 contentRect.size.width = (double)win->w;
13542 contentRect.size.height = (double)win->h;
13543 ((void(*)(id, SEL, CGRect))objc_msgSend)((id)win->src.view, sel_registerName("setFrame:"), contentRect);
13544
13545
13546 if (RGFW_COCOA_FRAME_NAME)
13547 objc_msgSend_ptr(win->src.view, sel_registerName("setFrameAutosaveName:"), RGFW_COCOA_FRAME_NAME);
13548
13549 object_setInstanceVariable((id)win->src.view, "RGFW_window", win);
13550 objc_msgSend_void_id((id)win->src.window, sel_registerName("setContentView:"), win->src.view);
13551 objc_msgSend_void_bool(win->src.view, sel_registerName("setWantsLayer:"), true);
13552 objc_msgSend_int((id)win->src.view, sel_registerName("setLayerContentsPlacement:"), 4);
13553
13554 id trackingArea = objc_msgSend_id(objc_getClass("NSTrackingArea"), sel_registerName("alloc"));
13555 trackingArea = ((id (*)(id, SEL, NSRect, NSUInteger, id, id))objc_msgSend)(
13556 trackingArea,
13557 sel_registerName("initWithRect:options:owner:userInfo:"),
13558 contentRect,
13559 NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingInVisibleRect,
13560 (id)win->src.view,
13561 nil
13562 );
13563
13564 ((void (*)(id, SEL, id))objc_msgSend)((id)win->src.view, sel_registerName("addTrackingArea:"), trackingArea);
13565 ((void (*)(id, SEL))objc_msgSend)(trackingArea, sel_registerName("release"));
13566 }
13567
13568 RGFW_window* RGFW_createWindowPlatform(const char* name, RGFW_windowFlags flags, RGFW_window* win) {
13569 /* RR Create an autorelease pool */
13570 id pool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
13571 pool = objc_msgSend_id(pool, sel_registerName("init"));
13572
13573 RGFW_window_setMouseDefault(win);
13574
13575 NSRect windowRect;
13576 windowRect.origin.x = (double)win->x;
13577 windowRect.origin.y = (double)RGFW_cocoaYTransform((float)(win->y + win->h - 1));
13578 windowRect.size.width = (double)win->w;
13579 windowRect.size.height = (double)win->h;
13580 NSBackingStoreType macArgs = (NSBackingStoreType)(NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSBackingStoreBuffered | NSWindowStyleMaskTitled);
13581
13582 if (!(flags & RGFW_windowNoResize))
13583 macArgs = (NSBackingStoreType)(macArgs | (NSBackingStoreType)NSWindowStyleMaskResizable);
13584 if (!(flags & RGFW_windowNoBorder))
13585 macArgs = (NSBackingStoreType)(macArgs | (NSBackingStoreType)NSWindowStyleMaskTitled);
13586 {
13587 void* nsclass = objc_getClass("NSWindow");
13588 SEL func = sel_registerName("initWithContentRect:styleMask:backing:defer:");
13589
13590 win->src.window = ((id(*)(id, SEL, NSRect, NSWindowStyleMask, NSBackingStoreType, bool))objc_msgSend)
13591 (NSAlloc(nsclass), func, windowRect, (NSWindowStyleMask)macArgs, macArgs, false);
13592 }
13593
13594 id str = NSString_stringWithUTF8String(name);
13595 objc_msgSend_void_id((id)win->src.window, sel_registerName("setTitle:"), str);
13596
13597 win->src.delegate = (void*)objc_msgSend_id(NSAlloc((Class)_RGFW->customWindowDelegateClass), sel_registerName("init"));
13598 object_setInstanceVariable((id)win->src.delegate, "RGFW_window", win);
13599
13600 objc_msgSend_void_id((id)win->src.window, sel_registerName("setDelegate:"), (id)win->src.delegate);
13601
13602 if (flags & RGFW_windowAllowDND) {
13603 win->internal.flags |= RGFW_windowAllowDND;
13604
13605 NSPasteboardType types[] = {NSPasteboardTypeURL, NSPasteboardTypeFileURL, NSPasteboardTypeString};
13606 NSregisterForDraggedTypes((id)win->src.window, types, 3);
13607 }
13608
13609 objc_msgSend_void_bool((id)win->src.window, sel_registerName("setAcceptsMouseMovedEvents:"), true);
13610
13611 if (flags & RGFW_windowTransparent) {
13612 objc_msgSend_void_bool(win->src.window, sel_registerName("setOpaque:"), false);
13613
13614 objc_msgSend_void_id((id)win->src.window, sel_registerName("setBackgroundColor:"),
13615 NSColor_colorWithSRGB(0, 0, 0, 0));
13616 }
13617
13618 /* Show the window */
13619 objc_msgSend_void_bool((id)_RGFW->NSApp, sel_registerName("activateIgnoringOtherApps:"), true);
13620
13621 if (_RGFW->root == NULL) {
13622 objc_msgSend_void(win->src.window, sel_registerName("makeMainWindow"));
13623 }
13624
13625 objc_msgSend_void(win->src.window, sel_registerName("makeKeyWindow"));
13626
13627 NSRetain(win->src.window);
13628
13629 win->src.view = ((id(*)(id, SEL, RGFW_window*))objc_msgSend) (NSAlloc((Class)_RGFW->customViewClasses[0]), sel_registerName("initWithRGFWWindow:"), win);
13630 return win;
13631 }
13632
13633 void RGFW_window_setBorder(RGFW_window* win, RGFW_bool border) {
13634 NSRect frame = ((NSRect(*)(id, SEL))abi_objc_msgSend_stret)((id)win->src.window, sel_registerName("frame"));
13635 NSRect content = ((NSRect(*)(id, SEL))abi_objc_msgSend_stret)((id)win->src.view, sel_registerName("frame"));
13636 double offset = 0;
13637
13638 RGFW_setBit(&win->internal.flags, RGFW_windowNoBorder, !border);
13639 NSBackingStoreType storeType = (NSBackingStoreType)(NSWindowStyleMaskBorderless | NSWindowStyleMaskFullSizeContentView);
13640 if (border)
13641 storeType = (NSBackingStoreType)(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable);
13642 if (!(win->internal.flags & RGFW_windowNoResize)) {
13643 storeType = (NSBackingStoreType)(storeType | (NSBackingStoreType)NSWindowStyleMaskResizable);
13644 }
13645
13646 ((void (*)(id, SEL, NSBackingStoreType))objc_msgSend)((id)win->src.window, sel_registerName("setStyleMask:"), storeType);
13647
13648 if (!border) {
13649 id miniaturizeButton = objc_msgSend_int((id)win->src.window, sel_registerName("standardWindowButton:"), NSWindowMiniaturizeButton);
13650 id titleBarView = objc_msgSend_id(miniaturizeButton, sel_registerName("superview"));
13651 objc_msgSend_void_bool(titleBarView, sel_registerName("setHidden:"), true);
13652
13653 offset = (double)(frame.size.height - content.size.height);
13654 }
13655
13656 RGFW_window_resize(win, win->w, win->h + (i32)offset);
13657 win->h -= (i32)offset;
13658 }
13659
13660 RGFW_bool RGFW_getGlobalMouse(i32* x, i32* y) {
13661 RGFW_ASSERT(_RGFW->root != NULL);
13662
13663 CGEventRef e = CGEventCreate(NULL);
13664 CGPoint point = CGEventGetLocation(e);
13665 CFRelease(e);
13666
13667 if (x) *x = (i32)point.x;
13668 if (y) *y = (i32)point.y;
13669 return RGFW_TRUE;
13670 }
13671
13672 void RGFW_stopCheckEvents(void) {
13673 id eventPool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
13674 eventPool = objc_msgSend_id(eventPool, sel_registerName("init"));
13675
13676 id e = (id) ((id(*)(Class, SEL, NSEventType, NSPoint, NSEventModifierFlags, void*, NSInteger, void**, short, NSInteger, NSInteger))objc_msgSend)
13677 (objc_getClass("NSEvent"), sel_registerName("otherEventWithType:location:modifierFlags:timestamp:windowNumber:context:subtype:data1:data2:"),
13678 NSEventTypeApplicationDefined, (NSPoint){0, 0}, (NSEventModifierFlags)0, NULL, (NSInteger)0, NULL, 0, 0, 0);
13679
13680 ((void (*)(id, SEL, id, bool))objc_msgSend)
13681 ((id)_RGFW->NSApp, sel_registerName("postEvent:atStart:"), e, 1);
13682
13683 objc_msgSend_bool_void(eventPool, sel_registerName("drain"));
13684 }
13685
13686 void RGFW_waitForEvent(i32 waitMS) {
13687 id eventPool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
13688 eventPool = objc_msgSend_id(eventPool, sel_registerName("init"));
13689
13690 void* date = (void*) ((id(*)(Class, SEL, double))objc_msgSend)
13691 (objc_getClass("NSDate"), sel_registerName("dateWithTimeIntervalSinceNow:"), waitMS);
13692
13693 SEL eventFunc = sel_registerName("nextEventMatchingMask:untilDate:inMode:dequeue:");
13694 id e = (id) ((id(*)(id, SEL, NSEventMask, void*, id, bool))objc_msgSend)
13695 ((id)_RGFW->NSApp, eventFunc,
13696 ULONG_MAX, date, NSString_stringWithUTF8String("kCFRunLoopDefaultMode"), true);
13697
13698 if (e) {
13699 ((void (*)(id, SEL, id, bool))objc_msgSend)
13700 ((id)_RGFW->NSApp, sel_registerName("postEvent:atStart:"), e, 1);
13701 }
13702
13703 objc_msgSend_bool_void(eventPool, sel_registerName("drain"));
13704 }
13705
13706 RGFW_key RGFW_physicalToMappedKey(RGFW_key key) {
13707 u16 keycode = (u16)RGFW_rgfwToApiKey(key);
13708 TISInputSourceRef source = TISCopyCurrentKeyboardLayoutInputSource();
13709 if (source == NULL)
13710 return key;
13711
13712 CFDataRef layoutData = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutDataSrc);
13713
13714 if (layoutData == NULL) {
13715 CFRelease(source);
13716 return key;
13717 }
13718
13719 UCKeyboardLayout *layout = (UCKeyboardLayout*)(void*)CFDataGetBytePtr(layoutData);
13720
13721 UInt32 deadKeyState = 0;
13722 UniChar chars[4];
13723 UniCharCount len = 0;
13724 u32 type = LMGetKbdType();
13725 OSStatus status = UCKeyTranslate(layout, keycode, kUCKeyActionDown, 0, type, kUCKeyTranslateNoDeadKeysBit, &deadKeyState, 4, &len, chars );
13726
13727 CFRelease(source);
13728
13729 if (status == noErr && len == 1 && chars[0] < 256) {
13730 return (RGFW_key)chars[0];
13731 }
13732
13733 return key;
13734 }
13735
13736 void RGFW_pollEvents(void) {
13737 RGFW_resetPrevState();
13738
13739 id eventPool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
13740 eventPool = objc_msgSend_id(eventPool, sel_registerName("init"));
13741 SEL eventFunc = sel_registerName("nextEventMatchingMask:untilDate:inMode:dequeue:");
13742
13743 while (1) {
13744 void* date = NULL;
13745 id e = (id) ((id(*)(id, SEL, NSEventMask, void*, id, bool))objc_msgSend)
13746 ((id)_RGFW->NSApp, eventFunc, ULONG_MAX, date, NSString_stringWithUTF8String("kCFRunLoopDefaultMode"), true);
13747
13748 if (e == NULL) {
13749 break;
13750 }
13751
13752 objc_msgSend_void_id((id)_RGFW->NSApp, sel_registerName("sendEvent:"), e);
13753 }
13754
13755 objc_msgSend_bool_void(eventPool, sel_registerName("drain"));
13756 }
13757
13758
13759 void RGFW_window_move(RGFW_window* win, i32 x, i32 y) {
13760 RGFW_ASSERT(win != NULL);
13761
13762 NSRect content = ((NSRect(*)(id, SEL))abi_objc_msgSend_stret)((id)win->src.view, sel_registerName("frame"));
13763
13764 win->x = x;
13765 win->y = (i32)RGFW_cocoaYTransform((float)y + (float)content.size.height - 1.0f);
13766
13767 ((void(*)(id,SEL,NSPoint))objc_msgSend)((id)win->src.window, sel_registerName("setFrameOrigin:"), (NSPoint){(double)x, (double)y});
13768 }
13769
13770 void RGFW_window_resize(RGFW_window* win, i32 w, i32 h) {
13771 RGFW_ASSERT(win != NULL);
13772
13773 NSRect frame = ((NSRect(*)(id, SEL))abi_objc_msgSend_stret)((id)win->src.window, sel_registerName("frame"));
13774 NSRect content = ((NSRect(*)(id, SEL))abi_objc_msgSend_stret)((id)win->src.view, sel_registerName("frame"));
13775 float offset = (float)(frame.size.height - content.size.height);
13776
13777 win->w = w;
13778 win->h = h;
13779
13780
13781 ((void(*)(id, SEL, CGRect))objc_msgSend)((id)win->src.view, sel_registerName("setFrame:"), (NSRect){{0, 0}, {(double)win->w, (double)win->h}});
13782 ((void(*)(id, SEL, NSRect, bool, bool))objc_msgSend)
13783 ((id)win->src.window, sel_registerName("setFrame:display:animate:"), (NSRect){{(double)win->x, (double)win->y}, {(double)win->w, (double)win->h + (double)offset}}, true, true);
13784 }
13785
13786 void RGFW_window_focus(RGFW_window* win) {
13787 RGFW_ASSERT(win);
13788 objc_msgSend_void_bool((id)_RGFW->NSApp, sel_registerName("activateIgnoringOtherApps:"), true);
13789 ((void (*)(id, SEL))objc_msgSend)((id)win->src.window, sel_registerName("makeKeyWindow"));
13790 }
13791
13792 void RGFW_window_raise(RGFW_window* win) {
13793 RGFW_ASSERT(win != NULL);
13794 ((id(*)(id, SEL, SEL))objc_msgSend)((id)win->src.window, sel_registerName("orderFront:"), (SEL)NULL);
13795 objc_msgSend_void_id(win->src.window, sel_registerName("setLevel:"), kCGNormalWindowLevelKey);
13796 }
13797
13798 void RGFW_window_setFullscreen(RGFW_window* win, RGFW_bool fullscreen) {
13799 RGFW_ASSERT(win != NULL);
13800 if (fullscreen && (win->internal.flags & RGFW_windowFullscreen)) return;
13801 if (!fullscreen && !(win->internal.flags & RGFW_windowFullscreen)) return;
13802
13803 if (fullscreen) {
13804 win->internal.oldX = win->x;
13805 win->internal.oldY = win->y;
13806 win->internal.oldW = win->w;
13807 win->internal.oldH = win->h;
13808
13809 win->internal.flags |= RGFW_windowFullscreen;
13810
13811 RGFW_monitor* mon = RGFW_window_getMonitor(win);
13812 RGFW_monitor_scaleToWindow(mon, win);
13813
13814 RGFW_window_setBorder(win, RGFW_FALSE);
13815
13816 if (mon != NULL) {
13817 win->x = mon->x;
13818 win->y = mon->y;
13819 win->w = mon->mode.w;
13820 win->h = mon->mode.h;
13821 RGFW_window_resize(win, mon->mode.w, mon->mode.h);
13822 RGFW_window_move(win, mon->x, mon->y);
13823 }
13824
13825 ((id(*)(id, SEL, SEL))objc_msgSend)((id)win->src.window, sel_registerName("orderFront:"), (SEL)NULL);
13826 objc_msgSend_void_id(win->src.window, sel_registerName("setLevel:"), 25);
13827 }
13828
13829 objc_msgSend_void_SEL(win->src.window, sel_registerName("toggleFullScreen:"), NULL);
13830
13831 if (!fullscreen) {
13832 win->x = win->internal.oldX;
13833 win->y = win->internal.oldY;
13834 win->w = win->internal.oldW;
13835 win->h = win->internal.oldH;
13836 win->internal.flags &= ~(u32)RGFW_windowFullscreen;
13837
13838 RGFW_window_resize(win, win->w, win->h);
13839 RGFW_window_move(win, win->x, win->y);
13840 }
13841 }
13842
13843 void RGFW_window_maximize(RGFW_window* win) {
13844 RGFW_ASSERT(win != NULL);
13845 if (RGFW_window_isMaximized(win)) return;
13846
13847 win->internal.flags |= RGFW_windowMaximize;
13848 objc_msgSend_void_SEL(win->src.window, sel_registerName("zoom:"), NULL);
13849 }
13850
13851 void RGFW_window_minimize(RGFW_window* win) {
13852 RGFW_ASSERT(win != NULL);
13853 objc_msgSend_void_SEL(win->src.window, sel_registerName("performMiniaturize:"), NULL);
13854 }
13855
13856 void RGFW_window_setFloating(RGFW_window* win, RGFW_bool floating) {
13857 RGFW_ASSERT(win != NULL);
13858 if (floating) objc_msgSend_void_id(win->src.window, sel_registerName("setLevel:"), kCGFloatingWindowLevelKey);
13859 else objc_msgSend_void_id(win->src.window, sel_registerName("setLevel:"), kCGNormalWindowLevelKey);
13860 }
13861
13862 void RGFW_window_setOpacity(RGFW_window* win, u8 opacity) {
13863 objc_msgSend_int(win->src.window, sel_registerName("setAlphaValue:"), opacity);
13864 objc_msgSend_void_bool(win->src.window, sel_registerName("setOpaque:"), (opacity < (u8)255));
13865
13866 if (opacity)
13867 objc_msgSend_void_id((id)win->src.window, sel_registerName("setBackgroundColor:"), NSColor_colorWithSRGB(0, 0, 0, opacity));
13868
13869 }
13870
13871 void RGFW_window_restore(RGFW_window* win) {
13872 RGFW_ASSERT(win != NULL);
13873
13874 if (RGFW_window_isMaximized(win))
13875 objc_msgSend_void_SEL(win->src.window, sel_registerName("zoom:"), NULL);
13876
13877 objc_msgSend_void_SEL(win->src.window, sel_registerName("deminiaturize:"), NULL);
13878 RGFW_window_show(win);
13879 }
13880
13881 RGFW_bool RGFW_window_isFloating(RGFW_window* win) {
13882 RGFW_ASSERT(win != NULL);
13883 int level = ((int (*)(id, SEL))objc_msgSend) ((id)(win->src.window), (SEL)sel_registerName("level"));
13884 return level > kCGNormalWindowLevelKey;
13885 }
13886
13887 void RGFW_window_setName(RGFW_window* win, const char* name) {
13888 RGFW_ASSERT(win != NULL);
13889 if (name == NULL) name = "\0";
13890
13891 id str = NSString_stringWithUTF8String(name);
13892 objc_msgSend_void_id((id)win->src.window, sel_registerName("setTitle:"), str);
13893 }
13894
13895 #ifndef RGFW_NO_PASSTHROUGH
13896 void RGFW_window_setMousePassthrough(RGFW_window* win, RGFW_bool passthrough) {
13897 objc_msgSend_void_bool(win->src.window, sel_registerName("setIgnoresMouseEvents:"), passthrough);
13898 }
13899 #endif
13900
13901 void RGFW_window_setAspectRatio(RGFW_window* win, i32 w, i32 h) {
13902 if (w == 0 && h == 0) { w = 1; h = 1; };
13903
13904 ((void (*)(id, SEL, NSSize))objc_msgSend)
13905 ((id)win->src.window, sel_registerName("setContentAspectRatio:"), (NSSize){(CGFloat)w, (CGFloat)h});
13906 }
13907
13908 void RGFW_window_setMinSize(RGFW_window* win, i32 w, i32 h) {
13909 ((void (*)(id, SEL, NSSize))objc_msgSend) ((id)win->src.window, sel_registerName("setMinSize:"), (NSSize){(CGFloat)w, (CGFloat)h});
13910 }
13911
13912 void RGFW_window_setMaxSize(RGFW_window* win, i32 w, i32 h) {
13913 if (w == 0 && h == 0) {
13914 RGFW_monitor* mon = RGFW_window_getMonitor(win);
13915 if (mon != NULL) {
13916 w = mon->mode.w;
13917 h = mon->mode.h;
13918 }
13919 }
13920
13921 ((void (*)(id, SEL, NSSize))objc_msgSend)
13922 ((id)win->src.window, sel_registerName("setMaxSize:"), (NSSize){(CGFloat)w, (CGFloat)h});
13923 }
13924
13925 RGFW_bool RGFW_window_setIconEx(RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format, RGFW_icon type) {
13926 RGFW_ASSERT(win != NULL);
13927 RGFW_UNUSED(type);
13928
13929 id pool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
13930 pool = objc_msgSend_id(pool, sel_registerName("init"));
13931
13932 if (data == NULL) {
13933 objc_msgSend_void_id((id)_RGFW->NSApp, sel_registerName("setApplicationIconImage:"), NULL);
13934 objc_msgSend_bool_void(pool, sel_registerName("drain"));
13935 return RGFW_TRUE;
13936 }
13937
13938 id representation = NSBitmapImageRep_initWithBitmapData(NULL, w, h, 8, (NSInteger)4, true, false, "NSCalibratedRGBColorSpace", 1 << 1, w * 4, 32);
13939 RGFW_copyImageData(NSBitmapImageRep_bitmapData(representation), w, h, RGFW_formatRGBA8, data, format, NULL);
13940
13941 id dock_image = ((id(*)(id, SEL, NSSize))objc_msgSend) (NSAlloc((id)objc_getClass("NSImage")), sel_registerName("initWithSize:"), ((NSSize){(CGFloat)w, (CGFloat)h}));
13942
13943 objc_msgSend_void_id(dock_image, sel_registerName("addRepresentation:"), representation);
13944
13945 objc_msgSend_void_id((id)_RGFW->NSApp, sel_registerName("setApplicationIconImage:"), dock_image);
13946
13947 NSRelease(dock_image);
13948 NSRelease(representation);
13949
13950 objc_msgSend_bool_void(pool, sel_registerName("drain"));
13951
13952 return RGFW_TRUE;
13953 }
13954
13955 id NSCursor_arrowStr(const char* str);
13956 id NSCursor_arrowStr(const char* str) {
13957 void* nclass = objc_getClass("NSCursor");
13958 SEL func = sel_registerName(str);
13959 return (id) objc_msgSend_id(nclass, func);
13960 }
13961
13962 RGFW_mouse* RGFW_loadMouse(u8* data, i32 w, i32 h, RGFW_format format) {
13963 id pool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
13964 pool = objc_msgSend_id(pool, sel_registerName("init"));
13965
13966 if (data == NULL) {
13967 objc_msgSend_void(NSCursor_arrowStr("arrowCursor"), sel_registerName("set"));
13968
13969 objc_msgSend_bool_void(pool, sel_registerName("drain"));
13970 return NULL;
13971 }
13972
13973 id representation = (id)NSBitmapImageRep_initWithBitmapData(NULL, w, h, 8, (NSInteger)4, true, false, "NSCalibratedRGBColorSpace", 1 << 1, w * 4, 32);
13974 RGFW_copyImageData(NSBitmapImageRep_bitmapData(representation), w, h, RGFW_formatRGBA8, data, format, NULL);
13975
13976 id cursor_image = ((id(*)(id, SEL, NSSize))objc_msgSend) (NSAlloc((id)objc_getClass("NSImage")), sel_registerName("initWithSize:"), ((NSSize){(CGFloat)w, (CGFloat)h}));
13977
13978 objc_msgSend_void_id(cursor_image, sel_registerName("addRepresentation:"), representation);
13979
13980 id cursor = (id) ((id(*)(id, SEL, id, NSPoint))objc_msgSend)
13981 (NSAlloc(objc_getClass("NSCursor")), sel_registerName("initWithImage:hotSpot:"), cursor_image, (NSPoint){0.0, 0.0});
13982
13983 NSRelease(cursor_image);
13984 NSRelease(representation);
13985
13986 objc_msgSend_bool_void(pool, sel_registerName("drain"));
13987
13988 return (void*)cursor;
13989 }
13990
13991 void RGFW_window_setMouse(RGFW_window* win, RGFW_mouse* mouse) {
13992 RGFW_ASSERT(win != NULL); RGFW_ASSERT(mouse);
13993 CGDisplayShowCursor(kCGDirectMainDisplay);
13994 objc_msgSend_void((id)mouse, sel_registerName("set"));
13995 win->src.mouse = mouse;
13996 }
13997
13998 void RGFW_freeMouse(RGFW_mouse* mouse) {
13999 RGFW_ASSERT(mouse);
14000 NSRelease((id)mouse);
14001 }
14002
14003 RGFW_bool RGFW_window_setMouseDefault(RGFW_window* win) {
14004 return RGFW_window_setMouseStandard(win, RGFW_mouseArrow);
14005 }
14006
14007 void RGFW_window_showMouse(RGFW_window* win, RGFW_bool show) {
14008 RGFW_window_showMouseFlags(win, show);
14009 if (show) CGDisplayShowCursor(kCGDirectMainDisplay);
14010 else CGDisplayHideCursor(kCGDirectMainDisplay);
14011 }
14012
14013 RGFW_bool RGFW_window_setMouseStandard(RGFW_window* win, u8 stdMouse) {
14014 const char* cursorSelectorStr;
14015 switch (stdMouse) {
14016 case RGFW_mouseNormal: cursorSelectorStr = "arrowCursor"; break;
14017 case RGFW_mouseArrow: cursorSelectorStr = "arrowCursor"; break;
14018 case RGFW_mouseIbeam: cursorSelectorStr = "IBeamCursor"; break;
14019 case RGFW_mouseCrosshair: cursorSelectorStr = "crosshairCursor"; break;
14020 case RGFW_mousePointingHand: cursorSelectorStr = "pointingHandCursor"; break;
14021 case RGFW_mouseResizeEW: cursorSelectorStr = "resizeLeftRightCursor"; break;
14022 case RGFW_mouseResizeE: cursorSelectorStr = "resizeLeftRightCursor"; break;
14023 case RGFW_mouseResizeW: cursorSelectorStr = "resizeLeftRightCursor"; break;
14024 case RGFW_mouseResizeNS: cursorSelectorStr = "resizeUpDownCursor"; break;
14025 case RGFW_mouseResizeN: cursorSelectorStr = "resizeUpDownCursor"; break;
14026 case RGFW_mouseResizeS: cursorSelectorStr = "resizeUpDownCursor"; break;
14027 case RGFW_mouseResizeNWSE: cursorSelectorStr = "_windowResizeNorthWestSouthEastCursor"; break;
14028 case RGFW_mouseResizeNW: cursorSelectorStr = "_windowResizeNorthWestSouthEastCursor"; break;
14029 case RGFW_mouseResizeSE: cursorSelectorStr = "_windowResizeNorthWestSouthEastCursor"; break;
14030 case RGFW_mouseResizeNESW: cursorSelectorStr = "_windowResizeNorthEastSouthWestCursor"; break;
14031 case RGFW_mouseResizeNE: cursorSelectorStr = "_windowResizeNorthEastSouthWestCursor"; break;
14032 case RGFW_mouseResizeSW: cursorSelectorStr = "_windowResizeNorthEastSouthWestCursor"; break;
14033 case RGFW_mouseResizeAll: cursorSelectorStr = "openHandCursor"; break;
14034 case RGFW_mouseNotAllowed: cursorSelectorStr = "operationNotAllowedCursor"; break;
14035 case RGFW_mouseWait: cursorSelectorStr = "arrowCursor"; break;
14036 case RGFW_mouseProgress: cursorSelectorStr = "arrowCursor"; break;
14037 default:
14038 return RGFW_FALSE;
14039 }
14040
14041 id mouse = NSCursor_arrowStr(cursorSelectorStr);
14042
14043 if (mouse == NULL)
14044 return RGFW_FALSE;
14045
14046 RGFW_UNUSED(win);
14047 CGDisplayShowCursor(kCGDirectMainDisplay);
14048 objc_msgSend_void(mouse, sel_registerName("set"));
14049 win->src.mouse = mouse;
14050
14051 return RGFW_TRUE;
14052 }
14053
14054 void RGFW_window_setRawMouseModePlatform(RGFW_window* win, RGFW_bool state) {
14055 RGFW_UNUSED(win); RGFW_UNUSED(state);
14056 }
14057
14058 void RGFW_window_captureMousePlatform(RGFW_window* win, RGFW_bool state) {
14059 RGFW_UNUSED(win);
14060 CGAssociateMouseAndMouseCursorPosition(!(state == RGFW_TRUE));
14061 }
14062
14063 void RGFW_window_moveMouse(RGFW_window* win, i32 x, i32 y) {
14064 RGFW_UNUSED(win);
14065
14066 win->internal.lastMouseX = x - win->x;
14067 win->internal.lastMouseY = y - win->y;
14068 CGWarpMouseCursorPosition((CGPoint){(CGFloat)x, (CGFloat)y});
14069 }
14070
14071
14072 void RGFW_window_hide(RGFW_window* win) {
14073 objc_msgSend_void_bool(win->src.window, sel_registerName("setIsVisible:"), false);
14074 }
14075
14076 void RGFW_window_show(RGFW_window* win) {
14077 if (win->internal.flags & RGFW_windowFocusOnShow)
14078 ((id(*)(id, SEL, SEL))objc_msgSend)((id)win->src.window, sel_registerName("makeKeyAndOrderFront:"), NULL);
14079
14080 ((id(*)(id, SEL, SEL))objc_msgSend)((id)win->src.window, sel_registerName("orderFront:"), NULL);
14081 objc_msgSend_void_bool(win->src.window, sel_registerName("setIsVisible:"), true);
14082 }
14083
14084 void RGFW_window_flash(RGFW_window* win, RGFW_flashRequest request) {
14085 if (RGFW_window_isInFocus(win) && request) {
14086 return;
14087 }
14088
14089 id pool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
14090 pool = objc_msgSend_id(pool, sel_registerName("init"));
14091
14092 if (_RGFW->flash) {
14093 ((void (*)(id, SEL, NSInteger))objc_msgSend) ((id)_RGFW->NSApp, sel_registerName("cancelUserAttentionRequest:"), _RGFW->flash);
14094 }
14095
14096 switch (request) {
14097 case RGFW_flashBriefly:
14098 _RGFW->flash = ((NSInteger (*)(id, SEL, NSInteger))objc_msgSend) ((id)_RGFW->NSApp, sel_registerName("requestUserAttention:"), NSInformationalRequest);
14099 break;
14100 case RGFW_flashUntilFocused:
14101 _RGFW->flash = ((NSInteger (*)(id, SEL, NSInteger))objc_msgSend) ((id)_RGFW->NSApp, sel_registerName("requestUserAttention:"), NSCriticalRequest);
14102 break;
14103 default: break;
14104 }
14105
14106 objc_msgSend_bool_void(pool, sel_registerName("drain"));
14107 }
14108
14109 RGFW_bool RGFW_window_isHidden(RGFW_window* win) {
14110 RGFW_ASSERT(win != NULL);
14111
14112 bool visible = objc_msgSend_bool(win->src.window, sel_registerName("isVisible"));
14113 return visible == NO && !RGFW_window_isMinimized(win);
14114 }
14115
14116 RGFW_bool RGFW_window_isMinimized(RGFW_window* win) {
14117 RGFW_ASSERT(win != NULL);
14118
14119 return objc_msgSend_bool(win->src.window, sel_registerName("isMiniaturized")) == YES;
14120 }
14121
14122 RGFW_bool RGFW_window_isMaximized(RGFW_window* win) {
14123 RGFW_ASSERT(win != NULL);
14124 RGFW_bool b = (RGFW_bool)objc_msgSend_bool(win->src.window, sel_registerName("isZoomed"));
14125 return b;
14126 }
14127
14128 RGFWDEF id RGFW_getNSScreenForDisplayUInt(u32 uintNum);
14129 id RGFW_getNSScreenForDisplayUInt(u32 uintNum) {
14130 Class NSScreenClass = objc_getClass("NSScreen");
14131
14132 id screens = objc_msgSend_id(NSScreenClass, sel_registerName("screens"));
14133
14134 NSUInteger count = (NSUInteger)objc_msgSend_uint(screens, sel_registerName("count"));
14135 NSUInteger i;
14136 for (i = 0; i < count; i++) {
14137 id screen = ((id (*)(id, SEL, int))objc_msgSend) (screens, sel_registerName("objectAtIndex:"), (int)i);
14138 id description = objc_msgSend_id(screen, sel_registerName("deviceDescription"));
14139 id screenNumberKey = NSString_stringWithUTF8String("NSScreenNumber");
14140 id screenNumber = objc_msgSend_id_id(description, sel_registerName("objectForKey:"), screenNumberKey);
14141
14142 if (CGDisplayUnitNumber((CGDirectDisplayID)objc_msgSend_uint(screenNumber, sel_registerName("unsignedIntValue"))) == uintNum) {
14143 return screen;
14144 }
14145 }
14146
14147 return NULL;
14148 }
14149
14150 float RGFW_osx_getRefreshRate(CGDirectDisplayID display, CGDisplayModeRef mode);
14151 float RGFW_osx_getRefreshRate(CGDirectDisplayID display, CGDisplayModeRef mode) {
14152 if (mode) {
14153 float refreshRate = (float)CGDisplayModeGetRefreshRate(mode);
14154 if (refreshRate != 0) return refreshRate;
14155 }
14156
14157 #ifndef RGFW_NO_IOKIT
14158 float res = RGFW_osx_getFallbackRefreshRate(display);
14159 if (res != 0) return res;
14160 #else
14161 RGFW_UNUSED(display);
14162 #endif
14163 return 60;
14164 }
14165
14166 void RGFW_pollMonitors(void) {
14167 static CGDirectDisplayID displays[RGFW_MAX_MONITORS];
14168 u32 count;
14169
14170 if (CGGetActiveDisplayList(RGFW_MAX_MONITORS, displays, &count) != kCGErrorSuccess) {
14171 return;
14172 }
14173
14174 if (count > RGFW_MAX_MONITORS) count = RGFW_MAX_MONITORS;
14175
14176 for (RGFW_monitorNode* node = _RGFW->monitors.list.head; node; node = node->next) {
14177 node->disconnected = RGFW_TRUE;
14178 }
14179
14180 CGDirectDisplayID primary = CGMainDisplayID();
14181
14182 u32 i;
14183 for (i = 0; i < count; i++) {
14184 RGFW_monitor monitor;
14185
14186 u32 uintNum = CGDisplayUnitNumber(displays[i]);
14187 id screen = RGFW_getNSScreenForDisplayUInt(uintNum);
14188
14189 RGFW_monitorNode* node;
14190 for (node = _RGFW->monitors.list.head; node; node = node->next) {
14191 if (node->uintNum == uintNum) break;
14192 }
14193
14194 if (node) {
14195 node->screen = (void*)screen;
14196 node->display = displays[i];
14197 node->disconnected = RGFW_FALSE;
14198 if (displays[i] == primary) {
14199 _RGFW->monitors.primary = node;
14200 }
14201 continue;
14202 }
14203
14204 const char name[] = "MacOS\0";
14205 RGFW_MEMCPY(monitor.name, name, 6);
14206
14207 CGRect bounds = CGDisplayBounds(displays[i]);
14208 monitor.x = (i32)bounds.origin.x;
14209 monitor.y = (i32)RGFW_cocoaYTransform((float)(bounds.origin.y + bounds.size.height - 1));
14210
14211 CGDisplayModeRef mode = CGDisplayCopyDisplayMode(displays[i]);
14212 monitor.mode.w = (i32)CGDisplayModeGetWidth(mode);
14213 monitor.mode.h = (i32)CGDisplayModeGetHeight(mode);
14214 monitor.mode.src = (void*)mode;
14215 monitor.mode.red = 8; monitor.mode.green = 8; monitor.mode.blue = 8;
14216
14217 monitor.mode.refreshRate = RGFW_osx_getRefreshRate(displays[i], mode);
14218 CFRelease(mode);
14219
14220 CGSize screenSizeMM = CGDisplayScreenSize(displays[i]);
14221 monitor.physW = (float)screenSizeMM.width / 25.4f;
14222 monitor.physH = (float)screenSizeMM.height / 25.4f;
14223
14224 float ppi_width = ((float)monitor.mode.w / monitor.physW);
14225 float ppi_height = ((float)monitor.mode.h / monitor.physH);
14226
14227 monitor.pixelRatio = (float)((CGFloat (*)(id, SEL))abi_objc_msgSend_fpret) (screen, sel_registerName("backingScaleFactor"));
14228 float dpi = 96.0f * monitor.pixelRatio;
14229
14230 monitor.scaleX = ((((float) (ppi_width) / dpi) * 10.0f)) / 10.0f;
14231 monitor.scaleY = ((((float) (ppi_height) / dpi) * 10.0f)) / 10.0f;
14232
14233 node = RGFW_monitors_add(&monitor);
14234
14235 node->screen = (void*)screen;
14236 node->uintNum = uintNum;
14237 node->display = displays[i];
14238
14239 if (displays[i] == primary) {
14240 _RGFW->monitors.primary = node;
14241 }
14242
14243 RGFW_monitorCallback(_RGFW->root, &node->mon, RGFW_TRUE);
14244 }
14245
14246 RGFW_monitors_refresh();
14247 }
14248
14249 RGFW_bool RGFW_monitor_getWorkarea(RGFW_monitor* monitor, i32* x, i32* y, i32* width, i32* height) {
14250 NSRect frameRect = ((NSRect(*)(id, SEL))abi_objc_msgSend_stret)((id)monitor->node->screen, sel_registerName("visibleFrame"));
14251
14252 if (x) *x = (i32)frameRect.origin.x;
14253 if (y) *y = (i32)RGFW_cocoaYTransform((float)(frameRect.origin.y + frameRect.size.height - (double)1.0f));
14254 if (width) *width = (i32)frameRect.size.width;
14255 if (height) *height = (i32)frameRect.size.height;
14256
14257 return RGFW_TRUE;
14258 }
14259
14260 size_t RGFW_monitor_getGammaRampPtr(RGFW_monitor* monitor, RGFW_gammaRamp* ramp) {
14261 id pool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
14262 pool = objc_msgSend_id(pool, sel_registerName("init"));
14263
14264 u32 size = CGDisplayGammaTableCapacity(monitor->node->display);
14265 CGGammaValue* values = (CGGammaValue*)RGFW_ALLOC(size * 3 * sizeof(CGGammaValue));
14266
14267 CGGetDisplayTransferByTable(monitor->node->display, size, values, values + size, values + size * 2, &size);
14268
14269 for (u32 i = 0; ramp && i < size; i++) {
14270 ramp->red[i] = (u16) (values[i] * 65535);
14271 ramp->green[i] = (u16) (values[i + size] * 65535);
14272 ramp->blue[i] = (u16) (values[i + size * 2] * 65535);
14273 }
14274
14275 RGFW_FREE(values);
14276
14277 objc_msgSend_bool_void(pool, sel_registerName("drain"));
14278 return size;
14279 }
14280
14281 RGFW_bool RGFW_monitor_setGammaRamp(RGFW_monitor* monitor, RGFW_gammaRamp* ramp) {
14282 id pool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
14283 pool = objc_msgSend_id(pool, sel_registerName("init"));
14284
14285 CGGammaValue* values = (CGGammaValue*)RGFW_ALLOC(ramp->count * 3 * sizeof(CGGammaValue));
14286
14287 for (u32 i = 0; i < ramp->count; i++) {
14288 values[i] = ramp->red[i] / 65535.f;
14289 values[i + ramp->count] = ramp->green[i] / 65535.f;
14290 values[i + ramp->count * 2] = ramp->blue[i] / 65535.f;
14291 }
14292
14293 CGSetDisplayTransferByTable(monitor->node->display, (u32)ramp->count, values, values + ramp->count, values + ramp->count * 2);
14294
14295 RGFW_FREE(values);
14296
14297 objc_msgSend_bool_void(pool, sel_registerName("drain"));
14298
14299 return RGFW_TRUE;
14300 }
14301
14302 size_t RGFW_monitor_getModesPtr(RGFW_monitor* mon, RGFW_monitorMode** modes) {
14303 CGDirectDisplayID display = mon->node->display;
14304 CFArrayRef allModes = CGDisplayCopyAllDisplayModes(display, NULL);
14305
14306 if (allModes == NULL) {
14307 return RGFW_FALSE;
14308 }
14309
14310 size_t count = (size_t)CFArrayGetCount(allModes);
14311
14312 CFIndex i;
14313 for (i = 0; i < (CFIndex)count && modes; i++) {
14314 CGDisplayModeRef cmode = (CGDisplayModeRef)CFArrayGetValueAtIndex(allModes, i);
14315
14316 RGFW_monitorMode foundMode;
14317 foundMode.w = (i32)CGDisplayModeGetWidth(cmode);
14318 foundMode.h = (i32)CGDisplayModeGetHeight(cmode);
14319 foundMode.refreshRate = RGFW_osx_getRefreshRate(display, cmode);
14320 foundMode.red = 8; foundMode.green = 8; foundMode.blue = 8;
14321 foundMode.src = (void*)cmode;
14322 (*modes)[i] = foundMode;
14323 }
14324
14325 CFRelease(allModes);
14326 return count;
14327 }
14328
14329 RGFW_bool RGFW_monitor_setMode(RGFW_monitor* mon, RGFW_monitorMode* mode) {
14330 if (CGDisplaySetDisplayMode(mon->node->display, (CGDisplayModeRef)mode->src, NULL) == kCGErrorSuccess) {
14331 return RGFW_TRUE;
14332 }
14333
14334 return RGFW_FALSE;
14335 }
14336
14337 RGFW_bool RGFW_monitor_requestMode(RGFW_monitor* mon, RGFW_monitorMode* mode, RGFW_modeRequest request) {
14338 CGDirectDisplayID display = mon->node->display;
14339 CFArrayRef allModes = CGDisplayCopyAllDisplayModes(display, NULL);
14340
14341 if (allModes == NULL) {
14342 return RGFW_FALSE;
14343 }
14344
14345 CGDisplayModeRef native = NULL;
14346
14347 CFIndex i;
14348 for (i = 0; i < CFArrayGetCount(allModes); i++) {
14349 CGDisplayModeRef cmode = (CGDisplayModeRef)CFArrayGetValueAtIndex(allModes, i);
14350
14351 RGFW_monitorMode foundMode;
14352 foundMode.w = (i32)CGDisplayModeGetWidth(cmode);
14353 foundMode.h = (i32)CGDisplayModeGetHeight(cmode);
14354 foundMode.refreshRate = RGFW_osx_getRefreshRate(display, cmode);
14355 foundMode.red = 8; foundMode.green = 8; foundMode.blue = 8;
14356 foundMode.src = (void*)cmode;
14357
14358 if (RGFW_monitorModeCompare(mode, &foundMode, request)) {
14359 native = cmode;
14360 mon->mode = foundMode;
14361 break;
14362 }
14363 }
14364
14365 CFRelease(allModes);
14366
14367 if (native) {
14368 if (CGDisplaySetDisplayMode(display, native, NULL) == kCGErrorSuccess) {
14369 return RGFW_TRUE;
14370 }
14371 }
14372
14373 return RGFW_FALSE;
14374 }
14375
14376 RGFW_monitor* RGFW_window_getMonitor(RGFW_window* win) {
14377 id screen = objc_msgSend_id(win->src.window, sel_registerName("screen"));
14378 id description = objc_msgSend_id(screen, sel_registerName("deviceDescription"));
14379 id screenNumberKey = NSString_stringWithUTF8String("NSScreenNumber");
14380 id screenNumber = objc_msgSend_id_id(description, sel_registerName("objectForKey:"), screenNumberKey);
14381
14382 CGDirectDisplayID display = (CGDirectDisplayID)objc_msgSend_uint(screenNumber, sel_registerName("unsignedIntValue"));
14383
14384 RGFW_monitorNode* node = _RGFW->monitors.list.head;
14385 for (node = _RGFW->monitors.list.head; node; node = node->next) {
14386 if (node->display == display && (id)node->screen == screen) {
14387 break;
14388 }
14389 }
14390
14391 return &node->mon;
14392 }
14393
14394 RGFW_ssize_t RGFW_readClipboardPtr(char* str, size_t strCapacity) {
14395 size_t clip_len;
14396 char* clip = (char*)NSPasteboard_stringForType(NSPasteboard_generalPasteboard(), NSPasteboardTypeString, &clip_len);
14397 if (clip == NULL) return -1;
14398
14399 if (str != NULL) {
14400 if (strCapacity < clip_len)
14401 return 0;
14402
14403 RGFW_MEMCPY(str, clip, clip_len);
14404
14405 str[clip_len] = '\0';
14406 }
14407
14408 return (RGFW_ssize_t)clip_len;
14409 }
14410
14411 void RGFW_writeClipboard(const char* text, u32 textLen) {
14412 RGFW_UNUSED(textLen);
14413
14414 NSPasteboardType array[] = { NSPasteboardTypeString, NULL };
14415 NSPasteBoard_declareTypes(NSPasteboard_generalPasteboard(), array, 1, NULL);
14416
14417 SEL func = sel_registerName("setString:forType:");
14418 ((bool (*)(id, SEL, id, id))objc_msgSend)
14419 (NSPasteboard_generalPasteboard(), func, NSString_stringWithUTF8String(text), NSString_stringWithUTF8String((const char*)NSPasteboardTypeString));
14420 }
14421
14422 #ifdef RGFW_OPENGL
14423 void NSOpenGLContext_setValues(id context, const int* vals, NSOpenGLContextParameter param);
14424 void NSOpenGLContext_setValues(id context, const int* vals, NSOpenGLContextParameter param) {
14425 ((void (*)(id, SEL, const int*, NSOpenGLContextParameter))objc_msgSend)
14426 (context, sel_registerName("setValues:forParameter:"), vals, param);
14427 }
14428
14429
14430 /* MacOS OpenGL API spares us yet again (there are no extensions) */
14431 RGFW_bool RGFW_extensionSupportedPlatform_OpenGL(const char * extension, size_t len) { RGFW_UNUSED(extension); RGFW_UNUSED(len); return RGFW_FALSE; }
14432
14433 RGFW_proc RGFW_getProcAddress_OpenGL(const char* procname) {
14434 static CFBundleRef RGFWnsglFramework = NULL;
14435 if (RGFWnsglFramework == NULL)
14436 RGFWnsglFramework = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl"));
14437
14438 CFStringRef symbolName = CFStringCreateWithCString(kCFAllocatorDefault, procname, kCFStringEncodingASCII);
14439
14440 RGFW_proc symbol = (RGFW_proc)CFBundleGetFunctionPointerForName(RGFWnsglFramework, symbolName);
14441
14442 CFRelease(symbolName);
14443
14444 return symbol;
14445 }
14446
14447 RGFW_bool RGFW_window_createContextPtr_OpenGL(RGFW_window* win, RGFW_glContext* ctx, RGFW_glHints* hints) {
14448 win->src.ctx.native = ctx;
14449 win->src.gfxType = RGFW_gfxNativeOpenGL;
14450
14451 i32 attribs[40];
14452 size_t render_type_index = 0;
14453 {
14454 RGFW_attribStack stack;
14455 RGFW_attribStack_init(&stack, attribs, 40);
14456
14457 i32 colorBits = (i32)(hints->red + hints->green + hints->blue + hints->alpha) / 4;
14458 RGFW_attribStack_pushAttribs(&stack, NSOpenGLPFAColorSize, colorBits);
14459
14460 RGFW_attribStack_pushAttribs(&stack, NSOpenGLPFAAlphaSize, hints->alpha);
14461 RGFW_attribStack_pushAttribs(&stack, NSOpenGLPFADepthSize, hints->depth);
14462 RGFW_attribStack_pushAttribs(&stack, NSOpenGLPFAStencilSize, hints->stencil);
14463 RGFW_attribStack_pushAttribs(&stack, NSOpenGLPFAAuxBuffers, hints->auxBuffers);
14464 RGFW_attribStack_pushAttrib(&stack, NSOpenGLPFAClosestPolicy);
14465 if (hints->samples) {
14466 RGFW_attribStack_pushAttribs(&stack, NSOpenGLPFASampleBuffers, 1);
14467 RGFW_attribStack_pushAttribs(&stack, NSOpenGLPFASamples, hints->samples);
14468 } else RGFW_attribStack_pushAttribs(&stack, NSOpenGLPFASampleBuffers, 0);
14469
14470 if (hints->doubleBuffer)
14471 RGFW_attribStack_pushAttrib(&stack, NSOpenGLPFADoubleBuffer);
14472
14473 #ifdef RGFW_COCOA_GRAPHICS_SWITCHING
14474 RGFW_attribStack_pushAttribs(&stack, NSOpenGLPFAAllowOfflineRenderers, kCGLPFASupportsAutomaticGraphicsSwitching);
14475 #endif
14476 #if MAC_OS_X_VERSION_MAX_ALLOWED < 101200
14477 if (hints->stereo) RGFW_attribStack_pushAttrib(&stack, NSOpenGLPFAStereo);
14478 #endif
14479
14480 /* macOS has the surface attribs and the OpenGL attribs connected for some reason maybe this is to give macOS more control to limit openGL/the OpenGL version? */
14481 RGFW_attribStack_pushAttribs(&stack, NSOpenGLPFAOpenGLProfile,
14482 (hints->major >= 4) ? NSOpenGLProfileVersion4_1Core : (hints->major >= 3) ?
14483 NSOpenGLProfileVersion3_2Core : NSOpenGLProfileVersionLegacy);
14484
14485 if (hints->major <= 2) {
14486 i32 accumSize = (i32)(hints->accumRed + hints->accumGreen + hints->accumBlue + hints->accumAlpha) / 4;
14487 RGFW_attribStack_pushAttribs(&stack, NSOpenGLPFAAccumSize, accumSize);
14488 }
14489
14490 if (hints->renderer == RGFW_glSoftware) {
14491 RGFW_attribStack_pushAttribs(&stack, NSOpenGLPFARendererID, kCGLRendererGenericFloatID);
14492 } else {
14493 RGFW_attribStack_pushAttrib(&stack, NSOpenGLPFAAccelerated);
14494 }
14495 render_type_index = stack.count - 1;
14496
14497 RGFW_attribStack_pushAttribs(&stack, 0, 0);
14498 }
14499
14500 void* format = (void*) ((id(*)(id, SEL, const u32*))objc_msgSend) (NSAlloc((id)objc_getClass("NSOpenGLPixelFormat")), sel_registerName("initWithAttributes:"), (u32*)attribs);
14501 if (format == NULL) {
14502 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errOpenGLContext, "Failed to load pixel format for OpenGL");
14503
14504 assert(render_type_index + 3 < (sizeof(attribs) / sizeof(attribs[0])));
14505 attribs[render_type_index] = NSOpenGLPFARendererID;
14506 attribs[render_type_index + 1] = kCGLRendererGenericFloatID;
14507 attribs[render_type_index + 3] = 0;
14508
14509 format = (void*) ((id(*)(id, SEL, const u32*))objc_msgSend) (NSAlloc((id)objc_getClass("NSOpenGLPixelFormat")), sel_registerName("initWithAttributes:"), (u32*)attribs);
14510 if (format == NULL)
14511 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errOpenGLContext, "and loading software rendering OpenGL failed");
14512 else
14513 RGFW_sendDebugInfo(RGFW_typeWarning, RGFW_warningOpenGL, "Switching to software rendering");
14514 }
14515
14516 /* the pixel format can be passed directly to OpenGL context creation to create a context
14517 this is because the format also includes information about the OpenGL version (which may be a bad thing) */
14518
14519 if (win->src.view)
14520 NSRelease(win->src.view);
14521 win->src.view = (id) ((id(*)(id, SEL, NSRect, u32*))objc_msgSend) (NSAlloc(_RGFW->customViewClasses[1]),
14522 sel_registerName("initWithFrame:pixelFormat:"), (NSRect){{0, 0}, {(double)win->w, (double)win->h}}, (u32*)format);
14523
14524 id share = NULL;
14525 if (hints->share) {
14526 share = (id)hints->share->ctx;
14527 }
14528
14529 win->src.ctx.native->ctx = ((id (*)(id, SEL, id, id))objc_msgSend)(NSAlloc(objc_getClass("NSOpenGLContext")),
14530 sel_registerName("initWithFormat:shareContext:"),
14531 (id)format, share);
14532
14533 win->src.ctx.native->format = format;
14534
14535 objc_msgSend_void_id(win->src.view, sel_registerName("setOpenGLContext:"), win->src.ctx.native->ctx);
14536 if (win->internal.flags & RGFW_windowTransparent) {
14537 i32 opacity = 0;
14538 #define NSOpenGLCPSurfaceOpacity 236
14539 NSOpenGLContext_setValues((id)win->src.ctx.native->ctx, &opacity, (NSOpenGLContextParameter)NSOpenGLCPSurfaceOpacity);
14540
14541 }
14542
14543 objc_msgSend_void(win->src.ctx.native->ctx, sel_registerName("makeCurrentContext"));
14544
14545 objc_msgSend_void_id((id)win->src.window, sel_registerName("setContentView:"), win->src.view);
14546 objc_msgSend_void_bool(win->src.view, sel_registerName("setWantsLayer:"), true);
14547 objc_msgSend_int((id)win->src.view, sel_registerName("setLayerContentsPlacement:"), 4);
14548
14549 RGFW_window_swapInterval_OpenGL(win, 0);
14550
14551 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoOpenGL, "OpenGL context initalized.");
14552 return RGFW_TRUE;
14553 }
14554
14555 void RGFW_window_deleteContextPtr_OpenGL(RGFW_window* win, RGFW_glContext* ctx) {
14556 objc_msgSend_void(ctx->format, sel_registerName("release"));
14557 win->src.ctx.native->format = NULL;
14558
14559 objc_msgSend_void(ctx->ctx, sel_registerName("release"));
14560 win->src.ctx.native->ctx = NULL;
14561 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoOpenGL, "OpenGL context freed.");
14562 }
14563
14564 void RGFW_window_makeCurrentContext_OpenGL(RGFW_window* win) {
14565 if (win) RGFW_ASSERT(win->src.ctx.native);
14566 if (win != NULL)
14567 objc_msgSend_void(win->src.ctx.native->ctx, sel_registerName("makeCurrentContext"));
14568 else
14569 objc_msgSend_id(objc_getClass("NSOpenGLContext"), sel_registerName("clearCurrentContext"));
14570 }
14571 void* RGFW_getCurrentContext_OpenGL(void) {
14572 return objc_msgSend_id(objc_getClass("NSOpenGLContext"), sel_registerName("currentContext"));
14573 }
14574
14575 void RGFW_window_swapBuffers_OpenGL(RGFW_window* win) {
14576 RGFW_ASSERT(win && win->src.ctx.native);
14577 objc_msgSend_void(win->src.ctx.native->ctx, sel_registerName("flushBuffer"));
14578 }
14579 void RGFW_window_swapInterval_OpenGL(RGFW_window* win, i32 swapInterval) {
14580 RGFW_ASSERT(win != NULL && win->src.ctx.native != NULL);
14581 NSOpenGLContext_setValues((id)win->src.ctx.native->ctx, &swapInterval, (NSOpenGLContextParameter)222);
14582 }
14583 #endif
14584
14585 void RGFW_deinitPlatform(void) {
14586 objc_msgSend_void_id(_RGFW->NSApp, sel_registerName("setDelegate:"), NULL);
14587
14588 objc_msgSend_void_id(_RGFW->NSApp, sel_registerName("stop:"), NULL);
14589 NSRelease(_RGFW->NSApp);
14590 _RGFW->NSApp = NULL;
14591
14592 NSRelease(_RGFW->customNSAppDelegate);
14593
14594 _RGFW->customNSAppDelegate = NULL;
14595
14596 objc_disposeClassPair((Class)_RGFW->customViewClasses[0]);
14597 objc_disposeClassPair((Class)_RGFW->customViewClasses[1]);
14598 objc_disposeClassPair((Class)_RGFW->customWindowDelegateClass);
14599 objc_disposeClassPair((Class)_RGFW->customNSAppDelegateClass);
14600 }
14601
14602 void RGFW_window_closePlatform(RGFW_window* win) {
14603 objc_msgSend_void_id((id)win->src.window, sel_registerName("setDelegate:"), NULL);
14604 NSRelease((id)win->src.delegate);
14605 NSRelease(win->src.view);
14606
14607 objc_msgSend_id(win->src.window, sel_registerName("close"));
14608 NSRelease(win->src.window);
14609 }
14610
14611 #ifdef RGFW_VULKAN
14612 VkResult RGFW_window_createSurface_Vulkan(RGFW_window* win, VkInstance instance, VkSurfaceKHR* surface) {
14613 RGFW_ASSERT(win != NULL); RGFW_ASSERT(instance);
14614 RGFW_ASSERT(surface != NULL);
14615
14616 *surface = VK_NULL_HANDLE;
14617 id pool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
14618 pool = objc_msgSend_id(pool, sel_registerName("init"));
14619
14620 id nsView = (id)win->src.view;
14621 if (!nsView) {
14622 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errMetal, "NSView is NULL for macOS window");
14623 return -1;
14624 }
14625
14626
14627 id layer = ((id (*)(id, SEL))objc_msgSend)(nsView, sel_registerName("layer"));
14628
14629 void* metalLayer = RGFW_getLayer_OSX();
14630 if (metalLayer == NULL) {
14631 return -1;
14632 }
14633 ((void (*)(id, SEL, id))objc_msgSend)((id)nsView, sel_registerName("setLayer:"), metalLayer);
14634 ((void (*)(id, SEL, BOOL))objc_msgSend)(nsView, sel_registerName("setWantsLayer:"), YES);
14635
14636 VkResult result;
14637 /*
14638 VkMetalSurfaceCreateInfoEXT macos;
14639 macos.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK;
14640 macos.slayer = metalLayer;
14641 RGFW_MEMSET(&macos, 0, sizeof(macos));
14642 result = vkCreateMacOSSurfaceMVK(instance, &macos, NULL, surface);
14643 */
14644
14645 VkMacOSSurfaceCreateInfoMVK macos;
14646 RGFW_MEMSET(&macos, 0, sizeof(macos));
14647 macos.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK;
14648 macos.pView = nsView;
14649
14650 result = vkCreateMacOSSurfaceMVK(instance, &macos, NULL, surface);
14651
14652 objc_msgSend_bool_void(pool, sel_registerName("drain"));
14653
14654 return result;
14655 }
14656 #endif
14657
14658 #ifdef RGFW_WEBGPU
14659 WGPUSurface RGFW_window_createSurface_WebGPU(RGFW_window* window, WGPUInstance instance) {
14660 WGPUSurfaceDescriptor surfaceDesc = {0};
14661 id* nsView = (id*)window->src.view;
14662 if (!nsView) {
14663 RGFW_sendDebugInfo(RGFW_typeError, RGFW_errMetal, "NSView is NULL for macOS window");
14664 return NULL;
14665 }
14666
14667 ((void (*)(id, SEL, BOOL))objc_msgSend)(nsView, sel_registerName("setWantsLayer:"), YES);
14668 id layer = ((id (*)(id, SEL))objc_msgSend)(nsView, sel_registerName("layer"));
14669
14670 void* metalLayer = RGFW_getLayer_OSX();
14671 if (metalLayer == NULL) {
14672 return NULL;
14673 }
14674 ((void (*)(id, SEL, id))objc_msgSend)((id)nsView, sel_registerName("setLayer:"), metalLayer);
14675 layer = metalLayer;
14676
14677 WGPUSurfaceSourceMetalLayer fromMetal = {0};
14678 fromMetal.chain.sType = WGPUSType_SurfaceSourceMetalLayer;
14679 #ifdef __OBJC__
14680 fromMetal.layer = (__bridge CAMetalLayer*)layer; /* Use __bridge for ARC compatibility if mixing C/Obj-C */
14681 #else
14682 fromMetal.layer = layer;
14683 #endif
14684
14685 surfaceDesc.nextInChain = (WGPUChainedStruct*)&fromMetal.chain;
14686 return wgpuInstanceCreateSurface(instance, &surfaceDesc);
14687 }
14688 #endif
14689
14690 #endif /* RGFW_MACOS */
14691
14692 /*
14693 End of MaOS defines
14694 */
14695
14696 /*
14697 WASM defines
14698 */
14699
14700 #ifdef RGFW_WASM
14701 EM_BOOL Emscripten_on_resize(int eventType, const EmscriptenUiEvent* E, void* userData) {
14702 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
14703 RGFW_windowResizedCallback(_RGFW->root, E->windowInnerWidth, E->windowInnerHeight);
14704 return EM_TRUE;
14705 }
14706
14707 EM_BOOL Emscripten_on_fullscreenchange(int eventType, const EmscriptenFullscreenChangeEvent* E, void* userData) {
14708 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
14709
14710 if (!(_RGFW->root->internal.enabledEvents & RGFW_windowResizedFlag)) return EM_TRUE;
14711
14712 static u8 fullscreen = RGFW_FALSE;
14713 static i32 originalW, originalH;
14714
14715 if (fullscreen == RGFW_FALSE) {
14716 originalW = _RGFW->root->w;
14717 originalH = _RGFW->root->h;
14718 }
14719
14720 fullscreen = !fullscreen;
14721 _RGFW->root->w = E->screenWidth;
14722 _RGFW->root->h = E->screenHeight;
14723
14724 EM_ASM("Module.canvas.focus();");
14725
14726 if (fullscreen == RGFW_FALSE) {
14727 _RGFW->root->w = originalW;
14728 _RGFW->root->h = originalH;
14729 } else {
14730 #if __EMSCRIPTEN_major__ >= 1 && __EMSCRIPTEN_minor__ >= 29 && __EMSCRIPTEN_tiny__ >= 0
14731 EmscriptenFullscreenStrategy FSStrat = {0};
14732 FSStrat.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
14733 FSStrat.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_HIDEF;
14734 FSStrat.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
14735 emscripten_request_fullscreen_strategy("#canvas", 1, &FSStrat);
14736 #else
14737 emscripten_request_fullscreen("#canvas", 1);
14738 #endif
14739 }
14740
14741 emscripten_set_canvas_element_size("#canvas", _RGFW->root->w, _RGFW->root->h);
14742 RGFW_windowResizedCallback(_RGFW->root, _RGFW->root->w, _RGFW->root->h);
14743 return EM_TRUE;
14744 }
14745
14746 EM_BOOL Emscripten_on_focusin(int eventType, const EmscriptenFocusEvent* E, void* userData) {
14747 RGFW_UNUSED(eventType); RGFW_UNUSED(userData); RGFW_UNUSED(E);
14748
14749 RGFW_focusCallback(_RGFW->root, 1);
14750 return EM_TRUE;
14751 }
14752
14753 EM_BOOL Emscripten_on_focusout(int eventType, const EmscriptenFocusEvent* E, void* userData) {
14754 RGFW_UNUSED(eventType); RGFW_UNUSED(userData); RGFW_UNUSED(E);
14755
14756 RGFW_focusCallback(_RGFW->root, 0);
14757 return EM_TRUE;
14758 }
14759
14760 EM_BOOL Emscripten_on_mousemove(int eventType, const EmscriptenMouseEvent* E, void* userData) {
14761 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
14762 RGFW_mousePosCallback(_RGFW->root, E->targetX, E->targetY, E->movementX, E->movementY);
14763 return EM_TRUE;
14764 }
14765
14766 EM_BOOL Emscripten_on_mousedown(int eventType, const EmscriptenMouseEvent* E, void* userData) {
14767 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
14768
14769 int button = E->button;
14770 if (button > 2)
14771 button += 2;
14772
14773 RGFW_mouseButtonCallback(_RGFW->root, button, 1);
14774 return EM_TRUE;
14775 }
14776
14777 EM_BOOL Emscripten_on_mouseup(int eventType, const EmscriptenMouseEvent* E, void* userData) {
14778 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
14779
14780 int button = E->button;
14781 if (button > 2)
14782 button += 2;
14783
14784 RGFW_mouseButtonCallback(_RGFW->root, button, 0);
14785 return EM_TRUE;
14786 }
14787
14788 EM_BOOL Emscripten_on_wheel(int eventType, const EmscriptenWheelEvent* E, void* userData) {
14789 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
14790
14791 RGFW_mouseScrollCallback(_RGFW->root, E->deltaX, E->deltaY);
14792
14793 return EM_TRUE;
14794 }
14795
14796 EM_BOOL Emscripten_on_touchstart(int eventType, const EmscriptenTouchEvent* E, void* userData) {
14797 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
14798
14799 if (!(_RGFW->root->internal.enabledEvents & RGFW_mouseButtonPressedFlag)) return EM_TRUE;
14800
14801 size_t i;
14802 for (i = 0; i < (size_t)E->numTouches; i++) {
14803 RGFW_mousePosCallback(_RGFW->root, E->touches[i].targetX, E->touches[i].targetY, 0, 0);
14804 RGFW_mouseButtonCallback(_RGFW->root, RGFW_mouseLeft, 1);
14805 }
14806
14807 return EM_TRUE;
14808 }
14809
14810 EM_BOOL Emscripten_on_touchmove(int eventType, const EmscriptenTouchEvent* E, void* userData) {
14811 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
14812
14813 if (!(_RGFW->root->internal.enabledEvents & RGFW_mousePosChangedFlag)) return EM_TRUE;
14814
14815 size_t i;
14816 for (i = 0; i < (size_t)E->numTouches; i++) {
14817 RGFW_mousePosCallback(_RGFW->root, E->touches[i].targetX, E->touches[i].targetY, 0, 0);
14818 }
14819 return EM_TRUE;
14820 }
14821
14822 EM_BOOL Emscripten_on_touchend(int eventType, const EmscriptenTouchEvent* E, void* userData) {
14823 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
14824
14825 if (!(_RGFW->root->internal.enabledEvents & RGFW_mouseButtonReleasedFlag)) return EM_TRUE;
14826
14827 size_t i;
14828 for (i = 0; i < (size_t)E->numTouches; i++) {
14829 RGFW_mousePosCallback(_RGFW->root, E->touches[i].targetX, E->touches[i].targetY, 0, 0);
14830 RGFW_mouseButtonCallback(_RGFW->root, RGFW_mouseLeft, 0);
14831 }
14832 return EM_TRUE;
14833 }
14834
14835 EM_BOOL Emscripten_on_touchcancel(int eventType, const EmscriptenTouchEvent* E, void* userData) { RGFW_UNUSED(eventType); RGFW_UNUSED(userData); return EM_TRUE; }
14836
14837 RGFW_key RGFW_WASMPhysicalToRGFW(u32 hash);
14838
14839 void EMSCRIPTEN_KEEPALIVE RGFW_handleKeyEvent(char* code, u32 codepoint, RGFW_bool press) {
14840 const char* iCode = code;
14841
14842 u32 hash = 0;
14843 while(*iCode) hash = ((hash ^ 0x7E057D79U) << 3) ^ (unsigned int)*iCode++;
14844
14845 u32 physicalKey = RGFW_WASMPhysicalToRGFW(hash);
14846
14847 RGFW_keyCallback(_RGFW->root, physicalKey, _RGFW->root->internal.mod, RGFW_window_isKeyDown(_RGFW->root, (u8)physicalKey), press);
14848 if (press) {
14849 ; RGFW_keyCharCallback(_RGFW->root, codepoint);
14850 }
14851 }
14852
14853 void EMSCRIPTEN_KEEPALIVE RGFW_handleKeyMods(RGFW_bool capital, RGFW_bool numlock, RGFW_bool control, RGFW_bool alt, RGFW_bool shift, RGFW_bool super, RGFW_bool scroll) {
14854 RGFW_updateKeyModsEx(_RGFW->root, capital, numlock, control, alt, shift, super, scroll);
14855 }
14856
14857 void EMSCRIPTEN_KEEPALIVE Emscripten_onDrop(size_t count) {
14858 RGFW_dataDropCallback(_RGFW->root, _RGFW->files, count);
14859 }
14860
14861 void RGFW_stopCheckEvents(void) {
14862 _RGFW->stopCheckEvents_bool = RGFW_TRUE;
14863 }
14864
14865 RGFW_bool RGFW_createSurfacePtr(u8* data, i32 w, i32 h, RGFW_format format, RGFW_surface* surface) {
14866 surface->data = data;
14867 surface->w = w;
14868 surface->h = h;
14869 surface->format = format;
14870 return RGFW_TRUE;
14871 }
14872
14873 void RGFW_window_blitSurface(RGFW_window* win, RGFW_surface* surface) {
14874 /* TODO: Needs fixing. */
14875 RGFW_copyImageData(surface->data, surface->w, RGFW_MIN(win->h, surface->h), RGFW_formatRGBA8, surface->data, surface->format, surface->convertFunc);
14876 EM_ASM_({
14877 var data = Module.HEAPU8.slice($0, $0 + $1 * $2 * 4);
14878 let context = document.getElementById("canvas").getContext("2d");
14879 let image = context.getImageData(0, 0, $1, $2);
14880 image.data.set(data);
14881 context.putImageData(image, 0, $4 - $2);
14882 }, surface->data, surface->w, surface->h, RGFW_MIN(win->h, surface->w), RGFW_MIN(win->h, surface->h));
14883 }
14884
14885 void RGFW_surface_freePtr(RGFW_surface* surface) { }
14886
14887 void EMSCRIPTEN_KEEPALIVE RGFW_makeSetValue(size_t index, char* file) {
14888 /* This seems like a terrible idea, don't replicate this unless you hate yourself or the OS */
14889 /* TODO: find a better way to do this
14890 */
14891 RGFW_STRNCPY((char*)_RGFW->files[index], file, RGFW_MAX_PATH - 1);
14892 _RGFW->files[index][RGFW_MAX_PATH - 1] = '\0';
14893 }
14894
14895 #include <sys/stat.h>
14896 #include <sys/types.h>
14897 #include <errno.h>
14898 #include <stdio.h>
14899
14900 void EMSCRIPTEN_KEEPALIVE RGFW_mkdir(char* name) { mkdir(name, 0755); }
14901
14902 void EMSCRIPTEN_KEEPALIVE RGFW_writeFile(const char *path, const char *data, size_t len) {
14903 FILE* file = fopen(path, "w+");
14904 if (file == NULL)
14905 return;
14906
14907 fwrite(data, sizeof(char), len, file);
14908 fclose(file);
14909 }
14910
14911 void RGFW_initKeycodesPlatform(void) {
14912 _RGFW->keycodes[DOM_VK_BACK_QUOTE] = RGFW_backtick;
14913 _RGFW->keycodes[DOM_VK_0] = RGFW_0;
14914 _RGFW->keycodes[DOM_VK_1] = RGFW_1;
14915 _RGFW->keycodes[DOM_VK_2] = RGFW_2;
14916 _RGFW->keycodes[DOM_VK_3] = RGFW_3;
14917 _RGFW->keycodes[DOM_VK_4] = RGFW_4;
14918 _RGFW->keycodes[DOM_VK_5] = RGFW_5;
14919 _RGFW->keycodes[DOM_VK_6] = RGFW_6;
14920 _RGFW->keycodes[DOM_VK_7] = RGFW_7;
14921 _RGFW->keycodes[DOM_VK_8] = RGFW_8;
14922 _RGFW->keycodes[DOM_VK_9] = RGFW_9;
14923 _RGFW->keycodes[DOM_VK_SPACE] = RGFW_space;
14924 _RGFW->keycodes[DOM_VK_A] = RGFW_a;
14925 _RGFW->keycodes[DOM_VK_B] = RGFW_b;
14926 _RGFW->keycodes[DOM_VK_C] = RGFW_c;
14927 _RGFW->keycodes[DOM_VK_D] = RGFW_d;
14928 _RGFW->keycodes[DOM_VK_E] = RGFW_e;
14929 _RGFW->keycodes[DOM_VK_F] = RGFW_f;
14930 _RGFW->keycodes[DOM_VK_G] = RGFW_g;
14931 _RGFW->keycodes[DOM_VK_H] = RGFW_h;
14932 _RGFW->keycodes[DOM_VK_I] = RGFW_i;
14933 _RGFW->keycodes[DOM_VK_J] = RGFW_j;
14934 _RGFW->keycodes[DOM_VK_K] = RGFW_k;
14935 _RGFW->keycodes[DOM_VK_L] = RGFW_l;
14936 _RGFW->keycodes[DOM_VK_M] = RGFW_m;
14937 _RGFW->keycodes[DOM_VK_N] = RGFW_n;
14938 _RGFW->keycodes[DOM_VK_O] = RGFW_o;
14939 _RGFW->keycodes[DOM_VK_P] = RGFW_p;
14940 _RGFW->keycodes[DOM_VK_Q] = RGFW_q;
14941 _RGFW->keycodes[DOM_VK_R] = RGFW_r;
14942 _RGFW->keycodes[DOM_VK_S] = RGFW_s;
14943 _RGFW->keycodes[DOM_VK_T] = RGFW_t;
14944 _RGFW->keycodes[DOM_VK_U] = RGFW_u;
14945 _RGFW->keycodes[DOM_VK_V] = RGFW_v;
14946 _RGFW->keycodes[DOM_VK_W] = RGFW_w;
14947 _RGFW->keycodes[DOM_VK_X] = RGFW_x;
14948 _RGFW->keycodes[DOM_VK_Y] = RGFW_y;
14949 _RGFW->keycodes[DOM_VK_Z] = RGFW_z;
14950 _RGFW->keycodes[DOM_VK_PERIOD] = RGFW_period;
14951 _RGFW->keycodes[DOM_VK_COMMA] = RGFW_comma;
14952 _RGFW->keycodes[DOM_VK_SLASH] = RGFW_slash;
14953 _RGFW->keycodes[DOM_VK_OPEN_BRACKET] = RGFW_bracket;
14954 _RGFW->keycodes[DOM_VK_CLOSE_BRACKET] = RGFW_closeBracket;
14955 _RGFW->keycodes[DOM_VK_SEMICOLON] = RGFW_semicolon;
14956 _RGFW->keycodes[DOM_VK_QUOTE] = RGFW_apostrophe;
14957 _RGFW->keycodes[DOM_VK_BACK_SLASH] = RGFW_backSlash;
14958 _RGFW->keycodes[DOM_VK_RETURN] = RGFW_return;
14959 _RGFW->keycodes[DOM_VK_DELETE] = RGFW_delete;
14960 _RGFW->keycodes[DOM_VK_NUM_LOCK] = RGFW_numLock;
14961 _RGFW->keycodes[DOM_VK_DIVIDE] = RGFW_kpSlash;
14962 _RGFW->keycodes[DOM_VK_MULTIPLY] = RGFW_kpMultiply;
14963 _RGFW->keycodes[DOM_VK_SUBTRACT] = RGFW_kpMinus;
14964 _RGFW->keycodes[DOM_VK_NUMPAD1] = RGFW_kp1;
14965 _RGFW->keycodes[DOM_VK_NUMPAD2] = RGFW_kp2;
14966 _RGFW->keycodes[DOM_VK_NUMPAD3] = RGFW_kp3;
14967 _RGFW->keycodes[DOM_VK_NUMPAD4] = RGFW_kp4;
14968 _RGFW->keycodes[DOM_VK_NUMPAD5] = RGFW_kp5;
14969 _RGFW->keycodes[DOM_VK_NUMPAD6] = RGFW_kp6;
14970 _RGFW->keycodes[DOM_VK_NUMPAD9] = RGFW_kp9;
14971 _RGFW->keycodes[DOM_VK_NUMPAD0] = RGFW_kp0;
14972 _RGFW->keycodes[DOM_VK_DECIMAL] = RGFW_kpPeriod;
14973 _RGFW->keycodes[DOM_VK_RETURN] = RGFW_kpReturn;
14974 _RGFW->keycodes[DOM_VK_HYPHEN_MINUS] = RGFW_minus;
14975 _RGFW->keycodes[DOM_VK_EQUALS] = RGFW_equals;
14976 _RGFW->keycodes[DOM_VK_BACK_SPACE] = RGFW_backSpace;
14977 _RGFW->keycodes[DOM_VK_TAB] = RGFW_tab;
14978 _RGFW->keycodes[DOM_VK_CAPS_LOCK] = RGFW_capsLock;
14979 _RGFW->keycodes[DOM_VK_SHIFT] = RGFW_shiftL;
14980 _RGFW->keycodes[DOM_VK_CONTROL] = RGFW_controlL;
14981 _RGFW->keycodes[DOM_VK_ALT] = RGFW_altL;
14982 _RGFW->keycodes[DOM_VK_META] = RGFW_superL;
14983 _RGFW->keycodes[DOM_VK_F1] = RGFW_F1;
14984 _RGFW->keycodes[DOM_VK_F2] = RGFW_F2;
14985 _RGFW->keycodes[DOM_VK_F3] = RGFW_F3;
14986 _RGFW->keycodes[DOM_VK_F4] = RGFW_F4;
14987 _RGFW->keycodes[DOM_VK_F5] = RGFW_F5;
14988 _RGFW->keycodes[DOM_VK_F6] = RGFW_F6;
14989 _RGFW->keycodes[DOM_VK_F7] = RGFW_F7;
14990 _RGFW->keycodes[DOM_VK_F8] = RGFW_F8;
14991 _RGFW->keycodes[DOM_VK_F9] = RGFW_F9;
14992 _RGFW->keycodes[DOM_VK_F10] = RGFW_F10;
14993 _RGFW->keycodes[DOM_VK_F11] = RGFW_F11;
14994 _RGFW->keycodes[DOM_VK_F12] = RGFW_F12;
14995 _RGFW->keycodes[DOM_VK_UP] = RGFW_up;
14996 _RGFW->keycodes[DOM_VK_DOWN] = RGFW_down;
14997 _RGFW->keycodes[DOM_VK_LEFT] = RGFW_left;
14998 _RGFW->keycodes[DOM_VK_RIGHT] = RGFW_right;
14999 _RGFW->keycodes[DOM_VK_INSERT] = RGFW_insert;
15000 _RGFW->keycodes[DOM_VK_END] = RGFW_end;
15001 _RGFW->keycodes[DOM_VK_PAGE_UP] = RGFW_pageUp;
15002 _RGFW->keycodes[DOM_VK_PAGE_DOWN] = RGFW_pageDown;
15003 _RGFW->keycodes[DOM_VK_ESCAPE] = RGFW_escape;
15004 _RGFW->keycodes[DOM_VK_HOME] = RGFW_home;
15005 _RGFW->keycodes[DOM_VK_SCROLL_LOCK] = RGFW_scrollLock;
15006 _RGFW->keycodes[DOM_VK_PRINTSCREEN] = RGFW_printScreen;
15007 _RGFW->keycodes[DOM_VK_PAUSE] = RGFW_pause;
15008 _RGFW->keycodes[DOM_VK_F13] = RGFW_F13;
15009 _RGFW->keycodes[DOM_VK_F14] = RGFW_F14;
15010 _RGFW->keycodes[DOM_VK_F15] = RGFW_F15;
15011 _RGFW->keycodes[DOM_VK_F16] = RGFW_F16;
15012 _RGFW->keycodes[DOM_VK_F17] = RGFW_F17;
15013 _RGFW->keycodes[DOM_VK_F18] = RGFW_F18;
15014 _RGFW->keycodes[DOM_VK_F19] = RGFW_F19;
15015 _RGFW->keycodes[DOM_VK_F20] = RGFW_F20;
15016 _RGFW->keycodes[DOM_VK_F21] = RGFW_F21;
15017 _RGFW->keycodes[DOM_VK_F22] = RGFW_F22;
15018 _RGFW->keycodes[DOM_VK_F23] = RGFW_F23;
15019 _RGFW->keycodes[DOM_VK_F24] = RGFW_F24;
15020 }
15021
15022 i32 RGFW_initPlatform(void) { return 0; }
15023
15024 RGFW_window* RGFW_createWindowPlatform(const char* name, RGFW_windowFlags flags, RGFW_window* win) {
15025 emscripten_set_canvas_element_size("#canvas", win->w, win->h);
15026 emscripten_set_window_title(name);
15027
15028 /* load callbacks */
15029 emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, EM_FALSE, Emscripten_on_resize);
15030 emscripten_set_fullscreenchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, NULL, EM_FALSE, Emscripten_on_fullscreenchange);
15031 emscripten_set_mousemove_callback("#canvas", NULL, EM_FALSE, Emscripten_on_mousemove);
15032 emscripten_set_touchstart_callback("#canvas", NULL, EM_FALSE, Emscripten_on_touchstart);
15033 emscripten_set_touchend_callback("#canvas", NULL, EM_FALSE, Emscripten_on_touchend);
15034 emscripten_set_touchmove_callback("#canvas", NULL, EM_FALSE, Emscripten_on_touchmove);
15035 emscripten_set_touchcancel_callback("#canvas", NULL, EM_FALSE, Emscripten_on_touchcancel);
15036 emscripten_set_mousedown_callback("#canvas", NULL, EM_FALSE, Emscripten_on_mousedown);
15037 emscripten_set_mouseup_callback("#canvas", NULL, EM_FALSE, Emscripten_on_mouseup);
15038 emscripten_set_wheel_callback("#canvas", NULL, EM_FALSE, Emscripten_on_wheel);
15039 emscripten_set_focusin_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, EM_FALSE, Emscripten_on_focusin);
15040 emscripten_set_focusout_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, EM_FALSE, Emscripten_on_focusout);
15041
15042 if (flags & RGFW_windowAllowDND) {
15043 win->internal.flags |= RGFW_windowAllowDND;
15044 }
15045
15046 EM_ASM({
15047 window.addEventListener("keydown",
15048 (event) => {
15049 var code = stringToNewUTF8(event.code);
15050 Module._RGFW_handleKeyMods(event.getModifierState("CapsLock"), event.getModifierState("NumLock"), event.getModifierState("Control"), event.getModifierState("Alt"), event.getModifierState("Shift"), event.getModifierState("Meta"), event.getModifierState("ScrollLock"));
15051
15052 var codepoint = event.key.charCodeAt(0);
15053 if(codepoint < 0x7f && event.key.length > 1) {
15054 codepoint = 0;
15055 }
15056
15057 Module._RGFW_handleKeyEvent(code, codepoint, 1);
15058 _free(code);
15059 },
15060 true);
15061 window.addEventListener("keyup",
15062 (event) => {
15063 var code = stringToNewUTF8(event.code);
15064 Module._RGFW_handleKeyMods(event.getModifierState("CapsLock"), event.getModifierState("NumLock"), event.getModifierState("Control"), event.getModifierState("Alt"), event.getModifierState("Shift"), event.getModifierState("Meta"), event.getModifierState("ScrollLock"));
15065 Module._RGFW_handleKeyEvent(code, 0, 0);
15066 _free(code);
15067 },
15068 true);
15069 });
15070
15071 EM_ASM({
15072 var canvas = document.getElementById('canvas');
15073 canvas.addEventListener('drop', function(e) {
15074 e.preventDefault();
15075 if (e.dataTransfer.file < 0)
15076 return;
15077
15078 var filenamesArray = [];
15079 var count = e.dataTransfer.files.length;
15080
15081 /* Read and save the files to emscripten's files */
15082 var drop_dir = '.rgfw_dropped_files';
15083 Module._RGFW_mkdir(drop_dir);
15084
15085 for (var i = 0; i < count; i++) {
15086 var file = e.dataTransfer.files[i];
15087
15088 var path = '/' + drop_dir + '/' + file.name.replace("//", '_');
15089 var reader = new FileReader();
15090
15091 reader.onloadend = (e) => {
15092 if (reader.readyState != 2) {
15093 out('failed to read dropped file: '+file.name+': '+reader.error);
15094 }
15095 else {
15096 var data = e.target.result;
15097
15098 Module._RGFW_writeFile(path, new Uint8Array(data), file.size);
15099 }
15100 };
15101
15102 reader.readAsArrayBuffer(file);
15103 /* This works weird on modern OpenGL */
15104 var filename = stringToNewUTF8(path);
15105
15106 filenamesArray.push(filename);
15107
15108 Module._RGFW_makeSetValue(i, filename);
15109 }
15110
15111 Module._Emscripten_onDrop(count);
15112
15113 for (var i = 0; i < count; i++) {
15114 _free(filenamesArray[i]);
15115 }
15116 }, true);
15117
15118 canvas.addEventListener('dragover', function(e) { e.preventDefault(); return false; }, true);
15119 });
15120
15121 return win;
15122 }
15123
15124 RGFW_key RGFW_physicalToMappedKey(RGFW_key key) {
15125 return key;
15126 }
15127
15128 void RGFW_pollEvents(void) {
15129 RGFW_resetPrevState();
15130 emscripten_sleep(0);
15131 }
15132
15133 void RGFW_window_resize(RGFW_window* win, i32 w, i32 h) {
15134 RGFW_UNUSED(win);
15135 emscripten_set_canvas_element_size("#canvas", w, h);
15136 }
15137
15138 /* NOTE: I don't know if this is possible */
15139 void RGFW_window_moveMouse(RGFW_window* win, i32 x, i32 y) { RGFW_UNUSED(win); RGFW_UNUSED(x); RGFW_UNUSED(y); }
15140 /* this one might be possible but it looks iffy */
15141 RGFW_mouse* RGFW_loadMouse(u8* data, i32 w, i32 h, RGFW_format format) { RGFW_UNUSED(data); RGFW_UNUSED(w); RGFW_UNUSED(h); RGFW_UNUSED(format); return NULL; }
15142
15143 void RGFW_window_setMouse(RGFW_window* win, RGFW_mouse* mouse) { RGFW_UNUSED(win); RGFW_UNUSED(mouse); }
15144 void RGFW_freeMouse(RGFW_mouse* mouse) { RGFW_UNUSED(mouse); }
15145
15146 RGFW_bool RGFW_window_setMouseStandard(RGFW_window* win, u8 mouse) {
15147 RGFW_UNUSED(win);
15148 char* cursorName = NULL;
15149
15150 switch (mouse) {
15151 case RGFW_mouseNormal: cursorName = (char*)"default"; break;
15152 case RGFW_mouseArrow: cursorName = (char*)"default"; break;
15153 case RGFW_mouseIbeam: cursorName = (char*)"text"; break;
15154 case RGFW_mouseCrosshair: cursorName = (char*)"crosshair"; break;
15155 case RGFW_mousePointingHand: cursorName = (char*)"pointer"; break;
15156 case RGFW_mouseResizeEW: cursorName = (char*)"ew-resize"; break;
15157 case RGFW_mouseResizeNS: cursorName = (char*)"ns-resize"; break;
15158 case RGFW_mouseResizeNWSE: cursorName = (char*)"nwse-resize"; break;
15159 case RGFW_mouseResizeNESW: cursorName = (char*)"nesw-resize"; break;
15160 case RGFW_mouseResizeNW: cursorName = (char*)"nw-resize"; break;
15161 case RGFW_mouseResizeN: cursorName = (char*)"n-resize"; break;
15162 case RGFW_mouseResizeNE: cursorName = (char*)"ne-resize"; break;
15163 case RGFW_mouseResizeE: cursorName = (char*)"e-resize"; break;
15164 case RGFW_mouseResizeSE: cursorName = (char*)"se-resize"; break;
15165 case RGFW_mouseResizeS: cursorName = (char*)"s-resize"; break;
15166 case RGFW_mouseResizeSW: cursorName = (char*)"sw-resize"; break;
15167 case RGFW_mouseResizeW: cursorName = (char*)"w-resize"; break;
15168 case RGFW_mouseResizeAll: cursorName = (char*)"move"; break;
15169 case RGFW_mouseNotAllowed: cursorName = (char*)"not-allowed"; break;
15170 case RGFW_mouseWait: cursorName = (char*)"wait"; break;
15171 case RGFW_mouseProgress: cursorName = (char*)"progress"; break;
15172 default: return RGFW_FALSE;
15173 }
15174
15175 EM_ASM( { document.getElementById("canvas").style.cursor = UTF8ToString($0); }, cursorName);
15176 return RGFW_TRUE;
15177 }
15178
15179 RGFW_bool RGFW_window_setMouseDefault(RGFW_window* win) {
15180 return RGFW_window_setMouseStandard(win, RGFW_mouseNormal);
15181 }
15182
15183 void RGFW_window_showMouse(RGFW_window* win, RGFW_bool show) {
15184 RGFW_window_showMouseFlags(win, show);
15185 if (show)
15186 RGFW_window_setMouseDefault(win);
15187 else
15188 EM_ASM(document.getElementById('canvas').style.cursor = 'none';);
15189 }
15190
15191 RGFW_bool RGFW_getGlobalMouse(i32* x, i32* y) {
15192 if(x) *x = EM_ASM_INT({
15193 return window.mouseX || 0;
15194 });
15195 if (y) *y = EM_ASM_INT({
15196 return window.mouseY || 0;
15197 });
15198 return RGFW_TRUE;
15199 }
15200
15201 void RGFW_window_setMousePassthrough(RGFW_window* win, RGFW_bool passthrough) {
15202 RGFW_UNUSED(win);
15203
15204 EM_ASM_({
15205 var canvas = document.getElementById('canvas');
15206 if ($0) {
15207 canvas.style.pointerEvents = 'none';
15208 } else {
15209 canvas.style.pointerEvents = 'auto';
15210 }
15211 }, passthrough);
15212 }
15213
15214 void RGFW_writeClipboard(const char* text, u32 textLen) {
15215 RGFW_UNUSED(textLen);
15216 EM_ASM({ navigator.clipboard.writeText(UTF8ToString($0)); }, text);
15217 }
15218
15219
15220 RGFW_ssize_t RGFW_readClipboardPtr(char* str, size_t strCapacity) {
15221 RGFW_UNUSED(str); RGFW_UNUSED(strCapacity);
15222 /*
15223 placeholder code for later
15224 I'm not sure if this is possible do the the async stuff
15225 */
15226 return 0;
15227 }
15228
15229 #ifdef RGFW_OPENGL
15230 RGFW_bool RGFW_window_createContextPtr_OpenGL(RGFW_window* win, RGFW_glContext* ctx, RGFW_glHints* hints) {
15231 win->src.ctx.native = ctx;
15232 win->src.gfxType = RGFW_gfxNativeOpenGL;
15233
15234 EmscriptenWebGLContextAttributes attrs;
15235 attrs.alpha = hints->alpha;
15236 attrs.depth = hints->depth;
15237 attrs.stencil = hints->stencil;
15238 attrs.antialias = hints->samples;
15239 attrs.premultipliedAlpha = EM_TRUE;
15240 attrs.preserveDrawingBuffer = EM_FALSE;
15241
15242 if (hints->doubleBuffer == 0)
15243 attrs.renderViaOffscreenBackBuffer = 0;
15244 else
15245 attrs.renderViaOffscreenBackBuffer = hints->auxBuffers;
15246
15247 attrs.failIfMajorPerformanceCaveat = EM_FALSE;
15248 attrs.majorVersion = (hints->major == 0) ? 1 : hints->major;
15249 attrs.minorVersion = hints->minor;
15250
15251 attrs.enableExtensionsByDefault = EM_TRUE;
15252 attrs.explicitSwapControl = EM_TRUE;
15253
15254 emscripten_webgl_init_context_attributes(&attrs);
15255 win->src.ctx.native->ctx = emscripten_webgl_create_context("#canvas", &attrs);
15256 emscripten_webgl_make_context_current(win->src.ctx.native->ctx);
15257
15258 #ifdef LEGACY_GL_EMULATION
15259 EM_ASM("Module.useWebGL = true; GLImmediate.init();");
15260 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoOpenGL, "OpenGL context initalized.");
15261 #endif
15262
15263 RGFW_window_swapInterval_OpenGL(win, 0);
15264
15265 return RGFW_TRUE;
15266 }
15267
15268 void RGFW_window_deleteContextPtr_OpenGL(RGFW_window* win, RGFW_glContext* ctx) {
15269 emscripten_webgl_destroy_context(ctx->ctx);
15270 win->src.ctx.native->ctx = 0;
15271 RGFW_sendDebugInfo(RGFW_typeInfo, RGFW_infoOpenGL, "OpenGL context freed.");
15272 }
15273
15274 void RGFW_window_makeCurrentContext_OpenGL(RGFW_window* win) {
15275 if (win) RGFW_ASSERT(win->src.ctx.native);
15276 if (win == NULL)
15277 emscripten_webgl_make_context_current(0);
15278 else
15279 emscripten_webgl_make_context_current(win->src.ctx.native->ctx);
15280 }
15281
15282 void RGFW_window_swapBuffers_OpenGL(RGFW_window* win) {
15283 RGFW_ASSERT(win && win->src.ctx.native);
15284 emscripten_webgl_commit_frame();
15285 }
15286 void* RGFW_getCurrentContext_OpenGL(void) { return (void*)emscripten_webgl_get_current_context(); }
15287
15288 RGFW_bool RGFW_extensionSupportedPlatform_OpenGL(const char* extension, size_t len) {
15289 return EM_ASM_INT({
15290 var ext = UTF8ToString($0, $1);
15291 var canvas = document.querySelector('canvas');
15292 var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
15293 if (!gl) return 0;
15294
15295 var supported = gl.getSupportedExtensions();
15296 return supported && supported.includes(ext) ? 1 : 0;
15297 }, extension, len);
15298 return RGFW_FALSE;
15299 }
15300
15301 RGFW_proc RGFW_getProcAddress_OpenGL(const char* procname) {
15302 return (RGFW_proc)emscripten_webgl_get_proc_address(procname);
15303 return NULL;
15304 }
15305
15306 #endif
15307
15308 void RGFW_window_swapInterval_OpenGL(RGFW_window* win, i32 swapInterval) { RGFW_UNUSED(win); RGFW_UNUSED(swapInterval); }
15309
15310 void RGFW_deinitPlatform(void) { }
15311
15312 void RGFW_window_closePlatform(RGFW_window* win) { }
15313
15314 int RGFW_innerWidth(void) { return EM_ASM_INT({ return window.innerWidth; }); }
15315 int RGFW_innerHeight(void) { return EM_ASM_INT({ return window.innerHeight; }); }
15316
15317 void RGFW_window_setRawMouseModePlatform(RGFW_window* win, RGFW_bool state) {
15318 RGFW_UNUSED(win); RGFW_UNUSED(state);
15319 }
15320
15321 void RGFW_window_captureMousePlatform(RGFW_window* win, RGFW_bool state) {
15322 RGFW_UNUSED(win);
15323 if (state) {
15324 emscripten_request_pointerlock("#canvas", 1);
15325 } else {
15326 emscripten_exit_pointerlock();
15327 }
15328 }
15329
15330 void RGFW_window_setName(RGFW_window* win, const char* name) {
15331 RGFW_UNUSED(win);
15332 if (name == NULL) name = "\0";
15333
15334 emscripten_set_window_title(name);
15335 }
15336
15337 void RGFW_window_maximize(RGFW_window* win) {
15338 RGFW_ASSERT(win != NULL);
15339
15340 RGFW_monitor* mon = RGFW_window_getMonitor(win);
15341 if (mon != NULL) {
15342 RGFW_window_resize(win, mon->mode.w, mon->mode.h);
15343 }
15344
15345 RGFW_window_move(win, 0, 0);
15346 }
15347
15348 void RGFW_window_setFullscreen(RGFW_window* win, RGFW_bool fullscreen) {
15349 RGFW_ASSERT(win != NULL);
15350 if (fullscreen) {
15351 win->internal.flags |= RGFW_windowFullscreen;
15352 EM_ASM( Module.requestFullscreen(false, true); );
15353 return;
15354 }
15355 win->internal.flags &= ~(u32)RGFW_windowFullscreen;
15356 EM_ASM( Module.exitFullscreen(false, true); );
15357 }
15358
15359 void RGFW_window_setOpacity(RGFW_window* win, u8 opacity) {
15360 RGFW_UNUSED(win);
15361 EM_ASM({
15362 var element = document.getElementById("canvas");
15363 if (element)
15364 element.style.opacity = $1;
15365 }, "elementId", opacity);
15366 }
15367
15368 #ifdef RGFW_WEBGPU
15369 WGPUSurface RGFW_window_createSurface_WebGPU(RGFW_window* window, WGPUInstance instance) {
15370 WGPUSurfaceDescriptor surfaceDesc = {0};
15371 WGPUEmscriptenSurfaceSourceCanvasHTMLSelector canvasDesc = {0};
15372 canvasDesc.chain.sType = WGPUSType_EmscriptenSurfaceSourceCanvasHTMLSelector;
15373 canvasDesc.selector = (WGPUStringView){.data = "#canvas", .length = 7};
15374
15375 surfaceDesc.nextInChain = &canvasDesc.chain;
15376 return wgpuInstanceCreateSurface(instance, &surfaceDesc);
15377 }
15378 #endif
15379
15380 RGFW_key RGFW_WASMPhysicalToRGFW(u32 hash) {
15381 switch(hash) { /* 0x0000 */
15382 case 0x67243A2DU /* Escape */: return RGFW_escape; /* 0x0001 */
15383 case 0x67251058U /* Digit0 */: return RGFW_0; /* 0x0002 */
15384 case 0x67251059U /* Digit1 */: return RGFW_1; /* 0x0003 */
15385 case 0x6725105AU /* Digit2 */: return RGFW_2; /* 0x0004 */
15386 case 0x6725105BU /* Digit3 */: return RGFW_3; /* 0x0005 */
15387 case 0x6725105CU /* Digit4 */: return RGFW_4; /* 0x0006 */
15388 case 0x6725105DU /* Digit5 */: return RGFW_5; /* 0x0007 */
15389 case 0x6725105EU /* Digit6 */: return RGFW_6; /* 0x0008 */
15390 case 0x6725105FU /* Digit7 */: return RGFW_7; /* 0x0009 */
15391 case 0x67251050U /* Digit8 */: return RGFW_8; /* 0x000A */
15392 case 0x67251051U /* Digit9 */: return RGFW_9; /* 0x000B */
15393 case 0x92E14DD3U /* Minus */: return RGFW_minus; /* 0x000C */
15394 case 0x92E1FBACU /* Equal */: return RGFW_equals; /* 0x000D */
15395 case 0x36BF1CB5U /* Backspace */: return RGFW_backSpace; /* 0x000E */
15396 case 0x7B8E51E2U /* Tab */: return RGFW_tab; /* 0x000F */
15397 case 0x2C595B51U /* KeyQ */: return RGFW_q; /* 0x0010 */
15398 case 0x2C595B57U /* KeyW */: return RGFW_w; /* 0x0011 */
15399 case 0x2C595B45U /* KeyE */: return RGFW_e; /* 0x0012 */
15400 case 0x2C595B52U /* KeyR */: return RGFW_r; /* 0x0013 */
15401 case 0x2C595B54U /* KeyT */: return RGFW_t; /* 0x0014 */
15402 case 0x2C595B59U /* KeyY */: return RGFW_y; /* 0x0015 */
15403 case 0x2C595B55U /* KeyU */: return RGFW_u; /* 0x0016 */
15404 case 0x2C595B4FU /* KeyO */: return RGFW_o; /* 0x0018 */
15405 case 0x2C595B50U /* KeyP */: return RGFW_p; /* 0x0019 */
15406 case 0x45D8158CU /* BracketLeft */: return RGFW_closeBracket; /* 0x001A */
15407 case 0xDEEABF7CU /* BracketRight */: return RGFW_bracket; /* 0x001B */
15408 case 0x92E1C5D2U /* Enter */: return RGFW_return; /* 0x001C */
15409 case 0xE058958CU /* ControlLeft */: return RGFW_controlL; /* 0x001D */
15410 case 0x2C595B41U /* KeyA */: return RGFW_a; /* 0x001E */
15411 case 0x2C595B53U /* KeyS */: return RGFW_s; /* 0x001F */
15412 case 0x2C595B44U /* KeyD */: return RGFW_d; /* 0x0020 */
15413 case 0x2C595B46U /* KeyF */: return RGFW_f; /* 0x0021 */
15414 case 0x2C595B47U /* KeyG */: return RGFW_g; /* 0x0022 */
15415 case 0x2C595B48U /* KeyH */: return RGFW_h; /* 0x0023 */
15416 case 0x2C595B4AU /* KeyJ */: return RGFW_j; /* 0x0024 */
15417 case 0x2C595B4BU /* KeyK */: return RGFW_k; /* 0x0025 */
15418 case 0x2C595B4CU /* KeyL */: return RGFW_l; /* 0x0026 */
15419 case 0x2707219EU /* Semicolon */: return RGFW_semicolon; /* 0x0027 */
15420 case 0x92E0B58DU /* Quote */: return RGFW_apostrophe; /* 0x0028 */
15421 case 0x36BF358DU /* Backquote */: return RGFW_backtick; /* 0x0029 */
15422 case 0x26B1958CU /* ShiftLeft */: return RGFW_shiftL; /* 0x002A */
15423 case 0x36BF2438U /* Backslash */: return RGFW_backSlash; /* 0x002B */
15424 case 0x2C595B5AU /* KeyZ */: return RGFW_z; /* 0x002C */
15425 case 0x2C595B58U /* KeyX */: return RGFW_x; /* 0x002D */
15426 case 0x2C595B43U /* KeyC */: return RGFW_c; /* 0x002E */
15427 case 0x2C595B56U /* KeyV */: return RGFW_v; /* 0x002F */
15428 case 0x2C595B42U /* KeyB */: return RGFW_b; /* 0x0030 */
15429 case 0x2C595B4EU /* KeyN */: return RGFW_n; /* 0x0031 */
15430 case 0x2C595B4DU /* KeyM */: return RGFW_m; /* 0x0032 */
15431 case 0x92E1A1C1U /* Comma */: return RGFW_comma; /* 0x0033 */
15432 case 0x672FFAD4U /* Period */: return RGFW_period; /* 0x0034 */
15433 case 0x92E0A438U /* Slash */: return RGFW_slash; /* 0x0035 */
15434 case 0xC5A6BF7CU /* ShiftRight */: return RGFW_shiftR;
15435 case 0x5D64DA91U /* NumpadMultiply */: return RGFW_kpMultiply;
15436 case 0xC914958CU /* AltLeft */: return RGFW_altL; /* 0x0038 */
15437 case 0x92E09CB5U /* Space */: return RGFW_space; /* 0x0039 */
15438 case 0xB8FAE73BU /* CapsLock */: return RGFW_capsLock; /* 0x003A */
15439 case 0x7174B789U /* F1 */: return RGFW_F1; /* 0x003B */
15440 case 0x7174B78AU /* F2 */: return RGFW_F2; /* 0x003C */
15441 case 0x7174B78BU /* F3 */: return RGFW_F3; /* 0x003D */
15442 case 0x7174B78CU /* F4 */: return RGFW_F4; /* 0x003E */
15443 case 0x7174B78DU /* F5 */: return RGFW_F5; /* 0x003F */
15444 case 0x7174B78EU /* F6 */: return RGFW_F6; /* 0x0040 */
15445 case 0x7174B78FU /* F7 */: return RGFW_F7; /* 0x0041 */
15446 case 0x7174B780U /* F8 */: return RGFW_F8; /* 0x0042 */
15447 case 0x7174B781U /* F9 */: return RGFW_F9; /* 0x0043 */
15448 case 0x7B8E57B0U /* F10 */: return RGFW_F10; /* 0x0044 */
15449 case 0xC925FCDFU /* Numpad7 */: return RGFW_kpMultiply; /* 0x0047 */
15450 case 0xC925FCD0U /* Numpad8 */: return RGFW_kp8; /* 0x0048 */
15451 case 0xC925FCD1U /* Numpad9 */: return RGFW_kp9; /* 0x0049 */
15452 case 0x5EA3E8A4U /* NumpadSubtract */: return RGFW_minus; /* 0x004A */
15453 case 0xC925FCDCU /* Numpad4 */: return RGFW_kp4; /* 0x004B */
15454 case 0xC925FCDDU /* Numpad5 */: return RGFW_kp5; /* 0x004C */
15455 case 0xC925FCDEU /* Numpad6 */: return RGFW_kp6; /* 0x004D */
15456 case 0xC925FCD9U /* Numpad1 */: return RGFW_kp1; /* 0x004F */
15457 case 0xC925FCDAU /* Numpad2 */: return RGFW_kp2; /* 0x0050 */
15458 case 0xC925FCDBU /* Numpad3 */: return RGFW_kp3; /* 0x0051 */
15459 case 0xC925FCD8U /* Numpad0 */: return RGFW_kp0; /* 0x0052 */
15460 case 0x95852DACU /* NumpadDecimal */: return RGFW_period; /* 0x0053 */
15461 case 0x7B8E57B1U /* F11 */: return RGFW_F11; /* 0x0057 */
15462 case 0x7B8E57B2U /* F12 */: return RGFW_F12; /* 0x0058 */
15463 case 0x7B8E57B3U /* F13 */: return DOM_PK_F13; /* 0x0064 */
15464 case 0x7B8E57B4U /* F14 */: return DOM_PK_F14; /* 0x0065 */
15465 case 0x7B8E57B5U /* F15 */: return DOM_PK_F15; /* 0x0066 */
15466 case 0x7B8E57B6U /* F16 */: return DOM_PK_F16; /* 0x0067 */
15467 case 0x7B8E57B7U /* F17 */: return DOM_PK_F17; /* 0x0068 */
15468 case 0x7B8E57B8U /* F18 */: return DOM_PK_F18; /* 0x0069 */
15469 case 0x7B8E57B9U /* F19 */: return DOM_PK_F19; /* 0x006A */
15470 case 0x7B8E57A8U /* F20 */: return DOM_PK_F20; /* 0x006B */
15471 case 0x7B8E57A9U /* F21 */: return DOM_PK_F21; /* 0x006C */
15472 case 0x7B8E57AAU /* F22 */: return DOM_PK_F22; /* 0x006D */
15473 case 0x7B8E57ABU /* F23 */: return DOM_PK_F23; /* 0x006E */
15474 case 0x7393FBACU /* NumpadEqual */: return RGFW_kpReturn;
15475 case 0xB88EBF7CU /* AltRight */: return RGFW_altR; /* 0xE038 */
15476 case 0xC925873BU /* NumLock */: return RGFW_numLock; /* 0xE045 */
15477 case 0x2C595F45U /* Home */: return RGFW_home; /* 0xE047 */
15478 case 0xC91BB690U /* ArrowUp */: return RGFW_up; /* 0xE048 */
15479 case 0x672F9210U /* PageUp */: return RGFW_pageUp; /* 0xE049 */
15480 case 0x3799258CU /* ArrowLeft */: return RGFW_left; /* 0xE04B */
15481 case 0x4CE33F7CU /* ArrowRight */: return RGFW_right; /* 0xE04D */
15482 case 0x7B8E55DCU /* End */: return RGFW_end; /* 0xE04F */
15483 case 0x3799379EU /* ArrowDown */: return RGFW_down; /* 0xE050 */
15484 case 0xBA90179EU /* PageDown */: return RGFW_pageDown; /* 0xE051 */
15485 case 0x6723CB2CU /* Insert */: return RGFW_insert; /* 0xE052 */
15486 case 0x6725C50DU /* Delete */: return RGFW_delete; /* 0xE053 */
15487 case 0x6723658CU /* OSLeft */: return RGFW_superL; /* 0xE05B */
15488 case 0x39643F7CU /* MetaRight */: return RGFW_superR; /* 0xE05C */
15489 case 0x380B9C8CU /* NumpadAdd */: return DOM_PK_NUMPAD_ADD; /* 0x004E */
15490 default: return DOM_PK_UNKNOWN;
15491 }
15492
15493 return 0;
15494 }
15495
15496 /* unsupported functions */
15497 void RGFW_window_focus(RGFW_window* win) { RGFW_UNUSED(win); }
15498 void RGFW_window_raise(RGFW_window* win) { RGFW_UNUSED(win); }
15499 RGFW_bool RGFW_monitor_requestMode(RGFW_monitor* mon, RGFW_monitorMode* mode, RGFW_modeRequest request) { RGFW_UNUSED(mon); RGFW_UNUSED(mode); RGFW_UNUSED(request); return RGFW_FALSE; }
15500 RGFW_bool RGFW_monitor_getWorkarea(RGFW_monitor* monitor, i32* x, i32* y, i32* width, i32* height) { RGFW_UNUSED(monitor); RGFW_UNUSED(x); RGFW_UNUSED(width); RGFW_UNUSED(height); return RGFW_FALSE; }
15501 size_t RGFW_monitor_getGammaRampPtr(RGFW_monitor* monitor, RGFW_gammaRamp* ramp) { RGFW_UNUSED(monitor); RGFW_UNUSED(ramp); return 0; }
15502 RGFW_bool RGFW_monitor_setGammaRamp(RGFW_monitor* monitor, RGFW_gammaRamp* ramp) { RGFW_UNUSED(monitor); RGFW_UNUSED(ramp); return RGFW_FALSE; }
15503 size_t RGFW_monitor_getModesPtr(RGFW_monitor* mon, RGFW_monitorMode** modes) { RGFW_UNUSED(mon); RGFW_UNUSED(modes); return 0; }
15504 RGFW_bool RGFW_monitor_setMode(RGFW_monitor* mon, RGFW_monitorMode* mode) { RGFW_UNUSED(mon); RGFW_UNUSED(mode); return RGFW_FALSE; }
15505 void RGFW_pollMonitors(void) { }
15506 void RGFW_window_move(RGFW_window* win, i32 x, i32 y) { RGFW_UNUSED(win); RGFW_UNUSED(x); RGFW_UNUSED(y); }
15507 void RGFW_window_setAspectRatio(RGFW_window* win, i32 w, i32 h) { RGFW_UNUSED(win); RGFW_UNUSED(w); RGFW_UNUSED(h); }
15508 void RGFW_window_setMinSize(RGFW_window* win, i32 w, i32 h) { RGFW_UNUSED(win); RGFW_UNUSED(w); RGFW_UNUSED(h); }
15509 void RGFW_window_setMaxSize(RGFW_window* win, i32 w, i32 h) { RGFW_UNUSED(win); RGFW_UNUSED(w); RGFW_UNUSED(h); }
15510 void RGFW_window_minimize(RGFW_window* win) { RGFW_UNUSED(win); }
15511 void RGFW_window_restore(RGFW_window* win) { RGFW_UNUSED(win); }
15512 void RGFW_window_setFloating(RGFW_window* win, RGFW_bool floating) { RGFW_UNUSED(win); RGFW_UNUSED(floating); }
15513 void RGFW_window_setBorder(RGFW_window* win, RGFW_bool border) { RGFW_UNUSED(win); RGFW_UNUSED(border); }
15514 RGFW_bool RGFW_window_setIconEx(RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format, RGFW_icon type) { RGFW_UNUSED(win); RGFW_UNUSED(data); RGFW_UNUSED(w); RGFW_UNUSED(h); RGFW_UNUSED(format); RGFW_UNUSED(type); return RGFW_FALSE; }
15515 void RGFW_window_hide(RGFW_window* win) { RGFW_UNUSED(win); }
15516 void RGFW_window_show(RGFW_window* win) {RGFW_UNUSED(win); }
15517 void RGFW_window_flash(RGFW_window* win, RGFW_flashRequest request) { RGFW_UNUSED(win); RGFW_UNUSED(request); }
15518 RGFW_bool RGFW_window_isHidden(RGFW_window* win) { RGFW_UNUSED(win); return RGFW_FALSE; }
15519 RGFW_bool RGFW_window_isMinimized(RGFW_window* win) { RGFW_UNUSED(win); return RGFW_FALSE; }
15520 RGFW_bool RGFW_window_isMaximized(RGFW_window* win) { RGFW_UNUSED(win); return RGFW_FALSE; }
15521 RGFW_bool RGFW_window_isFloating(RGFW_window* win) { RGFW_UNUSED(win); return RGFW_FALSE; }
15522 RGFW_monitor* RGFW_window_getMonitor(RGFW_window* win) { RGFW_UNUSED(win); return NULL; }
15523 void RGFW_waitForEvent(i32 waitMS) { RGFW_UNUSED(waitMS); }
15524 #endif
15525
15526 /* end of web asm defines */
15527
15528 /*
15529 * RGFW function pointer backend, made to allow you to compile for Wayland but fallback to X11
15530 */
15531 #ifdef RGFW_DYNAMIC
15532 typedef RGFW_window* (*RGFW_createWindowPlatform_ptr)(const char* name, RGFW_windowFlags flags, RGFW_window* win);
15533 typedef RGFW_bool (*RGFW_getMouse_ptr)(i32* x, i32* y);
15534 typedef RGFW_key (*RGFW_physicalToMappedKey_ptr)(RGFW_key key);
15535 typedef void (*RGFW_pollEvents_ptr)(void);
15536 typedef void (*RGFW_pollMonitors_ptr)(void);
15537 typedef void (*RGFW_window_move_ptr)(RGFW_window* win, i32 x, i32 y);
15538 typedef void (*RGFW_window_resize_ptr)(RGFW_window* win, i32 w, i32 h);
15539 typedef void (*RGFW_window_setAspectRatio_ptr)(RGFW_window* win, i32 w, i32 h);
15540 typedef void (*RGFW_window_setMinSize_ptr)(RGFW_window* win, i32 w, i32 h);
15541 typedef void (*RGFW_window_setMaxSize_ptr)(RGFW_window* win, i32 w, i32 h);
15542 typedef void (*RGFW_window_maximize_ptr)(RGFW_window* win);
15543 typedef void (*RGFW_window_focus_ptr)(RGFW_window* win);
15544 typedef void (*RGFW_window_raise_ptr)(RGFW_window* win);
15545 typedef void (*RGFW_window_setFullscreen_ptr)(RGFW_window* win, RGFW_bool fullscreen);
15546 typedef void (*RGFW_window_setFloating_ptr)(RGFW_window* win, RGFW_bool floating);
15547 typedef void (*RGFW_window_setOpacity_ptr)(RGFW_window* win, u8 opacity);
15548 typedef void (*RGFW_window_minimize_ptr)(RGFW_window* win);
15549 typedef void (*RGFW_window_restore_ptr)(RGFW_window* win);
15550 typedef RGFW_bool (*RGFW_window_isFloating_ptr)(RGFW_window* win);
15551 typedef void (*RGFW_window_setName_ptr)(RGFW_window* win, const char* name);
15552 typedef void (*RGFW_window_setMousePassthrough_ptr)(RGFW_window* win, RGFW_bool passthrough);
15553 typedef RGFW_bool (*RGFW_window_setIconEx_ptr)(RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format, u8 type);
15554 typedef RGFW_mouse* (*RGFW_loadMouse_ptr)(u8* data, i32 w, i32 h, RGFW_format format);
15555 typedef void (*RGFW_window_setMouse_ptr)(RGFW_window* win, RGFW_mouse* mouse);
15556 typedef void (*RGFW_window_moveMouse_ptr)(RGFW_window* win, i32 x, i32 y);
15557 typedef RGFW_bool (*RGFW_window_setMouseDefault_ptr)(RGFW_window* win);
15558 typedef RGFW_bool (*RGFW_window_setMouseStandard_ptr)(RGFW_window* win, u8 mouse);
15559 typedef void (*RGFW_window_hide_ptr)(RGFW_window* win);
15560 typedef void (*RGFW_window_show_ptr)(RGFW_window* win);
15561 typedef void (*RGFW_window_flash_ptr)(RGFW_window* win, RGFW_flashRequest request);
15562 typedef RGFW_ssize_t (*RGFW_readClipboardPtr_ptr)(char* str, size_t strCapacity);
15563 typedef void (*RGFW_writeClipboard_ptr)(const char* text, u32 textLen);
15564 typedef RGFW_bool (*RGFW_window_isHidden_ptr)(RGFW_window* win);
15565 typedef RGFW_bool (*RGFW_window_isMinimized_ptr)(RGFW_window* win);
15566 typedef RGFW_bool (*RGFW_window_isMaximized_ptr)(RGFW_window* win);
15567 typedef RGFW_bool (*RGFW_monitor_requestMode_ptr)(RGFW_monitor* mon, RGFW_monitorMode* mode, RGFW_modeRequest request);
15568 typedef RGFW_bool (*RGFW_monitor_getWorkarea_ptr)(RGFW_monitor* mon, i32* x, i32* y, i32* w, i32* h);
15569 typedef size_t (*RGFW_monitor_getModesPtr_ptr)(RGFW_monitor* mon, RGFW_monitorMode** modes);
15570 typedef size_t (*RGFW_monitor_getGammaRampPtr_ptr) (RGFW_monitor* monitor, RGFW_gammaRamp* ramp);
15571 typedef RGFW_bool (*RGFW_monitor_setGammaRamp_ptr) (RGFW_monitor* monitor, RGFW_gammaRamp* ramp);
15572 typedef RGFW_bool (*RGFW_monitor_setMode_ptr)(RGFW_monitor* mon, RGFW_monitorMode* mode);
15573 typedef RGFW_monitor* (*RGFW_window_getMonitor_ptr)(RGFW_window* win);
15574 typedef void (*RGFW_window_closePlatform_ptr)(RGFW_window* win);
15575 typedef RGFW_format (*RGFW_nativeFormat_ptr)(void);
15576 typedef RGFW_bool (*RGFW_createSurfacePtr_ptr)(u8* data, i32 w, i32 h, RGFW_format format, RGFW_surface* surface);
15577 typedef void (*RGFW_window_blitSurface_ptr)(RGFW_window* win, RGFW_surface* surface);
15578 typedef void (*RGFW_surface_freePtr_ptr)(RGFW_surface* surface);
15579 typedef void (*RGFW_freeMouse_ptr)(RGFW_mouse* mouse);
15580 typedef void (*RGFW_window_setBorder_ptr)(RGFW_window* win, RGFW_bool border);
15581 typedef void (*RGFW_window_captureMousePlatform_ptr)(RGFW_window* win, RGFW_bool state);
15582 typedef void (*RGFW_window_setRawMouseModePlatform_ptr)(RGFW_window* win, RGFW_bool state);
15583 #ifdef RGFW_OPENGL
15584 typedef void (*RGFW_window_makeCurrentContext_OpenGL_ptr)(RGFW_window* win);
15585 typedef void* (*RGFW_getCurrentContext_OpenGL_ptr)(void);
15586 typedef void (*RGFW_window_swapBuffers_OpenGL_ptr)(RGFW_window* win);
15587 typedef void (*RGFW_window_swapInterval_OpenGL_ptr)(RGFW_window* win, i32 swapInterval);
15588 typedef RGFW_bool (*RGFW_extensionSupportedPlatform_OpenGL_ptr)(const char* extension, size_t len);
15589 typedef RGFW_proc (*RGFW_getProcAddress_OpenGL_ptr)(const char* procname);
15590 typedef RGFW_bool (*RGFW_window_createContextPtr_OpenGL_ptr)(RGFW_window* win, RGFW_glContext* ctx, RGFW_glHints* hints);
15591 typedef void (*RGFW_window_deleteContextPtr_OpenGL_ptr)(RGFW_window* win, RGFW_glContext* ctx);
15592 #endif
15593 #ifdef RGFW_WEBGPU
15594 typedef WGPUSurface (*RGFW_window_createSurface_WebGPU_ptr)(RGFW_window* window, WGPUInstance instance);
15595 #endif
15596
15597 /* Structure to hold all function pointers */
15598 typedef struct RGFW_FunctionPointers {
15599 RGFW_nativeFormat_ptr nativeFormat;
15600 RGFW_createSurfacePtr_ptr createSurfacePtr;
15601 RGFW_window_blitSurface_ptr window_blitSurface;
15602 RGFW_surface_freePtr_ptr surface_freePtr;
15603 RGFW_freeMouse_ptr freeMouse;
15604 RGFW_window_setBorder_ptr window_setBorder;
15605 RGFW_window_captureMousePlatform_ptr window_captureMousePlatform;
15606 RGFW_window_setRawMouseModePlatform_ptr window_setRawMouseModePlatform;
15607 RGFW_createWindowPlatform_ptr createWindowPlatform;
15608 RGFW_getMouse_ptr getGlobalMouse;
15609 RGFW_physicalToMappedKey_ptr physicalToMappedKey;
15610 RGFW_pollEvents_ptr pollEvents;
15611 RGFW_pollMonitors_ptr pollMonitors;
15612 RGFW_window_move_ptr window_move;
15613 RGFW_window_resize_ptr window_resize;
15614 RGFW_window_setAspectRatio_ptr window_setAspectRatio;
15615 RGFW_window_setMinSize_ptr window_setMinSize;
15616 RGFW_window_setMaxSize_ptr window_setMaxSize;
15617 RGFW_window_maximize_ptr window_maximize;
15618 RGFW_window_focus_ptr window_focus;
15619 RGFW_window_raise_ptr window_raise;
15620 RGFW_window_setFullscreen_ptr window_setFullscreen;
15621 RGFW_window_setFloating_ptr window_setFloating;
15622 RGFW_window_setOpacity_ptr window_setOpacity;
15623 RGFW_window_minimize_ptr window_minimize;
15624 RGFW_window_restore_ptr window_restore;
15625 RGFW_window_isFloating_ptr window_isFloating;
15626 RGFW_window_setName_ptr window_setName;
15627 RGFW_window_setMousePassthrough_ptr window_setMousePassthrough;
15628 RGFW_window_setIconEx_ptr window_setIconEx;
15629 RGFW_loadMouse_ptr loadMouse;
15630 RGFW_window_setMouse_ptr window_setMouse;
15631 RGFW_window_moveMouse_ptr window_moveMouse;
15632 RGFW_window_setMouseDefault_ptr window_setMouseDefault;
15633 RGFW_window_setMouseStandard_ptr window_setMouseStandard;
15634 RGFW_window_hide_ptr window_hide;
15635 RGFW_window_show_ptr window_show;
15636 RGFW_window_flash_ptr window_flash;
15637 RGFW_readClipboardPtr_ptr readClipboardPtr;
15638 RGFW_writeClipboard_ptr writeClipboard;
15639 RGFW_window_isHidden_ptr window_isHidden;
15640 RGFW_window_isMinimized_ptr window_isMinimized;
15641 RGFW_window_isMaximized_ptr window_isMaximized;
15642 RGFW_monitor_requestMode_ptr monitor_requestMode;
15643 RGFW_monitor_getWorkarea_ptr monitor_getWorkarea;
15644 RGFW_monitor_getModesPtr_ptr monitor_getModesPtr;
15645 RGFW_monitor_getGammaRampPtr_ptr monitor_getGammaRampPtr;
15646 RGFW_monitor_setGammaRamp_ptr monitor_setGammaRamp;
15647 RGFW_monitor_setMode_ptr monitor_setMode;
15648 RGFW_window_getMonitor_ptr window_getMonitor;
15649 RGFW_window_closePlatform_ptr window_closePlatform;
15650 #ifdef RGFW_OPENGL
15651 RGFW_extensionSupportedPlatform_OpenGL_ptr extensionSupportedPlatform_OpenGL;
15652 RGFW_getProcAddress_OpenGL_ptr getProcAddress_OpenGL;
15653 RGFW_window_createContextPtr_OpenGL_ptr window_createContextPtr_OpenGL;
15654 RGFW_window_deleteContextPtr_OpenGL_ptr window_deleteContextPtr_OpenGL;
15655 RGFW_window_makeCurrentContext_OpenGL_ptr window_makeCurrentContext_OpenGL;
15656 RGFW_getCurrentContext_OpenGL_ptr getCurrentContext_OpenGL;
15657 RGFW_window_swapBuffers_OpenGL_ptr window_swapBuffers_OpenGL;
15658 RGFW_window_swapInterval_OpenGL_ptr window_swapInterval_OpenGL;
15659 #endif
15660 #ifdef RGFW_WEBGPU
15661 RGFW_window_createSurface_WebGPU_ptr window_createSurface_WebGPU;
15662 #endif
15663 } RGFW_functionPointers;
15664
15665 RGFW_functionPointers RGFW_api;
15666
15667 RGFW_format RGFW_nativeFormat(void) { return RGFW_api.nativeFormat(); }
15668 RGFW_bool RGFW_createSurfacePtr(u8* data, i32 w, i32 h, RGFW_format format, RGFW_surface* surface) { return RGFW_api.createSurfacePtr(data, w, h, format, surface); }
15669 void RGFW_surface_freePtr(RGFW_surface* surface) { RGFW_api.surface_freePtr(surface); }
15670 void RGFW_freeMouse(RGFW_mouse* mouse) { RGFW_api.freeMouse(mouse); }
15671 void RGFW_window_blitSurface(RGFW_window* win, RGFW_surface* surface) { RGFW_api.window_blitSurface(win, surface); }
15672 void RGFW_window_setBorder(RGFW_window* win, RGFW_bool border) { RGFW_api.window_setBorder(win, border); }
15673 void RGFW_window_captureMousePlatform(RGFW_window* win, RGFW_bool state) { RGFW_api.window_captureMousePlatform(win, state); }
15674 void RGFW_window_setRawMouseModePlatform(RGFW_window* win, RGFW_bool state) { RGFW_api.window_setRawMouseModePlatform(win, state); }
15675 RGFW_window* RGFW_createWindowPlatform(const char* name, RGFW_windowFlags flags, RGFW_window* win) { RGFW_init(); return RGFW_api.createWindowPlatform(name, flags, win); }
15676 RGFW_bool RGFW_getGlobalMouse(i32* x, i32* y) { return RGFW_api.getGlobalMouse(x, y); }
15677 RGFW_key RGFW_physicalToMappedKey(RGFW_key key) { return RGFW_api.physicalToMappedKey(key); }
15678 void RGFW_pollEvents(void) { RGFW_api.pollEvents(); }
15679 void RGFW_pollMonitors(void) { RGFW_api.pollMonitors(); }
15680 void RGFW_window_move(RGFW_window* win, i32 x, i32 y) { RGFW_api.window_move(win, x, y); }
15681 void RGFW_window_resize(RGFW_window* win, i32 w, i32 h) { RGFW_api.window_resize(win, w, h); }
15682 void RGFW_window_setAspectRatio(RGFW_window* win, i32 w, i32 h) { RGFW_api.window_setAspectRatio(win, w, h); }
15683 void RGFW_window_setMinSize(RGFW_window* win, i32 w, i32 h) { RGFW_api.window_setMinSize(win, w, h); }
15684 void RGFW_window_setMaxSize(RGFW_window* win, i32 w, i32 h) { RGFW_api.window_setMaxSize(win, w, h); }
15685 void RGFW_window_maximize(RGFW_window* win) { RGFW_api.window_maximize(win); }
15686 void RGFW_window_focus(RGFW_window* win) { RGFW_api.window_focus(win); }
15687 void RGFW_window_raise(RGFW_window* win) { RGFW_api.window_raise(win); }
15688 void RGFW_window_setFullscreen(RGFW_window* win, RGFW_bool fullscreen) { RGFW_api.window_setFullscreen(win, fullscreen); }
15689 void RGFW_window_setFloating(RGFW_window* win, RGFW_bool floating) { RGFW_api.window_setFloating(win, floating); }
15690 void RGFW_window_setOpacity(RGFW_window* win, u8 opacity) { RGFW_api.window_setOpacity(win, opacity); }
15691 void RGFW_window_minimize(RGFW_window* win) { RGFW_api.window_minimize(win); }
15692 void RGFW_window_restore(RGFW_window* win) { RGFW_api.window_restore(win); }
15693 RGFW_bool RGFW_window_isFloating(RGFW_window* win) { return RGFW_api.window_isFloating(win); }
15694 void RGFW_window_setName(RGFW_window* win, const char* name) { RGFW_api.window_setName(win, name); }
15695
15696 #ifndef RGFW_NO_PASSTHROUGH
15697 void RGFW_window_setMousePassthrough(RGFW_window* win, RGFW_bool passthrough) { RGFW_api.window_setMousePassthrough(win, passthrough); }
15698 #endif
15699
15700 RGFW_bool RGFW_window_setIconEx(RGFW_window* win, u8* data, i32 w, i32 h, RGFW_format format, u8 type) { return RGFW_api.window_setIconEx(win, data, w, h, format, type); }
15701 RGFW_mouse* RGFW_loadMouse(u8* data, i32 w, i32 h, RGFW_format format) { return RGFW_api.loadMouse(data, w, h, format); }
15702 void RGFW_window_setMouse(RGFW_window* win, RGFW_mouse* mouse) { RGFW_api.window_setMouse(win, mouse); }
15703 void RGFW_window_moveMouse(RGFW_window* win, i32 x, i32 y) { RGFW_api.window_moveMouse(win, x, y); }
15704 RGFW_bool RGFW_window_setMouseDefault(RGFW_window* win) { return RGFW_api.window_setMouseDefault(win); }
15705 RGFW_bool RGFW_window_setMouseStandard(RGFW_window* win, u8 mouse) { return RGFW_api.window_setMouseStandard(win, mouse); }
15706 void RGFW_window_hide(RGFW_window* win) { RGFW_api.window_hide(win); }
15707 void RGFW_window_show(RGFW_window* win) { RGFW_api.window_show(win); }
15708 void RGFW_window_flash(RGFW_window* win, RGFW_flashRequest request) { RGFW_api.window_flash(win, request); }
15709 RGFW_ssize_t RGFW_readClipboardPtr(char* str, size_t strCapacity) { return RGFW_api.readClipboardPtr(str, strCapacity); }
15710 void RGFW_writeClipboard(const char* text, u32 textLen) { RGFW_api.writeClipboard(text, textLen); }
15711 RGFW_bool RGFW_window_isHidden(RGFW_window* win) { return RGFW_api.window_isHidden(win); }
15712 RGFW_bool RGFW_window_isMinimized(RGFW_window* win) { return RGFW_api.window_isMinimized(win); }
15713 RGFW_bool RGFW_window_isMaximized(RGFW_window* win) { return RGFW_api.window_isMaximized(win); }
15714 RGFW_bool RGFW_monitor_requestMode(RGFW_monitor* mon, RGFW_monitorMode* mode, RGFW_modeRequest request) { return RGFW_api.monitor_requestMode(mon, mode, request); }
15715 RGFW_bool RGFW_monitor_getWorkarea(RGFW_monitor* monitor, i32* x, i32* y, i32* width, i32* height) { return RGFW_api.monitor_getWorkarea(monitor, x, y, width, height); }
15716 size_t RGFW_monitor_getGammaRampPtr(RGFW_monitor* monitor, RGFW_gammaRamp* ramp) { return RGFW_api.monitor_getGammaRampPtr(monitor, ramp); }
15717 RGFW_bool RGFW_monitor_setGammaRamp(RGFW_monitor* monitor, RGFW_gammaRamp* ramp) { return RGFW_api.monitor_setGammaRamp(monitor, ramp); }
15718 size_t RGFW_monitor_getModesPtr(RGFW_monitor* mon, RGFW_monitorMode** modes) { return RGFW_api.monitor_getModesPtr(mon, modes); }
15719 RGFW_bool RGFW_monitor_setMode(RGFW_monitor* mon, RGFW_monitorMode* mode) { return RGFW_api.monitor_setMode(mon, mode); }
15720 RGFW_monitor* RGFW_window_getMonitor(RGFW_window* win) { return RGFW_api.window_getMonitor(win); }
15721 void RGFW_window_closePlatform(RGFW_window* win) { RGFW_api.window_closePlatform(win); }
15722
15723 #ifdef RGFW_OPENGL
15724 RGFW_bool RGFW_extensionSupportedPlatform_OpenGL(const char* extension, size_t len) { return RGFW_api.extensionSupportedPlatform_OpenGL(extension, len); }
15725 RGFW_proc RGFW_getProcAddress_OpenGL(const char* procname) { return RGFW_api.getProcAddress_OpenGL(procname); }
15726 RGFW_bool RGFW_window_createContextPtr_OpenGL(RGFW_window* win, RGFW_glContext* ctx, RGFW_glHints* hints) { return RGFW_api.window_createContextPtr_OpenGL(win, ctx, hints); }
15727 void RGFW_window_deleteContextPtr_OpenGL(RGFW_window* win, RGFW_glContext* ctx) { RGFW_api.window_deleteContextPtr_OpenGL(win, ctx); }
15728 void RGFW_window_makeCurrentContext_OpenGL(RGFW_window* win) { RGFW_api.window_makeCurrentContext_OpenGL(win); }
15729 void* RGFW_getCurrentContext_OpenGL(void) { return RGFW_api.getCurrentContext_OpenGL(); }
15730 void RGFW_window_swapBuffers_OpenGL(RGFW_window* win) { RGFW_api.window_swapBuffers_OpenGL(win); }
15731 void RGFW_window_swapInterval_OpenGL(RGFW_window* win, i32 swapInterval) { RGFW_api.window_swapInterval_OpenGL(win, swapInterval); }
15732 #endif
15733
15734 #ifdef RGFW_WEBGPU
15735 WGPUSurface RGFW_window_createSurface_WebGPU(RGFW_window* window, WGPUInstance instance) { return RGFW_api.window_createSurface_WebGPU(window, instance); }
15736 #endif
15737 #endif /* RGFW_DYNAMIC */
15738
15739 /*
15740 * start of X11 AND wayland defines
15741 * this allows a single executable to support x11 AND wayland
15742 * falling back to x11 if wayland fails to initalize
15743 */
15744 #if defined(RGFW_WAYLAND) && defined(RGFW_X11)
15745 void RGFW_load_X11(void) {
15746 RGFW_api.nativeFormat = RGFW_nativeFormat_X11;
15747 RGFW_api.createSurfacePtr = RGFW_createSurfacePtr_X11;
15748 RGFW_api.window_blitSurface = RGFW_window_blitSurface_X11;
15749 RGFW_api.surface_freePtr = RGFW_surface_freePtr_X11;
15750 RGFW_api.freeMouse = RGFW_freeMouse_X11;
15751 RGFW_api.window_setBorder = RGFW_window_setBorder_X11;
15752 RGFW_api.window_captureMousePlatform = RGFW_window_captureMousePlatform_X11;
15753 RGFW_api.window_setRawMouseModePlatform = RGFW_window_setRawMouseModePlatform_X11;
15754 RGFW_api.createWindowPlatform = RGFW_createWindowPlatform_X11;
15755 RGFW_api.getGlobalMouse = RGFW_getGlobalMouse_X11;
15756 RGFW_api.physicalToMappedKey = RGFW_physicalToMappedKey_X11;
15757 RGFW_api.pollEvents = RGFW_pollEvents_X11;
15758 RGFW_api.pollMonitors = RGFW_pollMonitors_X11;
15759 RGFW_api.window_move = RGFW_window_move_X11;
15760 RGFW_api.window_resize = RGFW_window_resize_X11;
15761 RGFW_api.window_setAspectRatio = RGFW_window_setAspectRatio_X11;
15762 RGFW_api.window_setMinSize = RGFW_window_setMinSize_X11;
15763 RGFW_api.window_setMaxSize = RGFW_window_setMaxSize_X11;
15764 RGFW_api.window_maximize = RGFW_window_maximize_X11;
15765 RGFW_api.window_focus = RGFW_window_focus_X11;
15766 RGFW_api.window_raise = RGFW_window_raise_X11;
15767 RGFW_api.window_setFullscreen = RGFW_window_setFullscreen_X11;
15768 RGFW_api.window_setFloating = RGFW_window_setFloating_X11;
15769 RGFW_api.window_setOpacity = RGFW_window_setOpacity_X11;
15770 RGFW_api.window_minimize = RGFW_window_minimize_X11;
15771 RGFW_api.window_restore = RGFW_window_restore_X11;
15772 RGFW_api.window_isFloating = RGFW_window_isFloating_X11;
15773 RGFW_api.window_setName = RGFW_window_setName_X11;
15774 #ifndef RGFW_NO_PASSTHROUGH
15775 RGFW_api.window_setMousePassthrough = RGFW_window_setMousePassthrough_X11;
15776 #endif
15777 RGFW_api.window_setIconEx = RGFW_window_setIconEx_X11;
15778 RGFW_api.loadMouse = RGFW_loadMouse_X11;
15779 RGFW_api.window_setMouse = RGFW_window_setMouse_X11;
15780 RGFW_api.window_moveMouse = RGFW_window_moveMouse_X11;
15781 RGFW_api.window_setMouseDefault = RGFW_window_setMouseDefault_X11;
15782 RGFW_api.window_setMouseStandard = RGFW_window_setMouseStandard_X11;
15783 RGFW_api.window_hide = RGFW_window_hide_X11;
15784 RGFW_api.window_show = RGFW_window_show_X11;
15785 RGFW_api.window_flash = RGFW_window_flash_X11;
15786 RGFW_api.readClipboardPtr = RGFW_readClipboardPtr_X11;
15787 RGFW_api.writeClipboard = RGFW_writeClipboard_X11;
15788 RGFW_api.window_isHidden = RGFW_window_isHidden_X11;
15789 RGFW_api.window_isMinimized = RGFW_window_isMinimized_X11;
15790 RGFW_api.window_isMaximized = RGFW_window_isMaximized_X11;
15791 RGFW_api.monitor_requestMode = RGFW_monitor_requestMode_X11;
15792 RGFW_api.monitor_getModesPtr = RGFW_monitor_getModesPtr_X11;
15793 RGFW_api.monitor_setGammaRamp = RGFW_monitor_setGammaRamp_X11;
15794 RGFW_api.monitor_getGammaRampPtr = RGFW_monitor_getGammaRampPtr_X11;
15795 RGFW_api.monitor_setMode = RGFW_monitor_setMode_X11;
15796 RGFW_api.window_getMonitor = RGFW_window_getMonitor_X11;
15797 RGFW_api.window_closePlatform = RGFW_window_closePlatform_X11;
15798 #ifdef RGFW_OPENGL
15799 RGFW_api.extensionSupportedPlatform_OpenGL = RGFW_extensionSupportedPlatform_OpenGL_X11;
15800 RGFW_api.getProcAddress_OpenGL = RGFW_getProcAddress_OpenGL_X11;
15801 RGFW_api.window_createContextPtr_OpenGL = RGFW_window_createContextPtr_OpenGL_X11;
15802 RGFW_api.window_deleteContextPtr_OpenGL = RGFW_window_deleteContextPtr_OpenGL_X11;
15803 RGFW_api.window_makeCurrentContext_OpenGL = RGFW_window_makeCurrentContext_OpenGL_X11;
15804 RGFW_api.getCurrentContext_OpenGL = RGFW_getCurrentContext_OpenGL_X11;
15805 RGFW_api.window_swapBuffers_OpenGL = RGFW_window_swapBuffers_OpenGL_X11;
15806 RGFW_api.window_swapInterval_OpenGL = RGFW_window_swapInterval_OpenGL_X11;
15807 #endif
15808 #ifdef RGFW_WEBGPU
15809 RGFW_api.window_createSurface_WebGPU = RGFW_window_createSurface_WebGPU_X11;
15810 #endif
15811 }
15812
15813 void RGFW_load_Wayland(void) {
15814 RGFW_api.nativeFormat = RGFW_nativeFormat_Wayland;
15815 RGFW_api.createSurfacePtr = RGFW_createSurfacePtr_Wayland;
15816 RGFW_api.window_blitSurface = RGFW_window_blitSurface_Wayland;
15817 RGFW_api.surface_freePtr = RGFW_surface_freePtr_Wayland;
15818 RGFW_api.freeMouse = RGFW_freeMouse_Wayland;
15819 RGFW_api.window_setBorder = RGFW_window_setBorder_Wayland;
15820 RGFW_api.window_captureMousePlatform = RGFW_window_captureMousePlatform_Wayland;
15821 RGFW_api.window_setRawMouseModePlatform = RGFW_window_setRawMouseModePlatform_Wayland;
15822 RGFW_api.createWindowPlatform = RGFW_createWindowPlatform_Wayland;
15823 RGFW_api.getGlobalMouse = RGFW_getGlobalMouse_Wayland;
15824 RGFW_api.physicalToMappedKey = RGFW_physicalToMappedKey_Wayland;
15825 RGFW_api.pollEvents = RGFW_pollEvents_Wayland;
15826 RGFW_api.pollMonitors = RGFW_pollMonitors_Wayland;
15827 RGFW_api.window_move = RGFW_window_move_Wayland;
15828 RGFW_api.window_resize = RGFW_window_resize_Wayland;
15829 RGFW_api.window_setAspectRatio = RGFW_window_setAspectRatio_Wayland;
15830 RGFW_api.window_setMinSize = RGFW_window_setMinSize_Wayland;
15831 RGFW_api.window_setMaxSize = RGFW_window_setMaxSize_Wayland;
15832 RGFW_api.window_maximize = RGFW_window_maximize_Wayland;
15833 RGFW_api.window_focus = RGFW_window_focus_Wayland;
15834 RGFW_api.window_raise = RGFW_window_raise_Wayland;
15835 RGFW_api.window_setFullscreen = RGFW_window_setFullscreen_Wayland;
15836 RGFW_api.window_setFloating = RGFW_window_setFloating_Wayland;
15837 RGFW_api.window_setOpacity = RGFW_window_setOpacity_Wayland;
15838 RGFW_api.window_minimize = RGFW_window_minimize_Wayland;
15839 RGFW_api.window_restore = RGFW_window_restore_Wayland;
15840 RGFW_api.window_isFloating = RGFW_window_isFloating_Wayland;
15841 RGFW_api.window_setName = RGFW_window_setName_Wayland;
15842 #ifndef RGFW_NO_PASSTHROUGH
15843 RGFW_api.window_setMousePassthrough = RGFW_window_setMousePassthrough_Wayland;
15844 #endif
15845 RGFW_api.window_setIconEx = RGFW_window_setIconEx_Wayland;
15846 RGFW_api.loadMouse = RGFW_loadMouse_Wayland;
15847 RGFW_api.window_setMouse = RGFW_window_setMouse_Wayland;
15848 RGFW_api.window_moveMouse = RGFW_window_moveMouse_Wayland;
15849 RGFW_api.window_setMouseDefault = RGFW_window_setMouseDefault_Wayland;
15850 RGFW_api.window_setMouseStandard = RGFW_window_setMouseStandard_Wayland;
15851 RGFW_api.window_hide = RGFW_window_hide_Wayland;
15852 RGFW_api.window_show = RGFW_window_show_Wayland;
15853 RGFW_api.window_flash = RGFW_window_flash_X11;
15854 RGFW_api.readClipboardPtr = RGFW_readClipboardPtr_Wayland;
15855 RGFW_api.writeClipboard = RGFW_writeClipboard_Wayland;
15856 RGFW_api.window_isHidden = RGFW_window_isHidden_Wayland;
15857 RGFW_api.window_isMinimized = RGFW_window_isMinimized_Wayland;
15858 RGFW_api.window_isMaximized = RGFW_window_isMaximized_Wayland;
15859 RGFW_api.monitor_requestMode = RGFW_monitor_requestMode_Wayland;
15860 RGFW_api.monitor_getModesPtr = RGFW_monitor_getModesPtr_Wayland;
15861 RGFW_api.monitor_setGammaRamp = RGFW_monitor_setGammaRamp_Wayland;
15862 RGFW_api.monitor_getGammaRampPtr = RGFW_monitor_getGammaRampPtr_Wayland;
15863 RGFW_api.monitor_setMode = RGFW_monitor_setMode_Wayland;
15864 RGFW_api.window_getMonitor = RGFW_window_getMonitor_Wayland;
15865 RGFW_api.window_closePlatform = RGFW_window_closePlatform_Wayland;
15866 #ifdef RGFW_OPENGL
15867 RGFW_api.extensionSupportedPlatform_OpenGL = RGFW_extensionSupportedPlatform_OpenGL_Wayland;
15868 RGFW_api.getProcAddress_OpenGL = RGFW_getProcAddress_OpenGL_Wayland;
15869 RGFW_api.window_createContextPtr_OpenGL = RGFW_window_createContextPtr_OpenGL_Wayland;
15870 RGFW_api.window_deleteContextPtr_OpenGL = RGFW_window_deleteContextPtr_OpenGL_Wayland;
15871 RGFW_api.window_makeCurrentContext_OpenGL = RGFW_window_makeCurrentContext_OpenGL_Wayland;
15872 RGFW_api.getCurrentContext_OpenGL = RGFW_getCurrentContext_OpenGL_Wayland;
15873 RGFW_api.window_swapBuffers_OpenGL = RGFW_window_swapBuffers_OpenGL_Wayland;
15874 RGFW_api.window_swapInterval_OpenGL = RGFW_window_swapInterval_OpenGL_Wayland;
15875 #endif
15876 #ifdef RGFW_WEBGPU
15877 RGFW_api.window_createSurface_WebGPU = RGFW_window_createSurface_WebGPU_Wayland;
15878 #endif
15879 }
15880 #endif /* wayland AND x11 */
15881 /* end of X11 AND wayland defines */
15882
15883 #endif /* RGFW_IMPLEMENTATION */
15884
15885 #if defined(__cplusplus) && !defined(__EMSCRIPTEN__)
15886 }
15887 #endif
15888
15889 #if _MSC_VER
15890 #pragma warning( pop )
15891 #endif