Skip to content

Commit

Permalink
cxx-qt: add a CxxQtSignalHandler struct and closure trait
Browse files Browse the repository at this point in the history
This allows for FnMut to be used for signals later.

Related to #595
  • Loading branch information
ahayzen-kdab committed Oct 3, 2023
1 parent c408466 commit 25a71a4
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
52 changes: 52 additions & 0 deletions crates/cxx-qt/src/cxxqtsignalhandler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// SPDX-FileCopyrightText: 2023 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
// SPDX-FileContributor: Andrew Hayzen <andrew.hayzen@kdab.com>
// SPDX-FileContributor: Leon Matthes <leon.matthes@kdab.com>
//
// 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<T>
where
T: CxxQtSignalHandlerClosure,
{
closure: Box<T::FnType>,
}

impl<T> CxxQtSignalHandler<T>
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<T::FnType>) -> Self {
Self { closure }
}

/// A mutable reference to the inner closure
pub fn closure(&mut self) -> &mut Box<T::FnType> {
&mut self.closure
}
}

// Safety:
//
// Static checks on the C++ and Rust side to ensure the size is the same.
unsafe impl<T> ExternType for CxxQtSignalHandler<T>
where
T: CxxQtSignalHandlerClosure,
{
type Kind = cxx::kind::Trivial;
type Id = T::Id;
}
2 changes: 2 additions & 0 deletions crates/cxx-qt/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]`.
Expand Down

0 comments on commit 25a71a4

Please sign in to comment.