diff --git a/src/bin/rust_qt_binding_generator.rs b/src/bin/rust_qt_binding_generator.rs index 2117e80..8683a21 100644 --- a/src/bin/rust_qt_binding_generator.rs +++ b/src/bin/rust_qt_binding_generator.rs @@ -1,29 +1,31 @@ extern crate clap; extern crate rust_qt_binding_generator; use clap::{App, Arg}; use rust_qt_binding_generator::*; fn main() { let matches = App::new("rust_qt_binding_generator") .version(env!("CARGO_PKG_VERSION")) .about("Generates bindings between Qt and Rust") .arg( Arg::with_name("overwrite-implementation") .long("overwrite-implementation") .help("Overwrite existing implementation."), - ).arg( + ) + .arg( Arg::with_name("config") .multiple(true) .required(true) .takes_value(true) .help("Configuration file(s)"), - ).get_matches(); + ) + .get_matches(); let overwrite_implementation = matches.is_present("overwrite-implementation"); for config in matches.values_of("config").unwrap() { if let Err(e) = generate_bindings_from_config_file(config, overwrite_implementation) { eprintln!("{}", e); ::std::process::exit(1); } } } diff --git a/src/configuration.rs b/src/configuration.rs index 1b3790b..efeead1 100644 --- a/src/configuration.rs +++ b/src/configuration.rs @@ -1,491 +1,494 @@ use configuration_private::*; use serde_json; -use toml; use std::collections::{BTreeMap, BTreeSet}; use std::error::Error; use std::fs; use std::path::{Path, PathBuf}; use std::rc::Rc; +use toml; mod json { use super::Rust; use std::collections::BTreeMap; use std::path::PathBuf; pub fn false_bool() -> bool { false } fn object() -> super::ObjectType { super::ObjectType::Object } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct Config { #[serde(rename = "cppFile")] pub cpp_file: PathBuf, pub objects: BTreeMap, pub rust: Rust, #[serde(default = "false_bool")] pub overwrite_implementation: bool, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct Object { #[serde(default)] pub functions: BTreeMap, #[serde(rename = "itemProperties", default)] pub item_properties: BTreeMap, #[serde(rename = "type", default = "object")] pub object_type: super::ObjectType, #[serde(default)] pub properties: BTreeMap, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct Property { #[serde(default = "false_bool")] pub optional: bool, #[serde(rename = "type")] pub property_type: String, #[serde(rename = "rustByFunction", default = "false_bool")] pub rust_by_function: bool, #[serde(default = "false_bool")] pub write: bool, } } pub enum RustEdition { Rust2015, Rust2018, - Unknown + Unknown, } impl<'a> ::std::convert::From> for RustEdition { fn from(str: Option<&'a str>) -> RustEdition { match str { None | Some("2015") => RustEdition::Rust2015, Some("2018") => RustEdition::Rust2018, _ => RustEdition::Unknown, } } } pub struct Config { pub config_file: PathBuf, pub cpp_file: PathBuf, pub objects: BTreeMap>, pub rust: Rust, pub rust_edition: RustEdition, pub overwrite_implementation: bool, } impl ConfigPrivate for Config { fn types(&self) -> BTreeSet { let mut ops = BTreeSet::new(); for o in self.objects.values() { for p in o.properties.values() { ops.insert(p.type_name().into()); } for p in o.item_properties.values() { ops.insert(p.type_name().into()); } for f in o.functions.values() { ops.insert(f.return_type.name().into()); for a in &f.arguments { ops.insert(a.type_name().into()); } } } ops } fn optional_types(&self) -> BTreeSet { let mut ops = BTreeSet::new(); for o in self.objects.values() { for p in o.properties.values() { if p.optional { ops.insert(p.type_name().into()); } } for p in o.item_properties.values() { if p.optional { ops.insert(p.type_name().into()); } } if o.object_type != ObjectType::Object { ops.insert("quintptr".into()); } } ops } fn has_list_or_tree(&self) -> bool { self.objects .values() .any(|o| o.object_type == ObjectType::List || o.object_type == ObjectType::Tree) } } #[derive(PartialEq)] pub struct Object { pub name: String, pub functions: BTreeMap, pub item_properties: BTreeMap, pub object_type: ObjectType, pub properties: BTreeMap, } impl ObjectPrivate for Object { fn contains_object(&self) -> bool { self.properties.values().any(|p| p.is_object()) } fn column_count(&self) -> usize { let mut column_count = 1; for ip in self.item_properties.values() { column_count = column_count.max(ip.roles.len()); } column_count } } #[derive(PartialEq)] pub struct Property { pub optional: bool, pub property_type: Type, pub rust_by_function: bool, pub write: bool, } impl PropertyPrivate for Property { fn is_object(&self) -> bool { self.property_type.is_object() } fn is_complex(&self) -> bool { self.property_type.is_complex() } fn c_get_type(&self) -> String { let name = self.property_type.name(); name.to_string() + "*, " + &name.to_lowercase() + "_set" } } impl TypeName for Property { fn type_name(&self) -> &str { self.property_type.name() } } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct Rust { pub dir: PathBuf, #[serde(rename = "implementationModule")] pub implementation_module: String, #[serde(rename = "interfaceModule")] pub interface_module: String, } #[derive(Deserialize, Clone, Copy, PartialEq)] pub enum ObjectType { Object, List, Tree, } #[derive(Deserialize, Clone, Copy, PartialEq)] pub enum SimpleType { QString, QByteArray, #[serde(rename = "bool")] Bool, #[serde(rename = "float")] Float, #[serde(rename = "double")] Double, #[serde(rename = "void")] Void, #[serde(rename = "qint8")] Qint8, #[serde(rename = "qint16")] Qint16, #[serde(rename = "qint32")] Qint32, #[serde(rename = "qint64")] Qint64, #[serde(rename = "quint8")] QUint8, #[serde(rename = "quint16")] QUint16, #[serde(rename = "quint32")] QUint32, #[serde(rename = "quint64")] QUint64, } impl SimpleTypePrivate for SimpleType { fn name(&self) -> &str { match self { SimpleType::QString => "QString", SimpleType::QByteArray => "QByteArray", SimpleType::Bool => "bool", SimpleType::Float => "float", SimpleType::Double => "double", SimpleType::Void => "void", SimpleType::Qint8 => "qint8", SimpleType::Qint16 => "qint16", SimpleType::Qint32 => "qint32", SimpleType::Qint64 => "qint64", SimpleType::QUint8 => "quint8", SimpleType::QUint16 => "quint16", SimpleType::QUint32 => "quint32", SimpleType::QUint64 => "quint64", } } fn cpp_set_type(&self) -> &str { match self { SimpleType::QString => "const QString&", SimpleType::QByteArray => "const QByteArray&", _ => self.name(), } } fn c_set_type(&self) -> &str { match self { SimpleType::QString => "qstring_t", SimpleType::QByteArray => "qbytearray_t", _ => self.name(), } } fn rust_type(&self) -> &str { match self { SimpleType::QString => "String", SimpleType::QByteArray => "Vec", SimpleType::Bool => "bool", SimpleType::Float => "f32", SimpleType::Double => "f64", SimpleType::Void => "()", SimpleType::Qint8 => "i8", SimpleType::Qint16 => "i16", SimpleType::Qint32 => "i32", SimpleType::Qint64 => "i64", SimpleType::QUint8 => "u8", SimpleType::QUint16 => "u16", SimpleType::QUint32 => "u32", SimpleType::QUint64 => "u64", } } fn rust_type_init(&self) -> &str { match self { SimpleType::QString => "String::new()", SimpleType::QByteArray => "Vec::new()", SimpleType::Bool => "false", SimpleType::Float | SimpleType::Double => "0.0", SimpleType::Void => "()", _ => "0", } } fn is_complex(&self) -> bool { self == &SimpleType::QString || self == &SimpleType::QByteArray } } #[derive(PartialEq)] pub enum Type { Simple(SimpleType), Object(Rc), } impl TypePrivate for Type { fn is_object(&self) -> bool { match self { Type::Object(_) => true, _ => false, } } fn is_complex(&self) -> bool { match self { Type::Simple(simple) => simple.is_complex(), _ => false, } } fn name(&self) -> &str { match self { Type::Simple(s) => s.name(), Type::Object(o) => &o.name, } } fn cpp_set_type(&self) -> &str { match self { Type::Simple(s) => s.cpp_set_type(), Type::Object(o) => &o.name, } } fn c_set_type(&self) -> &str { match self { Type::Simple(s) => s.c_set_type(), Type::Object(o) => &o.name, } } fn rust_type(&self) -> &str { match self { Type::Simple(s) => s.rust_type(), Type::Object(o) => &o.name, } } fn rust_type_init(&self) -> &str { match self { Type::Simple(s) => s.rust_type_init(), Type::Object(_) => unimplemented!(), } } } #[derive(Deserialize, Clone, PartialEq)] #[serde(deny_unknown_fields)] pub struct ItemProperty { #[serde(rename = "type")] pub item_property_type: SimpleType, #[serde(default = "json::false_bool")] pub optional: bool, #[serde(default)] pub roles: Vec>, #[serde(rename = "rustByValue", default = "json::false_bool")] pub rust_by_value: bool, #[serde(default = "json::false_bool")] pub write: bool, } impl TypeName for ItemProperty { fn type_name(&self) -> &str { self.item_property_type.name() } } impl ItemPropertyPrivate for ItemProperty { fn is_complex(&self) -> bool { self.item_property_type.is_complex() } fn cpp_set_type(&self) -> String { let t = self.item_property_type.cpp_set_type().to_string(); if self.optional { return "option_".to_string() + &t; } t } fn c_get_type(&self) -> String { let name = self.item_property_type.name(); name.to_string() + "*, " + &name.to_lowercase() + "_set" } fn c_set_type(&self) -> &str { self.item_property_type.c_set_type() } } #[derive(Deserialize, Clone, PartialEq)] #[serde(deny_unknown_fields)] pub struct Function { #[serde(rename = "return")] pub return_type: SimpleType, #[serde(rename = "mut", default = "json::false_bool")] pub mutable: bool, #[serde(default)] pub arguments: Vec, } impl TypeName for Function { fn type_name(&self) -> &str { self.return_type.name() } } #[derive(Deserialize, Clone, PartialEq)] #[serde(deny_unknown_fields)] pub struct Argument { pub name: String, #[serde(rename = "type")] pub argument_type: SimpleType, } impl TypeName for Argument { fn type_name(&self) -> &str { self.argument_type.name() } } fn post_process_property( a: (&String, &json::Property), b: &mut BTreeMap>, c: &BTreeMap, ) -> Result> { let name = &a.1.property_type; let t = match serde_json::from_str::(&format!("\"{}\"", name)) { Err(_) => { if b.get(name).is_none() { if let Some(object) = c.get(name) { post_process_object((name, object), b, c)?; } else { return Err(format!("Type {} cannot be found.", name).into()); } } Type::Object(Rc::clone(b.get(name).unwrap())) } Ok(simple) => Type::Simple(simple), }; Ok(Property { property_type: t, optional: a.1.optional, rust_by_function: a.1.rust_by_function, write: a.1.write, }) } fn post_process_object( a: (&String, &json::Object), b: &mut BTreeMap>, c: &BTreeMap, ) -> Result<(), Box> { let mut properties = BTreeMap::default(); for p in &a.1.properties { properties.insert(p.0.clone(), post_process_property(p, b, c)?); } let object = Rc::new(Object { name: a.0.clone(), object_type: a.1.object_type, functions: a.1.functions.clone(), item_properties: a.1.item_properties.clone(), properties, }); b.insert(a.0.clone(), object); Ok(()) } fn post_process(config_file: &Path, json: json::Config) -> Result> { let mut objects = BTreeMap::default(); for object in &json.objects { post_process_object(object, &mut objects, &json.objects)?; } let rust_edition: RustEdition = { let mut buf = config_file.to_path_buf(); buf.pop(); buf.push("Cargo.toml"); let manifest: toml::Value = fs::read_to_string(&buf)?.parse()?; - manifest["package"].get("edition").and_then(|val| val.as_str()).into() + manifest["package"] + .get("edition") + .and_then(|val| val.as_str()) + .into() }; Ok(Config { config_file: config_file.into(), cpp_file: json.cpp_file, objects, rust: json.rust, rust_edition, overwrite_implementation: json.overwrite_implementation, }) } pub fn parse>(config_file: P) -> Result> { let contents = fs::read_to_string(config_file.as_ref())?; let config: json::Config = serde_json::from_str(&contents)?; post_process(config_file.as_ref(), config) } diff --git a/src/cpp.rs b/src/cpp.rs index 6213b8a..9b11823 100644 --- a/src/cpp.rs +++ b/src/cpp.rs @@ -1,1511 +1,1512 @@ //! `cpp` is the module that generates the cpp code for the bindings use configuration::*; use configuration_private::*; use std::io::{Result, Write}; use util::{snake_case, write_if_different}; fn property_type(p: &ItemProperty) -> String { if p.optional && !p.item_property_type.is_complex() { return "QVariant".into(); } p.type_name().to_string() } fn upper_initial(name: &str) -> String { format!("{}{}", &name[..1].to_uppercase(), &name[1..]) } fn lower_initial(name: &str) -> String { format!("{}{}", &name[..1].to_lowercase(), &name[1..]) } fn write_property(name: &str) -> String { format!("WRITE set{} ", upper_initial(name)) } fn base_type(o: &Object) -> &str { if o.object_type != ObjectType::Object { return "QAbstractItemModel"; } "QObject" } fn model_is_writable(o: &Object) -> bool { let mut write = false; for p in o.item_properties.values() { write |= p.write; } write } fn write_header_item_model(h: &mut Vec, o: &Object) -> Result<()> { writeln!( h, " int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &index) const override; bool hasChildren(const QModelIndex &parent = QModelIndex()) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; bool canFetchMore(const QModelIndex &parent) const override; void fetchMore(const QModelIndex &parent) override; Qt::ItemFlags flags(const QModelIndex &index) const override; void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override; int role(const char* name) const; QHash roleNames() const override; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::EditRole) override; Q_INVOKABLE bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; Q_INVOKABLE bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override;" )?; if model_is_writable(o) { writeln!( h, " bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;" )?; } for (name, ip) in &o.item_properties { let r = property_type(ip); let rw = if r == "QVariant" || ip.item_property_type.is_complex() { format!("const {}&", r) } else { r.clone() }; if o.object_type == ObjectType::List { writeln!(h, " Q_INVOKABLE {} {}(int row) const;", r, name)?; if ip.write { writeln!( h, " Q_INVOKABLE bool set{}(int row, {} value);", upper_initial(name), rw )?; } } else { writeln!( h, " Q_INVOKABLE {} {}(const QModelIndex& index) const;", r, name )?; if ip.write { writeln!( h, " Q_INVOKABLE bool set{}(const QModelIndex& index, {} value);", upper_initial(name), rw )?; } } } writeln!( h, " Q_SIGNALS: // new data is ready to be made available to the model with fetchMore() void newDataReady(const QModelIndex &parent) const; private: QHash, QVariant> m_headerData; void initHeaderData(); void updatePersistentIndexes();" )?; Ok(()) } fn write_header_object(h: &mut Vec, o: &Object, conf: &Config) -> Result<()> { writeln!( h, " class {} : public {} {{ Q_OBJECT", o.name, base_type(o) )?; for object in conf.objects.values() { if object.contains_object() && o.name != object.name { writeln!(h, " friend class {};", object.name)?; } } writeln!( h, "public: class Private; private:" )?; for (name, p) in &o.properties { if p.is_object() { writeln!(h, " {}* const m_{};", p.type_name(), name)?; } } writeln!( h, " Private * m_d; bool m_ownsPrivate;" )?; for (name, p) in &o.properties { let mut t = if p.optional && !p.is_complex() { "QVariant" } else { p.type_name() - }.to_string(); + } + .to_string(); if p.is_object() { t.push_str("*"); } writeln!( h, " Q_PROPERTY({0} {1} READ {1} {2}NOTIFY {1}Changed FINAL)", t, name, if p.write { write_property(name) } else { String::new() } )?; } writeln!( h, " explicit {}(bool owned, QObject *parent); public: explicit {0}(QObject *parent = nullptr); ~{0}();", o.name )?; for (name, p) in &o.properties { if p.is_object() { writeln!(h, " const {}* {}() const;", p.type_name(), name)?; writeln!(h, " {}* {}();", p.type_name(), name)?; } else { let (t, t2) = if p.optional && !p.is_complex() { ("QVariant", "const QVariant&") } else { (p.type_name(), p.property_type.cpp_set_type()) }; writeln!(h, " {} {}() const;", t, name)?; if p.write { writeln!(h, " void set{}({} v);", upper_initial(name), t2)?; } } } for (name, f) in &o.functions { write!(h, " Q_INVOKABLE {} {}(", f.return_type.name(), name)?; for (i, a) in f.arguments.iter().enumerate() { if i != 0 { write!(h, ", ")?; } write!(h, "{} {}", a.argument_type.cpp_set_type(), a.name)?; } writeln!(h, "){};", if f.mutable { "" } else { " const" })?; } if base_type(o) == "QAbstractItemModel" { write_header_item_model(h, o)?; } writeln!(h, "Q_SIGNALS:")?; for name in o.properties.keys() { writeln!(h, " void {}Changed();", name)?; } writeln!(h, "}};")?; Ok(()) } fn is_column_write(o: &Object, col: usize) -> bool { o.item_properties .values() - .any(|ip|ip.write && (col == 0 || (ip.roles.len() > col && !ip.roles[col].is_empty()))) + .any(|ip| ip.write && (col == 0 || (ip.roles.len() > col && !ip.roles[col].is_empty()))) } fn write_function_c_decl( w: &mut Vec, (name, f): (&String, &Function), lcname: &str, o: &Object, ) -> Result<()> { let lc = snake_case(name); write!(w, " ")?; if f.return_type.is_complex() { write!(w, "void")?; } else { write!(w, "{}", f.type_name())?; } let name = format!("{}_{}", lcname, lc); write!( w, " {}({}{}::Private*", name, if f.mutable { "" } else { "const " }, o.name )?; // write all the input arguments, for QString and QByteArray, write // pointers to their content and the length for a in &f.arguments { if a.type_name() == "QString" { write!(w, ", const ushort*, int")?; } else if a.type_name() == "QByteArray" { write!(w, ", const char*, int")?; } else { write!(w, ", {}", a.type_name())?; } } // If the return type is QString or QByteArray, append a pointer to the // variable that will be set to the argument list. Also add a setter // function. if f.return_type.name() == "QString" { write!(w, ", QString*, qstring_set")?; } else if f.return_type.name() == "QByteArray" { write!(w, ", QByteArray*, qbytearray_set")?; } writeln!(w, ");")?; Ok(()) } fn write_object_c_decl(w: &mut Vec, o: &Object, conf: &Config) -> Result<()> { let lcname = snake_case(&o.name); write!(w, " {}::Private* {}_new(", o.name, lcname)?; constructor_args_decl(w, o, conf)?; writeln!(w, ");")?; writeln!(w, " void {}_free({}::Private*);", lcname, o.name)?; for (name, p) in &o.properties { let base = format!("{}_{}", lcname, snake_case(name)); if p.is_object() { writeln!( w, " {}::Private* {}_get(const {}::Private*);", p.type_name(), base, o.name )?; } else if p.is_complex() { writeln!( w, " void {}_get(const {}::Private*, {});", base, o.name, p.c_get_type() )?; } else if p.optional { writeln!( w, " option_{} {}_get(const {}::Private*);", p.type_name(), base, o.name )?; } else { writeln!( w, " {} {}_get(const {}::Private*);", p.type_name(), base, o.name )?; } if p.write { let mut t = p.property_type.c_set_type(); if t == "qstring_t" { t = "const ushort *str, int len"; } else if t == "qbytearray_t" { t = "const char* bytes, int len"; } writeln!(w, " void {}_set({}::Private*, {});", base, o.name, t)?; if p.optional { writeln!(w, " void {}_set_none({}::Private*);", base, o.name)?; } } } for f in &o.functions { write_function_c_decl(w, f, &lcname, o)?; } Ok(()) } fn initialize_members_zero(w: &mut Vec, o: &Object) -> Result<()> { for (name, p) in &o.properties { if p.is_object() { writeln!(w, " m_{}(new {}(false, this)),", name, p.type_name())?; } } Ok(()) } fn initialize_members(w: &mut Vec, prefix: &str, o: &Object, conf: &Config) -> Result<()> { for (name, p) in &o.properties { if let Type::Object(object) = &p.property_type { writeln!( w, " {}m_{}->m_d = {}_{}_get({0}m_d);", prefix, name, snake_case(&o.name), snake_case(name) )?; initialize_members(w, &format!("m_{}->", name), object, conf)?; } } Ok(()) } fn connect(w: &mut Vec, d: &str, o: &Object, conf: &Config) -> Result<()> { for (name, p) in &o.properties { if let Type::Object(object) = &p.property_type { connect(w, &format!("{}->m_{}", d, name), object, conf)?; } } if o.object_type != ObjectType::Object { writeln!( w, " connect({}, &{1}::newDataReady, {0}, [this](const QModelIndex& i) {{ {0}->fetchMore(i); }}, Qt::QueuedConnection);", d, o.name )?; } Ok(()) } fn write_cpp_object(w: &mut Vec, o: &Object, conf: &Config) -> Result<()> { let lcname = snake_case(&o.name); writeln!( w, "{}::{0}(bool /*owned*/, QObject *parent): {}(parent),", o.name, base_type(o) )?; initialize_members_zero(w, o)?; writeln!( w, " m_d(nullptr), m_ownsPrivate(false) {{" )?; if o.object_type != ObjectType::Object { writeln!(w, " initHeaderData();")?; } writeln!( w, "}} {}::{0}(QObject *parent): {}(parent),", o.name, base_type(o) )?; initialize_members_zero(w, o)?; write!(w, " m_d({}_new(this", lcname)?; constructor_args(w, "", o, conf)?; writeln!( w, ")), m_ownsPrivate(true) {{" )?; initialize_members(w, "", o, conf)?; connect(w, "this", o, conf)?; if o.object_type != ObjectType::Object { writeln!(w, " initHeaderData();")?; } writeln!( w, "}} {}::~{0}() {{ if (m_ownsPrivate) {{ {1}_free(m_d); }} }}", o.name, lcname )?; if o.object_type != ObjectType::Object { writeln!(w, "void {}::initHeaderData() {{", o.name)?; for col in 0..o.column_count() { for (name, ip) in &o.item_properties { let empty = Vec::new(); let roles = ip.roles.get(col).unwrap_or(&empty); if roles.contains(&"display".to_string()) { writeln!( w, " m_headerData.insert(qMakePair({}, Qt::DisplayRole), QVariant(\"{}\"));", col, name )?; } } } writeln!(w, "}}")?; } for (name, p) in &o.properties { let base = format!("{}_{}", lcname, snake_case(name)); if p.is_object() { writeln!( w, "const {}* {}::{}() const {{ return m_{2}; }} {0}* {1}::{2}() {{ return m_{2}; }}", p.type_name(), o.name, name )?; } else if p.is_complex() { writeln!( w, "{} {}::{}() const {{ {0} v; {3}_get(m_d, &v, set_{4}); return v; }}", p.type_name(), o.name, name, base, p.type_name().to_lowercase() )?; } else if p.optional { writeln!( w, "QVariant {}::{}() const {{ QVariant v; auto r = {2}_get(m_d); if (r.some) {{ v.setValue(r.value); }} return r; }}", o.name, name, base )?; } else { writeln!( w, "{} {}::{}() const {{ return {}_get(m_d); }}", p.type_name(), o.name, name, base )?; } if p.write { let t = if p.optional && !p.is_complex() { "const QVariant&" } else { p.property_type.cpp_set_type() }; writeln!(w, "void {}::set{}({} v) {{", o.name, upper_initial(name), t)?; if p.optional { if p.is_complex() { writeln!(w, " if (v.isNull()) {{")?; } else { writeln!( w, " if (v.isNull() || !v.canConvert<{}>()) {{", p.type_name() )?; } writeln!(w, " {}_set_none(m_d);", base)?; writeln!(w, " }} else {{")?; if p.type_name() == "QString" { writeln!( w, " {}_set(m_d, reinterpret_cast(v.data()), v.size());", base )?; } else if p.type_name() == "QByteArray" { writeln!(w, " {}_set(m_d, v.data(), v.size());", base)?; } else if p.optional { writeln!( w, " {}_set(m_d, v.value<{}>());", base, p.type_name() )?; } else { writeln!(w, " {}_set(m_d, v);", base)?; } writeln!(w, " }}")?; } else if p.type_name() == "QString" { writeln!( w, " {}_set(m_d, reinterpret_cast(v.data()), v.size());", base )?; } else if p.type_name() == "QByteArray" { writeln!(w, " {}_set(m_d, v.data(), v.size());", base)?; } else { writeln!(w, " {}_set(m_d, v);", base)?; } writeln!(w, "}}")?; } } for (name, f) in &o.functions { let base = format!("{}_{}", lcname, snake_case(name)); write!(w, "{} {}::{}(", f.type_name(), o.name, name)?; for (i, a) in f.arguments.iter().enumerate() { write!( w, "{} {}{}", a.argument_type.cpp_set_type(), a.name, if i + 1 < f.arguments.len() { ", " } else { "" } )?; } writeln!(w, "){}\n{{", if f.mutable { "" } else { " const" })?; let mut arg_list = String::new(); for a in &f.arguments { if a.type_name() == "QString" { arg_list.push_str(&format!(", {}.utf16(), {0}.size()", a.name)); } else if a.type_name() == "QByteArray" { arg_list.push_str(&format!(", {}.data(), {0}.size()", a.name)); } else { arg_list.push_str(&format!(", {}", a.name)); } } if f.return_type.name() == "QString" { writeln!( w, " {} s; {}(m_d{}, &s, set_qstring); return s;", f.type_name(), base, arg_list )?; } else if f.return_type.name() == "QByteArray" { writeln!( w, " {} s; {}(m_d{}, &s, set_qbytearray); return s;", f.type_name(), base, arg_list )?; } else { writeln!(w, " return {}(m_d{});", base, arg_list)?; } writeln!(w, "}}")?; } Ok(()) } fn role_name(role: &str) -> String { match role { "display" => "DisplayRole".into(), "decoration" => "DecorationRole".into(), "edit" => "EditRole".into(), "toolTip" => "ToolTipRole".into(), "statustip" => "StatusTipRole".into(), "whatsthis" => "WhatsThisRole".into(), _ => panic!("Unknown role {}", role), } } fn write_model_getter_setter( w: &mut Vec, index: &str, name: &str, ip: &ItemProperty, o: &Object, ) -> Result<()> { let lcname = snake_case(&o.name); let mut idx = index; // getter let mut r = property_type(ip); if o.object_type == ObjectType::List { idx = ", row"; writeln!(w, "{} {}::{}(int row) const\n{{", r, o.name, name)?; } else { writeln!( w, "{} {}::{}(const QModelIndex& index) const\n{{", r, o.name, name )?; } if ip.type_name() == "QString" { writeln!(w, " QString s;")?; writeln!( w, " {}_data_{}(m_d{}, &s, set_{});", lcname, snake_case(name), idx, ip.type_name().to_lowercase() )?; writeln!(w, " return s;")?; } else if ip.type_name() == "QByteArray" { writeln!(w, " QByteArray b;")?; writeln!( w, " {}_data_{}(m_d{}, &b, set_{});", lcname, snake_case(name), idx, ip.type_name().to_lowercase() )?; writeln!(w, " return b;")?; } else if ip.optional { writeln!(w, " QVariant v;")?; writeln!( w, " v = {}_data_{}(m_d{});", lcname, snake_case(name), idx )?; writeln!(w, " return v;")?; } else { writeln!( w, " return {}_data_{}(m_d{});", lcname, snake_case(name), idx )?; } writeln!(w, "}}\n")?; if !ip.write { return Ok(()); } //setter if r == "QVariant" || ip.is_complex() { r = format!("const {}&", r); } if o.object_type == ObjectType::List { idx = ", row"; writeln!( w, "bool {}::set{}(int row, {} value)\n{{", o.name, upper_initial(name), r )?; } else { writeln!( w, "bool {}::set{}(const QModelIndex& index, {} value)\n{{", o.name, upper_initial(name), r )?; } writeln!(w, " bool set = false;")?; if ip.optional { let mut test = "value.isNull()".to_string(); if !ip.is_complex() { test += " || !value.isValid()"; } writeln!(w, " if ({}) {{", test)?; writeln!( w, " set = {}_set_data_{}_none(m_d{});", lcname, snake_case(name), idx )?; writeln!(w, " }} else {{")?; } if ip.optional && !ip.is_complex() { writeln!( w, " if (!value.canConvert(qMetaTypeId<{}>())) {{ return false; }}", ip.type_name() )?; writeln!( w, " set = {}_set_data_{}(m_d{}, value.value<{}>());", lcname, snake_case(name), idx, ip.type_name() )?; } else { let mut val = "value"; if ip.is_complex() { if ip.type_name() == "QString" { val = "value.utf16(), value.length()"; } else { val = "value.data(), value.length()"; } } writeln!( w, " set = {}_set_data_{}(m_d{}, {});", lcname, snake_case(name), idx, val )?; } if ip.optional { writeln!(w, " }}")?; } if o.object_type == ObjectType::List { writeln!( w, " if (set) {{ QModelIndex index = createIndex(row, 0, row); Q_EMIT dataChanged(index, index); }} return set; }} " )?; } else { writeln!( w, " if (set) {{ Q_EMIT dataChanged(index, index); }} return set; }} " )?; } Ok(()) } fn write_cpp_model(w: &mut Vec, o: &Object) -> Result<()> { let lcname = snake_case(&o.name); let (index_decl, index) = if o.object_type == ObjectType::Tree { (", quintptr", ", index.internalId()") } else { (", int", ", index.row()") }; writeln!(w, "extern \"C\" {{")?; for (name, ip) in &o.item_properties { if ip.is_complex() { writeln!( w, " void {}_data_{}(const {}::Private*{}, {});", lcname, snake_case(name), o.name, index_decl, ip.c_get_type() )?; } else { writeln!( w, " {} {}_data_{}(const {}::Private*{});", ip.cpp_set_type(), lcname, snake_case(name), o.name, index_decl )?; } if ip.write { let a = format!(" bool {}_set_data_{}", lcname, snake_case(name)); let b = format!("({}::Private*{}", o.name, index_decl); if ip.type_name() == "QString" { writeln!(w, "{}{}, const ushort* s, int len);", a, b)?; } else if ip.type_name() == "QByteArray" { writeln!(w, "{}{}, const char* s, int len);", a, b)?; } else { writeln!(w, "{}{}, {});", a, b, ip.c_set_type())?; } if ip.optional { writeln!(w, "{}_none{});", a, b)?; } } } writeln!( w, " void {}_sort({}::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder);", lcname, o.name )?; if o.object_type == ObjectType::List { writeln!( w, " int {1}_row_count(const {0}::Private*); bool {1}_insert_rows({0}::Private*, int, int); bool {1}_remove_rows({0}::Private*, int, int); bool {1}_can_fetch_more(const {0}::Private*); void {1}_fetch_more({0}::Private*); }} int {0}::columnCount(const QModelIndex &parent) const {{ return (parent.isValid()) ? 0 : {2}; }} bool {0}::hasChildren(const QModelIndex &parent) const {{ return rowCount(parent) > 0; }} int {0}::rowCount(const QModelIndex &parent) const {{ return (parent.isValid()) ? 0 : {1}_row_count(m_d); }} bool {0}::insertRows(int row, int count, const QModelIndex &) {{ return {1}_insert_rows(m_d, row, count); }} bool {0}::removeRows(int row, int count, const QModelIndex &) {{ return {1}_remove_rows(m_d, row, count); }} QModelIndex {0}::index(int row, int column, const QModelIndex &parent) const {{ if (!parent.isValid() && row >= 0 && row < rowCount(parent) && column >= 0 && column < {2}) {{ return createIndex(row, column, (quintptr)row); }} return QModelIndex(); }} QModelIndex {0}::parent(const QModelIndex &) const {{ return QModelIndex(); }} bool {0}::canFetchMore(const QModelIndex &parent) const {{ return (parent.isValid()) ? 0 : {1}_can_fetch_more(m_d); }} void {0}::fetchMore(const QModelIndex &parent) {{ if (!parent.isValid()) {{ {1}_fetch_more(m_d); }} }} void {0}::updatePersistentIndexes() {{}}", o.name, lcname, o.column_count() )?; } else { writeln!( w, " int {1}_row_count(const {0}::Private*, option_quintptr); bool {1}_can_fetch_more(const {0}::Private*, option_quintptr); void {1}_fetch_more({0}::Private*, option_quintptr); quintptr {1}_index(const {0}::Private*, option_quintptr, int); qmodelindex_t {1}_parent(const {0}::Private*, quintptr); int {1}_row(const {0}::Private*, quintptr); option_quintptr {1}_check_row(const {0}::Private*, quintptr, int); }} int {0}::columnCount(const QModelIndex &) const {{ return {2}; }} bool {0}::hasChildren(const QModelIndex &parent) const {{ return rowCount(parent) > 0; }} int {0}::rowCount(const QModelIndex &parent) const {{ if (parent.isValid() && parent.column() != 0) {{ return 0; }} const option_quintptr rust_parent = {{ parent.internalId(), parent.isValid() }}; return {1}_row_count(m_d, rust_parent); }} bool {0}::insertRows(int, int, const QModelIndex &) {{ return false; // not supported yet }} bool {0}::removeRows(int, int, const QModelIndex &) {{ return false; // not supported yet }} QModelIndex {0}::index(int row, int column, const QModelIndex &parent) const {{ if (row < 0 || column < 0 || column >= {2}) {{ return QModelIndex(); }} if (parent.isValid() && parent.column() != 0) {{ return QModelIndex(); }} if (row >= rowCount(parent)) {{ return QModelIndex(); }} const option_quintptr rust_parent = {{ parent.internalId(), parent.isValid() }}; const quintptr id = {1}_index(m_d, rust_parent, row); return createIndex(row, column, id); }} QModelIndex {0}::parent(const QModelIndex &index) const {{ if (!index.isValid()) {{ return QModelIndex(); }} const qmodelindex_t parent = {1}_parent(m_d, index.internalId()); return parent.row >= 0 ?createIndex(parent.row, 0, parent.id) :QModelIndex(); }} bool {0}::canFetchMore(const QModelIndex &parent) const {{ if (parent.isValid() && parent.column() != 0) {{ return false; }} const option_quintptr rust_parent = {{ parent.internalId(), parent.isValid() }}; return {1}_can_fetch_more(m_d, rust_parent); }} void {0}::fetchMore(const QModelIndex &parent) {{ const option_quintptr rust_parent = {{ parent.internalId(), parent.isValid() }}; {1}_fetch_more(m_d, rust_parent); }} void {0}::updatePersistentIndexes() {{ const auto from = persistentIndexList(); auto to = from; auto len = to.size(); for (int i = 0; i < len; ++i) {{ auto index = to.at(i); auto row = {1}_check_row(m_d, index.internalId(), index.row()); if (row.some) {{ to[i] = createIndex(row.value, index.column(), index.internalId()); }} else {{ to[i] = QModelIndex(); }} }} changePersistentIndexList(from, to); }}", o.name, lcname, o.column_count() )?; } writeln!( w, " void {0}::sort(int column, Qt::SortOrder order) {{ {1}_sort(m_d, column, order); }} Qt::ItemFlags {0}::flags(const QModelIndex &i) const {{ auto flags = QAbstractItemModel::flags(i);", o.name, lcname )?; for col in 0..o.column_count() { if is_column_write(o, col) { writeln!(w, " if (i.column() == {}) {{", col)?; writeln!(w, " flags |= Qt::ItemIsEditable;\n }}")?; } } writeln!(w, " return flags;\n}}\n")?; for ip in &o.item_properties { write_model_getter_setter(w, index, ip.0, ip.1, o)?; } writeln!( w, "QVariant {}::data(const QModelIndex &index, int role) const {{ Q_ASSERT(rowCount(index.parent()) > index.row()); switch (index.column()) {{", o.name )?; for col in 0..o.column_count() { writeln!(w, " case {}:", col)?; writeln!(w, " switch (role) {{")?; for (i, (name, ip)) in o.item_properties.iter().enumerate() { let empty = Vec::new(); let roles = ip.roles.get(col).unwrap_or(&empty); if col > 0 && roles.is_empty() { continue; } for role in roles { writeln!(w, " case Qt::{}:", role_name(role))?; } writeln!(w, " case Qt::UserRole + {}:", i)?; let ii = if o.object_type == ObjectType::List { ".row()" } else { "" }; if ip.optional && !ip.is_complex() { writeln!(w, " return {}(index{});", name, ii)?; } else if ip.optional { writeln!( w, " return cleanNullQVariant(QVariant::fromValue({}(index{})));", name, ii )?; } else { writeln!( w, " return QVariant::fromValue({}(index{}));", name, ii )?; } } writeln!(w, " }}\n break;")?; } writeln!( w, " }} return QVariant(); }} int {}::role(const char* name) const {{ auto names = roleNames(); auto i = names.constBegin(); while (i != names.constEnd()) {{ if (i.value() == name) {{ return i.key(); }} ++i; }} return -1; }} QHash {0}::roleNames() const {{ QHash names = QAbstractItemModel::roleNames();", o.name )?; for (i, (name, _)) in o.item_properties.iter().enumerate() { writeln!(w, " names.insert(Qt::UserRole + {}, \"{}\");", i, name)?; } writeln!( w, " return names; }} QVariant {0}::headerData(int section, Qt::Orientation orientation, int role) const {{ if (orientation != Qt::Horizontal) {{ return QVariant(); }} return m_headerData.value(qMakePair(section, (Qt::ItemDataRole)role), role == Qt::DisplayRole ?QString::number(section + 1) :QVariant()); }} bool {0}::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role) {{ if (orientation != Qt::Horizontal) {{ return false; }} m_headerData.insert(qMakePair(section, (Qt::ItemDataRole)role), value); return true; }} ", o.name )?; if model_is_writable(o) { writeln!( w, "bool {}::setData(const QModelIndex &index, const QVariant &value, int role)\n{{", o.name )?; for col in 0..o.column_count() { if !is_column_write(o, col) { continue; } writeln!(w, " if (index.column() == {}) {{", col)?; for (i, (name, ip)) in o.item_properties.iter().enumerate() { if !ip.write { continue; } let empty = Vec::new(); let roles = ip.roles.get(col).unwrap_or(&empty); if col > 0 && roles.is_empty() { continue; } write!(w, " if (")?; for role in roles { write!(w, "role == Qt::{} || ", role_name(role))?; } writeln!(w, "role == Qt::UserRole + {}) {{", i)?; let ii = if o.object_type == ObjectType::List { ".row()" } else { "" }; if ip.optional && !ip.is_complex() { writeln!( w, " return set{}(index{}, value);", upper_initial(name), ii )?; } else { let pre = if ip.optional { "!value.isValid() || value.isNull() ||" } else { "" }; writeln!( w, " if ({}value.canConvert(qMetaTypeId<{}>())) {{", pre, ip.type_name() )?; writeln!( w, " return set{}(index{}, value.value<{}>());", upper_initial(name), ii, ip.type_name() )?; writeln!(w, " }}")?; } writeln!(w, " }}")?; } writeln!(w, " }}")?; } writeln!(w, " return false;\n}}\n")?; } Ok(()) } fn constructor_args_decl(w: &mut Vec, o: &Object, conf: &Config) -> Result<()> { write!(w, "{}*", o.name)?; for p in o.properties.values() { if let Type::Object(object) = &p.property_type { write!(w, ", ")?; constructor_args_decl(w, object, conf)?; } else { write!(w, ", void (*)({}*)", o.name)?; } } if o.object_type == ObjectType::List { write!( w, ", void (*)(const {}*), void (*)({0}*), void (*)({0}*), void (*)({0}*, quintptr, quintptr), void (*)({0}*), void (*)({0}*), void (*)({0}*, int, int), void (*)({0}*), void (*)({0}*, int, int, int), void (*)({0}*), void (*)({0}*, int, int), void (*)({0}*)", o.name )?; } if o.object_type == ObjectType::Tree { write!( w, ", void (*)(const {0}*, option_quintptr), void (*)({0}*), void (*)({0}*), void (*)({0}*, quintptr, quintptr), void (*)({0}*), void (*)({0}*), void (*)({0}*, option_quintptr, int, int), void (*)({0}*), void (*)({0}*, option_quintptr, int, int, option_quintptr, int), void (*)({0}*), void (*)({0}*, option_quintptr, int, int), void (*)({0}*)", o.name )?; } Ok(()) } fn changed_f(o: &Object, p_name: &str) -> String { lower_initial(&o.name) + &upper_initial(p_name) + "Changed" } fn constructor_args(w: &mut Vec, prefix: &str, o: &Object, conf: &Config) -> Result<()> { let lcname = snake_case(&o.name); for (name, p) in &o.properties { if let Type::Object(object) = &p.property_type { write!(w, ", {}m_{}", prefix, name)?; constructor_args(w, &format!("m_{}->", name), object, conf)?; } else { write!(w, ",\n {}", changed_f(o, name))?; } } if o.object_type == ObjectType::List { writeln!( w, ", [](const {0}* o) {{ Q_EMIT o->newDataReady(QModelIndex()); }}, []({0}* o) {{ Q_EMIT o->layoutAboutToBeChanged(); }}, []({0}* o) {{ o->updatePersistentIndexes(); Q_EMIT o->layoutChanged(); }}, []({0}* o, quintptr first, quintptr last) {{ o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, {1}, last)); }}, []({0}* o) {{ o->beginResetModel(); }}, []({0}* o) {{ o->endResetModel(); }}, []({0}* o, int first, int last) {{ o->beginInsertRows(QModelIndex(), first, last); }}, []({0}* o) {{ o->endInsertRows(); }}, []({0}* o, int first, int last, int destination) {{ o->beginMoveRows(QModelIndex(), first, last, QModelIndex(), destination); }}, []({0}* o) {{ o->endMoveRows(); }}, []({0}* o, int first, int last) {{ o->beginRemoveRows(QModelIndex(), first, last); }}, []({0}* o) {{ o->endRemoveRows(); }}", o.name, o.column_count() - 1 )?; } if o.object_type == ObjectType::Tree { writeln!( w, ", [](const {0}* o, option_quintptr id) {{ if (id.some) {{ int row = {1}_row(o->m_d, id.value); Q_EMIT o->newDataReady(o->createIndex(row, 0, id.value)); }} else {{ Q_EMIT o->newDataReady(QModelIndex()); }} }}, []({0}* o) {{ Q_EMIT o->layoutAboutToBeChanged(); }}, []({0}* o) {{ o->updatePersistentIndexes(); Q_EMIT o->layoutChanged(); }}, []({0}* o, quintptr first, quintptr last) {{ quintptr frow = {1}_row(o->m_d, first); quintptr lrow = {1}_row(o->m_d, first); o->dataChanged(o->createIndex(frow, 0, first), o->createIndex(lrow, {2}, last)); }}, []({0}* o) {{ o->beginResetModel(); }}, []({0}* o) {{ o->endResetModel(); }}, []({0}* o, option_quintptr id, int first, int last) {{ if (id.some) {{ int row = {1}_row(o->m_d, id.value); o->beginInsertRows(o->createIndex(row, 0, id.value), first, last); }} else {{ o->beginInsertRows(QModelIndex(), first, last); }} }}, []({0}* o) {{ o->endInsertRows(); }}, []({0}* o, option_quintptr sourceParent, int first, int last, option_quintptr destinationParent, int destination) {{ QModelIndex s; if (sourceParent.some) {{ int row = {1}_row(o->m_d, sourceParent.value); s = o->createIndex(row, 0, sourceParent.value); }} QModelIndex d; if (destinationParent.some) {{ int row = {1}_row(o->m_d, destinationParent.value); d = o->createIndex(row, 0, destinationParent.value); }} o->beginMoveRows(s, first, last, d, destination); }}, []({0}* o) {{ o->endMoveRows(); }}, []({0}* o, option_quintptr id, int first, int last) {{ if (id.some) {{ int row = {1}_row(o->m_d, id.value); o->beginRemoveRows(o->createIndex(row, 0, id.value), first, last); }} else {{ o->beginRemoveRows(QModelIndex(), first, last); }} }}, []({0}* o) {{ o->endRemoveRows(); }}", o.name, lcname, o.column_count() - 1 )?; } Ok(()) } pub fn write_header(conf: &Config) -> Result<()> { let mut h_file = conf.config_file.parent().unwrap().join(&conf.cpp_file); h_file.set_extension("h"); let mut h = Vec::new(); let guard = h_file .file_name() .unwrap() .to_string_lossy() .replace(".", "_") .to_uppercase(); writeln!( h, "/* generated by rust_qt_binding_generator */ #ifndef {0} #define {0} #include #include ", guard )?; for name in conf.objects.keys() { writeln!(h, "class {};", name)?; } for object in conf.objects.values() { write_header_object(&mut h, object, conf)?; } writeln!(h, "#endif // {}", guard)?; write_if_different(h_file, &h)?; Ok(()) } pub fn write_cpp(conf: &Config) -> Result<()> { let mut w = Vec::new(); let mut h_file = conf.config_file.parent().unwrap().join(&conf.cpp_file); h_file.set_extension("h"); let file_name = h_file.file_name().unwrap().to_string_lossy(); writeln!( w, "/* generated by rust_qt_binding_generator */ #include \"{}\" namespace {{", file_name )?; for option in conf.optional_types() { if option != "QString" && option != "QByteArray" { writeln!( w, " struct option_{} {{ public: {0} value; bool some; operator QVariant() const {{ if (some) {{ return QVariant::fromValue(value); }} return QVariant(); }} }}; static_assert(std::is_pod::value, \"option_{0} must be a POD type.\");", option )?; } } if conf.types().contains("QString") { writeln!( w, " typedef void (*qstring_set)(QString* val, const char* utf8, int nbytes); void set_qstring(QString* val, const char* utf8, int nbytes) {{ *val = QString::fromUtf8(utf8, nbytes); }}" )?; } if conf.types().contains("QByteArray") { writeln!( w, " typedef void (*qbytearray_set)(QByteArray* val, const char* bytes, int nbytes); void set_qbytearray(QByteArray* v, const char* bytes, int nbytes) {{ if (v->isNull() && nbytes == 0) {{ *v = QByteArray(bytes, nbytes); }} else {{ v->truncate(0); v->append(bytes, nbytes); }} }}" )?; } if conf.has_list_or_tree() { writeln!( w, " struct qmodelindex_t {{ int row; quintptr id; }}; inline QVariant cleanNullQVariant(const QVariant& v) {{ return (v.isNull()) ?QVariant() :v; }}" )?; } for (name, o) in &conf.objects { for (p_name, p) in &o.properties { if p.is_object() { continue; } writeln!(w, " inline void {}({}* o)", changed_f(o, p_name), name)?; writeln!(w, " {{\n Q_EMIT o->{}Changed();\n }}", p_name)?; } } writeln!(w, "}}")?; for o in conf.objects.values() { if o.object_type != ObjectType::Object { write_cpp_model(&mut w, o)?; } writeln!(w, "extern \"C\" {{")?; write_object_c_decl(&mut w, o, conf)?; writeln!(w, "}};\n")?; } for o in conf.objects.values() { write_cpp_object(&mut w, o, conf)?; } let file = conf.config_file.parent().unwrap().join(&conf.cpp_file); write_if_different(file, &w) } diff --git a/src/lib.rs b/src/lib.rs index 9718e4e..acca2b8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,45 +1,43 @@ extern crate regex; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate serde_xml_rs; extern crate toml; pub mod build; pub mod configuration; mod configuration_private; mod cpp; mod rust; mod util; +use configuration::Config; use std::error::Error; use std::path::Path; -use configuration::Config; /// Read a file with bindings. -pub fn read_bindings_file>( - config_file: P, -) -> Result> { +pub fn read_bindings_file>(config_file: P) -> Result> { configuration::parse(config_file) } /// Generate bindings from a bindings configuration. pub fn generate_bindings(config: &Config) -> Result<(), Box> { cpp::write_header(config)?; cpp::write_cpp(config)?; rust::write_interface(config)?; rust::write_implementation(config)?; Ok(()) } /// Generate bindings from a bindings configuration file. pub fn generate_bindings_from_config_file>( config_file: P, overwrite_implementation: bool, ) -> Result<(), Box> { let mut config = read_bindings_file(config_file)?; if overwrite_implementation { config.overwrite_implementation = true; } generate_bindings(&config) } diff --git a/src/rust.rs b/src/rust.rs index 771dcf4..a56378f 100644 --- a/src/rust.rs +++ b/src/rust.rs @@ -1,1545 +1,1547 @@ //! `rust` is the module that generates the rust code for the binding use configuration::*; use configuration_private::*; use std::io::{Result, Write}; use util::{snake_case, write_if_different}; fn rust_type(p: &Property) -> String { if p.optional { return format!("Option<{}>", p.property_type.rust_type()); } p.property_type.rust_type().to_string() } fn rust_type_(p: &ItemProperty) -> String { if p.optional { return format!("Option<{}>", p.item_property_type.rust_type()); } p.item_property_type.rust_type().to_string() } fn rust_return_type(p: &Property) -> String { let mut type_: String = p.property_type.rust_type().to_string(); if type_ == "String" { type_ = "str".to_string(); } if type_ == "Vec" { type_ = "[u8]".to_string(); } if p.property_type.is_complex() { type_ = "&".to_string() + &type_; } if p.optional { return "Option<".to_string() + &type_ + ">"; } type_ } fn rust_return_type_(p: &ItemProperty) -> String { let mut type_: String = p.item_property_type.rust_type().to_string(); if type_ == "String" && !p.rust_by_value { type_ = "str".to_string(); } if type_ == "Vec" && !p.rust_by_value { type_ = "[u8]".to_string(); } if p.item_property_type.is_complex() && !p.rust_by_value { type_ = "&".to_string() + &type_; } if p.optional { return "Option<".to_string() + &type_ + ">"; } type_ } fn rust_c_type(p: &ItemProperty) -> String { if p.optional { return format!("COption<{}>", p.item_property_type.rust_type()); } p.item_property_type.rust_type().to_string() } fn rust_type_init(p: &Property) -> &str { if p.optional { return "None"; } p.property_type.rust_type_init() } fn r_constructor_args_decl(r: &mut Vec, name: &str, o: &Object, conf: &Config) -> Result<()> { write!(r, " {}: *mut {}QObject", snake_case(name), o.name)?; for (p_name, p) in &o.properties { if let Type::Object(object) = &p.property_type { writeln!(r, ",")?; r_constructor_args_decl(r, p_name, object, conf)?; } else { write!( r, ",\n {}_{}_changed: fn(*mut {}QObject)", snake_case(name), snake_case(p_name), o.name )?; } } if o.object_type == ObjectType::List { write!( r, ",\n {}_new_data_ready: fn(*mut {}QObject)", snake_case(name), o.name )?; } else if o.object_type == ObjectType::Tree { write!( r, ",\n {}_new_data_ready: fn(*mut {}QObject, index: COption)", snake_case(name), o.name )?; } if o.object_type != ObjectType::Object { let index_decl = if o.object_type == ObjectType::Tree { " index: COption," } else { "" }; let dest_decl = if o.object_type == ObjectType::Tree { " index: COption," } else { "" }; write!( r, ", {2}_layout_about_to_be_changed: fn(*mut {0}QObject), {2}_layout_changed: fn(*mut {0}QObject), {2}_data_changed: fn(*mut {0}QObject, usize, usize), {2}_begin_reset_model: fn(*mut {0}QObject), {2}_end_reset_model: fn(*mut {0}QObject), {2}_begin_insert_rows: fn(*mut {0}QObject,{1} usize, usize), {2}_end_insert_rows: fn(*mut {0}QObject), {2}_begin_move_rows: fn(*mut {0}QObject,{1} usize, usize,{3} usize), {2}_end_move_rows: fn(*mut {0}QObject), {2}_begin_remove_rows: fn(*mut {0}QObject,{1} usize, usize), {2}_end_remove_rows: fn(*mut {0}QObject)", o.name, index_decl, snake_case(name), dest_decl )?; } Ok(()) } fn r_constructor_args(r: &mut Vec, name: &str, o: &Object, conf: &Config) -> Result<()> { for (name, p) in &o.properties { if let Type::Object(object) = &p.property_type { r_constructor_args(r, name, object, conf)?; } } writeln!( r, " let {}_emit = {}Emitter {{ qobject: Arc::new(AtomicPtr::new({0})),", snake_case(name), o.name )?; for (p_name, p) in &o.properties { if p.is_object() { continue; } writeln!( r, " {}_changed: {}_{0}_changed,", snake_case(p_name), snake_case(name) )?; } if o.object_type != ObjectType::Object { writeln!( r, " new_data_ready: {}_new_data_ready,", snake_case(name) )?; } let mut model = String::new(); if o.object_type != ObjectType::Object { let type_ = if o.object_type == ObjectType::List { "List" } else { "Tree" }; model.push_str(", model"); writeln!( r, " }}; let model = {}{} {{ qobject: {}, layout_about_to_be_changed: {2}_layout_about_to_be_changed, layout_changed: {2}_layout_changed, data_changed: {2}_data_changed, begin_reset_model: {2}_begin_reset_model, end_reset_model: {2}_end_reset_model, begin_insert_rows: {2}_begin_insert_rows, end_insert_rows: {2}_end_insert_rows, begin_move_rows: {2}_begin_move_rows, end_move_rows: {2}_end_move_rows, begin_remove_rows: {2}_begin_remove_rows, end_remove_rows: {2}_end_remove_rows,", o.name, type_, snake_case(name) )?; } write!( r, " }};\n let d_{} = {}::new({0}_emit{}", snake_case(name), o.name, model )?; for (name, p) in &o.properties { if p.is_object() { write!(r, ",\n d_{}", snake_case(name))?; } } writeln!(r, ");") } fn write_function( r: &mut Vec, (name, f): (&String, &Function), lcname: &str, o: &Object, ) -> Result<()> { let lc = snake_case(name); write!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_{}(ptr: *{} {}", lcname, lc, if f.mutable { "mut" } else { "const" }, o.name )?; // write all the input arguments, for QString and QByteArray, write // pointers to their content and the length which is int in Qt for a in &f.arguments { write!(r, ", ")?; if a.argument_type.name() == "QString" { write!(r, "{}_str: *const c_ushort, {0}_len: c_int", a.name)?; } else if a.argument_type.name() == "QByteArray" { write!(r, "{}_str: *const c_char, {0}_len: c_int", a.name)?; } else { write!(r, "{}: {}", a.name, a.argument_type.rust_type())?; } } // If the return type is QString or QByteArray, append a pointer to the // variable that will be set to the argument list. Also add a setter // function. if f.return_type.is_complex() { writeln!( r, ", d: *mut {}, set: fn(*mut {0}, str: *const c_char, len: c_int)) {{", f.return_type.name() )?; } else { writeln!(r, ") -> {} {{", f.return_type.rust_type())?; } for a in &f.arguments { if a.argument_type.name() == "QString" { writeln!( r, " let mut {} = String::new(); set_string_from_utf16(&mut {0}, {0}_str, {0}_len);", a.name )?; } else if a.argument_type.name() == "QByteArray" { writeln!( r, " let {} = {{ slice::from_raw_parts({0}_str as *const u8, to_usize({0}_len)) }};", a.name )?; } } if f.mutable { writeln!(r, " let o = &mut *ptr;")?; } else { writeln!(r, " let o = &*ptr;")?; } write!(r, " let r = o.{}(", lc)?; for (i, a) in f.arguments.iter().enumerate() { if i > 0 { write!(r, ", ")?; } write!(r, "{}", a.name)?; } writeln!(r, ");")?; if f.return_type.is_complex() { writeln!( r, " let s: *const c_char = r.as_ptr() as (*const c_char); set(d, s, r.len() as i32);" )?; } else { writeln!(r, " r")?; } writeln!(r, "}}") } fn write_rust_interface_object(r: &mut Vec, o: &Object, conf: &Config) -> Result<()> { let lcname = snake_case(&o.name); writeln!( r, " pub struct {}QObject {{}} pub struct {0}Emitter {{ qobject: Arc>,", o.name )?; for (name, p) in &o.properties { if p.is_object() { continue; } writeln!( r, " {}_changed: fn(*mut {}QObject),", snake_case(name), o.name )?; } if o.object_type == ObjectType::List { writeln!(r, " new_data_ready: fn(*mut {}QObject),", o.name)?; } else if o.object_type == ObjectType::Tree { writeln!( r, " new_data_ready: fn(*mut {}QObject, index: COption),", o.name )?; } writeln!( r, "}} unsafe impl Send for {}Emitter {{}} impl {0}Emitter {{ /// Clone the emitter /// /// The emitter can only be cloned when it is mutable. The emitter calls /// into C++ code which may call into Rust again. If emmitting is possible /// from immutable structures, that might lead to access to a mutable /// reference. That is undefined behaviour and forbidden. pub fn clone(&mut self) -> {0}Emitter {{ {0}Emitter {{ - qobject: self.qobject.clone(),", o.name)?; + qobject: self.qobject.clone(),", + o.name + )?; for (name, p) in &o.properties { if p.is_object() { continue; } writeln!( r, " {}_changed: self.{0}_changed,", snake_case(name), )?; } if o.object_type != ObjectType::Object { writeln!(r, " new_data_ready: self.new_data_ready,")?; } writeln!( r, " }} }} fn clear(&self) {{ let n: *const {0}QObject = null(); self.qobject.store(n as *mut {0}QObject, Ordering::SeqCst); }}", o.name )?; for (name, p) in &o.properties { if p.is_object() { continue; } writeln!( r, " pub fn {}_changed(&mut self) {{ let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() {{ (self.{0}_changed)(ptr); }} }}", snake_case(name) )?; } if o.object_type == ObjectType::List { writeln!( r, " pub fn new_data_ready(&mut self) {{ let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() {{ (self.new_data_ready)(ptr); }} }}" )?; } else if o.object_type == ObjectType::Tree { writeln!( r, " pub fn new_data_ready(&mut self, item: Option) {{ let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() {{ (self.new_data_ready)(ptr, item.into()); }} }}" )?; } let mut model_struct = String::new(); if o.object_type != ObjectType::Object { let type_ = if o.object_type == ObjectType::List { "List" } else { "Tree" }; model_struct = format!(", model: {}{}", o.name, type_); let mut index = ""; let mut index_decl = ""; let mut index_c_decl = ""; let mut dest = ""; let mut dest_decl = ""; let mut dest_c_decl = ""; if o.object_type == ObjectType::Tree { index_decl = " index: Option,"; index_c_decl = " index: COption,"; index = " index.into(),"; dest_decl = " dest: Option,"; dest_c_decl = " dest: COption,"; dest = " dest.into(),"; } writeln!( r, "}} #[derive(Clone)] pub struct {0}{1} {{ qobject: *mut {0}QObject, layout_about_to_be_changed: fn(*mut {0}QObject), layout_changed: fn(*mut {0}QObject), data_changed: fn(*mut {0}QObject, usize, usize), begin_reset_model: fn(*mut {0}QObject), end_reset_model: fn(*mut {0}QObject), begin_insert_rows: fn(*mut {0}QObject,{4} usize, usize), end_insert_rows: fn(*mut {0}QObject), begin_move_rows: fn(*mut {0}QObject,{4} usize, usize,{7} usize), end_move_rows: fn(*mut {0}QObject), begin_remove_rows: fn(*mut {0}QObject,{4} usize, usize), end_remove_rows: fn(*mut {0}QObject), }} impl {0}{1} {{ pub fn layout_about_to_be_changed(&mut self) {{ (self.layout_about_to_be_changed)(self.qobject); }} pub fn layout_changed(&mut self) {{ (self.layout_changed)(self.qobject); }} pub fn data_changed(&mut self, first: usize, last: usize) {{ (self.data_changed)(self.qobject, first, last); }} pub fn begin_reset_model(&mut self) {{ (self.begin_reset_model)(self.qobject); }} pub fn end_reset_model(&mut self) {{ (self.end_reset_model)(self.qobject); }} pub fn begin_insert_rows(&mut self,{2} first: usize, last: usize) {{ (self.begin_insert_rows)(self.qobject,{3} first, last); }} pub fn end_insert_rows(&mut self) {{ (self.end_insert_rows)(self.qobject); }} pub fn begin_move_rows(&mut self,{2} first: usize, last: usize,{5} destination: usize) {{ (self.begin_move_rows)(self.qobject,{3} first, last,{6} destination); }} pub fn end_move_rows(&mut self) {{ (self.end_move_rows)(self.qobject); }} pub fn begin_remove_rows(&mut self,{2} first: usize, last: usize) {{ (self.begin_remove_rows)(self.qobject,{3} first, last); }} pub fn end_remove_rows(&mut self) {{ (self.end_remove_rows)(self.qobject); }}", o.name, type_, index_decl, index, index_c_decl, dest_decl, dest, dest_c_decl )?; } write!( r, "}} pub trait {}Trait {{ fn new(emit: {0}Emitter{}", o.name, model_struct )?; for (name, p) in &o.properties { if p.is_object() { write!(r, ",\n {}: {}", snake_case(name), p.type_name())?; } } writeln!( r, ") -> Self; fn emit(&mut self) -> &mut {}Emitter;", o.name )?; for (name, p) in &o.properties { let lc = snake_case(name).to_lowercase(); if p.is_object() { writeln!(r, " fn {}(&self) -> &{};", lc, rust_type(p))?; writeln!(r, " fn {}_mut(&mut self) -> &mut {};", lc, rust_type(p))?; } else { if p.rust_by_function { write!( r, " fn {}(&self, getter: F) where F: FnOnce({});", lc, rust_return_type(p) )?; } else { writeln!(r, " fn {}(&self) -> {};", lc, rust_return_type(p))?; } if p.write { if p.type_name() == "QByteArray" { if p.optional { writeln!(r, " fn set_{}(&mut self, value: Option<&[u8]>);", lc)?; } else { writeln!(r, " fn set_{}(&mut self, value: &[u8]);", lc)?; } } else { writeln!(r, " fn set_{}(&mut self, value: {});", lc, rust_type(p))?; } } } } for (name, f) in &o.functions { let lc = snake_case(name); let mut arg_list = String::new(); if !f.arguments.is_empty() { for a in &f.arguments { let t = if a.argument_type.name() == "QByteArray" { "&[u8]" } else { a.argument_type.rust_type() }; arg_list.push_str(&format!(", {}: {}", a.name, t)); } } writeln!( r, " fn {}(&{}self{}) -> {};", lc, if f.mutable { "mut " } else { "" }, arg_list, f.return_type.rust_type() )?; } if o.object_type == ObjectType::List { writeln!( r, " fn row_count(&self) -> usize; fn insert_rows(&mut self, _row: usize, _count: usize) -> bool {{ false }} fn remove_rows(&mut self, _row: usize, _count: usize) -> bool {{ false }} fn can_fetch_more(&self) -> bool {{ false }} fn fetch_more(&mut self) {{}} fn sort(&mut self, _: u8, _: SortOrder) {{}}" )?; } else if o.object_type == ObjectType::Tree { writeln!( r, " fn row_count(&self, _: Option) -> usize; fn can_fetch_more(&self, _: Option) -> bool {{ false }} fn fetch_more(&mut self, _: Option) {{}} fn sort(&mut self, _: u8, _: SortOrder) {{}} fn check_row(&self, index: usize, row: usize) -> Option; fn index(&self, item: Option, row: usize) -> usize; fn parent(&self, index: usize) -> Option; fn row(&self, index: usize) -> usize;" )?; } if o.object_type != ObjectType::Object { for (name, ip) in &o.item_properties { let name = snake_case(name); writeln!( r, " fn {}(&self, index: usize) -> {};", name, rust_return_type_(ip) )?; if ip.write { if ip.item_property_type.name() == "QByteArray" { if ip.optional { writeln!( r, " fn set_{}(&mut self, index: usize, _: Option<&[u8]>) -> bool;", name )?; } else { writeln!( r, " fn set_{}(&mut self, index: usize, &[u8]) -> bool;", name )?; } } else { writeln!( r, " fn set_{}(&mut self, index: usize, {}) -> bool;", name, rust_type_(ip) )?; } } } } writeln!( r, "}} #[no_mangle] pub extern \"C\" fn {}_new(", lcname )?; r_constructor_args_decl(r, &lcname, o, conf)?; writeln!(r, ",\n) -> *mut {} {{", o.name)?; r_constructor_args(r, &lcname, o, conf)?; writeln!( r, " Box::into_raw(Box::new(d_{})) }} #[no_mangle] pub unsafe extern \"C\" fn {0}_free(ptr: *mut {}) {{ Box::from_raw(ptr).emit().clear(); }}", lcname, o.name )?; for (name, p) in &o.properties { let base = format!("{}_{}", lcname, snake_case(name)); if p.is_object() { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_get(ptr: *mut {}) -> *mut {} {{ (&mut *ptr).{}_mut() }}", base, o.name, rust_type(p), snake_case(name) )?; } else if p.is_complex() && !p.optional { if p.rust_by_function { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_get( ptr: *const {}, p: *mut {}, set: fn(*mut {2}, *const c_char, c_int), ) {{ let o = &*ptr; o.{}(|v| {{ let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, to_c_int(v.len())); }}); }}", base, o.name, p.type_name(), snake_case(name) )?; } else { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_get( ptr: *const {}, p: *mut {}, set: fn(*mut {2}, *const c_char, c_int), ) {{ let o = &*ptr; let v = o.{}(); let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, to_c_int(v.len())); }}", base, o.name, p.type_name(), snake_case(name) )?; } if p.write && p.type_name() == "QString" { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_set(ptr: *mut {}, v: *const c_ushort, len: c_int) {{ let o = &mut *ptr; let mut s = String::new(); set_string_from_utf16(&mut s, v, len); o.set_{}(s); }}", base, o.name, snake_case(name) )?; } else if p.write { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_set(ptr: *mut {}, v: *const c_char, len: c_int) {{ let o = &mut *ptr; let v = slice::from_raw_parts(v as *const u8, to_usize(len)); o.set_{}(v); }}", base, o.name, snake_case(name) )?; } } else if p.is_complex() { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_get( ptr: *const {}, p: *mut {}, set: fn(*mut {2}, *const c_char, c_int), ) {{ let o = &*ptr; let v = o.{}(); if let Some(v) = v {{ let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, to_c_int(v.len())); }} }}", base, o.name, p.type_name(), snake_case(name) )?; if p.write && p.type_name() == "QString" { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_set(ptr: *mut {}, v: *const c_ushort, len: c_int) {{ let o = &mut *ptr; let mut s = String::new(); set_string_from_utf16(&mut s, v, len); o.set_{}(Some(s)); }}", base, o.name, snake_case(name) )?; } else if p.write { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_set(ptr: *mut {}, v: *const c_char, len: c_int) {{ let o = &mut *ptr; let v = slice::from_raw_parts(v as *const u8, to_usize(len)); o.set_{}(Some(v.into())); }}", base, o.name, snake_case(name) )?; } } else if p.optional { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_get(ptr: *const {}) -> COption<{}> {{ match (&*ptr).{}() {{ Some(value) => COption {{ data: value, some: true }}, None => COption {{ data: {2}::default(), some: false}} }} }}", base, o.name, p.property_type.rust_type(), snake_case(name) )?; if p.write { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_set(ptr: *mut {}, v: {}) {{ (&mut *ptr).set_{}(Some(v)); }}", base, o.name, p.property_type.rust_type(), snake_case(name) )?; } } else { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_get(ptr: *const {}) -> {} {{ (&*ptr).{}() }}", base, o.name, rust_type(p), snake_case(name) )?; if p.write { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_set(ptr: *mut {}, v: {}) {{ (&mut *ptr).set_{}(v); }}", base, o.name, rust_type(p), snake_case(name) )?; } } if p.write && p.optional { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_set_none(ptr: *mut {}) {{ let o = &mut *ptr; o.set_{}(None); }}", base, o.name, snake_case(name) )?; } } for f in &o.functions { write_function(r, f, &lcname, o)?; } if o.object_type == ObjectType::List { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {1}_row_count(ptr: *const {0}) -> c_int {{ to_c_int((&*ptr).row_count()) }} #[no_mangle] pub unsafe extern \"C\" fn {1}_insert_rows(ptr: *mut {0}, row: c_int, count: c_int) -> bool {{ (&mut *ptr).insert_rows(to_usize(row), to_usize(count)) }} #[no_mangle] pub unsafe extern \"C\" fn {1}_remove_rows(ptr: *mut {0}, row: c_int, count: c_int) -> bool {{ (&mut *ptr).remove_rows(to_usize(row), to_usize(count)) }} #[no_mangle] pub unsafe extern \"C\" fn {1}_can_fetch_more(ptr: *const {0}) -> bool {{ (&*ptr).can_fetch_more() }} #[no_mangle] pub unsafe extern \"C\" fn {1}_fetch_more(ptr: *mut {0}) {{ (&mut *ptr).fetch_more() }} #[no_mangle] pub unsafe extern \"C\" fn {1}_sort( ptr: *mut {0}, column: u8, order: SortOrder, ) {{ (&mut *ptr).sort(column, order) }}", o.name, lcname )?; } else if o.object_type == ObjectType::Tree { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {1}_row_count( ptr: *const {0}, index: COption, ) -> c_int {{ to_c_int((&*ptr).row_count(index.into())) }} #[no_mangle] pub unsafe extern \"C\" fn {1}_can_fetch_more( ptr: *const {0}, index: COption, ) -> bool {{ (&*ptr).can_fetch_more(index.into()) }} #[no_mangle] pub unsafe extern \"C\" fn {1}_fetch_more(ptr: *mut {0}, index: COption) {{ (&mut *ptr).fetch_more(index.into()) }} #[no_mangle] pub unsafe extern \"C\" fn {1}_sort( ptr: *mut {0}, column: u8, order: SortOrder ) {{ (&mut *ptr).sort(column, order) }} #[no_mangle] pub unsafe extern \"C\" fn {1}_check_row( ptr: *const {0}, index: usize, row: c_int, ) -> COption {{ (&*ptr).check_row(index.into(), to_usize(row)).into() }} #[no_mangle] pub unsafe extern \"C\" fn {1}_index( ptr: *const {0}, index: COption, row: c_int, ) -> usize {{ (&*ptr).index(index.into(), to_usize(row)) }} #[no_mangle] pub unsafe extern \"C\" fn {1}_parent(ptr: *const {0}, index: usize) -> QModelIndex {{ if let Some(parent) = (&*ptr).parent(index) {{ QModelIndex {{ row: to_c_int((&*ptr).row(parent)), internal_id: parent, }} }} else {{ QModelIndex {{ row: -1, internal_id: 0, }} }} }} #[no_mangle] pub unsafe extern \"C\" fn {1}_row(ptr: *const {0}, index: usize) -> c_int {{ to_c_int((&*ptr).row(index)) }}", o.name, lcname )?; } if o.object_type != ObjectType::Object { let (index_decl, index) = if o.object_type == ObjectType::Tree { (", index: usize", "index") } else { (", row: c_int", "to_usize(row)") }; for (name, ip) in &o.item_properties { if ip.is_complex() && !ip.optional { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_data_{}( ptr: *const {}{}, d: *mut {}, set: fn(*mut {4}, *const c_char, len: c_int), ) {{ let o = &*ptr; let data = o.{1}({}); let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, to_c_int(data.len())); }}", lcname, snake_case(name), o.name, index_decl, ip.type_name(), index )?; } else if ip.is_complex() { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_data_{}( ptr: *const {}{}, d: *mut {}, set: fn(*mut {4}, *const c_char, len: c_int), ) {{ let o = &*ptr; let data = o.{1}({}); if let Some(data) = data {{ let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, to_c_int(data.len())); }} }}", lcname, snake_case(name), o.name, index_decl, ip.type_name(), index )?; } else { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_data_{}(ptr: *const {}{}) -> {} {{ let o = &*ptr; o.{1}({}).into() }}", lcname, snake_case(name), o.name, index_decl, rust_c_type(ip), index )?; } if ip.write { let val = if ip.optional { "Some(v)" } else { "v" }; if ip.type_name() == "QString" { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_set_data_{}( ptr: *mut {}{}, s: *const c_ushort, len: c_int, ) -> bool {{ let o = &mut *ptr; let mut v = String::new(); set_string_from_utf16(&mut v, s, len); o.set_{1}({}, {}) }}", lcname, snake_case(name), o.name, index_decl, index, val )?; } else if ip.type_name() == "QByteArray" { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_set_data_{}( ptr: *mut {}{}, s: *const c_char, len: c_int, ) -> bool {{ let o = &mut *ptr; let slice = ::std::slice::from_raw_parts(s as *const u8, to_usize(len)); o.set_{1}({}, {}) }}", lcname, snake_case(name), o.name, index_decl, index, if ip.optional { "Some(slice)" } else { "slice" } )?; } else { let type_ = ip.item_property_type.rust_type(); writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_set_data_{}( ptr: *mut {}{}, v: {}, ) -> bool {{ (&mut *ptr).set_{1}({}, {}) }}", lcname, snake_case(name), o.name, index_decl, type_, index, val )?; } } if ip.write && ip.optional { writeln!( r, " #[no_mangle] pub unsafe extern \"C\" fn {}_set_data_{}_none(ptr: *mut {}{}) -> bool {{ (&mut *ptr).set_{1}({}, None) }}", lcname, snake_case(name), o.name, index_decl, index )?; } } } Ok(()) } fn write_rust_types(conf: &Config, r: &mut Vec) -> Result<()> { let mut has_option = false; let mut has_string = false; let mut has_byte_array = false; let mut has_list_or_tree = false; for o in conf.objects.values() { has_list_or_tree |= o.object_type != ObjectType::Object; for p in o.properties.values() { has_option |= p.optional; has_string |= p.property_type == Type::Simple(SimpleType::QString); has_byte_array |= p.property_type == Type::Simple(SimpleType::QByteArray); } for p in o.item_properties.values() { has_option |= p.optional; has_string |= p.item_property_type == SimpleType::QString; has_byte_array |= p.item_property_type == SimpleType::QByteArray; } for f in o.functions.values() { has_string |= f.return_type == SimpleType::QString; has_byte_array |= f.return_type == SimpleType::QByteArray; for a in &f.arguments { has_string |= a.argument_type == SimpleType::QString; has_byte_array |= a.argument_type == SimpleType::QByteArray; } } } if has_option || has_list_or_tree { writeln!( r, " #[repr(C)] pub struct COption {{ data: T, some: bool, }} impl COption {{ #![allow(dead_code)] fn into(self) -> Option {{ if self.some {{ Some(self.data) }} else {{ None }} }} }} impl From> for COption where T: Default, {{ fn from(t: Option) -> COption {{ if let Some(v) = t {{ COption {{ data: v, some: true, }} }} else {{ COption {{ data: T::default(), some: false, }} }} }} }}" )?; } if has_string { writeln!( r, " pub enum QString {{}} fn set_string_from_utf16(s: &mut String, str: *const c_ushort, len: c_int) {{ let utf16 = unsafe {{ slice::from_raw_parts(str, to_usize(len)) }}; let characters = decode_utf16(utf16.iter().cloned()) .map(|r| r.unwrap()); s.clear(); s.extend(characters); }} " )?; } if has_byte_array { writeln!( r, " pub enum QByteArray {{}}" )?; } if has_list_or_tree { writeln!( r, " #[repr(C)] #[derive(PartialEq, Eq, Debug)] pub enum SortOrder {{ Ascending = 0, Descending = 1, }} #[repr(C)] pub struct QModelIndex {{ row: c_int, internal_id: usize, }}" )?; } if has_string || has_byte_array || has_list_or_tree { writeln!( r, " fn to_usize(n: c_int) -> usize {{ if n < 0 {{ panic!(\"Cannot cast {{}} to usize\", n); }} n as usize }} " )?; } if has_string || has_byte_array || has_list_or_tree { writeln!( r, " fn to_c_int(n: usize) -> c_int {{ if n > c_int::max_value() as usize {{ panic!(\"Cannot cast {{}} to c_int\", n); }} n as c_int }} " )?; } Ok(()) } pub fn write_interface(conf: &Config) -> Result<()> { let mut r = Vec::new(); writeln!( r, "/* generated by rust_qt_binding_generator */ use libc::{{c_char, c_ushort, c_int}}; use std::slice; use std::char::decode_utf16; use std::sync::Arc; use std::sync::atomic::{{AtomicPtr, Ordering}}; use std::ptr::null; use {}{}::*;", get_module_prefix(conf), conf.rust.implementation_module )?; write_rust_types(conf, &mut r)?; for object in conf.objects.values() { write_rust_interface_object(&mut r, object, conf)?; } let mut file = conf .config_file .parent() .unwrap() .join(&conf.rust.dir) .join("src") .join(&conf.rust.interface_module); file.set_extension("rs"); write_if_different(file, &r) } fn write_rust_implementation_object(r: &mut Vec, o: &Object) -> Result<()> { if o.object_type != ObjectType::Object { writeln!(r, "#[derive(Default, Clone)]")?; writeln!(r, "struct {}Item {{", o.name)?; for (name, ip) in &o.item_properties { let lc = snake_case(name); if ip.optional { writeln!( r, " {}: Option<{}>,", lc, ip.item_property_type.rust_type() )?; } else { writeln!(r, " {}: {},", lc, ip.item_property_type.rust_type())?; } } writeln!(r, "}}\n")?; } let mut model_struct = String::new(); writeln!(r, "pub struct {} {{\n emit: {0}Emitter,", o.name)?; if o.object_type == ObjectType::List { model_struct = format!(", model: {}List", o.name); writeln!(r, " model: {}List,", o.name)?; } else if o.object_type == ObjectType::Tree { model_struct = format!(", model: {}Tree", o.name); writeln!(r, " model: {}Tree,", o.name)?; } for (name, p) in &o.properties { let lc = snake_case(name); writeln!(r, " {}: {},", lc, rust_type(p))?; } if o.object_type != ObjectType::Object { writeln!(r, " list: Vec<{}Item>,", o.name)?; } writeln!(r, "}}\n")?; for (name, p) in &o.properties { if p.is_object() { model_struct += &format!(", {}: {}", name, p.type_name()); } } writeln!( r, "impl {}Trait for {0} {{ fn new(emit: {0}Emitter{}) -> {0} {{ {0} {{ emit,", o.name, model_struct )?; if o.object_type != ObjectType::Object { writeln!(r, " model,")?; writeln!(r, " list: Vec::new(),")?; } for (name, p) in &o.properties { let lc = snake_case(name); if p.is_object() { writeln!(r, " {},", lc)?; } else { writeln!(r, " {}: {},", lc, rust_type_init(p))?; } } writeln!( r, " }} }} fn emit(&mut self) -> &mut {}Emitter {{ &self.emit }}", o.name )?; for (name, p) in &o.properties { let lc = snake_case(name); if p.is_object() { writeln!( r, " fn {}(&self) -> &{} {{ &self.{0} }} fn {0}_mut(&mut self) -> &mut {1} {{ &mut self.{0} }}", lc, rust_return_type(p) )?; } else if p.rust_by_function { writeln!( r, " fn {}(&self, getter: F) where F: FnOnce({}), {{ getter(&self.{0}) }}", lc, rust_return_type(p) )?; } else { writeln!(r, " fn {}(&self) -> {} {{", lc, rust_return_type(p))?; if p.is_complex() { if p.optional { writeln!(r, " self.{}.as_ref().map(|p| &p[..])", lc)?; } else { writeln!(r, " &self.{}", lc)?; } } else { writeln!(r, " self.{}", lc)?; } writeln!(r, " }}")?; } if !p.is_object() && p.write { let bytearray = p.property_type == Type::Simple(SimpleType::QByteArray); let (t, v) = if bytearray && p.optional { ("Option<&[u8]>".to_string(), ".map(|v| v.to_vec())") } else if bytearray { ("&[u8]".to_string(), ".to_vec()") } else { (rust_type(p), "") }; writeln!( r, " fn set_{}(&mut self, value: {}) {{ self.{0} = value{}; self.emit.{0}_changed(); }}", lc, t, v )?; } } if o.object_type == ObjectType::List { writeln!( r, " fn row_count(&self) -> usize {{\n self.list.len()\n }}" )?; } else if o.object_type == ObjectType::Tree { writeln!( r, " fn row_count(&self, item: Option) -> usize {{ self.list.len() }} fn index(&self, item: Option, row: usize) -> usize {{ 0 }} fn parent(&self, index: usize) -> Option {{ None }} fn row(&self, index: usize) -> usize {{ index }} fn check_row(&self, index: usize, _row: usize) -> Option {{ if index < self.list.len() {{ Some(index) }} else {{ None }} }}" )?; } if o.object_type != ObjectType::Object { for (name, ip) in &o.item_properties { let lc = snake_case(name); writeln!( r, " fn {}(&self, index: usize) -> {} {{", lc, rust_return_type_(ip) )?; if ip.is_complex() && ip.optional { writeln!( r, " self.list[index].{}.as_ref().map(|v| &v[..])", lc )?; } else if ip.is_complex() { writeln!(r, " &self.list[index].{}", lc)?; } else { writeln!(r, " self.list[index].{}", lc)?; } writeln!(r, " }}")?; let bytearray = ip.item_property_type == SimpleType::QByteArray; if ip.write && bytearray && ip.optional { writeln!( r, " fn set_{}(&mut self, index: usize, v: Option<&[u8]>) -> bool {{ self.list[index].{0} = v.map(|v| v.to_vec()); true }}", lc )?; } else if ip.write && bytearray { writeln!( r, " fn set_{}(&mut self, index: usize, v: &[u8]) -> bool {{ self.list[index].{0} = v.to_vec(); true }}", lc )?; } else if ip.write { writeln!( r, " fn set_{}(&mut self, index: usize, v: {}) -> bool {{ self.list[index].{0} = v; true }}", lc, rust_type_(ip) )?; } } } writeln!(r, "}}") } pub fn write_implementation(conf: &Config) -> Result<()> { let mut file = conf .config_file .parent() .unwrap() .join(&conf.rust.dir) .join("src") .join(&conf.rust.implementation_module); if !conf.overwrite_implementation && file.exists() { return Ok(()); } file.set_extension("rs"); if !conf.overwrite_implementation && file.exists() { return Ok(()); } let mut r = Vec::new(); writeln!( r, "#![allow(unused_imports)] #![allow(unused_variables)] #![allow(dead_code)] use {}{}::*; ", get_module_prefix(conf), conf.rust.interface_module )?; for object in conf.objects.values() { write_rust_implementation_object(&mut r, object)?; } write_if_different(file, &r) } /// Inspects the rust edition of the target crate to decide how the module /// imports should be written. /// /// As of Rust 2018, modules inside the crate should be prefixed with `crate::`. /// Prior to the 2018 edition, crate-local modules could be imported without /// this prefix. fn get_module_prefix(conf: &Config) -> &'static str { match conf.rust_edition { RustEdition::Rust2018 => "crate::", - _ => "" + _ => "", } }