Files
ab_glyph_rasterizer
addr2line
adler
andrew
approx
arrayvec
ash
atom
backtrace
bitflags
byteorder
calloop
cfg_if
colorful
conrod_core
conrod_derive
conrod_example_shared
conrod_gfx
conrod_glium
conrod_piston
conrod_rendy
conrod_vulkano
conrod_wgpu
conrod_winit
copyless
copypasta
crossbeam
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_queue
crossbeam_utils
daggy
dlib
downcast_rs
draw_state
either
fixedbitset
float
fnv
futures
futures_channel
futures_core
futures_executor
futures_io
futures_macro
futures_sink
futures_task
futures_util
async_await
future
io
lock
sink
stream
task
fxhash
getrandom
gfx
gfx_backend_empty
gfx_backend_vulkan
gfx_core
gfx_descriptor
gfx_hal
gfx_memory
gimli
glium
glutin
glutin_egl_sys
glutin_glx_sys
graphics
half
hibitset
inplace_it
input
instant
interpolation
iovec
itoa
lazy_static
lazycell
libc
libloading
line_drawing
linked_hash_map
lock_api
log
maybe_uninit
memchr
memmap
memoffset
miniz_oxide
mio
mio_extras
naga
net2
nix
nom
num
num_bigint
num_complex
num_cpus
num_integer
num_iter
num_rational
num_traits
object
once_cell
ordered_float
ordermap
osmesa_sys
owned_ttf_parser
parking_lot
parking_lot_core
percent_encoding
petgraph
pin_project
pin_project_internal
pin_project_lite
pin_utils
ppv_lite86
proc_macro2
proc_macro_hack
proc_macro_nested
quote
rand
rand_chacha
rand_core
raw_window_handle
read_color
relevant
rendy
rendy_chain
rendy_command
rendy_core
rendy_descriptor
rendy_factory
rendy_frame
rendy_graph
rendy_init
rendy_memory
rendy_mesh
rendy_resource
rendy_shader
rendy_texture
rendy_wsi
rustc_demangle
rustc_hash
rusttype
ryu
same_file
scoped_tls
scopeguard
serde
serde_derive
serde_json
shaderc
shaderc_sys
shared_library
slab
smallvec
smithay_client_toolkit
smithay_clipboard
spirv_headers
stb_truetype
syn
takeable_option
texture
thiserror
thiserror_impl
thread_profiler
time
tracing
tracing_core
ttf_parser
typed_arena
unicode_xid
vecmath
viewport
vk_sys
void
vulkano
buffer
command_buffer
descriptor
device
framebuffer
image
instance
memory
pipeline
query
swapchain
sync
vulkano_shaders
walkdir
wayland_client
wayland_commons
wayland_cursor
wayland_egl
wayland_protocols
wayland_sys
wgpu
wgpu_core
wgpu_types
winit
x11
x11_clipboard
x11_dl
xcb
xcursor
xdg
xml
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
use std::collections::HashMap;
use std::io::{Read, Result, Write};
use std::ops::Deref;
use std::os::unix::io::FromRawFd;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

use nix::fcntl::OFlag;
use nix::unistd::{close, pipe2};

use sctk::data_device::{DataDevice, DataSource, DataSourceEvent};
use sctk::keyboard::{map_keyboard_auto, Event as KbEvent};
use sctk::reexports::client::protocol::{
    wl_data_device_manager,
    wl_display::WlDisplay,
    wl_pointer::Event as PtrEvent,
    wl_registry,
    wl_seat::{self, Capability},
};

use sctk::reexports::client::{Display, EventQueue, GlobalEvent, GlobalManager, NewProxy};
use sctk::reexports::protocols::misc::gtk_primary_selection::client::{
    gtk_primary_selection_device::Event as GtkPrimarySelectionDeviceEvent,
    gtk_primary_selection_device::GtkPrimarySelectionDevice,
    gtk_primary_selection_device_manager::GtkPrimarySelectionDeviceManager,
    gtk_primary_selection_offer::GtkPrimarySelectionOffer, gtk_primary_selection_source,
};
use sctk::reexports::protocols::unstable::primary_selection::v1::client::{
    zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1 as PrimarySelectionDeviceMgr,
    zwp_primary_selection_device_v1::{
        Event as ZwpPrimarySelectionDeviceEvent,
        ZwpPrimarySelectionDeviceV1 as PrimarySelectionDevice,
    },
    zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1 as PrimarySelectionOffer,
    zwp_primary_selection_source_v1,
};
use sctk::wayland_client::sys::client::wl_display;

