druid-shell 0.8.3

Platform abstracting application shell used for Druid toolkit.
Documentation
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
// Copyright 2020 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Interactions with the system pasteboard on X11.

use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::convert::TryFrom;
use std::rc::Rc;
use std::time::{Duration, Instant};

use x11rb::connection::{Connection, RequestConnection};
use x11rb::errors::{ConnectionError, ReplyError, ReplyOrIdError};
use x11rb::protocol::xproto::{
    Atom, AtomEnum, ChangeWindowAttributesAux, ConnectionExt, EventMask, GetPropertyReply,
    GetPropertyType, PropMode, Property, PropertyNotifyEvent, SelectionClearEvent,
    SelectionNotifyEvent, SelectionRequestEvent, Timestamp, Window, WindowClass,
    SELECTION_NOTIFY_EVENT,
};
use x11rb::protocol::Event;
use x11rb::wrapper::ConnectionExt as _;
use x11rb::xcb_ffi::XCBConnection;

use super::application::AppAtoms;
use crate::clipboard::{ClipboardFormat, FormatId};
use tracing::{debug, error, warn};

// We can pick an arbitrary atom that is used for the transfer. This is our pick.
const TRANSFER_ATOM: AtomEnum = AtomEnum::CUT_BUFFE_R4;

const STRING_TARGETS: [&str; 5] = [
    "UTF8_STRING",
    "TEXT",
    "STRING",
    "text/plain;charset=utf-8",
    "text/plain",
];

#[derive(Debug, Clone)]
pub struct Clipboard(Rc<RefCell<ClipboardState>>);

impl Clipboard {
    pub(crate) fn new(
        connection: Rc<XCBConnection>,
        screen_num: usize,
        atoms: Rc<AppAtoms>,
        selection_name: Atom,
        event_queue: Rc<RefCell<VecDeque<Event>>>,
        timestamp: Rc<Cell<Timestamp>>,
    ) -> Self {
        Self(Rc::new(RefCell::new(ClipboardState::new(
            connection,
            screen_num,
            atoms,
            selection_name,
            event_queue,
            timestamp,
        ))))
    }

    pub(crate) fn handle_clear(&self, event: SelectionClearEvent) -> Result<(), ConnectionError> {
        self.0.borrow_mut().handle_clear(event)
    }

    pub(crate) fn handle_request(
        &self,
        event: &SelectionRequestEvent,
    ) -> Result<(), ReplyOrIdError> {
        self.0.borrow_mut().handle_request(event)
    }

    pub(crate) fn handle_property_notify(
        &self,
        event: PropertyNotifyEvent,
    ) -> Result<(), ReplyOrIdError> {
        self.0.borrow_mut().handle_property_notify(event)
    }

    pub fn put_string(&mut self, s: impl AsRef<str>) {
        let bytes = s.as_ref().as_bytes();
        let formats = STRING_TARGETS
            .iter()
            .map(|format| ClipboardFormat::new(format, bytes))
            .collect::<Vec<_>>();
        self.put_formats(&formats);
    }

    pub fn put_formats(&mut self, formats: &[ClipboardFormat]) {
        if let Err(err) = self.0.borrow_mut().put_formats(formats) {
            error!("Error in Clipboard::put_formats: {:?}", err);
        }
    }

    pub fn get_string(&self) -> Option<String> {
        self.0.borrow().get_string()
    }

    pub fn preferred_format(&self, formats: &[FormatId]) -> Option<FormatId> {
        self.0.borrow().preferred_format(formats)
    }

    pub fn get_format(&self, format: FormatId) -> Option<Vec<u8>> {
        self.0.borrow().get_format(format)
    }

    pub fn available_type_names(&self) -> Vec<String> {
        self.0.borrow().available_type_names()
    }
}

#[derive(Debug)]
struct ClipboardState {
    connection: Rc<XCBConnection>,
    screen_num: usize,
    atoms: Rc<AppAtoms>,
    selection_name: Atom,
    event_queue: Rc<RefCell<VecDeque<Event>>>,
    timestamp: Rc<Cell<Timestamp>>,
    contents: Option<ClipboardContents>,
    incremental: Vec<IncrementalTransfer>,
}

