diff --git a/crates/cxx-qt/src/cxxqtsignalhandler.rs b/crates/cxx-qt/src/cxxqtsignalhandler.rs new file mode 100644 index 000000000..a3b54f433 --- /dev/null +++ b/crates/cxx-qt/src/cxxqtsignalhandler.rs @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: 2023 Klarälvdalens Datakonsult AB, a KDAB Group company +// SPDX-FileContributor: Andrew Hayzen +// SPDX-FileContributor: Leon Matthes +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use cxx::ExternType; + +/// A trait which describes the closure to be used with [CxxQtSignalHandler]. +pub trait CxxQtSignalHandlerClosure { + /// The Id of the CXX type + type Id; + /// The type of the closure + type FnType: ?Sized; +} + +/// A signal handler helper which is used to move a FnMut closure into C++ +#[repr(transparent)] +pub struct CxxQtSignalHandler +where + T: CxxQtSignalHandlerClosure, +{ + closure: Box, +} + +impl CxxQtSignalHandler +where + T: CxxQtSignalHandlerClosure, +{ + /// Create a new signal handler with the given closure + // + // Note that we cannot use From as we cannot infer the type in the caller + pub fn new(closure: Box) -> Self { + Self { closure } + } + + /// A mutable reference to the inner closure + pub fn closure(&mut self) -> &mut Box { + &mut self.closure + } +} + +// Safety: +// +// Static checks on the C++ and Rust side to ensure the size is the same. +unsafe impl ExternType for CxxQtSignalHandler +where + T: CxxQtSignalHandlerClosure, +{ + type Kind = cxx::kind::Trivial; + type Id = T::Id; +} diff --git a/crates/cxx-qt/src/lib.rs b/crates/cxx-qt/src/lib.rs index 6c3558842..4614de801 100644 --- a/crates/cxx-qt/src/lib.rs +++ b/crates/cxx-qt/src/lib.rs @@ -9,11 +9,13 @@ //! //! See the [book](https://kdab.github.io/cxx-qt/book/) for more information. +mod cxxqtsignalhandler; mod cxxqtthread; pub use cxx_qt_macro::bridge; pub use cxx_qt_macro::qobject; +pub use cxxqtsignalhandler::{CxxQtSignalHandler, CxxQtSignalHandlerClosure}; pub use cxxqtthread::CxxQtThread; /// This trait is automatically implemented for all types which are marked as `#[qobject]`.