/// Used to store registered seats and their last event serial
type SeatMap = HashMap<
    String,
    (
        Arc<Mutex<Option<DataDevice>>>,
        u32,
        Arc<Mutex<Option<PrimarySelectionDevice>>>,
        Arc<Mutex<Option<PrimarySelectionOffer>>>,
        Arc<Mutex<Option<GtkPrimarySelectionDevice>>>,
        Arc<Mutex<Option<GtkPrimarySelectionOffer>>>,
    ),
>;

/// Object representing the Wayland clipboard
pub struct ThreadedClipboard {
    request_send: mpsc::Sender<ThreadRequest>,
    load_recv: mpsc::Receiver<Result<String>>,
}

// Kill thread when clipboard object is dropped
impl Drop for ThreadedClipboard {
    fn drop(&mut self) {
        self.request_send.send(ThreadRequest::Kill).unwrap()
    }
}

impl ThreadedClipboard {
    /// Creates a new wayland clipboard object
    ///
    /// Spawns a new thread to dispatch messages to the wayland server every
    /// 50ms to ensure the server can read stored data
    pub fn new(display: &Display) -> Self {
        let (request_send, request_recv) = mpsc::channel();
        let (load_send, load_recv) = mpsc::channel();
        let display = display.clone();

        // Spawn a thread to handle the clipboard as regular dispatching of the wayland thread is needed
        std::thread::spawn(move || {
            let mut event_queue = display.create_event_queue();
            let display = (*display)
                .as_ref()
                .make_wrapper(&event_queue.get_token())
                .unwrap();
            clipboard_thread(&display, &mut event_queue, request_recv, load_send);
        });

        ThreadedClipboard {
            request_send,
            load_recv,
        }
    }

    /// Creates a new wayland clipboard object from a mutable `wl_display` ptr
    ///
    /// Spawns a new thread to dispatch messages to the wayland server every
    /// 50ms to ensure the server can read stored data
    pub unsafe fn new_from_external(display_ptr: *mut wl_display) -> Self {
        let (request_send, request_recv) = mpsc::channel();
        let (load_send, load_recv) = mpsc::channel();
        let display = display_ptr.as_mut().unwrap();

        // Spawn a thread to handle the clipboard as regular dispatching of the wayland thread is needed
        std::thread::spawn(move || {
            let (display, mut event_queue) = Display::from_external_display(display);
            clipboard_thread(&display, &mut event_queue, request_recv, load_send);
        });

        ThreadedClipboard {
            request_send,
            load_recv,
        }
    }

    /// Returns text from the wayland clipboard
    ///
    /// If provided with a seat name that seat must be in
    /// focus to work. Otherwise if no seat name is provided
    /// the name of the seat to last generate a key or pointer event
    /// is used
    pub fn load(&mut self, seat_name: Option<String>) -> Result<String> {
        self.request_send
            .send(ThreadRequest::Load(seat_name))
            .unwrap();
        self.load_recv.recv().unwrap()
    }

    /// Stores text in the wayland clipboard
    ///
    /// If provided with a seat name that seat must be in
    /// focus to work. Otherwise if no seat name is provided
    /// the name of the seat to last generate a key or pointer event
    /// is used
    pub fn store<T>(&mut self, seat_name: Option<String>, text: T)
    where
        T: Into<String>,
    {
        self.request_send
            .send(ThreadRequest::Store(seat_name, text.into()))
            .unwrap()
    }

