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 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
|
use std::{
convert::TryInto,
fs::{self, File},
io::{BufRead, BufReader, Write},
os::unix::io::OwnedFd,
time::Duration,
};
use smithay_client_toolkit::reexports::calloop::{
EventLoop, LoopHandle, PostAction, RegistrationToken,
};
use smithay_client_toolkit::reexports::calloop_wayland_source::WaylandSource;
use smithay_client_toolkit::{
compositor::{CompositorHandler, CompositorState},
data_device_manager::{
data_device::{DataDevice, DataDeviceHandler},
data_offer::{DataOfferHandler, DragOffer, SelectionOffer},
data_source::{CopyPasteSource, DataSourceHandler, DragSource},
DataDeviceManagerState, WritePipe,
},
delegate_compositor, delegate_data_device, delegate_keyboard, delegate_output,
delegate_pointer, delegate_primary_selection, delegate_registry, delegate_seat, delegate_shm,
delegate_xdg_shell, delegate_xdg_window,
output::{OutputHandler, OutputState},
primary_selection::{
device::{PrimarySelectionDevice, PrimarySelectionDeviceHandler},
offer::PrimarySelectionOffer,
selection::{PrimarySelectionSource, PrimarySelectionSourceHandler},
PrimarySelectionManagerState,
},
registry::{ProvidesRegistryState, RegistryState},
registry_handlers,
seat::{
keyboard::{KeyEvent, KeyboardHandler, Keysym, Modifiers},
pointer::{PointerEvent, PointerEventKind, PointerHandler, BTN_LEFT},
Capability, SeatHandler, SeatState,
},
shell::{
xdg::{
window::{Window, WindowConfigure, WindowDecorations, WindowHandler},
XdgShell,
},
WaylandSurface,
},
shm::{
slot::{Buffer, SlotPool},
Shm, ShmHandler,
},
};
use wayland_client::{
globals::registry_queue_init,
protocol::{
wl_data_device::WlDataDevice,
wl_data_device_manager::DndAction,
wl_keyboard::{self, WlKeyboard},
wl_output,
wl_pointer::{self, WlPointer},
wl_seat::{self, WlSeat},
wl_shm, wl_surface,
},
Connection, QueueHandle,
};
use wayland_protocols::wp::primary_selection::zv1::client::{
zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
};
fn main() {
println!(
"Press c to set the selection, p to set primary selection, or click and drag on \
the window to drag and drop. Selection contents are printed automatically. Ctrl \
+ click and drag to start an internal drag."
);
env_logger::init();
// All Wayland apps start by connecting the compositor (server).
let conn = Connection::connect_to_env().unwrap();
// Enumerate the list of globals to get the protocols the server implements.
let (globals, event_queue) = registry_queue_init(&conn).unwrap();
let qh = event_queue.handle();
let mut event_loop: EventLoop<DataDeviceWindow> =
EventLoop::try_new().expect("Failed to initialize the event loop!");
let loop_handle = event_loop.handle();
WaylandSource::new(conn.clone(), event_queue).insert(loop_handle).unwrap();
// The compositor (not to be confused with the server which is commonly called the compositor) allows
// configuring surfaces to be presented.
let compositor = CompositorState::bind(&globals, &qh).expect("wl_compositor not available");
// For desktop platforms, the XDG shell is the standard protocol for creating desktop windows.
let xdg_shell = XdgShell::bind(&globals, &qh).expect("xdg shell is not available");
// Since we are not using the GPU in this example, we use wl_shm to allow software rendering to a buffer
// we share with the compositor process.
let shm = Shm::bind(&globals, &qh).expect("wl shm is not available.");
// A window is created from a surface.
let surface = compositor.create_surface(&qh);
// And then we can create the window.
let window = xdg_shell.create_window(surface, WindowDecorations::RequestServer, &qh);
// Configure the window, this may include hints to the compositor about the desired minimum size of the
// window, app id for WM identification, the window title, etc.
window.set_title("A wayland window");
// GitHub does not let projects use the `org.github` domain but the `io.github` domain is fine.
window.set_app_id("io.github.smithay.client-toolkit.SimpleWindow");
window.set_min_size(Some((256, 256)));
// In order for the window to be mapped, we need to perform an initial commit with no attached buffer.
// For more info, see WaylandSurface::commit
//
// The compositor will respond with an initial configure that we can then use to present to the window with
// the correct options.
window.commit();
let pool = SlotPool::new(256 * 256 * 4, &shm).expect("Failed to create pool");
// Create primary selection manager state and log if it's not present.
let primary_selection_manager_state = PrimarySelectionManagerState::bind(&globals, &qh).ok();
if primary_selection_manager_state.is_none() {
eprintln!("zwp_primary_selection_v1 is not available.");
}
let mut simple_window = DataDeviceWindow {
registry_state: RegistryState::new(&globals),
seat_state: SeatState::new(&globals, &qh),
output_state: OutputState::new(&globals, &qh),
shm_state: shm,
data_device_manager_state: DataDeviceManagerState::bind(&globals, &qh)
.expect("data device manager is not available"),
primary_selection_manager_state,
exit: false,
first_configure: true,
pool,
shift: None,
buffer: None,
window,
height: 256,
width: 256,
keyboard: None,
keyboard_focus: false,
modifiers: Modifiers::default(),
pointer: None,
seat_objects: Vec::new(),
copy_paste_sources: Vec::new(),
selection_sources: Vec::new(),
drag_sources: Vec::new(),
loop_handle: event_loop.handle(),
accept_counter: 0,
dnd_offers: Vec::new(),
selection_offers: Vec::new(),
primary_selection_offers: Vec::new(),
};
// We don't draw immediately, the configure will notify us when to first draw.
loop {
event_loop.dispatch(Duration::from_millis(30), &mut simple_window).unwrap();
if simple_window.exit {
println!("exiting example");
break;
}
}
}
struct DataDeviceWindow {
registry_state: RegistryState,
seat_state: SeatState,
output_state: OutputState,
shm_state: Shm,
data_device_manager_state: DataDeviceManagerState,
primary_selection_manager_state: Option<PrimarySelectionManagerState>,
exit: bool,
first_configure: bool,
pool: SlotPool,
width: u32,
height: u32,
shift: Option<u32>,
buffer: Option<Buffer>,
window: Window,
keyboard: Option<wl_keyboard::WlKeyboard>,
keyboard_focus: bool,
modifiers: Modifiers,
pointer: Option<wl_pointer::WlPointer>,
dnd_offers: Vec<(DragOffer, Vec<u8>, Option<RegistrationToken>)>,
selection_offers: Vec<(SelectionOffer, Vec<u8>, Option<RegistrationToken>)>,
primary_selection_offers: Vec<(PrimarySelectionOffer, Vec<u8>, Option<RegistrationToken>)>,
seat_objects: Vec<SeatObject>,
copy_paste_sources: Vec<CopyPasteSource>,
selection_sources: Vec<PrimarySelectionSource>,
drag_sources: Vec<(DragSource, bool)>,
loop_handle: LoopHandle<'static, DataDeviceWindow>,
accept_counter: u32,
}
impl CompositorHandler for DataDeviceWindow {
fn scale_factor_changed(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_surface: &wl_surface::WlSurface,
_new_factor: i32,
) {
// Not needed for this example.
}
fn transform_changed(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_surface: &wl_surface::WlSurface,
_new_transform: wl_output::Transform,
) {
// Not needed for this example.
}
fn frame(
&mut self,
conn: &Connection,
qh: &QueueHandle<Self>,
_surface: &wl_surface::WlSurface,
_time: u32,
) {
self.draw(conn, qh);
}
fn surface_enter(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_surface: &wl_surface::WlSurface,
_output: &wl_output::WlOutput,
) {
// Not needed for this example.
}
fn surface_leave(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_surface: &wl_surface::WlSurface,
_output: &wl_output::WlOutput,
) {
// Not needed for this example.
}
}
impl OutputHandler for DataDeviceWindow {
fn output_state(&mut self) -> &mut OutputState {
&mut self.output_state
}
fn new_output(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_output: wl_output::WlOutput,
) {
}
fn update_output(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_output: wl_output::WlOutput,
) {
}
fn output_destroyed(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_output: wl_output::WlOutput,
) {
}
}
impl WindowHandler for DataDeviceWindow {
fn request_close(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &Window) {
self.exit = true;
}
fn configure(
&mut self,
conn: &Connection,
qh: &QueueHandle<Self>,
_window: &Window,
configure: WindowConfigure,
_serial: u32,
) {
self.width = configure.new_size.0.map(|w| w.get()).unwrap_or(self.width);
self.height = configure.new_size.1.map(|h| h.get()).unwrap_or(self.height);
self.buffer = None;
// Initiate the first draw.
if self.first_configure {
self.first_configure = false;
self.draw(conn, qh);
}
}
}
impl SeatHandler for DataDeviceWindow {
fn seat_state(&mut self) -> &mut SeatState {
&mut self.seat_state
}
fn new_seat(&mut self, _: &Connection, _qh: &QueueHandle<Self>, _seat: wl_seat::WlSeat) {}
fn new_capability(
&mut self,
_conn: &Connection,
qh: &QueueHandle<Self>,
seat: wl_seat::WlSeat,
capability: Capability,
) {
let seat_object =
if let Some(seat_object) = self.seat_objects.iter_mut().find(|s| s.seat == seat) {
seat_object
} else {
// create the data device here for this seat
let data_device_manager = &self.data_device_manager_state;
let data_device = data_device_manager.get_data_device(qh, &seat);
let primary_device = self
.primary_selection_manager_state
.as_ref()
.map(|manager| manager.get_selection_device(qh, &seat));
self.seat_objects.push(SeatObject {
seat: seat.clone(),
keyboard: None,
pointer: None,
data_device,
primary_device,
});
self.seat_objects.last_mut().unwrap()
};
if capability == Capability::Keyboard && self.keyboard.is_none() {
let keyboard =
self.seat_state.get_keyboard(qh, &seat, None).expect("Failed to create keyboard");
self.keyboard = Some(keyboard.clone());
seat_object.keyboard.replace(keyboard);
}
if capability == Capability::Pointer && self.pointer.is_none() {
let pointer = self.seat_state.get_pointer(qh, &seat).expect("Failed to create pointer");
self.pointer = Some(pointer.clone());
seat_object.pointer.replace(pointer);
}
}
fn remove_capability(
&mut self,
_conn: &Connection,
_: &QueueHandle<Self>,
_: wl_seat::WlSeat,
capability: Capability,
) {
if capability == Capability::Keyboard && self.keyboard.is_some() {
println!("Unset keyboard capability");
self.keyboard.take().unwrap().release();
}
if capability == Capability::Pointer && self.pointer.is_some() {
println!("Unset pointer capability");
self.pointer.take().unwrap().release();
}
}
fn remove_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat) {}
}
impl KeyboardHandler for DataDeviceWindow {
fn enter(
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
_: &wl_keyboard::WlKeyboard,
surface: &wl_surface::WlSurface,
_: u32,
_: &[u32],
_keysyms: &[Keysym],
) {
if self.window.wl_surface() == surface {
self.keyboard_focus = true;
}
}
fn leave(
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
_: &wl_keyboard::WlKeyboard,
surface: &wl_surface::WlSurface,
_: u32,
) {
if self.window.wl_surface() == surface {
self.keyboard_focus = false;
}
}
fn press_key(
&mut self,
_conn: &Connection,
qh: &QueueHandle<Self>,
kbd: &wl_keyboard::WlKeyboard,
serial: u32,
event: KeyEvent,
) {
match event.utf8 {
Some(s) if s.to_lowercase() == "c" => {
println!("Creating copy paste source and setting selection...");
if let Some(data_device) = self.seat_objects.iter().find_map(|seat| {
if seat.keyboard.as_ref() == Some(kbd) {
Some(&seat.data_device)
} else {
None
}
}) {
let source = self
.data_device_manager_state
.create_copy_paste_source(qh, SUPPORTED_MIME_TYPES.to_vec());
source.set_selection(data_device, serial);
self.copy_paste_sources.push(source);
}
}
Some(s) if s.to_lowercase() == "p" => {
println!("Creating primary selection source and setting selection...");
if let Some(primary_selection_device) = self.seat_objects.iter().find_map(|seat| {
if seat.keyboard.as_ref() == Some(kbd) {
seat.primary_device.as_ref()
} else {
None
}
}) {
let source = self
.primary_selection_manager_state
.as_ref()
.unwrap()
.create_selection_source(qh, SUPPORTED_MIME_TYPES.to_vec());
source.set_selection(primary_selection_device, serial);
self.selection_sources.push(source);
}
}
_ => {}
};
}
fn release_key(
&mut self,
_: &Connection,
_qh: &QueueHandle<Self>,
_kbd: &wl_keyboard::WlKeyboard,
_serial: u32,
_event: KeyEvent,
) {
}
fn update_modifiers(
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
_: &wl_keyboard::WlKeyboard,
_serial: u32,
modifiers: Modifiers,
_layout: u32,
) {
self.modifiers = modifiers;
}
}
impl PointerHandler for DataDeviceWindow {
fn pointer_frame(
&mut self,
_conn: &Connection,
qh: &QueueHandle<Self>,
pointer: &wl_pointer::WlPointer,
events: &[PointerEvent],
) {
use PointerEventKind::*;
for event in events {
// Ignore events for other surfaces
if self.window.wl_surface() != &event.surface {
continue;
}
let surface = event.surface.clone();
match event.kind {
Press { button, serial, .. } if button == BTN_LEFT && self.modifiers.ctrl => {
if let Some(seat) =
self.seat_objects.iter().find(|seat| seat.pointer.as_ref() == Some(pointer))
{
println!("Starting an internal drag...");
DragSource::start_internal_drag(
&seat.data_device,
self.window.wl_surface(),
None,
serial,
);
}
}
Press { button, serial, .. } if button == BTN_LEFT => {
if let Some(seat) =
self.seat_objects.iter().find(|seat| seat.pointer.as_ref() == Some(pointer))
{
println!("Creating drag and drop source and starting drag...");
self.shift = self.shift.xor(Some(0));
let source = self.data_device_manager_state.create_drag_and_drop_source(
qh,
SUPPORTED_MIME_TYPES.to_vec(),
DndAction::Copy,
);
source.start_drag(&seat.data_device, &surface, None, serial);
self.drag_sources.push((source, false));
}
}
Motion { .. } => {}
_ => {}
}
}
}
}
impl ShmHandler for DataDeviceWindow {
fn shm_state(&mut self) -> &mut Shm {
&mut self.shm_state
}
}
impl DataDeviceWindow {
pub fn draw(&mut self, _conn: &Connection, qh: &QueueHandle<Self>) {
let width = self.width;
let height = self.height;
let stride = self.width as i32 * 4;
let buffer = self.buffer.get_or_insert_with(|| {
self.pool
.create_buffer(width as i32, height as i32, stride, wl_shm::Format::Argb8888)
.expect("create buffer")
.0
});
let canvas = match self.pool.canvas(buffer) {
Some(canvas) => canvas,
None => {
// This should be rare, but if the compositor has not released the previous
// buffer, we need double-buffering.
let (second_buffer, canvas) = self
.pool
.create_buffer(
self.width as i32,
self.height as i32,
stride,
wl_shm::Format::Argb8888,
)
.expect("create buffer");
*buffer = second_buffer;
canvas
}
};
// Draw to the window:
{
let shift = self.shift.unwrap_or(0);
canvas.chunks_exact_mut(4).enumerate().for_each(|(index, chunk)| {
let x = ((index + shift as usize) % width as usize) as u32;
let y = (index / width as usize) as u32;
let a = 0xFF;
let r = u32::min(((width - x) * 0xFF) / width, ((height - y) * 0xFF) / height);
let g = u32::min((x * 0xFF) / width, ((height - y) * 0xFF) / height);
let b = u32::min(((width - x) * 0xFF) / width, (y * 0xFF) / height);
let color = (a << 24) + (r << 16) + (g << 8) + b;
let array: &mut [u8; 4] = chunk.try_into().unwrap();
*array = color.to_le_bytes();
});
if let Some(shift) = &mut self.shift {
*shift = (*shift + 1) % width;
}
}
// Damage the entire window
self.window.wl_surface().damage_buffer(0, 0, self.width as i32, self.height as i32);
// Request our next frame
self.window.wl_surface().frame(qh, self.window.wl_surface().clone());
// Attach and commit to present.
buffer.attach_to(self.window.wl_surface()).expect("buffer attach");
self.window.wl_surface().commit();
}
}
impl DataDeviceHandler for DataDeviceWindow {
fn enter(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
wl_data_device: &WlDataDevice,
x: f64,
y: f64,
_surface: &wl_surface::WlSurface,
) {
println!("Data device enter x: {x:.2} y: {y:.2}");
let data_device = &self
.seat_objects
.iter()
.find(|seat| seat.data_device.inner() == wl_data_device)
.unwrap()
.data_device;
let Some(drag_offer) = data_device.data().drag_offer() else {
println!("Internal drag");
return;
};
// Accept the first mime type we support.
if let Some(mime) = drag_offer.with_mime_types(|mime_types| {
for mime in mime_types {
if SUPPORTED_MIME_TYPES.contains(&mime.as_str()) {
return Some(mime.clone());
}
}
None
}) {
drag_offer.accept_mime_type(0, Some(mime));
}
// Accept the action now just in case
drag_offer.set_actions(DndAction::Copy, DndAction::Copy);
}
fn leave(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, _data_device: &WlDataDevice) {
println!("Data device leave event");
}
fn motion(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_wl_data_device: &WlDataDevice,
x: f64,
y: f64,
) {
println!("Data Device motion event x: {:.2} y: {:.2}", x, y);
}
fn selection(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
wl_data_device: &WlDataDevice,
) {
let data_device = &self
.seat_objects
.iter()
.find(|seat| seat.data_device.inner() == wl_data_device)
.unwrap()
.data_device;
if let Some(offer) = data_device.data().selection_offer() {
offer.with_mime_types(|mimes| {
println!("Received selection offer with mime types:");
for mime in mimes {
println!("\t{mime}");
}
});
self.selection_offers.push((offer.clone(), Vec::new(), None));
let cur_offer = self.selection_offers.last_mut().unwrap();
let mime_type = match offer.with_mime_types(pick_mime) {
Some(mime_type) => mime_type,
None => return,
};
let read_pipe = match offer.receive(mime_type) {
Ok(p) => p,
Err(e) => {
eprintln!("Failed to receive the offer: {:?}", e);
return;
}
};
let cur_offer_ = cur_offer.0.clone();
if let Ok(token) = self.loop_handle.insert_source(read_pipe, move |_, f, state| {
let offer = match state.selection_offers.iter().position(|o| o.0 == cur_offer_) {
Some(s) => state.selection_offers.remove(s),
None => return PostAction::Continue,
};
let (offer, mut data, token) = match offer {
(o, d, Some(t)) => (o, d, t),
_ => return PostAction::Continue,
};
// SAFETY: it's safe as long as we don't close the underlying file.
let f: &mut fs::File = unsafe { f.get_mut() };
let mut reader = BufReader::new(f);
let consumed = match reader.fill_buf() {
Ok(buf) => {
if buf.is_empty() {
println!("selection data: {:?}", String::from_utf8(data.clone()));
state.selection_offers.push((offer, Vec::new(), None));
return PostAction::Remove;
} else {
data.extend_from_slice(buf);
state.selection_offers.push((offer, data, Some(token)));
}
buf.len()
}
Err(e) if matches!(e.kind(), std::io::ErrorKind::Interrupted) => {
state.selection_offers.push((offer, data, Some(token)));
return PostAction::Continue;
}
Err(e) => {
eprintln!("Error reading selection data: {}", e);
state.selection_offers.push((offer, Vec::new(), None));
return PostAction::Remove;
}
};
reader.consume(consumed);
PostAction::Continue
}) {
cur_offer.2 = Some(token);
}
}
}
fn drop_performed(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
wl_data_device: &WlDataDevice,
) {
let data_device = &self
.seat_objects
.iter()
.find(|seat| seat.data_device.inner() == wl_data_device)
.unwrap()
.data_device;
if let Some(offer) = data_device.data().drag_offer() {
println!("Data device dropped event: {offer:?}");
self.dnd_offers.push((offer.clone(), Vec::new(), None));
let cur_offer = self.dnd_offers.last_mut().unwrap();
let mime_type = match offer.with_mime_types(pick_mime) {
Some(mime) => mime,
None => return,
};
let read_pipe = match cur_offer.0.receive(mime_type.clone()) {
Ok(p) => p,
Err(e) => {
eprintln!("Failed to receive the offer: {:?}", e);
return;
}
};
self.accept_counter += 1;
cur_offer.0.accept_mime_type(self.accept_counter, Some(mime_type));
cur_offer.0.set_actions(DndAction::Copy, DndAction::Copy);
let cur_offer_ = cur_offer.0.clone();
match self.loop_handle.insert_source(read_pipe, move |_, f, state| {
let offer = match state.dnd_offers.iter().position(|o| o.0 == cur_offer_) {
Some(s) => state.dnd_offers.remove(s),
None => return PostAction::Continue,
};
let (offer, mut data, token) = match offer {
(o, d, Some(t)) => (o, d, t),
_ => return PostAction::Continue,
};
// SAFETY: it's safe as long as we don't close the underlying file.
let f: &mut fs::File = unsafe { f.get_mut() };
let mut reader = BufReader::new(f);
let consumed = match reader.fill_buf() {
Ok(buf) => {
if buf.is_empty() {
println!("Dropped data: {:?}", String::from_utf8(data.clone()));
offer.finish();
offer.destroy();
state.dnd_offers.push((offer, Vec::new(), None));
return PostAction::Remove;
} else {
data.extend_from_slice(buf);
state.dnd_offers.push((offer, data, Some(token)));
}
buf.len()
}
Err(e) if matches!(e.kind(), std::io::ErrorKind::Interrupted) => {
state.dnd_offers.push((offer, data, Some(token)));
return PostAction::Continue;
}
Err(e) => {
eprintln!("Error reading dropped data: {}", e);
offer.finish();
offer.destroy();
return PostAction::Remove;
}
};
reader.consume(consumed);
PostAction::Continue
}) {
Ok(token) => {
cur_offer.2 = Some(token);
}
Err(err) => {
eprintln!("{err}");
cur_offer.0.finish();
}
}
} else {
println!("Internal drop performed");
}
}
}
impl DataOfferHandler for DataDeviceWindow {
fn source_actions(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
offer: &mut DragOffer,
actions: wayland_client::protocol::wl_data_device_manager::DndAction,
) {
println!("Source actions: {actions:?}");
offer.set_actions(DndAction::Copy, DndAction::Copy);
}
fn selected_action(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_offer: &mut DragOffer,
actions: wayland_client::protocol::wl_data_device_manager::DndAction,
) {
// In this small example there isn't much to do here.
// Normal applications might track the action and then handling each differently.
println!("Selected action: {actions:?}");
}
}
impl DataSourceHandler for DataDeviceWindow {
fn accept_mime(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_source: &wayland_client::protocol::wl_data_source::WlDataSource,
mime: Option<String>,
) {
println!("Source mime type: {mime:?} was accepted");
}
fn send_request(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
source: &wayland_client::protocol::wl_data_source::WlDataSource,
mime: String,
write_pipe: WritePipe,
) {
let fd = OwnedFd::from(write_pipe);
if self
.copy_paste_sources
.iter_mut()
.any(|s| s.inner() == source && SUPPORTED_MIME_TYPES.contains(&mime.as_str()))
{
let mut f = File::from(fd);
writeln!(f, "Copied from selection via sctk").unwrap();
} else if self
.drag_sources
.iter_mut()
.any(|s| s.0.inner() == source && SUPPORTED_MIME_TYPES.contains(&mime.as_str()) && s.1)
{
let mut f = File::from(fd);
writeln!(f, "Dropped via sctk").unwrap();
}
}
fn cancelled(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
source: &wayland_client::protocol::wl_data_source::WlDataSource,
) {
self.drag_sources.retain(|s| s.0.inner() != source);
source.destroy();
}
fn dnd_dropped(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_source: &wayland_client::protocol::wl_data_source::WlDataSource,
) {
println!("Drop performed");
}
fn dnd_finished(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
source: &wayland_client::protocol::wl_data_source::WlDataSource,
) {
println!("Finished");
self.drag_sources.retain(|s| s.0.inner() != source);
source.destroy();
}
fn action(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
source: &wayland_client::protocol::wl_data_source::WlDataSource,
action: wayland_client::protocol::wl_data_device_manager::DndAction,
) {
if let Some(source) = self.drag_sources.iter_mut().find(|s| s.0.inner() == source) {
source.1 = action.contains(DndAction::Copy);
}
}
}
impl PrimarySelectionDeviceHandler for DataDeviceWindow {
fn selection(
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
primary_device: &ZwpPrimarySelectionDeviceV1,
) {
let primary_device = self
.seat_objects
.iter()
.find(|seat| seat.primary_device.as_ref().map(|p| p.inner()) == Some(primary_device))
.unwrap()
.primary_device
.as_ref()
.unwrap();
if let Some(offer) = primary_device.data().selection_offer() {
offer.with_mime_types(|mimes| {
println!("Received primary selection offer with mime types:");
for mime in mimes {
println!("\t{mime}");
}
});
// Add a new offer.
self.primary_selection_offers.push((offer.clone(), Vec::new(), None));
let mime_type = match offer.with_mime_types(pick_mime) {
Some(mime) => mime,
None => return,
};
let read_pipe = match offer.receive(mime_type) {
Ok(p) => p,
Err(e) => {
eprintln!("Failed to receive the offer: {:?}", e);
return;
}
};
if let Ok(token) = self.loop_handle.insert_source(read_pipe, move |_, f, state| {
let offer = match state.primary_selection_offers.iter().position(|of| of.0 == offer)
{
Some(s) => state.primary_selection_offers.remove(s),
None => return PostAction::Continue,
};
let (offer, mut data, token) = match offer {
(o, d, Some(t)) => (o, d, t),
_ => return PostAction::Continue,
};
// SAFETY: it's safe as long as we don't close the underlying file.
let f: &mut fs::File = unsafe { f.get_mut() };
let mut reader = BufReader::new(f);
let consumed = match reader.fill_buf() {
Ok(buf) => {
if buf.is_empty() {
println!(
"primary selection data: {:?}",
String::from_utf8(data.clone())
);
state.primary_selection_offers.push((offer, Vec::new(), None));
return PostAction::Remove;
} else {
data.extend_from_slice(buf);
state.primary_selection_offers.push((offer, data, Some(token)));
}
buf.len()
}
Err(e) if matches!(e.kind(), std::io::ErrorKind::Interrupted) => {
state.primary_selection_offers.push((offer, data, Some(token)));
return PostAction::Continue;
}
Err(e) => {
eprintln!("Error reading selection data: {}", e);
state.primary_selection_offers.push((offer, Vec::new(), None));
return PostAction::Remove;
}
};
reader.consume(consumed);
PostAction::Continue
}) {
self.primary_selection_offers.last_mut().unwrap().2 = Some(token);
}
}
}
}
impl PrimarySelectionSourceHandler for DataDeviceWindow {
fn send_request(
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
source: &ZwpPrimarySelectionSourceV1,
mime: String,
write_pipe: WritePipe,
) {
let fd = OwnedFd::from(write_pipe);
if self
.selection_sources
.iter_mut()
.any(|s| s.inner() == source && SUPPORTED_MIME_TYPES.contains(&mime.as_str()))
{
let mut f = File::from(fd);
writeln!(f, "Copied from primary selection via sctk").unwrap();
}
}
fn cancelled(
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
source: &ZwpPrimarySelectionSourceV1,
) {
self.selection_sources.retain(|s| s.inner() == source);
}
}
impl ProvidesRegistryState for DataDeviceWindow {
fn registry(&mut self) -> &mut RegistryState {
&mut self.registry_state
}
registry_handlers![OutputState, SeatState];
}
struct SeatObject {
seat: WlSeat,
keyboard: Option<WlKeyboard>,
pointer: Option<WlPointer>,
data_device: DataDevice,
primary_device: Option<PrimarySelectionDevice>,
}
delegate_compositor!(DataDeviceWindow);
delegate_output!(DataDeviceWindow);
delegate_shm!(DataDeviceWindow);
delegate_seat!(DataDeviceWindow);
delegate_keyboard!(DataDeviceWindow);
delegate_pointer!(DataDeviceWindow);
delegate_xdg_shell!(DataDeviceWindow);
delegate_xdg_window!(DataDeviceWindow);
delegate_data_device!(DataDeviceWindow);
delegate_primary_selection!(DataDeviceWindow);
delegate_registry!(DataDeviceWindow);
const SUPPORTED_MIME_TYPES: &[&str; 6] = &[
"text/plain;charset=utf-8",
"text/plain;charset=UTF-8",
"UTF8_STRING",
"STRING",
"text/plain",
"TEXT",
];
fn pick_mime(mime_types: &[String]) -> Option<String> {
for mime in mime_types {
if SUPPORTED_MIME_TYPES.contains(&mime.as_str()) {
return Some(mime.clone());
}
}
None
}
|