1// The window on Linux, through Wayland: libwayland-client, loaded while2// running, speaks the protocols wayland_protocol.alloy reads from their3// XML, one dispatcher receiving every event. The window is an xdg-shell4// toplevel, decorated by the compositor where it offers to5// (xdg-decoration; GNOME does not), at the compositor's fractional scale6// where it gives one (fractional-scale and viewporter), else its integer7// one. Frames `present` gives go through shared memory, a GPU surface8// drawing into the wl_surface itself.9// Input methods speak through text-input-unstable-v3, which GNOME and KDE10// implement.1112import std::ffi;13import std::option;14import std::dispose;15import std::string;16import std::vector;17import std::io;18import std::time;1920import window;21import loading;22import xkb;23import posix;24import portal;25import atspi;26import wayland_protocol;2728// The interfaces the window speaks, as indexes into INTERFACES.29type Interface = enum : u32 {30 Display = find_interface(&"wl_display"),31 Registry = find_interface(&"wl_registry"),32 Callback = find_interface(&"wl_callback"),33 Compositor = find_interface(&"wl_compositor"),34 Shm = find_interface(&"wl_shm"),35 ShmPool = find_interface(&"wl_shm_pool"),36 Buffer = find_interface(&"wl_buffer"),37 Surface = find_interface(&"wl_surface"),38 Seat = find_interface(&"wl_seat"),39 Pointer = find_interface(&"wl_pointer"),40 Keyboard = find_interface(&"wl_keyboard"),41 WmBase = find_interface(&"xdg_wm_base"),42 XdgSurface = find_interface(&"xdg_surface"),43 Toplevel = find_interface(&"xdg_toplevel"),44 DecorationManager = find_interface(&"zxdg_decoration_manager_v1"),45 Decoration = find_interface(&"zxdg_toplevel_decoration_v1"),46 Viewporter = find_interface(&"wp_viewporter"),47 Viewport = find_interface(&"wp_viewport"),48 FractionalManager = find_interface(&"wp_fractional_scale_manager_v1"),49 FractionalScale = find_interface(&"wp_fractional_scale_v1"),50 CursorManager = find_interface(&"wp_cursor_shape_manager_v1"),51 CursorDevice = find_interface(&"wp_cursor_shape_device_v1"),52 TextInputManager = find_interface(&"zwp_text_input_manager_v3"),53 TextInput = find_interface(&"zwp_text_input_v3"),54 DataDeviceManager = find_interface(&"wl_data_device_manager"),55 DataDevice = find_interface(&"wl_data_device"),56 DataSource = find_interface(&"wl_data_source"),57 DataOffer = find_interface(&"wl_data_offer")58};5960// The requests the window sends, each tagged with its interface's index61// in the high 16 bits and its opcode in the low.62type Request = enum : u32 {63 GetRegistry = sent(Interface::Display, &"get_registry"),64 Bind = sent(Interface::Registry, &"bind"),65 CreateSurface = sent(Interface::Compositor, &"create_surface"),66 CreatePool = sent(Interface::Shm, &"create_pool"),67 CreateBuffer = sent(Interface::ShmPool, &"create_buffer"),68 PoolDestroy = sent(Interface::ShmPool, &"destroy"),69 BufferDestroy = sent(Interface::Buffer, &"destroy"),70 SurfaceDestroy = sent(Interface::Surface, &"destroy"),71 Attach = sent(Interface::Surface, &"attach"),72 Frame = sent(Interface::Surface, &"frame"),73 Commit = sent(Interface::Surface, &"commit"),74 SetBufferScale = sent(Interface::Surface, &"set_buffer_scale"),75 DamageBuffer = sent(Interface::Surface, &"damage_buffer"),76 GetPointer = sent(Interface::Seat, &"get_pointer"),77 GetKeyboard = sent(Interface::Seat, &"get_keyboard"),78 Pong = sent(Interface::WmBase, &"pong"),79 GetXdgSurface = sent(Interface::WmBase, &"get_xdg_surface"),80 XdgSurfaceDestroy = sent(Interface::XdgSurface, &"destroy"),81 GetToplevel = sent(Interface::XdgSurface, &"get_toplevel"),82 AckConfigure = sent(Interface::XdgSurface, &"ack_configure"),83 ToplevelDestroy = sent(Interface::Toplevel, &"destroy"),84 SetTitle = sent(Interface::Toplevel, &"set_title"),85 SetAppId = sent(Interface::Toplevel, &"set_app_id"),86 SetMinSize = sent(Interface::Toplevel, &"set_min_size"),87 SetMaxSize = sent(Interface::Toplevel, &"set_max_size"),88 GetToplevelDecoration = sent(Interface::DecorationManager, &"get_toplevel_decoration"),89 SetMode = sent(Interface::Decoration, &"set_mode"),90 GetViewport = sent(Interface::Viewporter, &"get_viewport"),91 SetDestination = sent(Interface::Viewport, &"set_destination"),92 GetFractionalScale = sent(Interface::FractionalManager, &"get_fractional_scale"),93 GetCursorDevice = sent(Interface::CursorManager, &"get_pointer"),94 SetShape = sent(Interface::CursorDevice, &"set_shape"),95 GetTextInput = sent(Interface::TextInputManager, &"get_text_input"),96 TextEnable = sent(Interface::TextInput, &"enable"),97 TextDisable = sent(Interface::TextInput, &"disable"),98 SetContentType = sent(Interface::TextInput, &"set_content_type"),99 SetCursorRectangle = sent(Interface::TextInput, &"set_cursor_rectangle"),100 TextCommit = sent(Interface::TextInput, &"commit"),101 CreateDataSource = sent(Interface::DataDeviceManager, &"create_data_source"),102 GetDataDevice = sent(Interface::DataDeviceManager, &"get_data_device"),103 SourceOffer = sent(Interface::DataSource, &"offer"),104 SourceDestroy = sent(Interface::DataSource, &"destroy"),105 SetSelection = sent(Interface::DataDevice, &"set_selection"),106 OfferReceive = sent(Interface::DataOffer, &"receive"),107 OfferDestroy = sent(Interface::DataOffer, &"destroy"),108 OfferAccept = sent(Interface::DataOffer, &"accept"),109 OfferFinish = sent(Interface::DataOffer, &"finish"),110 OfferSetActions = sent(Interface::DataOffer, &"set_actions")111};112113// The events the window handles, as indexes into MESSAGES.114type WaylandEvent = enum : u32 {115 Global = received(Interface::Registry, &"global"),116 Done = received(Interface::Callback, &"done"),117 Release = received(Interface::Buffer, &"release"),118 PreferredBufferScale = received(Interface::Surface, &"preferred_buffer_scale"),119 Capabilities = received(Interface::Seat, &"capabilities"),120 PointerEnter = received(Interface::Pointer, &"enter"),121 PointerLeave = received(Interface::Pointer, &"leave"),122 PointerMotion = received(Interface::Pointer, &"motion"),123 PointerButton = received(Interface::Pointer, &"button"),124 PointerAxis = received(Interface::Pointer, &"axis"),125 PointerFrame = received(Interface::Pointer, &"frame"),126 PointerAxisValue120 = received(Interface::Pointer, &"axis_value120"),127 Keymap = received(Interface::Keyboard, &"keymap"),128 KeyboardEnter = received(Interface::Keyboard, &"enter"),129 KeyboardLeave = received(Interface::Keyboard, &"leave"),130 Key = received(Interface::Keyboard, &"key"),131 Modifiers = received(Interface::Keyboard, &"modifiers"),132 RepeatInfo = received(Interface::Keyboard, &"repeat_info"),133 Ping = received(Interface::WmBase, &"ping"),134 XdgConfigure = received(Interface::XdgSurface, &"configure"),135 ToplevelConfigure = received(Interface::Toplevel, &"configure"),136 ToplevelClose = received(Interface::Toplevel, &"close"),137 PreferredScale = received(Interface::FractionalScale, &"preferred_scale"),138 TextEnter = received(Interface::TextInput, &"enter"),139 TextLeave = received(Interface::TextInput, &"leave"),140 PreeditString = received(Interface::TextInput, &"preedit_string"),141 CommitString = received(Interface::TextInput, &"commit_string"),142 TextDone = received(Interface::TextInput, &"done"),143 DataOfferMade = received(Interface::DataDevice, &"data_offer"),144 Selection = received(Interface::DataDevice, &"selection"),145 Offered = received(Interface::DataOffer, &"offer"),146 SourceSend = received(Interface::DataSource, &"send"),147 SourceCancelled = received(Interface::DataSource, &"cancelled"),148 DragEnter = received(Interface::DataDevice, &"enter"),149 DragLeave = received(Interface::DataDevice, &"leave"),150 DragMotion = received(Interface::DataDevice, &"motion"),151 DragDrop = received(Interface::DataDevice, &"drop")152};153154fn sent(owner: Interface, name: &[u8]) -> u32 {155 return (owner to u32) << 16 | request(owner to u32, &name);156}157158fn received(owner: Interface, name: &[u8]) -> u32 => event(owner to u32, &name);159160fn opcode(self r: &Request) -> u32 => (r to u32) & 0xFFFF;161162// The text types the clipboard offers and takes, the preferred first.163const TEXT_TYPES: [&[u8] : 3] = [&"text/plain;charset=utf-8", &"UTF8_STRING", &"text/plain"];164165// A global the window binds, at most at the version the code here166// handles.167type Global = struct {168 kind: Interface,169 version: u32,170};171172const GLOBALS: [Global : 10] = [173 Global { .kind = Interface::Compositor, .version = 6 },174 Global { .kind = Interface::Shm, .version = 1 },175 Global { .kind = Interface::Seat, .version = 8 },176 Global { .kind = Interface::WmBase, .version = 2 },177 Global { .kind = Interface::DecorationManager, .version = 1 },178 Global { .kind = Interface::Viewporter, .version = 1 },179 Global { .kind = Interface::FractionalManager, .version = 1 },180 Global { .kind = Interface::CursorManager, .version = 1 },181 Global { .kind = Interface::TextInputManager, .version = 1 },182 Global { .kind = Interface::DataDeviceManager, .version = 3 }183];184185type Dispatcher = extern (c_pointer, c_pointer, u32, c_pointer, c_pointer) -> i32;186187type Client = struct {188 display_connect: extern (c_pointer) -> c_pointer,189 display_disconnect: extern (c_pointer),190 display_get_fd: extern (c_pointer) -> i32,191 display_dispatch_pending: extern (c_pointer) -> i32,192 display_prepare_read: extern (c_pointer) -> i32,193 display_read_events: extern (c_pointer) -> i32,194 display_cancel_read: extern (c_pointer),195 display_flush: extern (c_pointer) -> i32,196 display_roundtrip: extern (c_pointer) -> i32,197 proxy_marshal_array_flags: extern (c_pointer, u32, c_pointer, u32, u32, c_pointer) -> c_pointer,198 proxy_add_dispatcher: extern (c_pointer, Dispatcher, c_pointer, c_pointer) -> i32,199 proxy_get_version: extern (c_pointer) -> u32,200 proxy_destroy: extern (c_pointer),201};202203fn Client::load(library: &Library) -> Client {204 return Client {205 .display_connect = function(&library, &"wl_display_connect"),206 .display_disconnect = function(&library, &"wl_display_disconnect"),207 .display_get_fd = function(&library, &"wl_display_get_fd"),208 .display_dispatch_pending = function(&library, &"wl_display_dispatch_pending"),209 .display_prepare_read = function(&library, &"wl_display_prepare_read"),210 .display_read_events = function(&library, &"wl_display_read_events"),211 .display_cancel_read = function(&library, &"wl_display_cancel_read"),212 .display_flush = function(&library, &"wl_display_flush"),213 .display_roundtrip = function(&library, &"wl_display_roundtrip"),214 .proxy_marshal_array_flags = function(&library, &"wl_proxy_marshal_array_flags"),215 .proxy_add_dispatcher = function(&library, &"wl_proxy_add_dispatcher"),216 .proxy_get_version = function(&library, &"wl_proxy_get_version"),217 .proxy_destroy = function(&library, &"wl_proxy_destroy")218 };219}220221// A shared-memory buffer the window's pixels go through.222type Buffer = struct {223 proxy: c_pointer,224 pool: c_pointer,225 fd: i32,226 memory: c_pointer,227 bytes: u64,228 size: Size,229 busy: bool, // the compositor has not released it yet230};231232pub type Wayland : Disposable = struct {233 client: Client,234 wake: Option<i32>, // the eventfd other tasks wake the loop through235 protocol: Protocol,236 keys: Option<Keyboard>,237 window: Window,238 handler: |&| (&var Window, &Event),239 resizable: bool,240 display: c_pointer,241 registry: c_pointer = 0,242 // the globals, 0 for those the compositor lacks243 globals: [c_pointer : 10] = [0 : 10],244 seat_version: u32 = 0,245 // the window's objects246 surface: c_pointer = 0,247 xdg_surface: c_pointer = 0,248 toplevel: c_pointer = 0,249 viewport: c_pointer = 0,250 fractional: c_pointer = 0,251 pointer: c_pointer = 0,252 keyboard: c_pointer = 0,253 cursor: c_pointer = 0,254 pointer_serial: u64 = 0, // of the pointer's last entering, which setting a cursor names255 pointer_inside: bool = false,256 frame_callback: c_pointer = 0,257 text_input: c_pointer = 0,258 buffers: Vector<Buffer> = Vector<Buffer>::empty(),259 // its state260 logical: Size,261 // the size the compositor proposes, 0 for the window's choice262 pending: Size = Size { .width = 0, .height = 0 },263 configured: bool = false,264 integer_scale: i32 = 1,265 fractional_scale: Option<u32> = ::None, // in 120ths, once the compositor gives one266 shown_scale: i32 = 1,267 shown_destination: Size = Size { .width = 0, .height = 0 },268 attached: bool = false,269 needs_redraw: bool = false,270 wants_frame: bool = false,271 // input272 position: Point = Point { .x = 0.0, .y = 0.0 },273 motion: bool = false, // a move not yet delivered, which the pointer's frame ends274 scroll: Point = Point { .x = 0.0, .y = 0.0 },275 scroll_lines: Point = Point { .x = 0.0, .y = 0.0 },276 wheel: bool = false,277 scrolled: bool = false,278 repeat_rate: i32 = 25,279 repeat_delay: i32 = 600,280 repeat: Option<Repeat> = ::None,281 start: Instant,282 failed: bool = false,283 // the input method: whether the window has its focus and it is on,284 // what the next done event applies, and whether a composition shows285 text_entered: bool = false,286 text_enabled: bool = false,287 text_secret: bool = false, // a password's content type sent since enabling288 pending_preedit: Preedit,289 pending_commit: String = String::empty(),290 composing: bool = false,291 // the clipboard: the data device, the source holding what the window292 // copied, the offers the compositor made, the selection's, and a293 // paste being read294 data_device: c_pointer = 0,295 input_serial: u64 = 0, // of the last key or button, which a copy names296 source: c_pointer = 0,297 copied: String = String::empty(),298 offers: Vector<Offer> = Vector<Offer>::empty(),299 selection: c_pointer = 0,300 paste: Option<Transfer> = ::None,301 // something dragged over the window: its offer and where, and a drop302 // being read303 drag_offer: c_pointer = 0,304 drag_position: Point = Point { .x = 0.0, .y = 0.0 },305 drop: Option<Transfer> = ::None,306 // file dialogs and the wish for less motion through the desktop307 // portal, and screen readers through AT-SPI when the session's308 // accessibility is on, once installed (window.alloy's Start)309 portal: Portal = Portal::empty(),310 atspi: Option<Atspi> = ::None,311 parts: Parts = Parts {},312};313314// What the loop calls of what a program installed, set as each starts,315// so that a program installing nothing links none of it: AT-SPI's bus316// read and given the handler's requests, the portal's bus read (its317// settings, and with files its dialogs' answers), the dialogs asked for,318// things dragged over the window and a drop's pipe read.319type Parts = struct {320 atspi: Option<(&var Wayland)> = ::None,321 access: Option<(&var Wayland, &var Requests)> = ::None,322 portal: Option<(&var Wayland)> = ::None,323 dialogs: Option<(&var Wayland, &var Requests)> = ::None,324 drag: Option<(&var Wayland, WaylandEvent, &[u64])> = ::None,325 dropped: Option<(&var Wayland)> = ::None,326};327328// A key held, repeating.329type Repeat = struct {330 code: u32,331 at: f64, // when it next repeats, in milliseconds since start332};333334// What another program offers: the text type it has, as an index into335// TEXT_TYPES, and whether it has files (text/uri-list).336type Offer = struct {337 proxy: c_pointer,338 text_type: Option<u64>,339 uris: bool,340};341342// What another program sends through a pipe the loop polls: a paste, or343// a drop of files or text.344type Transfer = struct {345 fd: i32,346 bytes: Vector<u8>,347 files: bool,348};349350pub fn run_wayland(config: &WindowConfig, handler: |&| (&var Window, &Event)) -> i32 {351 const library = if (Library::open(&"libwayland-client.so.0") is ::Some |l|) l else {352 return failure(&"libwayland-client.so.0 cannot be loaded");353 };354 if (library.symbol<extern (c_pointer)>(&"wl_proxy_marshal_array_flags") is ::None) {355 return failure(&"libwayland-client is older than 1.20");356 }357 const client = Client::load(&library);358 const display = client.display_connect(0);359 if (display == 0) {360 return failure(&"no Wayland compositor to connect to");361 }362 var w = Wayland {363 .client = client,364 .wake = open_eventfd(),365 .protocol = Protocol::build(),366 .keys = Keyboard::load(),367 .window = Window::opening(&config, 1.0),368 .handler = move handler,369 .resizable = config.resizable,370 .display = display,371 .logical = config.size,372 .start = Instant::now(),373 .pending_preedit = Preedit { .text = String::empty(), .cursor = 0 }374 };375 if (w.wake is ::Some |fd|) {376 w.window.waker = Waker::Eventfd(fd);377 }378 const opened = w.open();379 if (opened) {380 w.run();381 }382 w.close_window();383 w.client.display_disconnect(w.display);384 if (w.wake is ::Some |fd|) {385 close_fd(fd);386 }387 if (w.keys is ::Some |&var keys|) {388 keys.release();389 }390 const failed = w.failed;391 w.dispose();392 if (!opened) {393 return 1;394 }395 if (failed) {396 return failure(&"the connection to the compositor failed");397 }398 return 0;399}400401fn dispose(self w: &var Wayland) {402 w.portal.dispose();403 w.atspi.dispose();404}405406/* --- What a program installs --- */407408// Joins the accessibility bus when the session's accessibility is on,409// the program then sending its tree, and reads the desktop's wish for410// less motion.411pub fn start_atspi(self w: &var Wayland) {412 w.parts.access = ::Some(give_atspi);413 w.start_portal();414 w.atspi = Atspi::connect(&w.window.title.view());415 if (w.atspi is ::Some |&var atspi|) {416 w.parts.atspi = ::Some(read_atspi);417 atspi.set_language(&w.window.language.view());418 w.deliver(&Event::AccessRequested);419 }420}421422// What a screen reader asked, read from the accessibility bus.423fn read_atspi(w: &var Wayland) {424 var actions = Vector<ActionRequest>::empty();425 if (w.atspi is ::Some |&var atspi|) {426 actions = atspi.answer();427 }428 for (actions.items()) |&var action| {429 w.deliver(&Event::Action(move action));430 }431}432433// Gives AT-SPI the window's language, the tree's updates and what to434// say.435fn give_atspi(w: &var Wayland, asked: &var Requests) {436 if (w.atspi is ::Some |&var atspi|) {437 if (asked.language) {438 atspi.set_language(&w.window.language.view());439 }440 for (asked.access.items()) |&var update| {441 take_tree(&var atspi, move update);442 }443 for (asked.announcements.view()) |&said| {444 atspi.announce(&said.text, said.assertive);445 }446 }447}448449// Shows file dialogs through the portal and takes drops.450pub fn start_files_wayland(w: &var Wayland) {451 w.parts.dialogs = ::Some(ask_portal);452 w.parts.drag = ::Some(on_drag);453 w.parts.dropped = ::Some(finish_drop);454 w.parts.portal = ::Some(read_portal);455 w.start_portal();456}457458// Reads the desktop's wish for less motion through the settings portal,459// the first time, and follows its changes.460fn start_portal(self w: &var Wayland) {461 if (w.parts.portal is ::None) {462 w.parts.portal = ::Some(read_settings);463 }464 if (w.portal.tried) {465 return;466 }467 const reduced = w.portal.reduced_motion();468 if (reduced != w.window.reduced_motion) {469 w.deliver(&Event::ReducedMotion(reduced));470 }471}472473// What the portal's bus sent: the dialogs' answers and the settings'474// changes.475fn read_portal(w: &var Wayland) {476 var answers = w.portal.answers();477 for (answers.items()) |&var chosen| {478 w.deliver(&Event::FilesChosen(move chosen));479 }480 w.motion_changed();481}482483// What the portal's bus sent of the settings' changes.484fn read_settings(w: &var Wayland) {485 w.portal.read_settings();486 w.motion_changed();487}488489fn motion_changed(self w: &var Wayland) {490 if (w.portal.motion is ::Some |reduced|) {491 w.portal.motion = ::None;492 if (reduced != w.window.reduced_motion) {493 w.deliver(&Event::ReducedMotion(reduced));494 }495 }496}497498// Shows the dialogs asked for, answering at once with no files where499// there is no portal.500fn ask_portal(w: &var Wayland, asked: &var Requests) {501 for (asked.dialogs.view()) |&dialog| {502 if (!w.portal.ask(&dialog)) {503 w.deliver(&Event::FilesChosen(Chosen {504 .request = dialog.id,505 .files = Vector<ChosenFile>::empty()506 }));507 }508 }509}510511fn failure(message: &[u8]) -> i32 {512 print_error(&f"pkg::alloy::window: {message}\n".view());513 return 1;514}515516/* --- Opening and closing --- */517518// Opens the window, once configured; whether it could.519fn open(self w: &var Wayland) -> bool {520 var none: [u64 : 1] = [0];521 w.registry = w.create(522 w.display,523 ::GetRegistry,524 ::Registry,525 w.client.proxy_get_version(w.display),526 &var none527 );528 w.client.display_roundtrip(w.display);529 if (w.global(::Compositor) == 0 || w.global(::Shm) == 0 || w.global(::WmBase) == 0) {530 failure(&"the compositor lacks wl_compositor, wl_shm or xdg_wm_base");531 return false;532 }533 if (w.global(::TextInputManager) != 0 && w.global(::Seat) != 0) {534 var text_input: [u64 : 2] = [0, w.global(::Seat) to u64];535 w.text_input = w.create(536 w.global(::TextInputManager),537 ::GetTextInput,538 ::TextInput,539 0,540 &var text_input541 );542 }543 if (w.global(::DataDeviceManager) != 0 && w.global(::Seat) != 0) {544 var device: [u64 : 2] = [0, w.global(::Seat) to u64];545 w.data_device = w.create(546 w.global(::DataDeviceManager),547 ::GetDataDevice,548 ::DataDevice,549 0,550 &var device551 );552 }553 var surface: [u64 : 1] = [0];554 w.surface = w.create(w.global(::Compositor), ::CreateSurface, ::Surface, 0, &var surface);555 w.window.target = Target::Wayland(WaylandTarget { .display = w.display, .surface = w.surface });556 if (w.global(::Viewporter) != 0) {557 var viewport: [u64 : 2] = [0, w.surface to u64];558 w.viewport = w.create(w.global(::Viewporter), ::GetViewport, ::Viewport, 0, &var viewport);559 if (w.global(::FractionalManager) != 0) {560 var fractional: [u64 : 2] = [0, w.surface to u64];561 w.fractional = w.create(562 w.global(::FractionalManager),563 ::GetFractionalScale,564 ::FractionalScale,565 0,566 &var fractional567 );568 }569 }570 var xdg: [u64 : 2] = [0, w.surface to u64];571 w.xdg_surface = w.create(w.global(::WmBase), ::GetXdgSurface, ::XdgSurface, 0, &var xdg);572 var toplevel: [u64 : 1] = [0];573 w.toplevel = w.create(w.xdg_surface, ::GetToplevel, ::Toplevel, 0, &var toplevel);574 w.send_title();575 const app = c_text_of(&w.window.app.view());576 var app_id: [u64 : 1] = [c_pointer::of(&app.view()) to u64];577 w.send(w.toplevel, ::SetAppId, &var app_id);578 if (!w.resizable) {579 var size: [u64 : 2] = [w.logical.width to u64, w.logical.height to u64];580 w.send(w.toplevel, ::SetMinSize, &var size);581 w.send(w.toplevel, ::SetMaxSize, &var size);582 }583 if (w.global(::DecorationManager) != 0) {584 var decoration: [u64 : 2] = [0, w.toplevel to u64];585 const made = w.create(586 w.global(::DecorationManager),587 ::GetToplevelDecoration,588 ::Decoration,589 0,590 &var decoration591 );592 var server_side: [u64 : 1] = [2];593 w.send(made, ::SetMode, &var server_side);594 }595 w.commit();596 while (!w.configured && !w.failed) {597 if (w.client.display_roundtrip(w.display) < 0) {598 w.failed = true;599 }600 }601 return true;602}603604fn close_window(self w: &var Wayland) {605 for (w.buffers.view()) |&b| {606 w.destroy_buffer(&b);607 }608 w.buffers.clear();609 if (w.toplevel != 0) {610 w.destroy(w.toplevel, ::ToplevelDestroy);611 w.destroy(w.xdg_surface, ::XdgSurfaceDestroy);612 }613 if (w.surface != 0) {614 w.destroy(w.surface, ::SurfaceDestroy);615 }616 w.client.display_flush(w.display);617}618619fn global(self w: &Wayland, kind: Interface) -> c_pointer {620 for ([..GLOBALS.length()]) |k| {621 if (GLOBALS[k].kind == kind) {622 return w.globals[k];623 }624 }625 return 0;626}627628/* --- The event loop --- */629630fn run(self w: &var Wayland) {631 while (!w.window.closing && !w.failed) {632 if (w.configured && w.needs_redraw) {633 w.needs_redraw = false;634 w.redraw();635 // what came meanwhile, when a surface's presenting paced the636 // frame rather than the compositor's callback637 w.wait(false);638 continue;639 }640 if (w.window.take_due()) {641 w.deliver(&Event::Timer);642 continue;643 }644 const now = w.now();645 if (w.repeat is ::Some |repeat| && now >= repeat.at) {646 // a handler slower than the rate skips repeats rather than647 // falling behind, which would starve the loop's waiting648 const interval = 1000.0 / w.repeat_rate to f64;649 var at = repeat.at + interval;650 if (at < now) {651 at = now + interval;652 }653 w.repeat = ::Some(Repeat { .code = repeat.code, .at = at });654 w.press(repeat.code, true);655 continue;656 }657 w.wait(true);658 }659}660661fn now(self w: &Wayland) -> f64 {662 return w.start.elapsed().milliseconds();663}664665// Waits for the compositor's next events, or until a key repeats or the666// program's deadline comes, and handles them; only handles those already667// there unless `block`.668fn wait(self w: &var Wayland, block: bool) {669 while (w.client.display_prepare_read(w.display) != 0) {670 if (w.client.display_dispatch_pending(w.display) < 0) {671 w.failed = true;672 return;673 }674 }675 w.client.display_flush(w.display);676 var timeout: i32 = if (block) -1 else 0;677 if (block && w.repeat is ::Some |repeat|) {678 const left = repeat.at - w.now();679 timeout = if (left <= 0.0) 0 else (left + 1.0) to i32;680 }681 if (block && w.window.until_wake() is ::Some |left|) {682 // whole milliseconds, rounded up so the deadline has come683 const ms = ((left.nanoseconds + 999999) / 1000000) to i32;684 timeout = if (timeout < 0 || ms < timeout) ms else timeout;685 }686 if (w.portal.has_waiting()) {687 timeout = 0;688 }689 // the compositor's socket, the waker's eventfd, a paste and a drop690 // being read, the portal's session bus and the accessibility bus691 var atspi_fd = Option<i32>::None;692 if (w.atspi is ::Some |&atspi|) {693 atspi_fd = ::Some(atspi.fd());694 }695 var fds: [u64 : 6] = [696 readable(::Some(w.client.display_get_fd(w.display))),697 readable(w.wake),698 readable(fd_of(&w.paste)),699 readable(fd_of(&w.drop)),700 readable(w.portal.fd()),701 readable(atspi_fd)702 ];703 if (poll(c_pointer::of(&fds[..]), 6, timeout) > 0 && ready(fds[0])) {704 if (w.client.display_read_events(w.display) < 0) {705 w.failed = true;706 return;707 }708 } else {709 w.client.display_cancel_read(w.display);710 }711 if (w.client.display_dispatch_pending(w.display) < 0) {712 w.failed = true;713 return;714 }715 if (ready(fds[1]) && w.wake is ::Some |fd|) {716 drain_eventfd(fd);717 w.deliver(&Event::Woken);718 }719 if (ready(fds[2]) && w.paste is ::Some |&var paste| && paste.read()) {720 w.finish_paste();721 }722 if (723 ready(fds[3])724 && w.drop is ::Some |&var drop|725 && drop.read()726 && w.parts.dropped is ::Some |dropped|727 ) {728 dropped(&var w);729 }730 if ((ready(fds[4]) || w.portal.has_waiting()) && w.parts.portal is ::Some |read|) {731 read(&var w);732 }733 if (ready(fds[5]) && w.parts.atspi is ::Some |read|) {734 read(&var w);735 }736}737738fn fd_of(transfer: &Option<Transfer>) -> Option<i32> {739 return if (transfer is ::Some |&t|) ::Some(t.fd) else ::None;740}741742// Gives the event to the handler, then does what it asked.743fn deliver(self w: &var Wayland, event: &Event) {744 if (w.window.closing) {745 return;746 }747 w.window.apply(&event);748 w.handler(&var w.window, &event);749 w.after();750}751752fn after(self w: &var Wayland) {753 var asked = w.window.take_requests();754 for (asked.starting.view()) |&start| {755 if (start is ::Wayland |f|) {756 f(&var w);757 }758 }759 if (asked.title) {760 w.send_title();761 }762 if (asked.cursor) {763 w.update_cursor();764 }765 if (asked.text_input) {766 w.update_text_input();767 }768 if (asked.clipboard is ::Some |move text|) {769 w.copy_text(move text);770 }771 if (w.parts.access is ::Some |give|) {772 give(&var w, &var asked);773 }774 if (w.parts.dialogs is ::Some |ask|) {775 ask(&var w, &var asked);776 }777 if (asked.clipboard_wanted) {778 w.paste();779 }780 const requested = w.window.redraw_requested;781 w.window.redraw_requested = false;782 if (w.window.surface_presented) {783 // the surface committed its frame, and its presenting paces the784 // next785 w.window.surface_presented = false;786 w.window.presented = false;787 w.attached = true;788 if (requested) {789 w.needs_redraw = true;790 }791 } else if (w.window.presented) {792 w.window.presented = false;793 if (requested) {794 w.wants_frame = true;795 w.request_frame();796 }797 w.show();798 } else if (requested) {799 if (w.frame_callback != 0) {800 w.wants_frame = true;801 } else {802 w.needs_redraw = true;803 }804 }805}806807fn redraw(self w: &var Wayland) {808 w.deliver(&Event::Redraw(w.window.now()));809 if (!w.attached) {810 // something to show, so the window appears811 const size = w.window.size;812 w.window.frame = new [0xFFFFFF to u32 : 1];813 w.window.frame_size = Size { .width = 1, .height = 1 };814 w.show();815 w.window.frame_size = size;816 }817}818819fn request_frame(self w: &var Wayland) {820 if (w.frame_callback == 0) {821 var callback: [u64 : 1] = [0];822 w.frame_callback = w.create(w.surface, ::Frame, ::Callback, 0, &var callback);823 }824}825826/* --- Events --- */827828fn dispatch(829 data: c_pointer,830 proxy: c_pointer,831 opcode: u32,832 message: c_pointer,833 arguments: c_pointer834) -> i32 {835 const w: &var Wayland = &var data.as_var<Wayland>();836 // the closure's arguments: an array of 20 unions of 8 bytes837 w.on_event(proxy, w.protocol.message_index(message) to u32, &arguments.view<u64>(20));838 return 0;839}840841fn on_event(self w: &var Wayland, proxy: c_pointer, index: u32, a: &[u64]) {842 const message = if (WaylandEvent::from(index) is ::Some |m|) m else {843 return; // an event the window does not handle844 };845 match (message) {846 ::Global {847 w.bind(word(a[0]), &(a[1] to c_pointer).c_text(), word(a[2]));848 }849 ::Ping {850 var serial: [u64 : 1] = [a[0]];851 w.send(proxy, ::Pong, &var serial);852 }853 ::ToplevelConfigure {854 w.pending = Size { .width = word(a[0]), .height = word(a[1]) };855 }856 ::XdgConfigure {857 var serial: [u64 : 1] = [a[0]];858 w.send(w.xdg_surface, ::AckConfigure, &var serial);859 w.configure();860 }861 ::ToplevelClose {862 w.deliver(&Event::CloseRequested);863 }864 ::Done {865 w.client.proxy_destroy(proxy);866 if (proxy == w.frame_callback) {867 w.frame_callback = 0;868 if (w.wants_frame) {869 w.wants_frame = false;870 w.needs_redraw = true;871 }872 }873 }874 ::Release {875 for (w.buffers.items()) |&var b| {876 if (b.proxy == proxy) {877 b.busy = false;878 }879 }880 }881 ::PreferredScale {882 w.fractional_scale = ::Some(word(a[0]));883 w.rescale();884 }885 ::PreferredBufferScale {886 w.integer_scale = word(a[0]) as i32;887 w.rescale();888 }889 ::Capabilities {890 w.capabilities(word(a[0]));891 }892 ::TextEnter, ::TextLeave, ::PreeditString, ::CommitString, ::TextDone {893 w.on_text_input(message, &a);894 }895 ::DataOfferMade, ::Selection, ::Offered, ::SourceSend, ::SourceCancelled, ::DragEnter,896 ::DragLeave, ::DragMotion, ::DragDrop {897 w.on_clipboard(proxy, message, &a);898 }899 else {900 w.on_input(message, &a);901 }902 }903}904905// The input method's events: a done event applies those before it, the906// composition ending before the text it commits.907fn on_text_input(self w: &var Wayland, message: WaylandEvent, a: &[u64]) {908 match (message) {909 ::TextEnter {910 w.text_entered = true;911 w.update_text_input();912 }913 ::TextLeave {914 w.text_entered = false;915 w.text_enabled = false;916 w.text_secret = false;917 if (w.composing) {918 w.composing = false;919 w.deliver(&Event::Preedit(Preedit { .text = String::empty(), .cursor = 0 }));920 }921 }922 ::PreeditString {923 var text = if (a[0] == 0) String::empty() else String::from(924 &(a[0] to c_pointer).c_text()925 );926 // a hidden cursor is -1: at the end927 const begin = word(a[1]) as i32;928 const cursor = if (929 begin < 0930 || begin to u64 > text.length()931 ) text.length() else begin to u64;932 w.pending_preedit = Preedit { .text = move text, .cursor = cursor };933 }934 ::CommitString {935 w.pending_commit = if (a[0] == 0) String::empty() else String::from(936 &(a[0] to c_pointer).c_text()937 );938 }939 ::TextDone {940 var commit = move w.pending_commit;941 var preedit = move w.pending_preedit;942 w.pending_commit = String::empty();943 w.pending_preedit = Preedit { .text = String::empty(), .cursor = 0 };944 if (commit.length() != 0) {945 if (w.composing) {946 w.composing = false;947 w.deliver(&Event::Preedit(Preedit { .text = String::empty(), .cursor = 0 }));948 }949 w.deliver(&Event::Text(move commit));950 }951 if (preedit.text.length() != 0 || w.composing) {952 w.composing = preedit.text.length() != 0;953 w.deliver(&Event::Preedit(move preedit));954 }955 }956 }957}958959// Turns the input method on or off as the window asks, while the window960// has its focus, with the caret's rectangle in logical pixels; a961// password's field is the content purpose password with its text hidden962// and not to be kept, which enabling again sets back to normal.963fn update_text_input(self w: &var Wayland) {964 if (w.text_input == 0 || !w.text_entered) {965 return;966 }967 if (w.window.text_input is ::Some |area|) {968 const secret = w.window.secret_input;969 if (!w.text_enabled || w.text_secret != secret) {970 w.send_bare(w.text_input, ::TextEnable);971 w.text_enabled = true;972 w.text_secret = false;973 }974 if (secret && !w.text_secret) {975 // hidden_text and sensitive_data, purpose password976 var content: [u64 : 2] = [0x40 | 0x80, 8];977 w.send(w.text_input, ::SetContentType, &var content);978 w.text_secret = true;979 }980 const s = w.window.scale;981 var rectangle: [u64 : 4] = [982 ((area.x / s) to i32) as u32 to u64,983 ((area.y / s) to i32) as u32 to u64,984 ((area.width / s + 0.5) to i32) as u32 to u64,985 ((area.height / s + 0.5) to i32) as u32 to u64986 ];987 w.send(w.text_input, ::SetCursorRectangle, &var rectangle);988 } else if (w.text_enabled) {989 w.send_bare(w.text_input, ::TextDisable);990 w.text_enabled = false;991 w.text_secret = false;992 } else {993 return;994 }995 w.send_bare(w.text_input, ::TextCommit);996}997998// Shows the window's cursor, by cursor-shape's numbers, while the999// pointer is over the window.1000fn update_cursor(self w: &var Wayland) {1001 if (w.cursor == 0 || !w.pointer_inside) {1002 return;1003 }1004 const shape: u64 = match (w.window.cursor) {1005 ::Arrow 1;1006 ::Hand 4;1007 ::Text 9;1008 };1009 var request: [u64 : 2] = [w.pointer_serial, shape];1010 w.send(w.cursor, ::SetShape, &var request);1011}10121013fn on_input(self w: &var Wayland, message: WaylandEvent, a: &[u64]) {1014 match (message) {1015 ::PointerEnter {1016 w.pointer_serial = a[0];1017 w.pointer_inside = true;1018 w.update_cursor();1019 w.moved(a[2], a[3]);1020 }1021 ::PointerMotion {1022 w.position = Point {1023 .x = fixed(a[1]) * w.window.scale,1024 .y = fixed(a[2]) * w.window.scale1025 };1026 w.motion = true;1027 if (w.seat_version < 5) {1028 w.motion_frame();1029 }1030 }1031 ::PointerLeave {1032 w.motion = false;1033 w.pointer_inside = false;1034 w.deliver(&Event::PointerLeft);1035 }1036 ::PointerButton {1037 w.motion_frame();1038 w.input_serial = a[0];1039 const event = Event::Button(ButtonEvent {1040 .button = button(word(a[2])),1041 .pressed = word(a[3]) == 1,1042 .position = w.position,1043 .modifiers = w.modifiers()1044 });1045 w.deliver(&event);1046 }1047 ::PointerAxis {1048 const value = fixed(a[2]) * w.window.scale;1049 if (word(a[1]) == 0) {1050 w.scroll.y += value;1051 } else {1052 w.scroll.x += value;1053 }1054 w.scrolled = true;1055 if (w.seat_version < 5) {1056 w.scroll_frame();1057 }1058 }1059 ::PointerAxisValue120 {1060 const lines = (word(a[1]) as i32) to f32 / 120.0;1061 if (word(a[0]) == 0) {1062 w.scroll_lines.y += lines;1063 } else {1064 w.scroll_lines.x += lines;1065 }1066 w.wheel = true;1067 }1068 ::PointerFrame {1069 w.motion_frame();1070 w.scroll_frame();1071 }1072 else {1073 w.on_keyboard(message, &a);1074 }1075 }1076}10771078fn on_keyboard(self w: &var Wayland, message: WaylandEvent, a: &[u64]) {1079 match (message) {1080 ::Keymap {1081 const fd = word(a[1]) as i32;1082 const size = word(a[2]) to u64;1083 // PROT_READ, MAP_PRIVATE1084 const memory = mmap(0, size to c_size, 1, 2, fd, 0);1085 if (memory != ~(0 to c_pointer) && word(a[0]) == 1) {1086 if (w.keys is ::Some |&var keys|) {1087 keys.set_keymap(&memory.view<u8>(size));1088 }1089 munmap(memory, size to c_size);1090 }1091 close_fd(fd);1092 }1093 ::KeyboardEnter {1094 w.input_serial = a[0];1095 w.deliver(&Event::Focused(true));1096 }1097 ::KeyboardLeave {1098 w.repeat = ::None;1099 w.deliver(&Event::Focused(false));1100 }1101 ::Key {1102 w.input_serial = a[0];1103 const code = word(a[2]);1104 if (word(a[3]) == 1) {1105 w.press(code, false);1106 if (w.repeat_rate > 0 && w.repeats(code)) {1107 w.repeat = ::Some(Repeat {1108 .code = code,1109 .at = w.now() + w.repeat_delay to f641110 });1111 }1112 } else {1113 if (w.repeat is ::Some |repeat| && repeat.code == code) {1114 w.repeat = ::None;1115 }1116 const event = Event::Key(KeyEvent {1117 .key = w.key(code),1118 .pressed = false,1119 .repeat = false,1120 .modifiers = w.modifiers()1121 });1122 w.deliver(&event);1123 }1124 }1125 ::Modifiers {1126 if (w.keys is ::Some |&var keys|) {1127 keys.update_modifiers(word(a[1]), word(a[2]), word(a[3]), word(a[4]));1128 }1129 }1130 ::RepeatInfo {1131 w.repeat_rate = word(a[0]) as i32;1132 w.repeat_delay = word(a[1]) as i32;1133 }1134 }1135}11361137// A key pressed, or repeated while held: its Key event, then the text it1138// types.1139fn press(self w: &var Wayland, code: u32, repeat: bool) {1140 const event = Event::Key(KeyEvent {1141 .key = w.key(code),1142 .pressed = true,1143 .repeat = repeat,1144 .modifiers = w.modifiers()1145 });1146 w.deliver(&event);1147 if (w.keys is ::Some |&keys|) {1148 var text = keys.text(code);1149 if (text.length() != 0) {1150 w.deliver(&Event::Text(move text));1151 }1152 }1153}11541155fn key(self w: &Wayland, code: u32) -> Key {1156 if (w.keys is ::Some |&keys|) {1157 return keys.key(code);1158 }1159 return Key::Unknown(code);1160}11611162fn repeats(self w: &Wayland, code: u32) -> bool {1163 if (w.keys is ::Some |&keys|) {1164 return keys.repeats(code);1165 }1166 return false;1167}11681169fn modifiers(self w: &Wayland) -> Modifiers {1170 if (w.keys is ::Some |&keys|) {1171 return keys.modifiers();1172 }1173 return Modifiers::none();1174}11751176fn moved(self w: &var Wayland, x: u64, y: u64) {1177 w.position = Point { .x = fixed(x) * w.window.scale, .y = fixed(y) * w.window.scale };1178 w.deliver(&Event::PointerMoved(w.position));1179}11801181// Delivers the pointer's last position of a frame, the moves before it1182// in the frame left out.1183fn motion_frame(self w: &var Wayland) {1184 if (w.motion) {1185 w.motion = false;1186 w.deliver(&Event::PointerMoved(w.position));1187 }1188}11891190fn scroll_frame(self w: &var Wayland) {1191 if (!w.scrolled) {1192 return;1193 }1194 const event = Event::Scroll(ScrollEvent {1195 .delta = if (w.wheel) w.scroll_lines else w.scroll,1196 .precise = !w.wheel,1197 .modifiers = w.modifiers()1198 });1199 w.scroll = Point { .x = 0.0, .y = 0.0 };1200 w.scroll_lines = Point { .x = 0.0, .y = 0.0 };1201 w.wheel = false;1202 w.scrolled = false;1203 w.deliver(&event);1204}12051206// BTN_LEFT and the next ones, from linux/input-event-codes.h1207fn button(code: u32) -> PointerButton {1208 return match (code) {1209 0x110 PointerButton::Left;1210 0x111 PointerButton::Right;1211 0x112 PointerButton::Middle;1212 0x113 PointerButton::Back;1213 0x114 PointerButton::Forward;1214 else PointerButton::Other(code);1215 };1216}12171218fn capabilities(self w: &var Wayland, capabilities: u32) {1219 const seat = w.global(::Seat);1220 if ((capabilities & 1) != 0 && w.pointer == 0) {1221 var pointer: [u64 : 1] = [0];1222 w.pointer = w.create(seat, ::GetPointer, ::Pointer, 0, &var pointer);1223 if (w.global(::CursorManager) != 0) {1224 var device: [u64 : 2] = [0, w.pointer to u64];1225 w.cursor = w.create(1226 w.global(::CursorManager),1227 ::GetCursorDevice,1228 ::CursorDevice,1229 0,1230 &var device1231 );1232 }1233 }1234 if ((capabilities & 2) != 0 && w.keyboard == 0) {1235 var keyboard: [u64 : 1] = [0];1236 w.keyboard = w.create(seat, ::GetKeyboard, ::Keyboard, 0, &var keyboard);1237 }1238}12391240fn bind(self w: &var Wayland, name: u32, interface_name: &[u8], version: u32) {1241 for ([..GLOBALS.length()]) |k| {1242 const kind = GLOBALS[k].kind;1243 const row = &INTERFACES[kind to u64];1244 if (w.globals[k] == 0 && name_at(&NAMES, row.name) == interface_name) {1245 const bound = if (version < GLOBALS[k].version) version else GLOBALS[k].version;1246 const registry_name = c_pointer::of(&NAMES[row.name to u64..]);1247 var arguments: [u64 : 4] = [name to u64, registry_name to u64, bound to u64, 0];1248 w.globals[k] = w.create(w.registry, ::Bind, kind, bound, &var arguments);1249 if (kind == Interface::Seat) {1250 w.seat_version = bound;1251 }1252 }1253 }1254}12551256/* --- The clipboard --- */12571258fn on_clipboard(self w: &var Wayland, proxy: c_pointer, message: WaylandEvent, a: &[u64]) {1259 match (message) {1260 ::DataOfferMade {1261 const offer = a[0] to c_pointer;1262 w.client.proxy_add_dispatcher(offer, dispatch, c_pointer::from(&w), 0);1263 w.offers.push(Offer { .proxy = offer, .text_type = ::None, .uris = false });1264 }1265 ::Offered {1266 const offered = &(a[0] to c_pointer).c_text();1267 for (w.offers.items()) |&var o| {1268 if (o.proxy == proxy) {1269 o.take(&offered);1270 }1271 }1272 }1273 ::Selection {1274 // the offers before it are gone with the old selection1275 const kept = a[0] to c_pointer;1276 var k: u64 = 0;1277 while (k < w.offers.length()) {1278 const o = w.offers.get(k);1279 if (o.proxy != kept && o.proxy != w.drag_offer) {1280 w.destroy(o.proxy, ::OfferDestroy);1281 w.offers.swap_remove(k);1282 } else {1283 k += 1;1284 }1285 }1286 w.selection = kept;1287 }1288 ::SourceSend {1289 const fd = word(a[1]) as i32;1290 if (proxy == w.source) {1291 write_all(fd, &w.copied.view());1292 }1293 close_fd(fd);1294 }1295 ::SourceCancelled {1296 w.destroy(proxy, ::SourceDestroy);1297 if (proxy == w.source) {1298 w.source = 0;1299 }1300 }1301 else {1302 if (w.parts.drag is ::Some |drag|) {1303 drag(&var w, message, &a);1304 } else {1305 w.refuse_drag(message, &a);1306 }1307 }1308 }1309}13101311// Notes a type the offer has: files, or text of a type preferred to the1312// one it had.1313fn take(self o: &var Offer, offered: &[u8]) {1314 if (offered == "text/uri-list") {1315 o.uris = true;1316 }1317 for ([..TEXT_TYPES.length()]) |k| {1318 if (offered == TEXT_TYPES[k]) {1319 const preferred = if (o.text_type is ::Some |had|) k < had else true;1320 if (preferred) {1321 o.text_type = ::Some(k);1322 }1323 }1324 }1325}13261327// The offer the proxy is, if the compositor made it.1328fn offer(self w: &Wayland, proxy: c_pointer) -> Option<Offer> {1329 for (w.offers.view()) |&o| {1330 if (o.proxy == proxy && proxy != 0) {1331 return ::Some(o);1332 }1333 }1334 return ::None;1335}13361337// Asks the offer for its data of the type, which comes through a pipe the1338// loop polls; none when no pipe opens.1339fn receive(self w: &var Wayland, offer: c_pointer, mime: &[u8], files: bool) -> Option<Transfer> {1340 const fds = if (open_pipe() is ::Some |p|) p else {1341 return ::None;1342 };1343 const name = c_text_of(&mime);1344 var arguments: [u64 : 2] = [c_pointer::of(&name.view()) to u64, fds[1] as u32 to u64];1345 w.send(offer, ::OfferReceive, &var arguments);1346 w.client.display_flush(w.display);1347 close_fd(fds[1]);1348 return ::Some(Transfer { .fd = fds[0], .bytes = Vector<u8>::empty(), .files = files });1349}13501351// Reads what the pipe has; whether it ended, the pipe closed then.1352fn read(self t: &var Transfer) -> bool {1353 var buffer: [u8 : 4096] = [0 : 4096];1354 while (true) {1355 const count = read_some(t.fd, &var buffer[..]);1356 if (count < 0) {1357 return false; // more to come1358 }1359 if (count == 0) {1360 close_fd(t.fd);1361 return true;1362 }1363 t.bytes.append(&buffer[..count to u64]);1364 }1365}13661367/* --- Drops --- */13681369// Something dragged from another program over the window: the data1370// device's enter, motion, leave and drop. The window accepts files (as1371// text/uri-list) or text, and reads what is dropped through a pipe the1372// loop polls, as a paste.1373fn on_drag(w: &var Wayland, message: WaylandEvent, a: &[u64]) {1374 match (message) {1375 ::DragEnter {1376 w.forget_drag();1377 w.drag_offer = a[4] to c_pointer;1378 w.drag_position = Point {1379 .x = fixed(a[2]) * w.window.scale,1380 .y = fixed(a[3]) * w.window.scale1381 };1382 var files = false;1383 var text = false;1384 if (w.offer(w.drag_offer) is ::Some |o|) {1385 files = o.uris;1386 text = o.text_type is ::Some;1387 }1388 if (w.drag_offer != 0) {1389 // accepting a type, copying1390 const accepted = if (files) c_text_of(&"text/uri-list") else c_text_of(1391 &TEXT_TYPES[0]1392 );1393 var accept: [u64 : 2] = [1394 a[0],1395 if (files || text) c_pointer::of(&accepted.view()) to u64 else 01396 ];1397 w.send(w.drag_offer, ::OfferAccept, &var accept);1398 var actions: [u64 : 2] = [1, 1];1399 w.send(w.drag_offer, ::OfferSetActions, &var actions);1400 }1401 w.deliver(&Event::DragEntered(Dragged {1402 .position = w.drag_position,1403 .files = files,1404 .text = text1405 }));1406 }1407 ::DragMotion {1408 w.drag_position = Point {1409 .x = fixed(a[1]) * w.window.scale,1410 .y = fixed(a[2]) * w.window.scale1411 };1412 w.deliver(&Event::DragMoved(w.drag_position));1413 }1414 ::DragLeave {1415 // the compositor leaves after a drop too, which Dropped answers1416 if (w.drop is ::None) {1417 w.forget_drag();1418 w.deliver(&Event::DragLeft);1419 }1420 }1421 ::DragDrop {1422 w.receive_drop();1423 }1424 }1425}14261427// Something dragged over the window, with no files installed: its offer1428// is let go as it leaves or drops, accepting nothing.1429fn refuse_drag(self w: &var Wayland, message: WaylandEvent, a: &[u64]) {1430 if (!(message is ::DragMotion)) {1431 w.forget_drag();1432 }1433 if (message is ::DragEnter) {1434 w.drag_offer = a[4] to c_pointer;1435 }1436}14371438// Asks for what was dropped: files if it has them, else text.1439fn receive_drop(self w: &var Wayland) {1440 var files = false;1441 var text_type = Option<u64>::None;1442 if (w.offer(w.drag_offer) is ::Some |o|) {1443 files = o.uris;1444 text_type = o.text_type;1445 }1446 if (w.drag_offer == 0 || (!files && text_type is ::None) || w.drop is ::Some) {1447 w.deliver(&Event::Dropped(Drop {1448 .position = w.drag_position,1449 .files = Vector<ChosenFile>::empty(),1450 .text = ::None1451 }));1452 w.forget_drag();1453 return;1454 }1455 const mime: &[u8] = if (files) &"text/uri-list" else if (1456 text_type is ::Some |k|1457 ) &TEXT_TYPES[k] else &"";1458 w.drop = w.receive(w.drag_offer, &mime, files);1459 if (w.drop is ::None) {1460 w.forget_drag();1461 }1462}14631464// What was dropped, read whole.1465fn finish_drop(w: &var Wayland) {1466 var drop = Drop {1467 .position = w.drag_position,1468 .files = Vector<ChosenFile>::empty(),1469 .text = ::None1470 };1471 if (w.drop is ::Some |&t|) {1472 if (t.files) {1473 drop.files = files_of_uri_list(&t.bytes.view());1474 } else {1475 drop.text = ::Some(String::from(&t.bytes.view()));1476 }1477 }1478 w.drop = ::None;1479 if (w.drag_offer != 0) {1480 w.send_bare(w.drag_offer, ::OfferFinish);1481 }1482 w.forget_drag();1483 w.deliver(&Event::Dropped(move drop));1484}14851486// Lets the dragged offer go.1487fn forget_drag(self w: &var Wayland) {1488 if (w.drag_offer == 0) {1489 return;1490 }1491 var k: u64 = 0;1492 while (k < w.offers.length()) {1493 if (w.offers.get(k).proxy == w.drag_offer) {1494 if (w.drag_offer != w.selection) {1495 w.destroy(w.drag_offer, ::OfferDestroy);1496 }1497 w.offers.swap_remove(k);1498 } else {1499 k += 1;1500 }1501 }1502 w.drag_offer = 0;1503}15041505// Offers the text as the selection, in place of what the window offered1506// before.1507fn copy_text(self w: &var Wayland, text: String) {1508 if (w.data_device == 0) {1509 return;1510 }1511 if (w.source != 0) {1512 w.destroy(w.source, ::SourceDestroy);1513 }1514 var none: [u64 : 1] = [0];1515 w.source = w.create(1516 w.global(::DataDeviceManager),1517 ::CreateDataSource,1518 ::DataSource,1519 0,1520 &var none1521 );1522 for (TEXT_TYPES) |&text_type| {1523 const name = c_text_of(&text_type);1524 var arguments: [u64 : 1] = [c_pointer::of(&name.view()) to u64];1525 w.send(w.source, ::SourceOffer, &var arguments);1526 }1527 var selection: [u64 : 2] = [w.source to u64, w.input_serial];1528 w.send(w.data_device, ::SetSelection, &var selection);1529 w.copied = move text;1530}15311532// Reads the selection's text, which a Clipboard event gives once read:1533// the window's own at once, another program's through a pipe the loop1534// polls.1535fn paste(self w: &var Wayland) {1536 if (w.source != 0) {1537 w.deliver(&Event::Clipboard(copy w.copied));1538 return;1539 }1540 if (w.paste is ::Some) {1541 return;1542 }1543 if (w.offer(w.selection) is ::Some |o| && o.text_type is ::Some |k|) {1544 w.paste = w.receive(w.selection, &TEXT_TYPES[k], false);1545 }1546 if (w.paste is ::None) {1547 w.deliver(&Event::Clipboard(String::empty()));1548 }1549}15501551// The pasted text, read whole.1552fn finish_paste(self w: &var Wayland) {1553 var text = String::empty();1554 if (w.paste is ::Some |&t|) {1555 text = String::from(&t.bytes.view());1556 }1557 w.paste = ::None;1558 w.deliver(&Event::Clipboard(move text));1559}15601561/* --- Size and scale --- */15621563fn configure(self w: &var Wayland) {1564 if (w.resizable && w.pending.width != 0 && w.pending.height != 0) {1565 w.logical = w.pending;1566 }1567 w.configured = true;1568 w.resize();1569 w.needs_redraw = true;1570}15711572fn rescale(self w: &var Wayland) {1573 const scale = if (1574 w.fractional_scale is ::Some |fraction|1575 ) fraction to f32 / 120.0 else w.integer_scale to f32;1576 if (scale != w.window.scale) {1577 w.deliver(&Event::Scaled(scale));1578 w.resize();1579 w.needs_redraw = true;1580 }1581}15821583fn resize(self w: &var Wayland) {1584 const size = physical(&w.logical, w.window.scale);1585 if (size.width != w.window.size.width || size.height != w.window.size.height || !w.attached) {1586 w.place();1587 w.deliver(&Event::Resized(size));1588 }1589}15901591// How the surface's pixels map to the window: through the viewport, to1592// the logical size, or at the integer scale. Asked before any frame of1593// the new size, whoever commits it.1594fn place(self w: &var Wayland) {1595 if (w.viewport != 0) {1596 if (1597 w.shown_destination.width != w.logical.width1598 || w.shown_destination.height != w.logical.height1599 ) {1600 var destination: [u64 : 2] = [w.logical.width to u64, w.logical.height to u64];1601 w.send(w.viewport, ::SetDestination, &var destination);1602 w.shown_destination = w.logical;1603 }1604 } else {1605 const scale = w.window.scale to i32;1606 if (scale != w.shown_scale) {1607 var buffer_scale: [u64 : 1] = [scale as u32 to u64];1608 w.send(w.surface, ::SetBufferScale, &var buffer_scale);1609 w.shown_scale = scale;1610 }1611 }1612}16131614/* --- Frames --- */16151616// Shows the window's frame: in a free buffer of the window's size, at its1617// scale, then committed.1618fn show(self w: &var Wayland) {1619 const size = w.window.size;1620 if (size.width == 0 || size.height == 0) {1621 return;1622 }1623 const k = if (w.free_buffer(size) is ::Some |free|) free else {1624 return;1625 };1626 const target = &var w.buffers.get_var(k);1627 copy_scaled(1628 &w.window.frame,1629 w.window.frame_size,1630 &var target.memory.view_var<u32>(target.bytes / 4),1631 size1632 );1633 target.busy = true;1634 var attach: [u64 : 3] = [target.proxy to u64, 0, 0];1635 const proxy = target.proxy;1636 w.send(w.surface, ::Attach, &var attach);1637 var damage: [u64 : 4] = [0, 0, size.width to u64, size.height to u64];1638 w.send(w.surface, ::DamageBuffer, &var damage);1639 w.place();1640 w.commit();1641 w.attached = true;1642}16431644// A buffer of the size the compositor is not reading, made when none is;1645// none when none can be made.1646fn free_buffer(self w: &var Wayland, size: Size) -> Option<u64> {1647 var k: u64 = 0;1648 while (k < w.buffers.length()) {1649 const busy = w.buffers.get(k).busy;1650 const fits = w.buffers.get(k).size == size;1651 if (!busy && !fits) {1652 const old = w.buffers.swap_remove(k);1653 w.destroy_buffer(&old);1654 continue;1655 }1656 if (!busy) {1657 return ::Some(k);1658 }1659 k += 1;1660 }1661 const bytes = size.width to u64 * size.height to u64 * 4;1662 const fd = memfd_create(&"alloy-window\0", 1);1663 if (fd < 0) {1664 return ::None;1665 }1666 if (ftruncate(fd, bytes to i64) != 0) {1667 close_fd(fd);1668 return ::None;1669 }1670 // PROT_READ | PROT_WRITE, MAP_SHARED1671 const memory = mmap(0, bytes to c_size, 3, 1, fd, 0);1672 if (memory == ~(0 to c_pointer)) {1673 close_fd(fd);1674 return ::None;1675 }1676 var pool_arguments: [u64 : 3] = [0, fd as u32 to u64, bytes];1677 const pool = w.create(w.global(::Shm), ::CreatePool, ::ShmPool, 0, &var pool_arguments);1678 // XRGB88881679 var buffer_arguments: [u64 : 6] = [1680 0,1681 0,1682 size.width to u64,1683 size.height to u64,1684 size.width to u64 * 4,1685 11686 ];1687 const proxy = w.create(pool, ::CreateBuffer, ::Buffer, 0, &var buffer_arguments);1688 w.buffers.push(Buffer {1689 .proxy = proxy,1690 .pool = pool,1691 .fd = fd,1692 .memory = memory,1693 .bytes = bytes,1694 .size = size,1695 .busy = false1696 });1697 return ::Some(w.buffers.length() - 1);1698}16991700fn destroy_buffer(self w: &var Wayland, b: &Buffer) {1701 w.destroy(b.proxy, ::BufferDestroy);1702 w.destroy(b.pool, ::PoolDestroy);1703 munmap(b.memory, b.bytes to c_size);1704 close_fd(b.fd);1705}17061707/* --- Requests --- */17081709fn send_title(self w: &var Wayland) {1710 const title = c_text_of(&w.window.title.view());1711 var arguments: [u64 : 1] = [c_pointer::of(&title.view()) to u64];1712 w.send(w.toplevel, ::SetTitle, &var arguments);1713}17141715fn commit(self w: &var Wayland) {1716 w.send_bare(w.surface, ::Commit);1717}17181719// Sends the request, which creates the object of the interface, at the1720// version, and handles its events; the argument creating it is left 0.1721fn create(1722 self w: &var Wayland,1723 proxy: c_pointer,1724 request: Request,1725 kind: Interface,1726 version: u32,1727 arguments: &var [u64]1728) -> c_pointer {1729 const at = if (version == 0) w.client.proxy_get_version(proxy) else version;1730 const made = w.client.proxy_marshal_array_flags(1731 proxy,1732 request.opcode(),1733 w.protocol.address(kind to u64),1734 at,1735 0,1736 c_pointer::of(&arguments)1737 );1738 if (made != 0) {1739 w.client.proxy_add_dispatcher(made, dispatch, c_pointer::from(&w), 0);1740 }1741 return made;1742}17431744fn send(self w: &var Wayland, proxy: c_pointer, request: Request, arguments: &var [u64]) {1745 w.client.proxy_marshal_array_flags(proxy, request.opcode(), 0, 0, 0, c_pointer::of(&arguments));1746}17471748// Sends a request taking no arguments.1749fn send_bare(self w: &var Wayland, proxy: c_pointer, request: Request) {1750 var none: [u64 : 1] = [0];1751 w.send(proxy, request, &var none);1752}17531754// Sends a destructor request, which destroys the object too.1755fn destroy(self w: &var Wayland, proxy: c_pointer, request: Request) {1756 var none: [u64 : 1] = [0];1757 // WL_MARSHAL_FLAG_DESTROY1758 w.client.proxy_marshal_array_flags(proxy, request.opcode(), 0, 0, 1, c_pointer::of(&none[..]));1759}17601761// The low 32 bits of an argument: an integer, enum or descriptor.1762fn word(argument: u64) -> u32 {1763 return (argument & 0xFFFFFFFF) to u32;1764}17651766// A wl_fixed_t argument: 24.8 fixed point.1767fn fixed(argument: u64) -> f32 {1768 return (word(argument) as i32) to f32 / 256.0;1769}