impl ClipboardState {
    fn new(
        connection: Rc<XCBConnection>,
        screen_num: usize,
        atoms: Rc<AppAtoms>,
        selection_name: Atom,
        event_queue: Rc<RefCell<VecDeque<Event>>>,
        timestamp: Rc<Cell<Timestamp>>,
    ) -> Self {
        Self {
            connection,
            screen_num,
            atoms,
            selection_name,
            event_queue,
            timestamp,
            contents: None,
            incremental: Vec::new(),
        }
    }

    fn put_formats(&mut self, formats: &[ClipboardFormat]) -> Result<(), ReplyOrIdError> {
        let conn = &*self.connection;

        // Create a window for selection ownership and save the necessary state
        let contents = ClipboardContents::new(conn, self.screen_num, formats)?;

        // Become selection owner of our selection
        conn.set_selection_owner(
            contents.owner_window,
            self.selection_name,
            self.timestamp.get(),
        )?;

        // Check if we really are the selection owner; this might e.g. fail if our timestamp is too
        // old and some other program became the selection owner with a newer timestamp
        let owner = conn.get_selection_owner(self.selection_name)?.reply()?;
        if owner.owner == contents.owner_window {
            // We are the new selection owner! Remember our contents for later.
            debug!("put_formats(): became selection owner");
            if let Some(mut old_owner) = std::mem::replace(&mut self.contents, Some(contents)) {
                // We already where the owner before. Destroy the old contents.
                old_owner.destroy(conn)?;
            }
        } else {
            debug!("put_formats(): failed to become selection owner");
        }

        Ok(())
    }

    fn get_string(&self) -> Option<String> {
        STRING_TARGETS.iter().find_map(|target| {
            self.get_format(target)
                .and_then(|data| String::from_utf8(data).ok())
        })
    }

    fn preferred_format(&self, formats: &[FormatId]) -> Option<FormatId> {
        let available = self.available_type_names();
        formats
            .iter()
            .find(|f1| available.iter().any(|f2| *f1 == f2))
            .copied()
    }

    fn get_format(&self, format: FormatId) -> Option<Vec<u8>> {
        if let Some(contents) = self.contents.as_ref() {
            // We are the selection owner and can directly return the result
            contents
                .data
                .iter()
                .find(|(_, fmt, _)| fmt == format)
                .map(|(_, _, data)| data.to_vec())
        } else {
            self.do_transfer(format, |prop| prop.value)
        }
    }

    #[allow(clippy::needless_collect)]
    fn available_type_names(&self) -> Vec<String> {
        if let Some(contents) = self.contents.as_ref() {
            // We are the selection owner and can directly return the result
            return contents
                .data
                .iter()
                .map(|(_, format, _)| format.to_string())
                .collect();
        }
        let requests = self
            .do_transfer("TARGETS", |prop| {
                prop.value32()
                    .map(|iter| iter.collect())
                    .unwrap_or_default()
            })
            .unwrap_or_default()
            .into_iter()
            .filter_map(|atom| self.connection.get_atom_name(atom).ok())
            .collect::<Vec<_>>();
        // We first send all requests above and then fetch the replies with only one round-trip to
        // the X11 server. Hence, the collect() above is not unnecessary!
        requests
            .into_iter()
            .filter_map(|req| req.reply().ok())
            .filter_map(|reply| String::from_utf8(reply.name).ok())
            .collect()
    }

    fn do_transfer<R, F>(&self, format: FormatId, converter: F) -> Option<Vec<R>>
    where
        R: Clone,
        F: FnMut(GetPropertyReply) -> Vec<R>,
    {
        match self.do_transfer_impl(format, converter) {
            Ok(result) => result,
            Err(error) => {
                warn!("Error in Clipboard::do_transfer: {:?}", error);
                None
            }
        }
    }

