1 #define _POSIX_C_SOURCE 200809
2 #include <assert.h>
3 #include <cairo.h>
4 #include <fcntl.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <sys/mman.h>
9 #include <unistd.h>
10 #include <wayland-client.h>
11 #include "pool-buffer.h"
12
set_cloexec(int fd)13 static bool set_cloexec(int fd) {
14 long flags = fcntl(fd, F_GETFD);
15 if (flags == -1) {
16 return false;
17 }
18
19 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
20 return false;
21 }
22
23 return true;
24 }
25
create_pool_file(size_t size,char ** name)26 static int create_pool_file(size_t size, char **name) {
27 static const char template[] = "sway-client-XXXXXX";
28 const char *path = getenv("XDG_RUNTIME_DIR");
29 if (path == NULL) {
30 fprintf(stderr, "XDG_RUNTIME_DIR is not set\n");
31 return -1;
32 }
33
34 size_t name_size = strlen(template) + 1 + strlen(path) + 1;
35 *name = malloc(name_size);
36 if (*name == NULL) {
37 fprintf(stderr, "allocation failed\n");
38 return -1;
39 }
40 snprintf(*name, name_size, "%s/%s", path, template);
41
42 int fd = mkstemp(*name);
43 if (fd < 0) {
44 return -1;
45 }
46
47 if (!set_cloexec(fd)) {
48 close(fd);
49 return -1;
50 }
51
52 if (ftruncate(fd, size) < 0) {
53 close(fd);
54 return -1;
55 }
56
57 return fd;
58 }
59
create_buffer(struct pool_buffer * buf,struct wl_shm * shm,int32_t width,int32_t height,uint32_t format)60 bool create_buffer(struct pool_buffer *buf, struct wl_shm *shm,
61 int32_t width, int32_t height, uint32_t format) {
62 uint32_t stride = width * 4;
63 size_t size = stride * height;
64
65 char *name;
66 int fd = create_pool_file(size, &name);
67 assert(fd != -1);
68 void *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
69 struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, size);
70 buf->buffer = wl_shm_pool_create_buffer(pool, 0,
71 width, height, stride, format);
72 wl_shm_pool_destroy(pool);
73 close(fd);
74 unlink(name);
75 free(name);
76 fd = -1;
77
78 buf->size = size;
79 buf->data = data;
80 buf->surface = cairo_image_surface_create_for_data(data,
81 CAIRO_FORMAT_ARGB32, width, height, stride);
82 buf->cairo = cairo_create(buf->surface);
83 return true;
84 }
85
destroy_buffer(struct pool_buffer * buffer)86 void destroy_buffer(struct pool_buffer *buffer) {
87 if (buffer->buffer) {
88 wl_buffer_destroy(buffer->buffer);
89 }
90 if (buffer->cairo) {
91 cairo_destroy(buffer->cairo);
92 }
93 if (buffer->surface) {
94 cairo_surface_destroy(buffer->surface);
95 }
96 if (buffer->data) {
97 munmap(buffer->data, buffer->size);
98 }
99 }
100