    /// Returns text from the primary selection of the wayland clipboard
    ///
    /// If provided with a seat name that seat must be in
    /// focus to work. Otherwise if no seat name is provided
    /// the name of the seat to last generate a key or pointer event
    /// is used
    pub fn load_primary(&mut self, seat_name: Option<String>) -> Result<String> {
        self.request_send
            .send(ThreadRequest::LoadPrimary(seat_name))
            .unwrap();
        self.load_recv.recv().unwrap()
    }

    /// Stores text in the primary selection of the wayland clipboard
    ///
    /// If provided with a seat name that seat must be in
    /// focus to work. Otherwise if no seat name is provided
    /// the name of the seat to last generate a key or pointer event
    /// is used
    pub fn store_primary(&mut self, seat_name: Option<String>, text: String) {
        self.request_send
            .send(ThreadRequest::StorePrimary(seat_name, text))
            .unwrap()
    }
}

/// Requests sent to the clipboard thread
enum ThreadRequest {
    /// Store text in a specific seats clipboard
    Store(Option<String>, String),
    /// Load text from a specific seats clipboard
    Load(Option<String>),
    /// Store text in a specific seats primary clipboard
    StorePrimary(Option<String>, String),
    /// Load text in a specific seats primary clipboard
    LoadPrimary(Option<String>),
    /// Kill the thread
    Kill,
}