    fn do_transfer_impl<R, F>(
        &self,
        format: FormatId,
        mut converter: F,
    ) -> Result<Option<Vec<R>>, ReplyOrIdError>
    where
        R: Clone,
        F: FnMut(GetPropertyReply) -> Vec<R>,
    {
        debug!("Getting clipboard contents in format {}", format);

        let deadline = Instant::now() + Duration::from_secs(5);

        let conn = &*self.connection;
        let format_atom = conn.intern_atom(false, format.as_bytes())?.reply()?.atom;

        // Create a window for the transfer
        let window = WindowContainer::new(conn, self.screen_num)?;

        conn.convert_selection(
            window.window,
            self.selection_name,
            format_atom,
            TRANSFER_ATOM,
            self.timestamp.get(),
        )?;

        // Now wait for the selection notify event
        conn.flush()?;
        let notify = loop {
            match wait_for_event_with_deadline(conn, deadline)? {
                Event::SelectionNotify(notify) if notify.requestor == window.window => {
                    break notify
                }
                Event::SelectionRequest(request) if request.requestor == window.window => {
                    // The callers should catch this situation before and not even call us
                    // do_transfer()
                    error!("BUG! We are doing a selection transfer while we are the selection owner. This will hang!");
                }
                event => self.event_queue.borrow_mut().push_back(event),
            }
        };

        if notify.property == x11rb::NONE {
            // Selection is empty
            debug!("Selection transfer was rejected");
            return Ok(None);
        }

        conn.change_window_attributes(
            window.window,
            &ChangeWindowAttributesAux::default().event_mask(EventMask::PROPERTY_CHANGE),
        )?;

        let property = conn
            .get_property(
                true,
                window.window,
                TRANSFER_ATOM,
                GetPropertyType::ANY,
                0,
                u32::MAX,
            )?
            .reply()?;

        if property.type_ != self.atoms.INCR {
            debug!("Got selection contents directly");
            return Ok(Some(converter(property)));
        }

        // The above GetProperty with delete=true indicated that the INCR transfer starts
        // now, wait for the property notifies
        debug!("Doing an INCR transfer for the selection");
        conn.flush()?;
        let mut value = Vec::new();
        loop {
            match wait_for_event_with_deadline(conn, deadline)? {
                Event::PropertyNotify(notify)
                    if (notify.window, notify.state) == (window.window, Property::NEW_VALUE) =>
                {
                    let property = conn
                        .get_property(
                            true,
                            window.window,
                            TRANSFER_ATOM,
                            GetPropertyType::ANY,
                            0,
                            u32::MAX,
                        )?
                        .reply()?;
                    if property.value.is_empty() {
                        debug!("INCR transfer finished");
                        return Ok(Some(value));
                    } else {
                        value.extend_from_slice(&converter(property));
                    }
                }
                event => self.event_queue.borrow_mut().push_back(event),
            }
        }
    }

    fn handle_clear(&mut self, event: SelectionClearEvent) -> Result<(), ConnectionError> {
        if event.selection != self.selection_name {
            // This event is meant for another Clipboard instance
            return Ok(());
        }

        let window = self.contents.as_ref().map(|c| c.owner_window);
        if Some(event.owner) == window {
            // We lost ownership of the selection, clean up
            if let Some(mut contents) = self.contents.take() {
                contents.destroy(&self.connection)?;
            }
        }
        Ok(())
    }

