Skip to content

Commit

Permalink
Allow custom setters/getters/notify for qproperty (#994)
Browse files Browse the repository at this point in the history
This adds support for three flags to the qproperty macro: `read`,`write`,`notify`.

If any of them is used, the user is in control of what is generated by CXX-Qt.
Using the flags without an argument will cause CXX-Qt to auto-generate that part of the property.
This means that `read, write, notify` is equivalent to the current behavior, which continues to be supported for convenience.

If the user specifies a value (e.g. `read=my_getter`), CXX-Qt will no longer auto-generate anything, but simply link to that function in the definition of the Q_PROPERTY macro in C++.
The corresponding function/signal must already be exported to C++ by the user with the correct name & signature.

This allows user complete control over their signals.

We will likely follow this up with the remaining valid flags on Q_PROPERTY.
  • Loading branch information
BenFordTytherington authored Jul 22, 2024
1 parent 02e5be6 commit 0ed19c6
Show file tree
Hide file tree
Showing 19 changed files with 907 additions and 213 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add cxx-qt-lib-extras crate which contains: `QCommandLineOption`, `QCommandLineParser`, `QElapsedTimer`, `QApplication`
- Serde support for `QString` (requires "serde" feature on cxx-qt-lib)
- A new QuickControls module, which exposes `QQuickStyle`. This module is enabled by default and is behind the `qt_quickcontrols` feature.
- Add support for specifying read write and notify in qproperty macro, including support for custom user defined functions

### Changed

Expand Down
18 changes: 17 additions & 1 deletion book/src/bridge/extern_rustqt.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,23 @@ Where `<Property>` is the name of the property.

These setters and getters assure that the changed signal is emitted every time the property is edited.

> Note that in the future it will be possible to specify custom getters and setters
It is also possible to specify custom getters, setters and notify signals, using flags passed like so:
`#[qproperty(TYPE, NAME, read = myGetter, write = mySetter, notify = myOnChanged)]`

> Note: currently the rust name must be in camel case or specified like `#[cxx_name = "my_getter"]` if not
It is also possible to use any combination of custom functions or omit them entirely, but if flags are specified, read must be included as all properties need to be able to be read.

Using the read flag will cause CXX-Qt to generate a getter function with an automatic name based off the property. e.g. `#[qproperty(i32, num, read)]` will have a getter function generated called get_num in Rust, and getNum in C++.

If a custom function is specified, an implementation both in qobject::MyObject and and export in the bridge is expected.

### Examples

- `#[qproperty(TYPE, NAME, read)]` A read only prop
- `#[qproperty(TYPE, NAME, read = myGetter, write, notify)]` custom getter provided but will generate setter and on-changed
- `#[qproperty(TYPE, NAME)]` is syntactic sugar for `#[qproperty(TYPE, NAME, read, write, notify)]`
- `#[qproperty(TYPE, NAME, write)]` is an error as read was not explicitly passed

## Methods

Expand Down
6 changes: 5 additions & 1 deletion crates/cxx-qt-gen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
[package]
name = "cxx-qt-gen"
version.workspace = true
authors = ["Andrew Hayzen <[email protected]>", "Gerhard de Clercq <[email protected]>", "Leon Matthes <[email protected]>"]
authors = [
"Andrew Hayzen <[email protected]>",
"Gerhard de Clercq <[email protected]>",
"Leon Matthes <[email protected]>",
]
edition.workspace = true
license.workspace = true
description = "Code generation for integrating `cxx-qt` into higher level tools"
Expand Down
62 changes: 38 additions & 24 deletions crates/cxx-qt-gen/src/generator/cpp/property/getter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,47 @@
//
// SPDX-License-Identifier: MIT OR Apache-2.0

use crate::generator::{cpp::fragment::CppFragment, naming::property::QPropertyNames};
use crate::generator::{
cpp::fragment::CppFragment,
naming::property::{NameState, QPropertyNames},
};
use indoc::formatdoc;

pub fn generate(idents: &QPropertyNames, qobject_ident: &str, return_cxx_ty: &str) -> CppFragment {
CppFragment::Pair {
header: format!(
"{return_cxx_ty} const& {ident_getter}() const;",
ident_getter = idents.getter.cxx_unqualified()
),
source: formatdoc!(
r#"
{return_cxx_ty} const&
{qobject_ident}::{ident_getter}() const
{{
const ::rust::cxxqt1::MaybeLockGuard<{qobject_ident}> guard(*this);
return {ident_getter_wrapper}();
}}
"#,
ident_getter = idents.getter.cxx_unqualified(),
ident_getter_wrapper = idents.getter_wrapper.cxx_unqualified(),
),
pub fn generate(
idents: &QPropertyNames,
qobject_ident: &str,
return_cxx_ty: &str,
) -> Option<CppFragment> {
if let (NameState::Auto(name), Some(getter_wrapper)) = (&idents.getter, &idents.getter_wrapper)
{
Some(CppFragment::Pair {
header: format!(
"{return_cxx_ty} const& {ident_getter}() const;",
ident_getter = name.cxx_unqualified()
),
source: formatdoc!(
r#"
{return_cxx_ty} const&
{qobject_ident}::{ident_getter}() const
{{
const ::rust::cxxqt1::MaybeLockGuard<{qobject_ident}> guard(*this);
return {ident_getter_wrapper}();
}}
"#,
ident_getter = name.cxx_unqualified(),
ident_getter_wrapper = getter_wrapper.cxx_unqualified(),
),
})
} else {
None
}
}

pub fn generate_wrapper(idents: &QPropertyNames, cxx_ty: &str) -> CppFragment {
CppFragment::Header(format!(
"{cxx_ty} const& {ident_getter_wrapper}() const noexcept;",
ident_getter_wrapper = idents.getter_wrapper.cxx_unqualified()
))
pub fn generate_wrapper(idents: &QPropertyNames, cxx_ty: &str) -> Option<CppFragment> {
idents.getter_wrapper.as_ref().map(|name| {
CppFragment::Header(format!(
"{cxx_ty} const& {ident_getter_wrapper}() const noexcept;",
ident_getter_wrapper = name.cxx_unqualified()
))
})
}
19 changes: 15 additions & 4 deletions crates/cxx-qt-gen/src/generator/cpp/property/meta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,23 @@ use crate::generator::naming::property::QPropertyNames;

/// Generate the metaobject line for a given property
pub fn generate(idents: &QPropertyNames, cxx_ty: &str) -> String {
let mut parts = vec![format!(
"READ {ident_getter}",
ident_getter = idents.getter.cxx_unqualified()
)];

if let Some(setter) = &idents.setter {
parts.push(format!("WRITE {}", setter.cxx_unqualified()));
}

if let Some(notify) = &idents.notify {
parts.push(format!("NOTIFY {}", notify.cxx_unqualified()));
}

format!(
"Q_PROPERTY({ty} {ident} READ {ident_getter} WRITE {ident_setter} NOTIFY {ident_notify})",
"Q_PROPERTY({ty} {ident} {meta_parts})",
ty = cxx_ty,
ident = idents.name.cxx_unqualified(),
ident_getter = idents.getter.cxx_unqualified(),
ident_setter = idents.setter.cxx_unqualified(),
ident_notify = idents.notify.cxx_unqualified()
meta_parts = parts.join(" ")
)
}
104 changes: 82 additions & 22 deletions crates/cxx-qt-gen/src/generator/cpp/property/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,26 @@ pub fn generate_cpp_properties(
let cxx_ty = syn_type_to_cpp_type(&property.ty, type_names)?;

generated.metaobjects.push(meta::generate(&idents, &cxx_ty));
generated
.methods
.push(getter::generate(&idents, &qobject_ident, &cxx_ty));
generated
.private_methods
.push(getter::generate_wrapper(&idents, &cxx_ty));
generated
.methods
.push(setter::generate(&idents, &qobject_ident, &cxx_ty));
generated
.private_methods
.push(setter::generate_wrapper(&idents, &cxx_ty));
signals.push(signal::generate(&idents, qobject_idents));

if let Some(getter) = getter::generate(&idents, &qobject_ident, &cxx_ty) {
generated.methods.push(getter);
}

if let Some(getter_wrapper) = getter::generate_wrapper(&idents, &cxx_ty) {
generated.private_methods.push(getter_wrapper);
}

if let Some(setter) = setter::generate(&idents, &qobject_ident, &cxx_ty) {
generated.methods.push(setter)
}

if let Some(setter_wrapper) = setter::generate_wrapper(&idents, &cxx_ty) {
generated.private_methods.push(setter_wrapper)
}

if let Some(notify) = signal::generate(&idents, qobject_idents) {
signals.push(notify)
}
}

generated.append(&mut generate_cpp_signals(
Expand All @@ -60,25 +67,75 @@ pub fn generate_cpp_properties(
mod tests {
use super::*;

use crate::parser::property::QPropertyFlags;

use crate::generator::naming::qobject::tests::create_qobjectname;
use crate::CppFragment;
use indoc::indoc;
use pretty_assertions::assert_str_eq;
use quote::format_ident;
use syn::parse_quote;
use syn::{parse_quote, ItemStruct};

#[test]
fn test_custom_setter() {
let mut input: ItemStruct = parse_quote! {
#[qproperty(i32, num, read, write = mySetter)]
struct MyStruct;
};
let property = ParsedQProperty::parse(input.attrs.remove(0)).unwrap();

let properties = vec![property];

let qobject_idents = create_qobjectname();

let type_names = TypeNames::mock();
let generated = generate_cpp_properties(&properties, &qobject_idents, &type_names).unwrap();

assert_eq!(generated.metaobjects.len(), 1);
assert_str_eq!(
generated.metaobjects[0],
"Q_PROPERTY(::std::int32_t num READ getNum WRITE mySetter)"
);

// Methods
assert_eq!(generated.methods.len(), 1);
let (header, source) = if let CppFragment::Pair { header, source } = &generated.methods[0] {
(header, source)
} else {
panic!("Expected pair!")
};

assert_str_eq!(header, "::std::int32_t const& getNum() const;");
assert_str_eq!(
source,
indoc! {r#"
::std::int32_t const&
MyObject::getNum() const
{
const ::rust::cxxqt1::MaybeLockGuard<MyObject> guard(*this);
return getNumWrapper();
}
"#}
);
}

#[test]
fn test_generate_cpp_properties() {
let mut input1: ItemStruct = parse_quote! {
#[qproperty(i32, trivial_property, read, write, notify)]
struct MyStruct;
};

let mut input2: ItemStruct = parse_quote! {
#[qproperty(UniquePtr<QColor>, opaque_property)]
struct MyStruct;
};

let properties = vec![
ParsedQProperty {
ident: format_ident!("trivial_property"),
ty: parse_quote! { i32 },
},
ParsedQProperty {
ident: format_ident!("opaque_property"),
ty: parse_quote! { UniquePtr<QColor> },
},
ParsedQProperty::parse(input1.attrs.remove(0)).unwrap(),
ParsedQProperty::parse(input2.attrs.remove(0)).unwrap(),
];

let qobject_idents = create_qobjectname();

let mut type_names = TypeNames::mock();
Expand All @@ -97,6 +154,7 @@ mod tests {
} else {
panic!("Expected pair!")
};

assert_str_eq!(header, "::std::int32_t const& getTrivialProperty() const;");
assert_str_eq!(
source,
Expand Down Expand Up @@ -136,6 +194,7 @@ mod tests {
} else {
panic!("Expected pair!")
};

assert_str_eq!(
header,
"::std::unique_ptr<QColor> const& getOpaqueProperty() const;"
Expand Down Expand Up @@ -358,6 +417,7 @@ mod tests {
let properties = vec![ParsedQProperty {
ident: format_ident!("mapped_property"),
ty: parse_quote! { A },
flags: QPropertyFlags::default(),
}];
let qobject_idents = create_qobjectname();

Expand Down
64 changes: 38 additions & 26 deletions crates/cxx-qt-gen/src/generator/cpp/property/setter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,47 @@
//
// SPDX-License-Identifier: MIT OR Apache-2.0

use crate::generator::{cpp::fragment::CppFragment, naming::property::QPropertyNames};
use crate::generator::{
cpp::fragment::CppFragment,
naming::property::{NameState, QPropertyNames},
};
use indoc::formatdoc;

pub fn generate(idents: &QPropertyNames, qobject_ident: &str, cxx_ty: &str) -> CppFragment {
CppFragment::Pair {
header: format!(
"Q_SLOT void {ident_setter}({cxx_ty} const& value);",
ident_setter = idents.setter.cxx_unqualified(),
),
source: formatdoc! {
r#"
void
{qobject_ident}::{ident_setter}({cxx_ty} const& value)
{{
const ::rust::cxxqt1::MaybeLockGuard<{qobject_ident}> guard(*this);
{ident_setter_wrapper}(value);
}}
"#,
ident_setter = idents.setter.cxx_unqualified(),
ident_setter_wrapper = idents.setter_wrapper.cxx_unqualified(),
},
pub fn generate(idents: &QPropertyNames, qobject_ident: &str, cxx_ty: &str) -> Option<CppFragment> {
// Only generates setter code if the state provided is Auto (not custom provided by user)
if let (Some(NameState::Auto(setter)), Some(setter_wrapper)) =
(&idents.setter, &idents.setter_wrapper)
{
Some(CppFragment::Pair {
header: format!(
"Q_SLOT void {ident_setter}({cxx_ty} const& value);",
ident_setter = setter.cxx_unqualified(),
),
source: formatdoc! {
r#"
void
{qobject_ident}::{ident_setter}({cxx_ty} const& value)
{{
const ::rust::cxxqt1::MaybeLockGuard<{qobject_ident}> guard(*this);
{ident_setter_wrapper}(value);
}}
"#,
ident_setter = setter.cxx_unqualified(),
ident_setter_wrapper = setter_wrapper.cxx_unqualified(),
},
})
} else {
None
}
}

pub fn generate_wrapper(idents: &QPropertyNames, cxx_ty: &str) -> CppFragment {
CppFragment::Header(format!(
// Note that we pass T not const T& to Rust so that it is by-value
// https://github.com/KDAB/cxx-qt/issues/463
"void {ident_setter_wrapper}({cxx_ty} value) noexcept;",
ident_setter_wrapper = idents.setter_wrapper.cxx_unqualified()
))
pub fn generate_wrapper(idents: &QPropertyNames, cxx_ty: &str) -> Option<CppFragment> {
idents.setter_wrapper.as_ref().map(|setter_wrapper| {
CppFragment::Header(format!(
// Note that we pass T not const T& to Rust so that it is by-value
// https://github.com/KDAB/cxx-qt/issues/463
"void {ident_setter_wrapper}({cxx_ty} value) noexcept;",
ident_setter_wrapper = setter_wrapper.cxx_unqualified()
))
})
}
Loading

0 comments on commit 0ed19c6

Please sign in to comment.