/// Handles the setup and running of the clipboard thread
fn clipboard_thread(
    display: &WlDisplay,
    event_queue: &mut EventQueue,
    request_recv: mpsc::Receiver<ThreadRequest>,
    load_send: mpsc::Sender<Result<String>>,
) {
    // Create a seat map to register seats
    let seat_map = Arc::new(Mutex::new(SeatMap::new()));

    // Store unimplemented seats so we can implement them when the data device manager is implemented
    let data_device_manager = Arc::new(Mutex::new(None));
    let mut unimplemented_seats = Vec::new();

    let primary_selection_device_manager = Arc::new(Mutex::new(None));
    let gtk_primary_selection_device_manager = Arc::new(Mutex::new(None));

    // Store the name of the seat that last sends an event for use as the default seat
    let last_seat_name = Arc::new(Mutex::new(String::new()));

    let data_device_manager_clone = data_device_manager.clone();
    let primary_selection_device_manager_clone = primary_selection_device_manager.clone();
    let gtk_primary_selection_device_manager_clone = gtk_primary_selection_device_manager.clone();
    let seat_map_clone = seat_map.clone();
    let last_seat_name_clone = last_seat_name.clone();

    // Register wl_seat objects and wl_data_device_manager
    GlobalManager::new_with_cb(&display, move |event, reg| {
        if let GlobalEvent::New {
            id,
            ref interface,
            version,
        } = event
        {
            if "wl_seat" == interface.as_str() && version >= 2 {
                if let Some(ref data_device_manager) =
                    data_device_manager_clone.lock().unwrap().deref()
                {
                    // Implement the seat
                    implement_seat(
                        id,
                        std::cmp::min(version, 6), // only seat up to version 6 is supported
                        seat_map_clone.clone(),
                        last_seat_name_clone.clone(),
                        data_device_manager,
                        &reg,
                        primary_selection_device_manager_clone.clone(),
                        gtk_primary_selection_device_manager_clone.clone(),
                    );
                } else {
                    // Store the seat for implementation once wl_data_device_manager is registered
                    unimplemented_seats.push((id, version));
                }
            } else if "wl_data_device_manager" == interface.as_str() {
                // Register the wl_data_device_manager
                *data_device_manager_clone.lock().unwrap() = Some(
                    reg.bind::<wl_data_device_manager::WlDataDeviceManager, _>(
                        version,
                        id,
                        NewProxy::implement_dummy,
                    )
                    .unwrap(),
                );
                // Implement the unimplemented seats
                for (id, version) in &unimplemented_seats {
                    implement_seat(
                        *id,
                        std::cmp::min(*version, 6), // only seat up to version 6 is supported
                        seat_map_clone.clone(),
                        last_seat_name_clone.clone(),
                        data_device_manager_clone.lock().unwrap().as_ref().unwrap(),
                        &reg,
                        primary_selection_device_manager_clone.clone(),
                        gtk_primary_selection_device_manager_clone.clone(),
                    );
                }
            } else if "zwp_primary_selection_device_manager_v1" == interface.as_str() {
                // Register the zwp_primary_selection_device_manager
                *primary_selection_device_manager_clone.lock().unwrap() = Some(
                    reg.bind::<PrimarySelectionDeviceMgr, _>(
                        version,
                        id,
                        NewProxy::implement_dummy,
                    )
                    .unwrap(),
                );
            } else if "gtk_primary_selection_device_manager" == interface.as_str() {
                *gtk_primary_selection_device_manager_clone.lock().unwrap() = Some(
                    reg.bind::<GtkPrimarySelectionDeviceManager, _>(
                        version,
                        id,
                        NewProxy::implement_dummy,
                    )
                    .unwrap(),
                );
            }
        }
    });
    event_queue.sync_roundtrip().unwrap();

    // We should provide lower sleep amounts in a moments of spaming our clipboard
    let mut sleep_amount = 50;
    // Provide our clipboard a warm start, so 16 initial cycles will be at 1ms and other will go
    // like 1 2 4 8 16 32 50 50 and so on
    let mut warm_start_amount = 0;

    // Thread loop to handle requests and dispatch the event queue
    loop {
        if let Ok(request) = request_recv.try_recv() {
            // Lower sleep amount to zero, so the next recv will be instant
            sleep_amount = 0;

            match request {
                // Load text from clipboard
                ThreadRequest::Load(seat_name) => {
                    event_queue.sync_roundtrip().unwrap();
                    let seat_map = seat_map.lock().unwrap().clone();

                    // Get the clipboard contents of the requested seat from the seat map
                    let contents = seat_map
                        .get(&seat_name.unwrap_or_else(|| last_seat_name.lock().unwrap().clone()))
                        .map_or(Ok(String::new()), |seat| {
                            let mut reader = None;
                            if let Some(device) = seat.0.lock().unwrap().as_ref() {
                                device.with_selection(|offer| {
                                    if let Some(offer) = offer {
                                        offer.with_mime_types(|types| {
                                            if types
                                                .contains(&"text/plain;charset=utf-8".to_string())
                                            {
                                                reader = Some(
                                                    offer
                                                        .receive("text/plain;charset=utf-8".into())
                                                        .unwrap(),
                                                );
                                            }
                                        });
                                    }
                                });

                                event_queue.sync_roundtrip().unwrap();
                            }
                            reader.map_or(Ok(String::new()), |mut reader| {
                                let mut contents = String::new();
                                if let Err(err) = reader.read_to_string(&mut contents) {
                                    Err(err)
                                } else {
                                    Ok(contents)
                                }
                            })
                        });
                    // Normalization should happen only on `text/plain;charset=utf-8`, in case we
                    // add other mime types consult gtk for normalization.
                    let contents = contents.and_then(|contents| Ok(normilize_to_lf(contents)));
                    load_send.send(contents).unwrap();
                }
                // Store text in the clipboard
                ThreadRequest::Store(seat_name, contents) => {
                    event_queue.sync_roundtrip().unwrap();
                    let seat_map = seat_map.lock().unwrap().clone();

                    // Get the requested seat from the seat map
                    if let Some((device, enter_serial, _, _, _, _)) = seat_map
                        .get(&seat_name.unwrap_or_else(|| last_seat_name.lock().unwrap().clone()))
                    {
                        if let Some(device) = device.lock().unwrap().as_ref() {
                            let data_source = DataSource::new(
                                data_device_manager.lock().unwrap().as_ref().unwrap(),
                                &["text/plain;charset=utf-8"],
                                move |source_event| {
                                    if let DataSourceEvent::Send { mut pipe, .. } = source_event {
                                        write!(pipe, "{}", contents).unwrap();
                                    }
                                },
                            );

                            device.set_selection(&Some(data_source), *enter_serial);

                            event_queue.sync_roundtrip().unwrap();
                        }
                    }
                }
                // Load text from primary clipboard
                ThreadRequest::LoadPrimary(seat_name) => {
                    event_queue.sync_roundtrip().unwrap();
                    let seat_map = seat_map.lock().unwrap().clone();

                    // Get the primary clipboard contents of the requested seat from the seat map
                    let contents = if primary_selection_device_manager.lock().unwrap().is_some() {
                        seat_map
                            .get(
                                &seat_name
                                    .unwrap_or_else(|| last_seat_name.lock().unwrap().clone()),
                            )
                            .map_or(Ok(String::new()), |seat| {
                                seat.3.lock().unwrap().as_ref().map_or(
                                    Ok(String::new()),
                                    |primary_offer| {
                                        let (readfd, writefd) = pipe2(OFlag::O_CLOEXEC).unwrap();
                                        let mut file =
                                            unsafe { std::fs::File::from_raw_fd(readfd) };
                                        primary_offer.receive(
                                            "text/plain;charset=utf-8".to_string(),
                                            writefd,
                                        );
                                        close(writefd).unwrap();
                                        let mut contents = String::new();
                                        event_queue.sync_roundtrip().unwrap();
                                        if let Err(err) = file.read_to_string(&mut contents) {
                                            Err(err)
                                        } else {
                                            Ok(contents)
                                        }
                                    },
                                )
                            })
                    } else if gtk_primary_selection_device_manager
                        .lock()
                        .unwrap()
                        .is_some()
                    {
                        seat_map
                            .get(
                                &seat_name
                                    .unwrap_or_else(|| last_seat_name.lock().unwrap().clone()),
                            )
                            .map_or(Ok(String::new()), |seat| {
                                seat.5.lock().unwrap().as_ref().map_or(
                                    Ok(String::new()),
                                    |primary_offer| {
                                        let (readfd, writefd) = pipe2(OFlag::O_CLOEXEC).unwrap();
                                        let mut file =
                                            unsafe { std::fs::File::from_raw_fd(readfd) };
                                        primary_offer.receive(
                                            "text/plain;charset=utf-8".to_string(),
                                            writefd,
                                        );
                                        close(writefd).unwrap();
                                        let mut contents = String::new();
                                        event_queue.sync_roundtrip().unwrap();
                                        if let Err(err) = file.read_to_string(&mut contents) {
                                            Err(err)
                                        } else {
                                            Ok(contents)
                                        }
                                    },
                                )
                            })
                    } else {
                        Ok(String::new())
                    };
                    // Normalization should happen only on `text/plain;charset=utf-8`, in case we
                    // add other mime types consult gtk for normalization.
                    let contents = contents.and_then(|contents| Ok(normilize_to_lf(contents)));
                    load_send.send(contents).unwrap();
                }
                // Store text in the primary clipboard
                ThreadRequest::StorePrimary(seat_name, contents) => {
                    event_queue.sync_roundtrip().unwrap();
                    let seat_map = seat_map.lock().unwrap().clone();

                    // Get the requested seat from the seat map
                    if let Some((_, enter_serial, primary_device, _, gtk_primary_device, _)) =
                        seat_map.get(
                            &seat_name.unwrap_or_else(|| last_seat_name.lock().unwrap().clone()),
                        )
                    {
                        if let Some(manager) = &*primary_selection_device_manager.lock().unwrap() {
                            if let Some(primary_device) = &*primary_device.lock().unwrap() {
                                let source = manager.create_source(|proxy| {
                                    proxy.implement_closure(
                                        move |event, _| {
                                            if let zwp_primary_selection_source_v1::Event::Send {
                                                mime_type,
                                                fd,
                                            } = event
                                            {
                                                if mime_type == "text/plain;charset=utf-8" {
                                                    let mut file =
                                                        unsafe { std::fs::File::from_raw_fd(fd) };
                                                    file.write_fmt(format_args!("{}", contents))
                                                        .unwrap();
                                                }
                                            }
                                        },
                                        (),
                                    )
                                });
                                if let Ok(source) = &source {
                                    source.offer("text/plain;charset=utf-8".to_string());
                                }
                                primary_device.set_selection(source.ok().as_ref(), *enter_serial);
                            }
                        } else if let Some(manager) =
                            &*gtk_primary_selection_device_manager.lock().unwrap()
                        {
                            if let Some(gtk_primary_device) = &*gtk_primary_device.lock().unwrap() {
                                let source = manager.create_source(|proxy| {
                                    proxy.implement_closure(
                                        move |event, _| {
                                            if let gtk_primary_selection_source::Event::Send {
                                                mime_type,
                                                fd,
                                            } = event
                                            {
                                                if mime_type == "text/plain;charset=utf-8" {
                                                    let mut file =
                                                        unsafe { std::fs::File::from_raw_fd(fd) };
                                                    file.write_fmt(format_args!("{}", contents))
                                                        .unwrap();
                                                }
                                            }
                                        },
                                        (),
                                    )
                                });
                                if let Ok(source) = &source {
                                    source.offer("text/plain;charset=utf-8".to_string());
                                }
                                gtk_primary_device
                                    .set_selection(source.ok().as_ref(), *enter_serial);
                            }
                        }
                    }
                }
                ThreadRequest::Kill => break,
            }
        }
        // Dispatch the event queue and block for `sleep_amount`
        let pending_events = event_queue.dispatch_pending().unwrap();
        let num_seats = seat_map.lock().unwrap().len();

        // If some app is trying to spam us when there no seats, it's likely that someone is
        // trying to paste from us
        if num_seats == 0 && pending_events != 0 {
            sleep_amount = 0;
        } else if sleep_amount > 0 {
            thread::sleep(Duration::from_millis(sleep_amount));

            if warm_start_amount < 16 {
                warm_start_amount += 1;
                if warm_start_amount == 16 {
                    sleep_amount = 1;
                }
            } else if sleep_amount < 50 {
                // The aim of this different sleep times is to provide a good performance under
                // high load and not waste system resources too much when idle
                sleep_amount = std::cmp::min(2 * sleep_amount, 50);
            }
        } else if sleep_amount == 0 {
            // Reset sleep amount from zero back to one, so sleep sequence could reach 50
            sleep_amount = 1;
            // Reset warm start to accelerate the initial clipboard requests
            warm_start_amount = 0;
        }
    }
}