    fn handle_request(&mut self, event: &SelectionRequestEvent) -> Result<(), ReplyOrIdError> {
        if event.selection != self.selection_name {
            // This request is meant for another Clipboard instance
            return Ok(());
        }

        let conn = &*self.connection;
        let contents = match &self.contents {
            Some(contents) if contents.owner_window == event.owner => contents,
            _ => {
                // We do not know what to do with this transfer
                debug!("Got non-matching selection request event");
                reject_transfer(conn, event)?;
                return Ok(());
            }
        };

        // TODO: ICCCM has TIMESTAMP as a required target (but no one uses it...?)
        if event.target == self.atoms.TARGETS {
            // TARGETS is a special case: reply is list of u32
            let mut atoms = contents
                .data
                .iter()
                .map(|(atom, _, _)| *atom)
                .collect::<Vec<_>>();
            atoms.push(self.atoms.TARGETS);
            conn.change_property32(
                PropMode::REPLACE,
                event.requestor,
                event.property,
                AtomEnum::ATOM,
                &atoms,
            )?;
        } else {
            // Find the request target
            let content = contents
                .data
                .iter()
                .find(|(atom, _, _)| *atom == event.target);
            match content {
                None => {
                    reject_transfer(conn, event)?;
                    return Ok(());
                }
                Some((atom, _, data)) => {
                    if data.len() > maximum_property_length(conn) {
                        // We need to do an INCR transfer.
                        debug!("Starting new INCR transfer");
                        let transfer =
                            IncrementalTransfer::new(conn, event, Rc::clone(data), self.atoms.INCR);
                        match transfer {
                            Ok(transfer) => self.incremental.push(transfer),
                            Err(err) => {
                                reject_transfer(conn, event)?;
                                return Err(err.into());
                            }
                        }
                    } else {
                        // We can provide the data directly
                        conn.change_property8(
                            PropMode::REPLACE,
                            event.requestor,
                            event.property,
                            *atom,
                            data,
                        )?;
                    }
                }
            }
        }

        // Inform the requestor that we sent the data
        debug!("Replying to selection request event");
        let event = SelectionNotifyEvent {
            response_type: SELECTION_NOTIFY_EVENT,
            sequence: 0,
            requestor: event.requestor,
            selection: event.selection,
            target: event.target,
            property: event.property,
            time: event.time,
        };
        conn.send_event(false, event.requestor, EventMask::NO_EVENT, event)?;

        Ok(())
    }

    fn handle_property_notify(&mut self, event: PropertyNotifyEvent) -> Result<(), ReplyOrIdError> {
        fn matches(transfer: &IncrementalTransfer, event: PropertyNotifyEvent) -> bool {
            transfer.requestor == event.window && transfer.property == event.atom
        }

        if event.state != Property::DELETE {
            return Ok(());
        }
        // Deleting the target property indicates that an INCR transfer should continue. Find that
        // transfer
        if let Some(transfer) = self
            .incremental
            .iter_mut()
            .find(|transfer| matches(transfer, event))
        {
            let done = transfer.continue_incremental(&self.connection)?;
            if done {
                debug!("INCR transfer finished");
                // Remove the transfer
                self.incremental
                    .retain(|transfer| !matches(transfer, event));
            }
        }
        Ok(())
    }
}

#[derive(Debug)]
struct ClipboardContents {
    owner_window: Window,
    data: Vec<(Atom, String, Rc<[u8]>)>,
}

impl ClipboardContents {
    fn new(
        conn: &XCBConnection,
        screen_num: usize,
        formats: &[ClipboardFormat],
    ) -> Result<Self, ReplyOrIdError> {
        // Send InternAtom requests for all formats
        let data = formats
            .iter()
            .map(|format| {
                conn.intern_atom(false, format.identifier.as_bytes())
                    .map(|cookie| (cookie, format))
            })
            .collect::<Result<Vec<_>, ConnectionError>>()?;
        // Get the replies for all InternAtom requests
        let data = data
            .into_iter()
            .map(|(cookie, format)| {
                cookie.reply().map(|reply| {
                    (
                        reply.atom,
                        format.identifier.to_string(),
                        format.data[..].into(),
                    )
                })
            })
            .collect::<Result<Vec<_>, ReplyError>>()?;

        let owner_window = conn.generate_id()?;
        conn.create_window(
            x11rb::COPY_DEPTH_FROM_PARENT,
            owner_window,
            conn.setup().roots[screen_num].root,
            0,
            0,
            1,
            1,
            0,
            WindowClass::INPUT_OUTPUT,
            x11rb::COPY_FROM_PARENT,
            &Default::default(),
        )?;
        Ok(Self { owner_window, data })
    }

    fn destroy(&mut self, conn: &XCBConnection) -> Result<(), ConnectionError> {
        conn.destroy_window(std::mem::replace(&mut self.owner_window, x11rb::NONE))?;
        Ok(())
    }
}

#[derive(Debug)]
struct IncrementalTransfer {
    requestor: Window,
    target: Atom,
    property: Atom,
    data: Rc<[u8]>,
    data_offset: usize,
}

