selection.c (2712B)
1 /* swc: selection.c 2 * 3 * the clipboard for a compositor that keeps it itself, see swc.h 4 * 5 * Permission is hereby granted, free of charge, to any person obtaining a copy 6 * of this software and associated documentation files (the "Software"), to deal 7 * in the Software without restriction, including without limitation the rights 8 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 * copies of the Software, and to permit persons to whom the Software is 10 * furnished to do so, subject to the following conditions: 11 * 12 * The above copyright notice and this permission notice shall be included in 13 * all copies or substantial portions of the Software. 14 */ 15 16 #include "swc.h" 17 #include "data.h" 18 #include "data_device.h" 19 #include "event.h" 20 #include "internal.h" 21 #include "seat.h" 22 #include "util.h" 23 24 #include <string.h> 25 26 #define MAX_TYPES 64 27 28 static struct { 29 const struct swc_selection_handler *handler; 30 void *data; 31 struct wl_listener listener; 32 bool hooked; 33 } selection; 34 35 static void 36 handle_event(struct wl_listener *listener, void *data) 37 { 38 struct event *ev = data; 39 struct data *source; 40 const char *types[MAX_TYPES]; 41 unsigned i, count = 0; 42 43 if (ev->type != DATA_DEVICE_EVENT_SELECTION_CHANGED || ev->data || !selection.handler) { 44 return; 45 } 46 if ((source = data_device_client_selection(swc.seat->data_device))) { 47 count = data_type_count(source); 48 if (count > MAX_TYPES) { 49 count = MAX_TYPES; 50 } 51 for (i = 0; i < count; i++) { 52 types[i] = data_type_at(source, i); 53 } 54 } 55 selection.handler->changed(selection.data, types, count); 56 } 57 58 EXPORT void 59 swc_selection_set_handler(const struct swc_selection_handler *handler, void *data) 60 { 61 selection.handler = handler; 62 selection.data = data; 63 if (!selection.hooked && swc.seat) { 64 selection.listener.notify = handle_event; 65 wl_signal_add(&swc.seat->data_device->event_signal, &selection.listener); 66 selection.hooked = true; 67 } 68 } 69 70 EXPORT bool 71 swc_selection_request(const char *mime_type, int fd) 72 { 73 struct data *source = data_device_client_selection(swc.seat->data_device); 74 unsigned i; 75 76 if (!source) { 77 return false; 78 } 79 for (i = 0; i < data_type_count(source); i++) { 80 if (strcmp(data_type_at(source, i), mime_type) == 0) { 81 data_request(source, mime_type, fd); 82 return true; 83 } 84 } 85 return false; 86 } 87 88 EXPORT bool 89 swc_selection_offer(const char *const *mime_types, unsigned count, 90 const struct swc_selection_source *source, void *data) 91 { 92 struct data_host host = { .send = source->send, .cancelled = source->cancelled }; 93 struct data *offered = data_host_new(mime_types, count, &host, data); 94 95 if (!offered) { 96 return false; 97 } 98 data_device_set_host(swc.seat->data_device, offered); 99 return true; 100 }