Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use BorrowedFd in arguments #640

Merged
merged 1 commit into from
Sep 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions wayland-client/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- Updated wayland-backend to 0.2
- Calloop integration is now removed, to avoid tying wayland-client to it you can use the
`calloop-wayland-source` crate instead
- Use `BorrowedFd<'_>` arguments instead of `RawFd`

## 0.30.2 -- 30/05/2023

Expand Down
5 changes: 2 additions & 3 deletions wayland-client/examples/simple_window.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{fs::File, os::unix::prelude::AsRawFd};
use std::{fs::File, os::unix::prelude::AsFd};

use wayland_client::{
delegate_noop,
Expand Down Expand Up @@ -73,8 +73,7 @@ impl Dispatch<wl_registry::WlRegistry, ()> for State {

let mut file = tempfile::tempfile().unwrap();
draw(&mut file, (init_w, init_h));
let pool =
shm.create_pool(file.as_raw_fd(), (init_w * init_h * 4) as i32, qh, ());
let pool = shm.create_pool(file.as_fd(), (init_w * init_h * 4) as i32, qh, ());
let buffer = pool.create_buffer(
0,
init_w as i32,
Expand Down
3 changes: 2 additions & 1 deletion wayland-client/src/conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,10 +196,11 @@ impl Connection {
pub fn send_request<I: Proxy>(
&self,
proxy: &I,
request: I::Request,
request: I::Request<'_>,
data: Option<Arc<dyn ObjectData>>,
) -> Result<ObjectId, InvalidId> {
let (msg, child_spec) = proxy.write_request(self, request)?;
let msg = msg.map_fd(|fd| fd.as_raw_fd());
self.backend.send_request(msg, data, child_spec)
}

Expand Down
15 changes: 7 additions & 8 deletions wayland-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,7 @@
use std::{
fmt,
hash::{Hash, Hasher},
os::unix::io::OwnedFd,
os::unix::io::RawFd,
os::unix::io::{BorrowedFd, OwnedFd},
sync::Arc,
};
use wayland_backend::{
Expand Down Expand Up @@ -226,7 +225,7 @@ pub trait Proxy: Clone + std::fmt::Debug + Sized {
/// The event enum for this interface
type Event;
/// The request enum for this interface
type Request;
type Request<'a>;

/// The interface description
fn interface() -> &'static Interface;
Expand Down Expand Up @@ -277,15 +276,15 @@ pub trait Proxy: Clone + std::fmt::Debug + Sized {
///
/// It is an error to use this function on requests that create objects; use
/// [Proxy::send_constructor] for such requests.
fn send_request(&self, req: Self::Request) -> Result<(), InvalidId>;
fn send_request(&self, req: Self::Request<'_>) -> Result<(), InvalidId>;

/// Send a request for this object that creates another object.
///
/// It is an error to use this function on requests that do not create objects; use
/// [Proxy::send_request] for such requests.
fn send_constructor<I: Proxy>(
&self,
req: Self::Request,
req: Self::Request<'_>,
data: Arc<dyn ObjectData>,
) -> Result<I, InvalidId>;

Expand All @@ -303,11 +302,11 @@ pub trait Proxy: Clone + std::fmt::Debug + Sized {
/// **Note:** This method is mostly meant as an implementation detail to be
/// used by code generated by wayland-scanner.
#[allow(clippy::type_complexity)]
fn write_request(
fn write_request<'a>(
&self,
conn: &Connection,
req: Self::Request,
) -> Result<(Message<ObjectId, RawFd>, Option<(&'static Interface, u32)>), InvalidId>;
req: Self::Request<'a>,
) -> Result<(Message<ObjectId, BorrowedFd<'a>>, Option<(&'static Interface, u32)>), InvalidId>;

/// Creates a weak handle to this object
///
Expand Down
5 changes: 2 additions & 3 deletions wayland-cursor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@
use std::fs::File;
use std::io::{Error as IoError, Read, Result as IoResult, Seek, SeekFrom, Write};
use std::ops::{Deref, Index};
use std::os::unix::io::OwnedFd;
use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
use std::os::unix::io::{AsFd, FromRawFd, OwnedFd, RawFd};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

Expand Down Expand Up @@ -145,7 +144,7 @@

let pool_id = conn.send_request(
&shm,
wl_shm::Request::CreatePool { fd: file.as_raw_fd(), size: INITIAL_POOL_SIZE },
wl_shm::Request::CreatePool { fd: file.as_fd(), size: INITIAL_POOL_SIZE },

Check warning on line 147 in wayland-cursor/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

wayland-cursor/src/lib.rs#L147

Added line #L147 was not covered by tests
Some(Arc::new(IgnoreObjectData)),
)?;
let pool = WlShmPool::from_id(conn, pool_id)?;
Expand Down
1 change: 1 addition & 0 deletions wayland-scanner/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

- Bump bitflags to 2.0
- Remove `io-lifetimes` from the generated code following wayland-backend 0.3 dropping it.
- Generate `BorrowedFd<'_>` arguments instead of `RawFd`

# 0.30.1 -- 2023-06-17

Expand Down
10 changes: 5 additions & 5 deletions wayland-scanner/src/client_gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ fn generate_objects_for(interface: &Interface) -> TokenStream {
}

impl super::wayland_client::Proxy for #iface_name {
type Request = Request;
type Request<'request> = Request<'request>;
type Event = Event;

#[inline]
Expand Down Expand Up @@ -135,14 +135,14 @@ fn generate_objects_for(interface: &Interface) -> TokenStream {
&self.backend
}

fn send_request(&self, req: Self::Request) -> Result<(), InvalidId> {
fn send_request(&self, req: Self::Request<'_>) -> Result<(), InvalidId> {
let conn = Connection::from_backend(self.backend.upgrade().ok_or(InvalidId)?);
let id = conn.send_request(self, req, None)?;
debug_assert!(id.is_null());
Ok(())
}

fn send_constructor<I: Proxy>(&self, req: Self::Request, data: Arc<dyn ObjectData>) -> Result<I, InvalidId> {
fn send_constructor<I: Proxy>(&self, req: Self::Request<'_>, data: Arc<dyn ObjectData>) -> Result<I, InvalidId> {
let conn = Connection::from_backend(self.backend.upgrade().ok_or(InvalidId)?);
let id = conn.send_request(self, req, Some(data))?;
Proxy::from_id(&conn, id)
Expand All @@ -168,7 +168,7 @@ fn generate_objects_for(interface: &Interface) -> TokenStream {
#parse_body
}

fn write_request(&self, conn: &Connection, msg: Self::Request) -> Result<(Message<ObjectId, std::os::unix::io::RawFd>, Option<(&'static Interface, u32)>), InvalidId> {
fn write_request<'a>(&self, conn: &Connection, msg: Self::Request<'a>) -> Result<(Message<ObjectId, std::os::unix::io::BorrowedFd<'a>>, Option<(&'static Interface, u32)>), InvalidId> {
#write_body
}
}
Expand Down Expand Up @@ -212,7 +212,7 @@ fn gen_methods(interface: &Interface) -> TokenStream {
Type::Fixed => quote! { f64 },
Type::String => if arg.allow_null { quote!{ Option<String> } } else { quote!{ String } },
Type::Array => if arg.allow_null { quote!{ Option<Vec<u8>> } } else { quote!{ Vec<u8> } },
Type::Fd => quote! { ::std::os::unix::io::RawFd },
Type::Fd => quote! { ::std::os::unix::io::BorrowedFd<'_> },
Type::Object => {
let iface = arg.interface.as_ref().unwrap();
let iface_mod = Ident::new(iface, Span::call_site());
Expand Down
93 changes: 57 additions & 36 deletions wayland-scanner/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,29 +160,33 @@ pub(crate) fn gen_message_enum(
receiver: bool,
messages: &[Message],
) -> TokenStream {
let variants = messages.iter().map(|msg| {
let mut docs = String::new();
if let Some((ref short, ref long)) = msg.description {
write!(docs, "{}\n\n{}\n", short, long.trim()).unwrap();
}
if let Some(Type::Destructor) = msg.typ {
write!(
docs,
"\nThis is a destructor, once {} this object cannot be used any longer.",
if receiver { "received" } else { "sent" },
)
.unwrap()
}
if msg.since > 1 {
write!(docs, "\nOnly available since version {} of the interface", msg.since).unwrap();
}
let variants = messages
.iter()
.map(|msg| {
let mut docs = String::new();
if let Some((ref short, ref long)) = msg.description {
write!(docs, "{}\n\n{}\n", short, long.trim()).unwrap();
}
if let Some(Type::Destructor) = msg.typ {
write!(
docs,
"\nThis is a destructor, once {} this object cannot be used any longer.",
if receiver { "received" } else { "sent" },
)
.unwrap()
}
if msg.since > 1 {
write!(docs, "\nOnly available since version {} of the interface", msg.since)
.unwrap();
}

let doc_attr = to_doc_attr(&docs);
let msg_name = Ident::new(&snake_to_camel(&msg.name), Span::call_site());
let msg_variant_decl = if msg.args.is_empty() {
msg_name.into_token_stream()
} else {
let fields = msg.args.iter().flat_map(|arg| {
let doc_attr = to_doc_attr(&docs);
let msg_name = Ident::new(&snake_to_camel(&msg.name), Span::call_site());
let msg_variant_decl =
if msg.args.is_empty() {
msg_name.into_token_stream()
} else {
let fields = msg.args.iter().flat_map(|arg| {
let field_name =
format_ident!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name);
let field_type_inner = if let Some(ref enu) = arg.enum_ {
Expand All @@ -199,7 +203,7 @@ pub(crate) fn gen_message_enum(
if receiver {
quote! { OwnedFd }
} else {
quote! { std::os::unix::io::RawFd }
quote! { std::os::unix::io::BorrowedFd<'a> }
}
}
Type::Object => {
Expand Down Expand Up @@ -264,18 +268,19 @@ pub(crate) fn gen_message_enum(
})
});

quote! {
#msg_name {
#(#fields,)*
}
}
};

quote! {
#msg_name {
#(#fields,)*
}
#doc_attr
#msg_variant_decl
}
};

quote! {
#doc_attr
#msg_variant_decl
}
});
})
.collect::<Vec<_>>();

let opcodes = messages.iter().enumerate().map(|(opcode, msg)| {
let msg_name = Ident::new(&snake_to_camel(&msg.name), Span::call_site());
Expand All @@ -291,18 +296,33 @@ pub(crate) fn gen_message_enum(
}
});

// Placeholder to allow generic argument to be added later, without ABI
// break.
// TODO Use never type.
let (generic, phantom_variant, phantom_case) = if !receiver {
(
quote! { 'a },
quote! { #[doc(hidden)] __phantom_lifetime { phantom: std::marker::PhantomData<&'a ()> } },
quote! { #name::__phantom_lifetime { .. } => unreachable!() },
)
} else {
(quote! {}, quote! {}, quote! {})
};

quote! {
#[derive(Debug)]
#[non_exhaustive]
pub enum #name {
pub enum #name<#generic> {
#(#variants,)*
#phantom_variant
}

impl #name {
impl<#generic> #name<#generic> {
#[doc="Get the opcode number of this message"]
pub fn opcode(&self) -> u16 {
match *self {
#(#opcodes,)*
#phantom_case
}
}
}
Expand Down Expand Up @@ -604,7 +624,8 @@ pub(crate) fn gen_write_body(interface: &Interface, side: Side) -> TokenStream {
});
quote! {
match msg {
#(#arms),*
#(#arms,)*
#msg_type::__phantom_lifetime { .. } => unreachable!()
}
}
}
8 changes: 4 additions & 4 deletions wayland-scanner/src/server_gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ fn generate_objects_for(interface: &Interface) -> TokenStream {

impl super::wayland_server::Resource for #iface_name {
type Request = Request;
type Event = Event;
type Event<'event> = Event<'event>;

#[inline]
fn interface() -> &'static Interface{
Expand Down Expand Up @@ -151,7 +151,7 @@ fn generate_objects_for(interface: &Interface) -> TokenStream {
Ok(#iface_name { id, data, version, handle: conn.backend_handle().downgrade() })
}

fn send_event(&self, evt: Self::Event) -> Result<(), InvalidId> {
fn send_event(&self, evt: Self::Event<'_>) -> Result<(), InvalidId> {
let handle = DisplayHandle::from(self.handle.upgrade().ok_or(InvalidId)?);
handle.send_event(self, evt)
}
Expand All @@ -160,7 +160,7 @@ fn generate_objects_for(interface: &Interface) -> TokenStream {
#parse_body
}

fn write_event(&self, conn: &DisplayHandle, msg: Self::Event) -> Result<Message<ObjectId, std::os::unix::io::RawFd>, InvalidId> {
fn write_event<'a>(&self, conn: &DisplayHandle, msg: Self::Event<'a>) -> Result<Message<ObjectId, std::os::unix::io::BorrowedFd<'a>>, InvalidId> {
#write_body
}

Expand Down Expand Up @@ -214,7 +214,7 @@ fn gen_methods(interface: &Interface) -> TokenStream {
quote! { Vec<u8> }
}
}
Type::Fd => quote! { ::std::os::unix::io::RawFd },
Type::Fd => quote! { ::std::os::unix::io::BorrowedFd<'_> },
Type::Object | Type::NewId => {
let iface = arg.interface.as_ref().unwrap();
let iface_mod = Ident::new(iface, Span::call_site());
Expand Down
Loading
Loading