impl IncrementalTransfer {
    fn new(
        conn: &XCBConnection,
        event: &SelectionRequestEvent,
        data: Rc<[u8]>,
        incr: Atom,
    ) -> Result<Self, ConnectionError> {
        // We need PropertyChange events on the window
        conn.change_window_attributes(
            event.requestor,
            &ChangeWindowAttributesAux::new().event_mask(EventMask::PROPERTY_CHANGE),
        )?;
        // Indicate that we are doing an INCR transfer
        let length = u32::try_from(data.len()).unwrap_or(u32::MAX);
        conn.change_property32(
            PropMode::REPLACE,
            event.requestor,
            event.property,
            incr,
            &[length],
        )?;
        Ok(Self {
            requestor: event.requestor,
            target: event.target,
            property: event.property,
            data,
            data_offset: 0,
        })
    }

    /// Continue an incremental transfer, returning true if the transfer is finished
    fn continue_incremental(&mut self, conn: &XCBConnection) -> Result<bool, ConnectionError> {
        let remaining = &self.data[self.data_offset..];
        let next_length = remaining.len().min(maximum_property_length(conn));
        conn.change_property8(
            PropMode::REPLACE,
            self.requestor,
            self.property,
            self.target,
            &remaining[..next_length],
        )?;
        self.data_offset += next_length;
        Ok(remaining.is_empty())
    }
}

struct WindowContainer<'a> {
    window: u32,
    conn: &'a XCBConnection,
}

impl<'a> WindowContainer<'a> {
    fn new(conn: &'a XCBConnection, screen_num: usize) -> Result<Self, ReplyOrIdError> {
        let window = conn.generate_id()?;
        conn.create_window(
            x11rb::COPY_DEPTH_FROM_PARENT,
            window,
            conn.setup().roots[screen_num].root,
            0,
            0,
            1,
            1,
            0,
            WindowClass::INPUT_OUTPUT,
            x11rb::COPY_FROM_PARENT,
            &Default::default(),
        )?;
        Ok(WindowContainer { window, conn })
    }
}

impl Drop for WindowContainer<'_> {
    fn drop(&mut self) {
        let _ = self.conn.destroy_window(self.window);
    }
}

fn maximum_property_length(connection: &XCBConnection) -> usize {
    let change_property_header_size = 24;
    // Apply an arbitrary limit to the property size to not stress the server too much
    let max_request_length = connection
        .maximum_request_bytes()
        .min(usize::from(u16::MAX));
    max_request_length - change_property_header_size
}

fn reject_transfer(
    conn: &XCBConnection,
    event: &SelectionRequestEvent,
) -> Result<(), ConnectionError> {
    let event = SelectionNotifyEvent {
        response_type: SELECTION_NOTIFY_EVENT,
        sequence: 0,
        requestor: event.requestor,
        selection: event.selection,
        target: event.target,
        property: x11rb::NONE,
        time: event.time,
    };
    conn.send_event(false, event.requestor, EventMask::NO_EVENT, event)?;
    Ok(())
}

/// Wait for an X11 event or return a timeout error if the given deadline is in the past.
fn wait_for_event_with_deadline(
    conn: &XCBConnection,
    deadline: Instant,
) -> Result<Event, ConnectionError> {
    use nix::poll::{poll, PollFd, PollFlags};
    use std::os::raw::c_int;
    use std::os::unix::io::AsRawFd;

    loop {
        // Is there already an event?
        if let Some(event) = conn.poll_for_event()? {
            return Ok(event);
        }

        // Are we past the deadline?
        let now = Instant::now();
        if deadline <= now {
            return Err(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "Timeout while waiting for selection owner to reply",
            )
            .into());
        }

        // Use poll() to wait for the socket to become readable.
        let mut poll_fds = [PollFd::new(conn.as_raw_fd(), PollFlags::POLLIN)];
        let poll_timeout = c_int::try_from(deadline.duration_since(now).as_millis())
            .unwrap_or(c_int::max_value() - 1)
            // The above rounds down, but we don't want to wake up to early, so add one
            .saturating_add(1);

        // Wait for the socket to be readable via poll() and try again
        match poll(&mut poll_fds, poll_timeout) {
            Ok(_) => {}
            Err(nix::errno::Errno::EINTR) => {}
            Err(e) => return Err(std::io::Error::from(e).into()),
        }
    }
}