/// Implement seats that we register
fn implement_seat(
    id: u32,
    version: u32,
    seat_map: Arc<Mutex<SeatMap>>,
    last_seat_name: Arc<Mutex<String>>,
    data_device_manager: &wl_data_device_manager::WlDataDeviceManager,
    reg: &wl_registry::WlRegistry,
    primary_device_manager: Arc<Mutex<Option<PrimarySelectionDeviceMgr>>>,
    gtk_primary_device_manager: Arc<Mutex<Option<GtkPrimarySelectionDeviceManager>>>,
) {
    let device = Arc::new(Mutex::new(None));
    let device_clone = device.clone();
    let seat_name = Arc::new(Mutex::new(String::new()));
    let seat_name_clone = seat_name.clone();
    let seat_map_clone = seat_map.clone();

    let primary_device = Arc::new(Mutex::new(None));
    let primary_offer = Arc::new(Mutex::new(None));

    let primary_device_clone = primary_device.clone();
    let primary_offer_clone = primary_offer.clone();

    let gtk_primary_device = Arc::new(Mutex::new(None));
    let gtk_primary_offer = Arc::new(Mutex::new(None));

    let gtk_primary_device_clone = gtk_primary_device.clone();
    let gtk_primary_offer_clone = gtk_primary_offer.clone();

    let mut pointer = None;
    let mut keyboard = None;

    // Register the seat
    let seat = reg
        .bind::<wl_seat::WlSeat, _>(version, id, move |proxy| {
            proxy.implement_closure(
                move |event, seat| match event {
                    wl_seat::Event::Name { name } => *seat_name_clone.lock().unwrap() = name,
                    wl_seat::Event::Capabilities { capabilities } => {
                        if capabilities.contains(Capability::Pointer) {
                            if pointer.is_none() {
                                let device_clone = device_clone.clone();

                                let primary_device_clone = primary_device_clone.clone();
                                let primary_offer_clone = primary_offer_clone.clone();

                                let gtk_primary_device_clone = gtk_primary_device_clone.clone();
                                let gtk_primary_offer_clone = gtk_primary_offer_clone.clone();

                                let last_seat_name_clone = last_seat_name.clone();
                                let seat_map_clone = seat_map_clone.clone();
                                let seat_name_clone = seat_name_clone.clone();
                                pointer = Some(
                                    seat.get_pointer(move |pointer| {
                                        pointer.implement_closure(
                                            move |evt, _| {
                                                // Set this seat as the last to send an event
                                                *last_seat_name_clone.lock().unwrap() =
                                                    seat_name_clone.lock().unwrap().clone();

                                                // Get serials from recieved events from the seat
                                                // pointer
                                                match evt {
                                                    PtrEvent::Enter { serial, .. } => {
                                                        if let Some(seat) =
                                                            seat_map_clone.lock().unwrap().get_mut(
                                                                &seat_name_clone
                                                                    .lock()
                                                                    .unwrap()
                                                                    .clone(),
                                                            )
                                                        {
                                                            // Update serial if "seat" is already
                                                            // presented
                                                            seat.1 = serial;
                                                            return;
                                                        }

                                                        seat_map_clone.lock().unwrap().insert(
                                                            seat_name_clone.lock().unwrap().clone(),
                                                            (
                                                                device_clone.clone(),
                                                                serial,
                                                                primary_device_clone.clone(),
                                                                primary_offer_clone.clone(),
                                                                gtk_primary_device_clone.clone(),
                                                                gtk_primary_offer_clone.clone(),
                                                            ),
                                                        );
                                                    }
                                                    PtrEvent::Button { serial, .. } => {
                                                        if let Some(seat) =
                                                            seat_map_clone.lock().unwrap().get_mut(
                                                                &seat_name_clone
                                                                    .lock()
                                                                    .unwrap()
                                                                    .clone(),
                                                            )
                                                        {
                                                            // Update serial if seat is already
                                                            // presented
                                                            seat.1 = serial;
                                                            return;
                                                        }

                                                        // This is for consistency with
                                                        // `PtrEvent::Enter`
                                                        seat_map_clone.lock().unwrap().insert(
                                                            seat_name_clone.lock().unwrap().clone(),
                                                            (
                                                                device_clone.clone(),
                                                                serial,
                                                                primary_device_clone.clone(),
                                                                primary_offer_clone.clone(),
                                                                gtk_primary_device_clone.clone(),
                                                                gtk_primary_offer_clone.clone(),
                                                            ),
                                                        );
                                                    }
                                                    _ => {}
                                                }
                                            },
                                            (),
                                        )
                                    })
                                    .unwrap(),
                                );
                            }
                        } else if let Some(pointer) = pointer.take() {
                            // Release old pointer
                            if pointer.as_ref().version() >= 3 {
                                pointer.release();
                            }
                        }

                        if capabilities.contains(Capability::Keyboard) {
                            if keyboard.is_none() {
                                let device_clone = device_clone.clone();

                                let primary_device_clone = primary_device_clone.clone();
                                let primary_offer_clone = primary_offer_clone.clone();

                                let gtk_primary_device_clone = gtk_primary_device_clone.clone();
                                let gtk_primary_offer_clone = gtk_primary_offer_clone.clone();

                                let last_seat_name_clone = last_seat_name.clone();
                                let seat_map_clone = seat_map_clone.clone();
                                let seat_name_clone = seat_name_clone.clone();
                                keyboard = Some(
                                    map_keyboard_auto(&seat, move |event, _| {
                                        // Set this seat as the last to send an event
                                        *last_seat_name_clone.lock().unwrap() =
                                            seat_name_clone.lock().unwrap().clone();

                                        // Get serials from recieved events from the seat keyboard
                                        match event {
                                            KbEvent::Enter { serial, .. } => {
                                                seat_map_clone.lock().unwrap().insert(
                                                    seat_name_clone.lock().unwrap().clone(),
                                                    (
                                                        device_clone.clone(),
                                                        serial,
                                                        primary_device_clone.clone(),
                                                        primary_offer_clone.clone(),
                                                        gtk_primary_device_clone.clone(),
                                                        gtk_primary_offer_clone.clone(),
                                                    ),
                                                );
                                            }
                                            KbEvent::Key { serial, .. } => {
                                                seat_map_clone.lock().unwrap().insert(
                                                    seat_name_clone.lock().unwrap().clone(),
                                                    (
                                                        device_clone.clone(),
                                                        serial,
                                                        primary_device_clone.clone(),
                                                        primary_offer_clone.clone(),
                                                        gtk_primary_device_clone.clone(),
                                                        gtk_primary_offer_clone.clone(),
                                                    ),
                                                );
                                            }
                                            KbEvent::Leave { .. } => {
                                                seat_map_clone
                                                    .lock()
                                                    .unwrap()
                                                    .remove(&*seat_name_clone.lock().unwrap());
                                            }
                                            _ => {}
                                        }
                                    })
                                    .unwrap(),
                                );
                            }
                        } else if let Some(keyboard) = keyboard.take() {
                            // Release old keyboard
                            if keyboard.as_ref().version() >= 3 {
                                keyboard.release();
                            }
                        }
                    }
                    _ => (),
                },
                (),
            )
        })
        .unwrap();

    // Create a device for the seat
    *device.lock().unwrap() = Some(DataDevice::init_for_seat(
        data_device_manager,
        &seat,
        |_| {},
    ));

    if let Some(manager) = &*primary_device_manager.lock().unwrap() {
        *primary_device.lock().unwrap() = manager
            .get_device(&seat, |proxy| {
                proxy.implement_closure(
                    move |event, _| {
                        if let ZwpPrimarySelectionDeviceEvent::DataOffer { offer } = event {
                            *primary_offer.lock().unwrap() = Some(offer.implement_dummy());

                            let map_contents = seat_map
                                .lock()
                                .unwrap()
                                .get(&seat_name.lock().unwrap().clone())
                                .cloned();
                            if let Some(map_contents) = map_contents {
                                seat_map.lock().unwrap().insert(
                                    seat_name.lock().unwrap().clone(),
                                    (
                                        map_contents.0.clone(),
                                        map_contents.1,
                                        map_contents.2,
                                        primary_offer.clone(),
                                        Arc::new(Mutex::new(None)),
                                        Arc::new(Mutex::new(None)),
                                    ),
                                );
                            }
                        }
                    },
                    (),
                )
            })
            .ok();
    } else if let Some(manager) = &*gtk_primary_device_manager.lock().unwrap() {
        *gtk_primary_device.lock().unwrap() = manager
            .get_device(&seat, |proxy| {
                proxy.implement_closure(
                    move |event, _| {
                        if let GtkPrimarySelectionDeviceEvent::DataOffer { offer } = event {
                            *gtk_primary_offer.lock().unwrap() = Some(offer.implement_dummy());

                            let map_contents = seat_map
                                .lock()
                                .unwrap()
                                .get(&seat_name.lock().unwrap().clone())
                                .cloned();
                            if let Some(map_contents) = map_contents {
                                seat_map.lock().unwrap().insert(
                                    seat_name.lock().unwrap().clone(),
                                    (
                                        map_contents.0.clone(),
                                        map_contents.1,
                                        Arc::new(Mutex::new(None)),
                                        Arc::new(Mutex::new(None)),
                                        map_contents.4,
                                        gtk_primary_offer.clone(),
                                    ),
                                );
                            }
                        }
                    },
                    (),
                )
            })
            .ok();
    }
}

// Normalize \r and \r\n into \n.
//
// Gtk does this for text/plain;charset=utf-8, so following them here, otherwise there is
// a chance of getting extra new lines on load, since they're converting \r and \n into
// \r\n on every store.
fn normilize_to_lf(text: String) -> String {
    text.replace("\r\n", "\n").replace("\r", "\n")
}