main.c (2281B)
1 #include <assert.h> 2 #include <errno.h> 3 #include <fcntl.h> 4 #include <stdint.h> 5 #include <stdio.h> 6 #include <stdlib.h> 7 #include <string.h> 8 #include <sys/mman.h> 9 #include <sys/socket.h> 10 #include <sys/stat.h> 11 #include <sys/un.h> 12 #include <unistd.h> 13 14 #include "types.h" 15 16 static void create_shared_memory_file(uint64_t size, state_t *state) { 17 string name = {.data = "/", .len = 255}; 18 19 for (uint64_t i = 1; i < name.len; i++) { 20 name.data[i] = ((double)rand()) / (double)RAND_MAX * 26 + 'a'; 21 } 22 23 int fd = shm_open(name.data, O_RDWR | O_EXCL | O_CREAT, 0600); 24 if (fd == -1) 25 exit(errno); 26 27 assert(shm_unlink(name.data) != -1); 28 29 if (ftruncate(fd, size) == -1) 30 exit(errno); 31 32 state->shm_pool_data = 33 mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); 34 assert((void *)-1 != state->shm_pool_data); 35 assert(state->shm_pool_data != NULL); 36 state->shm_fd = fd; 37 } 38 39 int main(void) { 40 41 string xdg_runtime_dir = { 42 .data = getenv("XDG_RUNTIME_DIR"), 43 .len = strlen(xdg_runtime_dir.data), 44 }; // we can keep this data for future use (temporary logs, pipewire, mpd, 45 // etc) 46 47 string wayland_display = { 48 .data = getenv("WAYLAND_DISPLAY"), 49 .len = strlen(wayland_display.data), 50 }; // might be of use later idk yet 51 52 string wl_sock_path = { 53 .data = strcat(strcat(xdg_runtime_dir.data, "/"), 54 wayland_display.data), // convoluted to make it a path 55 .len = strlen(wl_sock_path.data), 56 }; 57 58 if (wayland_display.data == NULL || xdg_runtime_dir.data == NULL) { 59 puts("Ensure XDG_RUNTIME_DIR and/or WAYLAND_DISPLAY are set."); 60 return 1; 61 } 62 63 int fd = wayland_display_connect(&wl_sock_path); 64 65 state_t state = { 66 .wl_registry = wayland_wl_display_get_registry(fd), 67 .w = 117, 68 .h = 150, 69 .stride = 117 * color_channels, 70 }; 71 72 // Single buffering. 73 state.shm_pool_size = state.h * state.stride; 74 75 while (1) { 76 string read_buf = { 77 .data = "", 78 .len = 4096, 79 }; 80 int64_t read_bytes = recv(fd, read_buf.data, sizeof(read_buf.data), 0); 81 if (read_bytes == -1) 82 exit(errno); 83 84 char *msg = read_buf.data; 85 uint64_t msg_len = (uint64_t)read_bytes; 86 87 while (msg_len > 0) 88 wayland_handle_message(fd, &state, &msg, &msg_len); 89 } 90 91 return 0; 92 }