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

Add HashSet of flags to ParsedQPoperty for optional getters and setters #994

Merged
merged 19 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
dc49d33
Add HashSet of flags to ParsedQPoperty for optional getters and setters
BenFordTytherington Jul 9, 2024
452ba32
Add support to parse input into a hashset of flags in the ParsedQProp…
BenFordTytherington Jul 10, 2024
4e82194
Refactor for QPropertyFlag to use Idents instead of Strings
BenFordTytherington Jul 10, 2024
1eead3f
Make setter optional
BenFordTytherington Jul 11, 2024
50df978
Make Notify optional
BenFordTytherington Jul 11, 2024
eb0bdb5
Improve error handling
BenFordTytherington Jul 12, 2024
fe3ecfd
Misc changes before QPropertyFlag rewrite
BenFordTytherington Jul 11, 2024
1fa65fa
Refactor to QPropertyFlags struct with Options<> instead of a HashSet.
BenFordTytherington Jul 11, 2024
865d7fe
Rewrite property parser with new layout for storing flags
BenFordTytherington Jul 12, 2024
209bff4
Improve Error checking and refactor the generators
BenFordTytherington Jul 16, 2024
eeb2ba6
Fix Issues raised in code review, including refactor to use Enum in Q…
BenFordTytherington Jul 17, 2024
73e3cc9
Refactor to use a new NameState enum to simplify checks before genera…
BenFordTytherington Jul 17, 2024
8570970
Merge remote-tracking branch 'upstream/main' into feature-optional-rw
BenFordTytherington Jul 17, 2024
5dfe239
Cleanup and comments
BenFordTytherington Jul 17, 2024
dd50978
Fix nitpicks in PR and update docs and changelog with changes
BenFordTytherington Jul 19, 2024
4c3b3fd
Fix md lints
BenFordTytherington Jul 19, 2024
eea3a53
Improve docs and remove some commented code
BenFordTytherington Jul 22, 2024
ffccc51
Fix typo in docs
BenFordTytherington Jul 22, 2024
5f4917f
Fix asserts in tests
BenFordTytherington Jul 22, 2024
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 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
}
}

ahayzen-kdab marked this conversation as resolved.
Show resolved Hide resolved
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);
}
ahayzen-kdab marked this conversation as resolved.
Show resolved Hide resolved

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
Loading