diff --git a/demo/rust/src/implementation/fibonacci.rs b/demo/rust/src/implementation/fibonacci.rs index b2fb3b2..43bcc20 100644 --- a/demo/rust/src/implementation/fibonacci.rs +++ b/demo/rust/src/implementation/fibonacci.rs @@ -1,102 +1,102 @@ // Copyright 2017 Jos van den Oever // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License or (at your option) version 3 or any later version // accepted by the membership of KDE e.V. (or its successor approved // by the membership of KDE e.V.), which shall act as a proxy // defined in Section 14 of version 3 of the license. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . use std::thread; use interface::*; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::Arc; fn fibonacci(input: u32) -> usize { if input <= 1 { return input as usize; } let mut i = 0; let mut sum = 0; let mut last = 0; let mut cur = 1; while i < input - 1 { sum = last + cur; last = cur; cur = sum; i += 1; } sum } pub struct Fibonacci { emit: FibonacciEmitter, input: u32, result: Arc, } impl FibonacciTrait for Fibonacci { fn new(emit: FibonacciEmitter) -> Fibonacci { Fibonacci { emit, input: 0, result: Arc::new(AtomicUsize::new(0)), } } fn emit(&self) -> &FibonacciEmitter { &self.emit } fn input(&self) -> u32 { self.input } fn set_input(&mut self, value: u32) { self.input = value; self.emit.input_changed(); - let emit = self.emit.clone(); + let mut emit = self.emit.clone(); let result = self.result.clone(); result.swap(0, Ordering::SeqCst); emit.result_changed(); thread::spawn(move || { let r = fibonacci(value); result.swap(r, Ordering::SeqCst); emit.result_changed(); }); } fn result(&self) -> u64 { self.result.fetch_add(0, Ordering::SeqCst) as u64 } } pub struct FibonacciList { emit: FibonacciListEmitter, } impl FibonacciListTrait for FibonacciList { fn new(emit: FibonacciListEmitter, _: FibonacciListList) -> FibonacciList { FibonacciList { emit, } } fn emit(&self) -> &FibonacciListEmitter { &self.emit } fn row_count(&self) -> usize { 93 } fn row(&self, row: usize) -> u64 { row as u64 + 1 } fn fibonacci_number(&self, row: usize) -> u64 { fibonacci(row as u32 + 1) as u64 } } diff --git a/demo/rust/src/implementation/file_system_tree.rs b/demo/rust/src/implementation/file_system_tree.rs index 38000dd..4285207 100644 --- a/demo/rust/src/implementation/file_system_tree.rs +++ b/demo/rust/src/implementation/file_system_tree.rs @@ -1,309 +1,310 @@ // Copyright 2017 Jos van den Oever // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License or (at your option) version 3 or any later version // accepted by the membership of KDE e.V. (or its successor approved // by the membership of KDE e.V.), which shall act as a proxy // defined in Section 14 of version 3 of the license. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . use interface::*; use std::fs::*; use std::fs::read_dir; use std::path::PathBuf; use std::ffi::OsString; use std::default::Default; use std::thread; -use std::sync::{Arc, Mutex}; +use std::sync::mpsc::{Receiver, Sender, channel}; use std::marker::Sync; -use std::collections::HashMap; pub struct DirEntry { name: OsString, metadata: Option, path: Option, icon: Vec, } -type Incoming = Arc>>>; - impl Item for DirEntry { fn new(name: &str) -> DirEntry { DirEntry { name: OsString::from(name), metadata: metadata(name).ok(), path: None, - icon: Vec::new() + icon: Vec::new(), } } fn can_fetch_more(&self) -> bool { self.metadata.as_ref().map_or(false, |m| m.is_dir()) } fn file_name(&self) -> String { self.name.to_string_lossy().to_string() } fn file_path(&self) -> Option { self.path.as_ref().map(|p| p.to_string_lossy().into()) } fn file_permissions(&self) -> i32 { 42 } fn file_type(&self) -> i32 { 0 } fn file_size(&self) -> Option { self.metadata.as_ref().map(|m| m.len()) } fn icon(&self) -> &[u8] { &self.icon } - fn retrieve(id: usize, parents: Vec<&DirEntry>, q: Incoming, emit: FileSystemTreeEmitter) { - let mut v = Vec::new(); + fn retrieve(id: usize, parents: Vec<&Self>, outgoing: &Sender<(usize, PathBuf)>) { let path: PathBuf = parents.into_iter().map(|e| &e.name).collect(); - thread::spawn(move || { + if let Err(e) = outgoing.send((id, path)) { + eprintln!("{}", e); + } + } + fn read_files( + incoming: Receiver<(usize, PathBuf)>, + outgoing: Sender<(usize, Vec)>, + mut emit: FileSystemTreeEmitter, + ) { + thread::spawn(move || while let Ok((id, path)) = incoming.recv() { + let mut v = Vec::new(); if let Ok(it) = read_dir(&path) { for i in it.filter_map(|v| v.ok()) { let de = DirEntry { name: i.file_name(), metadata: i.metadata().ok(), path: Some(i.path()), icon: Vec::new(), }; v.push(de); } } v.sort_by(|a, b| a.name.cmp(&b.name)); - let mut map = q.lock().unwrap(); - if !map.contains_key(&id) { - map.insert(id, v); - emit.new_data_ready(Some(id)); - } + if let Ok(()) = outgoing.send((id, v)) { + emit.new_data_ready(Some(id)); + } else { + return; + } }); } } impl Default for DirEntry { fn default() -> DirEntry { DirEntry { name: OsString::new(), metadata: None, path: None, icon: Vec::new(), } } } pub trait Item: Default { fn new(name: &str) -> Self; fn can_fetch_more(&self) -> bool; - fn retrieve(id: usize, parents: Vec<&Self>, q: Incoming, emit: FileSystemTreeEmitter); + fn retrieve(id: usize, parents: Vec<&Self>, outgoing: &Sender<(usize, PathBuf)>); + fn read_files( + incoming: Receiver<(usize, PathBuf)>, + outgoing: Sender<(usize, Vec)>, + emit: FileSystemTreeEmitter, + ); fn file_name(&self) -> String; fn file_path(&self) -> Option; fn file_permissions(&self) -> i32; fn file_type(&self) -> i32; fn file_size(&self) -> Option; fn icon(&self) -> &[u8]; } pub type FileSystemTree = RGeneralItemModel; struct Entry { parent: Option, row: usize, children: Option>, data: T, } pub struct RGeneralItemModel { emit: FileSystemTreeEmitter, model: FileSystemTreeTree, entries: Vec>, path: Option, - incoming: Incoming, + outgoing: Sender<(usize, PathBuf)>, + incoming: Receiver<(usize, Vec)>, } impl RGeneralItemModel where T: Sync + Send, { fn reset(&mut self) { self.model.begin_reset_model(); self.entries.clear(); if let Some(ref path) = self.path { let root = Entry { parent: None, row: 0, children: None, data: T::new(path), }; self.entries.push(root); } self.model.end_reset_model(); } fn get(&self, index: usize) -> &Entry { &self.entries[index] } - fn retrieve(&mut self, index: usize) { + fn retrieve(&self, index: usize) { let parents = self.get_parents(index); - let incoming = self.incoming.clone(); - T::retrieve(index, parents, incoming, self.emit.clone()); + T::retrieve(index, parents, &self.outgoing); } fn process_incoming(&mut self) { - if let Ok(ref mut incoming) = self.incoming.try_lock() { - for (id, entries) in incoming.drain() { - if self.entries[id].children.is_some() { - continue; - } - let mut new_entries = Vec::new(); - let mut children = Vec::new(); - { - for (r, d) in entries.into_iter().enumerate() { - let e = Entry { - parent: Some(id), - row: r, - children: None, - data: d, - }; - children.push(self.entries.len() + r); - new_entries.push(e); - } - if !new_entries.is_empty() { - self.model.begin_insert_rows( - Some(id), - 0, - new_entries.len() - 1, - ); - } - } + while let Ok((id, entries)) = self.incoming.try_recv() { + if self.entries[id].children.is_some() { + continue; + } + let mut new_entries = Vec::new(); + let mut children = Vec::new(); + for (r, d) in entries.into_iter().enumerate() { + new_entries.push(Entry { + parent: Some(id), + row: r, + children: None, + data: d, + }); + children.push(self.entries.len() + r); + } + if new_entries.is_empty() { self.entries[id].children = Some(children); - if !new_entries.is_empty() { - self.entries.append(&mut new_entries); - self.model.end_insert_rows(); - } + } else { + self.model.begin_insert_rows( + Some(id), + 0, + new_entries.len() - 1, + ); + self.entries[id].children = Some(children); + self.entries.append(&mut new_entries); + self.model.end_insert_rows(); } } } fn get_parents(&self, id: usize) -> Vec<&T> { let mut pos = Some(id); let mut e = Vec::new(); while let Some(p) = pos { e.push(p); pos = self.entries[p].parent; } e.into_iter().rev().map(|i| &self.entries[i].data).collect() } } impl FileSystemTreeTrait for RGeneralItemModel where T: Sync + Send, { - fn new(emit: FileSystemTreeEmitter, model: FileSystemTreeTree) -> Self { - let mut tree = RGeneralItemModel { + fn new(mut emit: FileSystemTreeEmitter, model: FileSystemTreeTree) -> Self { + let (outgoing, thread_incoming) = channel(); + let (thread_outgoing, incoming) = channel::<(usize, Vec)>(); + T::read_files(thread_incoming, thread_outgoing, emit.clone()); + let mut tree: RGeneralItemModel = RGeneralItemModel { emit, model, entries: Vec::new(), path: None, - incoming: Arc::new(Mutex::new(HashMap::new())), + outgoing, + incoming, }; tree.reset(); tree } fn emit(&self) -> &FileSystemTreeEmitter { &self.emit } fn path(&self) -> Option<&str> { - self.path.as_ref().map(|s|&s[..]) + self.path.as_ref().map(|s| &s[..]) } fn set_path(&mut self, value: Option) { if self.path != value { self.path = value; self.emit.path_changed(); self.reset(); } } fn can_fetch_more(&self, index: Option) -> bool { - if let Some(index) = index { - let entry = self.get(index); - entry.children.is_none() && entry.data.can_fetch_more() - } else { - false - } + let entry = self.get(index.unwrap_or(0)); + entry.children.is_none() && entry.data.can_fetch_more() } fn fetch_more(&mut self, index: Option) { self.process_incoming(); if !self.can_fetch_more(index) { return; } - if let Some(index) = index { - self.retrieve(index); - } + self.retrieve(index.unwrap_or(0)); } fn row_count(&self, index: Option) -> usize { if self.entries.is_empty() { return 0; } if let Some(i) = index { let entry = self.get(i); if let Some(ref children) = entry.children { children.len() } else { - // model does lazy loading, signal that data may be available - if self.can_fetch_more(index) { - self.emit.new_data_ready(index); - } + self.retrieve(i); 0 } } else { 1 } } fn index(&self, index: Option, row: usize) -> usize { if let Some(index) = index { self.get(index).children.as_ref().unwrap()[row] } else { 0 } } fn parent(&self, index: usize) -> Option { self.entries[index].parent } fn row(&self, index: usize) -> usize { self.entries[index].row } fn check_row(&self, index: usize, _row: usize) -> Option { if index < self.entries.len() { Some(self.row(index)) } else { None } } fn file_name(&self, index: usize) -> String { self.get(index).data.file_name() } fn file_permissions(&self, index: usize) -> i32 { self.get(index).data.file_permissions() } #[allow(unused_variables)] fn file_icon(&self, index: usize) -> &[u8] { self.get(index).data.icon() } fn file_path(&self, index: usize) -> Option { self.get(index).data.file_path() } fn file_type(&self, index: usize) -> i32 { self.get(index).data.file_type() } fn file_size(&self, index: usize) -> Option { self.get(index).data.file_size() } } diff --git a/demo/rust/src/implementation/processes.rs b/demo/rust/src/implementation/processes.rs index 44cdc4b..dcc1b98 100644 --- a/demo/rust/src/implementation/processes.rs +++ b/demo/rust/src/implementation/processes.rs @@ -1,442 +1,442 @@ // Copyright 2017 Jos van den Oever // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License or (at your option) version 3 or any later version // accepted by the membership of KDE e.V. (or its successor approved // by the membership of KDE e.V.), which shall act as a proxy // defined in Section 14 of version 3 of the license. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . use interface::*; use sysinfo::*; use std::sync::{Arc, Mutex}; use std::collections::HashMap; use libc::pid_t; use std::thread; use std::time::Duration; use std::sync::mpsc::{channel, Sender, Receiver, RecvTimeoutError}; struct ProcessItem { row: usize, tasks: Vec, process: Process, } #[derive(Default)] struct ProcessTree { top: Vec, processes: HashMap, cpusum: f32, } enum ChangeState { Active, Inactive, Quit } pub struct Processes { emit: ProcessesEmitter, model: ProcessesTree, p: ProcessTree, incoming: Arc>>, active: bool, channel: Sender } fn check_process_hierarchy(parent: Option, processes: &HashMap) { for (pid, process) in processes { assert_eq!(process.pid, *pid); if parent.is_some() { assert_eq!(process.parent, parent); } check_process_hierarchy(Some(*pid), &process.tasks); } } fn collect_processes( tasks: &HashMap, mut processes: &mut HashMap, ) -> f32 { let mut cpusum = 0.0; for process in tasks.values() { processes.insert( process.pid, ProcessItem { row: 0, tasks: Vec::new(), process: process.clone(), }, ); let s = collect_processes(&process.tasks, &mut processes); cpusum += process.cpu_usage + s; } cpusum } // reconstruct process hierarchy fn handle_tasks(processes: &mut HashMap) -> Vec { let mut top = Vec::new(); let pids: Vec = processes.keys().cloned().collect(); for pid in pids { if let Some(parent) = processes[&pid].process.parent { let p = processes.get_mut(&parent).unwrap(); p.tasks.push(pid); } else { top.push(pid); } } top } fn update_rows(list: &[pid_t], processes: &mut HashMap) { for (row, pid) in list.iter().enumerate() { processes.get_mut(pid).unwrap().row = row; let l = processes[pid].tasks.clone(); update_rows(&l, processes); } } fn sort_tasks(p: &mut ProcessTree) { for process in p.processes.values_mut() { process.tasks.sort(); } p.top.sort(); update_rows(&p.top, &mut p.processes); } fn update() -> ProcessTree { let mut p = ProcessTree::default(); let mut sysinfo = System::new(); sysinfo.refresh_processes(); let list = sysinfo.get_process_list(); check_process_hierarchy(None, list); p.cpusum = collect_processes(list, &mut p.processes); p.top = handle_tasks(&mut p.processes); sort_tasks(&mut p); p } fn update_thread( - emit: ProcessesEmitter, + mut emit: ProcessesEmitter, incoming: Arc>>, mut active: bool, status_channel: Receiver, ) { thread::spawn(move || { loop { let timeout = if active { *incoming.lock().unwrap() = Some(update()); emit.new_data_ready(None); Duration::from_secs(1) } else { Duration::from_secs(10_000) }; match status_channel.recv_timeout(timeout) { Err(RecvTimeoutError::Timeout) => {}, Err(RecvTimeoutError::Disconnected) | Ok(ChangeState::Quit) => { return; }, Ok(ChangeState::Active) => { active = true; }, Ok(ChangeState::Inactive) => { active = false; }, } } }); } impl Processes { fn get(&self, index: usize) -> &ProcessItem { let pid = index as pid_t; &self.p.processes[&pid] } fn process(&self, index: usize) -> &Process { let pid = index as pid_t; &self.p.processes[&pid].process } } fn move_process( pid: pid_t, amap: &mut HashMap, bmap: &mut HashMap, ) { if let Some(e) = bmap.remove(&pid) { amap.insert(pid, e); let ts = amap[&pid].tasks.clone(); for t in ts { move_process(t, amap, bmap); } } } fn remove_row( - model: &ProcessesTree, + model: &mut ProcessesTree, parent: pid_t, row: usize, map: &mut HashMap, ) { let pid = map[&parent].tasks[row]; println!( "removing {} '{}' {}", pid, map[&pid].process.exe, map[&pid].process.cmd.join(" ") ); model.begin_remove_rows(Some(parent as usize), row, row); map.remove(&pid); let len = { let tasks = &mut map.get_mut(&parent).unwrap().tasks; tasks.remove(row); tasks.len() }; for r in row..len { let pid = map.get_mut(&parent).unwrap().tasks[r]; map.get_mut(&pid).unwrap().row = r; } model.end_remove_rows(); } fn insert_row( - model: &ProcessesTree, + model: &mut ProcessesTree, parent: pid_t, row: usize, map: &mut HashMap, pid: pid_t, source: &mut HashMap, ) { println!( "adding {} '{}' {}", pid, source[&pid].process.exe, source[&pid].process.cmd.join(" ") ); model.begin_insert_rows(Some(parent as usize), row, row); move_process(pid, map, source); let len = { let tasks = &mut map.get_mut(&parent).unwrap().tasks; tasks.insert(row, pid); tasks.len() }; for r in row..len { let pid = map.get_mut(&parent).unwrap().tasks[r]; map.get_mut(&pid).unwrap().row = r; } model.end_insert_rows(); } fn cmp_f32(a: f32, b: f32) -> bool { ((a - b) / a).abs() < 0.01 } -fn sync_row(model: &ProcessesTree, pid: pid_t, a: &mut Process, b: &Process) -> f32 { +fn sync_row(model: &mut ProcessesTree, pid: pid_t, a: &mut Process, b: &Process) -> f32 { let mut changed = a.name != b.name; if changed { a.name.clone_from(&b.name); } if !cmp_f32(a.cpu_usage, b.cpu_usage) { a.cpu_usage = b.cpu_usage; changed = true; } if a.cmd != b.cmd { a.cmd.clone_from(&b.cmd); changed = true; } if a.exe != b.exe { a.exe.clone_from(&b.exe); changed = true; } if a.memory != b.memory { a.memory = b.memory; changed = true; } if changed { model.data_changed(pid as usize, pid as usize); } b.cpu_usage } fn sync_tree( - model: &ProcessesTree, + model: &mut ProcessesTree, parent: pid_t, amap: &mut HashMap, bmap: &mut HashMap, ) -> f32 { let mut a = 0; let mut b = 0; let mut alen = amap[&parent].tasks.len(); let blen = bmap[&parent].tasks.len(); let mut cpu_total = bmap[&parent].process.cpu_usage; while a < alen && b < blen { let apid = amap[&parent].tasks[a]; let bpid = bmap[&parent].tasks[b]; if apid < bpid { // a process has disappeared remove_row(model, parent, a, amap); alen -= 1; } else if apid > bpid { // a process has appeared insert_row(model, parent, a, amap, bpid, bmap); cpu_total += amap[&bpid].process.cpu_usage; a += 1; alen += 1; b += 1; } else { cpu_total += sync_row( model, apid, &mut amap.get_mut(&apid).unwrap().process, &bmap[&apid].process, ); cpu_total += sync_tree(model, apid, amap, bmap); a += 1; b += 1; } } while a < blen { let bpid = bmap[&parent].tasks[b]; insert_row(model, parent, a, amap, bpid, bmap); a += 1; alen += 1; b += 1; } while b < alen { remove_row(model, parent, a, amap); alen -= 1; } if !cmp_f32(cpu_total, bmap[&parent].process.cpu_usage) { amap.get_mut(&parent).unwrap().process.cpu_usage = cpu_total; model.data_changed(parent as usize, parent as usize); } assert_eq!(a, b); cpu_total } impl ProcessesTrait for Processes { - fn new(emit: ProcessesEmitter, model: ProcessesTree) -> Processes { + fn new(mut emit: ProcessesEmitter, model: ProcessesTree) -> Processes { let (tx, rx) = channel(); let p = Processes { emit: emit.clone(), model, p: ProcessTree::default(), incoming: Arc::new(Mutex::new(None)), active: false, channel: tx, }; update_thread(emit, p.incoming.clone(), p.active, rx); p } fn emit(&self) -> &ProcessesEmitter { &self.emit } fn row_count(&self, index: Option) -> usize { if let Some(index) = index { self.get(index).tasks.len() } else { self.p.top.len() } } fn index(&self, index: Option, row: usize) -> usize { if let Some(index) = index { self.get(index).tasks[row] as usize } else { self.p.top[row] as usize } } fn parent(&self, index: usize) -> Option { self.get(index).process.parent.map(|pid| pid as usize) } fn can_fetch_more(&self, index: Option) -> bool { if index.is_some() || !self.active { return false; } if let Ok(ref incoming) = self.incoming.try_lock() { incoming.is_some() } else { false } } fn fetch_more(&mut self, index: Option) { if index.is_some() || !self.active { return; } let new = if let Ok(ref mut incoming) = self.incoming.try_lock() { incoming.take() } else { None }; if let Some(mut new) = new { // alert! at the top level, only adding is supported! if self.p.top.is_empty() { self.model.begin_reset_model(); self.p = new; self.model.end_reset_model(); } else { let top = self.p.top.clone(); for pid in top { - sync_tree(&self.model, pid, &mut self.p.processes, &mut new.processes); + sync_tree(&mut self.model, pid, &mut self.p.processes, &mut new.processes); } } } } fn row(&self, index: usize) -> usize { self.get(index).row } fn check_row(&self, index: usize, _row: usize) -> Option { let pid = index as pid_t; if self.p.processes.contains_key(&pid) { Some(self.row(index)) } else { None } } fn pid(&self, index: usize) -> u32 { self.process(index).pid as u32 } fn uid(&self, index: usize) -> u32 { self.process(index).uid as u32 } fn cpu_usage(&self, index: usize) -> f32 { self.process(index).cpu_usage } fn cpu_percentage(&self, index: usize) -> u8 { let cpu = self.process(index).cpu_usage / self.p.cpusum; (cpu * 100.0) as u8 } fn memory(&self, index: usize) -> u64 { self.process(index).memory } fn name(&self, index: usize) -> &str { &self.process(index).name } fn cmd(&self, index: usize) -> String { self.process(index).cmd.join(" ") } fn active(&self) -> bool { self.active } fn set_active(&mut self, active: bool) { if self.active != active { self.active = active; if active { self.channel.send(ChangeState::Active) } else { self.channel.send(ChangeState::Inactive) }.expect("Process thread died."); } } } impl Drop for Processes { fn drop(&mut self) { self.channel.send(ChangeState::Quit).expect("Process thread died."); } } diff --git a/demo/rust/src/interface.rs b/demo/rust/src/interface.rs index 112f102..866bbaa 100644 --- a/demo/rust/src/interface.rs +++ b/demo/rust/src/interface.rs @@ -1,1342 +1,1410 @@ /* 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 implementation::*; #[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, } } } } 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); } pub enum QByteArray {} #[repr(C)] #[derive(PartialEq, Eq, Debug)] pub enum SortOrder { Ascending = 0, Descending = 1, } #[repr(C)] pub struct QModelIndex { row: c_int, internal_id: usize, } fn to_usize(n: c_int) -> usize { if n < 0 { panic!("Cannot cast {} to usize", n); } n as usize } 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 } pub struct DemoQObject {} -#[derive(Clone)] pub struct DemoEmitter { qobject: Arc>, } unsafe impl Send for DemoEmitter {} impl DemoEmitter { + /// 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) -> DemoEmitter { + DemoEmitter { + qobject: self.qobject.clone(), + } + } fn clear(&self) { let n: *const DemoQObject = null(); self.qobject.store(n as *mut DemoQObject, Ordering::SeqCst); } } pub trait DemoTrait { fn new(emit: DemoEmitter, fibonacci: Fibonacci, fibonacci_list: FibonacciList, file_system_tree: FileSystemTree, processes: Processes, time_series: TimeSeries) -> Self; fn emit(&self) -> &DemoEmitter; fn fibonacci(&self) -> &Fibonacci; fn fibonacci_mut(&mut self) -> &mut Fibonacci; fn fibonacci_list(&self) -> &FibonacciList; fn fibonacci_list_mut(&mut self) -> &mut FibonacciList; fn file_system_tree(&self) -> &FileSystemTree; fn file_system_tree_mut(&mut self) -> &mut FileSystemTree; fn processes(&self) -> &Processes; fn processes_mut(&mut self) -> &mut Processes; fn time_series(&self) -> &TimeSeries; fn time_series_mut(&mut self) -> &mut TimeSeries; } #[no_mangle] pub extern "C" fn demo_new( demo: *mut DemoQObject, fibonacci: *mut FibonacciQObject, - fibonacci_input_changed: fn(*const FibonacciQObject), - fibonacci_result_changed: fn(*const FibonacciQObject), + fibonacci_input_changed: fn(*mut FibonacciQObject), + fibonacci_result_changed: fn(*mut FibonacciQObject), fibonacci_list: *mut FibonacciListQObject, - fibonacci_list_new_data_ready: fn(*const FibonacciListQObject), - fibonacci_list_layout_about_to_be_changed: fn(*const FibonacciListQObject), - fibonacci_list_layout_changed: fn(*const FibonacciListQObject), - fibonacci_list_data_changed: fn(*const FibonacciListQObject, usize, usize), - fibonacci_list_begin_reset_model: fn(*const FibonacciListQObject), - fibonacci_list_end_reset_model: fn(*const FibonacciListQObject), - fibonacci_list_begin_insert_rows: fn(*const FibonacciListQObject, usize, usize), - fibonacci_list_end_insert_rows: fn(*const FibonacciListQObject), - fibonacci_list_begin_move_rows: fn(*const FibonacciListQObject, usize, usize, usize), - fibonacci_list_end_move_rows: fn(*const FibonacciListQObject), - fibonacci_list_begin_remove_rows: fn(*const FibonacciListQObject, usize, usize), - fibonacci_list_end_remove_rows: fn(*const FibonacciListQObject), + fibonacci_list_new_data_ready: fn(*mut FibonacciListQObject), + fibonacci_list_layout_about_to_be_changed: fn(*mut FibonacciListQObject), + fibonacci_list_layout_changed: fn(*mut FibonacciListQObject), + fibonacci_list_data_changed: fn(*mut FibonacciListQObject, usize, usize), + fibonacci_list_begin_reset_model: fn(*mut FibonacciListQObject), + fibonacci_list_end_reset_model: fn(*mut FibonacciListQObject), + fibonacci_list_begin_insert_rows: fn(*mut FibonacciListQObject, usize, usize), + fibonacci_list_end_insert_rows: fn(*mut FibonacciListQObject), + fibonacci_list_begin_move_rows: fn(*mut FibonacciListQObject, usize, usize, usize), + fibonacci_list_end_move_rows: fn(*mut FibonacciListQObject), + fibonacci_list_begin_remove_rows: fn(*mut FibonacciListQObject, usize, usize), + fibonacci_list_end_remove_rows: fn(*mut FibonacciListQObject), file_system_tree: *mut FileSystemTreeQObject, - file_system_tree_path_changed: fn(*const FileSystemTreeQObject), - file_system_tree_new_data_ready: fn(*const FileSystemTreeQObject, index: COption), - file_system_tree_layout_about_to_be_changed: fn(*const FileSystemTreeQObject), - file_system_tree_layout_changed: fn(*const FileSystemTreeQObject), - file_system_tree_data_changed: fn(*const FileSystemTreeQObject, usize, usize), - file_system_tree_begin_reset_model: fn(*const FileSystemTreeQObject), - file_system_tree_end_reset_model: fn(*const FileSystemTreeQObject), - file_system_tree_begin_insert_rows: fn(*const FileSystemTreeQObject, index: COption, usize, usize), - file_system_tree_end_insert_rows: fn(*const FileSystemTreeQObject), - file_system_tree_begin_move_rows: fn(*const FileSystemTreeQObject, index: COption, usize, usize, index: COption, usize), - file_system_tree_end_move_rows: fn(*const FileSystemTreeQObject), - file_system_tree_begin_remove_rows: fn(*const FileSystemTreeQObject, index: COption, usize, usize), - file_system_tree_end_remove_rows: fn(*const FileSystemTreeQObject), + file_system_tree_path_changed: fn(*mut FileSystemTreeQObject), + file_system_tree_new_data_ready: fn(*mut FileSystemTreeQObject, index: COption), + file_system_tree_layout_about_to_be_changed: fn(*mut FileSystemTreeQObject), + file_system_tree_layout_changed: fn(*mut FileSystemTreeQObject), + file_system_tree_data_changed: fn(*mut FileSystemTreeQObject, usize, usize), + file_system_tree_begin_reset_model: fn(*mut FileSystemTreeQObject), + file_system_tree_end_reset_model: fn(*mut FileSystemTreeQObject), + file_system_tree_begin_insert_rows: fn(*mut FileSystemTreeQObject, index: COption, usize, usize), + file_system_tree_end_insert_rows: fn(*mut FileSystemTreeQObject), + file_system_tree_begin_move_rows: fn(*mut FileSystemTreeQObject, index: COption, usize, usize, index: COption, usize), + file_system_tree_end_move_rows: fn(*mut FileSystemTreeQObject), + file_system_tree_begin_remove_rows: fn(*mut FileSystemTreeQObject, index: COption, usize, usize), + file_system_tree_end_remove_rows: fn(*mut FileSystemTreeQObject), processes: *mut ProcessesQObject, - processes_active_changed: fn(*const ProcessesQObject), - processes_new_data_ready: fn(*const ProcessesQObject, index: COption), - processes_layout_about_to_be_changed: fn(*const ProcessesQObject), - processes_layout_changed: fn(*const ProcessesQObject), - processes_data_changed: fn(*const ProcessesQObject, usize, usize), - processes_begin_reset_model: fn(*const ProcessesQObject), - processes_end_reset_model: fn(*const ProcessesQObject), - processes_begin_insert_rows: fn(*const ProcessesQObject, index: COption, usize, usize), - processes_end_insert_rows: fn(*const ProcessesQObject), - processes_begin_move_rows: fn(*const ProcessesQObject, index: COption, usize, usize, index: COption, usize), - processes_end_move_rows: fn(*const ProcessesQObject), - processes_begin_remove_rows: fn(*const ProcessesQObject, index: COption, usize, usize), - processes_end_remove_rows: fn(*const ProcessesQObject), + processes_active_changed: fn(*mut ProcessesQObject), + processes_new_data_ready: fn(*mut ProcessesQObject, index: COption), + processes_layout_about_to_be_changed: fn(*mut ProcessesQObject), + processes_layout_changed: fn(*mut ProcessesQObject), + processes_data_changed: fn(*mut ProcessesQObject, usize, usize), + processes_begin_reset_model: fn(*mut ProcessesQObject), + processes_end_reset_model: fn(*mut ProcessesQObject), + processes_begin_insert_rows: fn(*mut ProcessesQObject, index: COption, usize, usize), + processes_end_insert_rows: fn(*mut ProcessesQObject), + processes_begin_move_rows: fn(*mut ProcessesQObject, index: COption, usize, usize, index: COption, usize), + processes_end_move_rows: fn(*mut ProcessesQObject), + processes_begin_remove_rows: fn(*mut ProcessesQObject, index: COption, usize, usize), + processes_end_remove_rows: fn(*mut ProcessesQObject), time_series: *mut TimeSeriesQObject, - time_series_new_data_ready: fn(*const TimeSeriesQObject), - time_series_layout_about_to_be_changed: fn(*const TimeSeriesQObject), - time_series_layout_changed: fn(*const TimeSeriesQObject), - time_series_data_changed: fn(*const TimeSeriesQObject, usize, usize), - time_series_begin_reset_model: fn(*const TimeSeriesQObject), - time_series_end_reset_model: fn(*const TimeSeriesQObject), - time_series_begin_insert_rows: fn(*const TimeSeriesQObject, usize, usize), - time_series_end_insert_rows: fn(*const TimeSeriesQObject), - time_series_begin_move_rows: fn(*const TimeSeriesQObject, usize, usize, usize), - time_series_end_move_rows: fn(*const TimeSeriesQObject), - time_series_begin_remove_rows: fn(*const TimeSeriesQObject, usize, usize), - time_series_end_remove_rows: fn(*const TimeSeriesQObject), + time_series_new_data_ready: fn(*mut TimeSeriesQObject), + time_series_layout_about_to_be_changed: fn(*mut TimeSeriesQObject), + time_series_layout_changed: fn(*mut TimeSeriesQObject), + time_series_data_changed: fn(*mut TimeSeriesQObject, usize, usize), + time_series_begin_reset_model: fn(*mut TimeSeriesQObject), + time_series_end_reset_model: fn(*mut TimeSeriesQObject), + time_series_begin_insert_rows: fn(*mut TimeSeriesQObject, usize, usize), + time_series_end_insert_rows: fn(*mut TimeSeriesQObject), + time_series_begin_move_rows: fn(*mut TimeSeriesQObject, usize, usize, usize), + time_series_end_move_rows: fn(*mut TimeSeriesQObject), + time_series_begin_remove_rows: fn(*mut TimeSeriesQObject, usize, usize), + time_series_end_remove_rows: fn(*mut TimeSeriesQObject), ) -> *mut Demo { let fibonacci_emit = FibonacciEmitter { qobject: Arc::new(AtomicPtr::new(fibonacci)), input_changed: fibonacci_input_changed, result_changed: fibonacci_result_changed, }; let d_fibonacci = Fibonacci::new(fibonacci_emit); let fibonacci_list_emit = FibonacciListEmitter { qobject: Arc::new(AtomicPtr::new(fibonacci_list)), new_data_ready: fibonacci_list_new_data_ready, }; let model = FibonacciListList { qobject: fibonacci_list, layout_about_to_be_changed: fibonacci_list_layout_about_to_be_changed, layout_changed: fibonacci_list_layout_changed, data_changed: fibonacci_list_data_changed, begin_reset_model: fibonacci_list_begin_reset_model, end_reset_model: fibonacci_list_end_reset_model, begin_insert_rows: fibonacci_list_begin_insert_rows, end_insert_rows: fibonacci_list_end_insert_rows, begin_move_rows: fibonacci_list_begin_move_rows, end_move_rows: fibonacci_list_end_move_rows, begin_remove_rows: fibonacci_list_begin_remove_rows, end_remove_rows: fibonacci_list_end_remove_rows, }; let d_fibonacci_list = FibonacciList::new(fibonacci_list_emit, model); let file_system_tree_emit = FileSystemTreeEmitter { qobject: Arc::new(AtomicPtr::new(file_system_tree)), path_changed: file_system_tree_path_changed, new_data_ready: file_system_tree_new_data_ready, }; let model = FileSystemTreeTree { qobject: file_system_tree, layout_about_to_be_changed: file_system_tree_layout_about_to_be_changed, layout_changed: file_system_tree_layout_changed, data_changed: file_system_tree_data_changed, begin_reset_model: file_system_tree_begin_reset_model, end_reset_model: file_system_tree_end_reset_model, begin_insert_rows: file_system_tree_begin_insert_rows, end_insert_rows: file_system_tree_end_insert_rows, begin_move_rows: file_system_tree_begin_move_rows, end_move_rows: file_system_tree_end_move_rows, begin_remove_rows: file_system_tree_begin_remove_rows, end_remove_rows: file_system_tree_end_remove_rows, }; let d_file_system_tree = FileSystemTree::new(file_system_tree_emit, model); let processes_emit = ProcessesEmitter { qobject: Arc::new(AtomicPtr::new(processes)), active_changed: processes_active_changed, new_data_ready: processes_new_data_ready, }; let model = ProcessesTree { qobject: processes, layout_about_to_be_changed: processes_layout_about_to_be_changed, layout_changed: processes_layout_changed, data_changed: processes_data_changed, begin_reset_model: processes_begin_reset_model, end_reset_model: processes_end_reset_model, begin_insert_rows: processes_begin_insert_rows, end_insert_rows: processes_end_insert_rows, begin_move_rows: processes_begin_move_rows, end_move_rows: processes_end_move_rows, begin_remove_rows: processes_begin_remove_rows, end_remove_rows: processes_end_remove_rows, }; let d_processes = Processes::new(processes_emit, model); let time_series_emit = TimeSeriesEmitter { qobject: Arc::new(AtomicPtr::new(time_series)), new_data_ready: time_series_new_data_ready, }; let model = TimeSeriesList { qobject: time_series, layout_about_to_be_changed: time_series_layout_about_to_be_changed, layout_changed: time_series_layout_changed, data_changed: time_series_data_changed, begin_reset_model: time_series_begin_reset_model, end_reset_model: time_series_end_reset_model, begin_insert_rows: time_series_begin_insert_rows, end_insert_rows: time_series_end_insert_rows, begin_move_rows: time_series_begin_move_rows, end_move_rows: time_series_end_move_rows, begin_remove_rows: time_series_begin_remove_rows, end_remove_rows: time_series_end_remove_rows, }; let d_time_series = TimeSeries::new(time_series_emit, model); let demo_emit = DemoEmitter { qobject: Arc::new(AtomicPtr::new(demo)), }; let d_demo = Demo::new(demo_emit, d_fibonacci, d_fibonacci_list, d_file_system_tree, d_processes, d_time_series); Box::into_raw(Box::new(d_demo)) } #[no_mangle] pub unsafe extern "C" fn demo_free(ptr: *mut Demo) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn demo_fibonacci_get(ptr: *mut Demo) -> *mut Fibonacci { (&mut *ptr).fibonacci_mut() } #[no_mangle] pub unsafe extern "C" fn demo_fibonacci_list_get(ptr: *mut Demo) -> *mut FibonacciList { (&mut *ptr).fibonacci_list_mut() } #[no_mangle] pub unsafe extern "C" fn demo_file_system_tree_get(ptr: *mut Demo) -> *mut FileSystemTree { (&mut *ptr).file_system_tree_mut() } #[no_mangle] pub unsafe extern "C" fn demo_processes_get(ptr: *mut Demo) -> *mut Processes { (&mut *ptr).processes_mut() } #[no_mangle] pub unsafe extern "C" fn demo_time_series_get(ptr: *mut Demo) -> *mut TimeSeries { (&mut *ptr).time_series_mut() } pub struct FibonacciQObject {} -#[derive(Clone)] pub struct FibonacciEmitter { qobject: Arc>, - input_changed: fn(*const FibonacciQObject), - result_changed: fn(*const FibonacciQObject), + input_changed: fn(*mut FibonacciQObject), + result_changed: fn(*mut FibonacciQObject), } unsafe impl Send for FibonacciEmitter {} impl FibonacciEmitter { + /// 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) -> FibonacciEmitter { + FibonacciEmitter { + qobject: self.qobject.clone(), + input_changed: self.input_changed, + result_changed: self.result_changed, + } + } fn clear(&self) { let n: *const FibonacciQObject = null(); self.qobject.store(n as *mut FibonacciQObject, Ordering::SeqCst); } - pub fn input_changed(&self) { + pub fn input_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.input_changed)(ptr); } } - pub fn result_changed(&self) { + pub fn result_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.result_changed)(ptr); } } } pub trait FibonacciTrait { fn new(emit: FibonacciEmitter) -> Self; fn emit(&self) -> &FibonacciEmitter; fn input(&self) -> u32; fn set_input(&mut self, value: u32); fn result(&self) -> u64; } #[no_mangle] pub extern "C" fn fibonacci_new( fibonacci: *mut FibonacciQObject, - fibonacci_input_changed: fn(*const FibonacciQObject), - fibonacci_result_changed: fn(*const FibonacciQObject), + fibonacci_input_changed: fn(*mut FibonacciQObject), + fibonacci_result_changed: fn(*mut FibonacciQObject), ) -> *mut Fibonacci { let fibonacci_emit = FibonacciEmitter { qobject: Arc::new(AtomicPtr::new(fibonacci)), input_changed: fibonacci_input_changed, result_changed: fibonacci_result_changed, }; let d_fibonacci = Fibonacci::new(fibonacci_emit); Box::into_raw(Box::new(d_fibonacci)) } #[no_mangle] pub unsafe extern "C" fn fibonacci_free(ptr: *mut Fibonacci) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn fibonacci_input_get(ptr: *const Fibonacci) -> u32 { (&*ptr).input() } #[no_mangle] pub unsafe extern "C" fn fibonacci_input_set(ptr: *mut Fibonacci, v: u32) { (&mut *ptr).set_input(v); } #[no_mangle] pub unsafe extern "C" fn fibonacci_result_get(ptr: *const Fibonacci) -> u64 { (&*ptr).result() } pub struct FibonacciListQObject {} -#[derive(Clone)] pub struct FibonacciListEmitter { qobject: Arc>, - new_data_ready: fn(*const FibonacciListQObject), + new_data_ready: fn(*mut FibonacciListQObject), } unsafe impl Send for FibonacciListEmitter {} impl FibonacciListEmitter { + /// 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) -> FibonacciListEmitter { + FibonacciListEmitter { + qobject: self.qobject.clone(), + new_data_ready: self.new_data_ready, + } + } fn clear(&self) { let n: *const FibonacciListQObject = null(); self.qobject.store(n as *mut FibonacciListQObject, Ordering::SeqCst); } - pub fn new_data_ready(&self) { + pub fn new_data_ready(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.new_data_ready)(ptr); } } } #[derive(Clone)] pub struct FibonacciListList { - qobject: *const FibonacciListQObject, - layout_about_to_be_changed: fn(*const FibonacciListQObject), - layout_changed: fn(*const FibonacciListQObject), - data_changed: fn(*const FibonacciListQObject, usize, usize), - begin_reset_model: fn(*const FibonacciListQObject), - end_reset_model: fn(*const FibonacciListQObject), - begin_insert_rows: fn(*const FibonacciListQObject, usize, usize), - end_insert_rows: fn(*const FibonacciListQObject), - begin_move_rows: fn(*const FibonacciListQObject, usize, usize, usize), - end_move_rows: fn(*const FibonacciListQObject), - begin_remove_rows: fn(*const FibonacciListQObject, usize, usize), - end_remove_rows: fn(*const FibonacciListQObject), + qobject: *mut FibonacciListQObject, + layout_about_to_be_changed: fn(*mut FibonacciListQObject), + layout_changed: fn(*mut FibonacciListQObject), + data_changed: fn(*mut FibonacciListQObject, usize, usize), + begin_reset_model: fn(*mut FibonacciListQObject), + end_reset_model: fn(*mut FibonacciListQObject), + begin_insert_rows: fn(*mut FibonacciListQObject, usize, usize), + end_insert_rows: fn(*mut FibonacciListQObject), + begin_move_rows: fn(*mut FibonacciListQObject, usize, usize, usize), + end_move_rows: fn(*mut FibonacciListQObject), + begin_remove_rows: fn(*mut FibonacciListQObject, usize, usize), + end_remove_rows: fn(*mut FibonacciListQObject), } impl FibonacciListList { - pub fn layout_about_to_be_changed(&self) { + pub fn layout_about_to_be_changed(&mut self) { (self.layout_about_to_be_changed)(self.qobject); } - pub fn layout_changed(&self) { + pub fn layout_changed(&mut self) { (self.layout_changed)(self.qobject); } - pub fn data_changed(&self, first: usize, last: usize) { + pub fn data_changed(&mut self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } - pub fn begin_reset_model(&self) { + pub fn begin_reset_model(&mut self) { (self.begin_reset_model)(self.qobject); } - pub fn end_reset_model(&self) { + pub fn end_reset_model(&mut self) { (self.end_reset_model)(self.qobject); } - pub fn begin_insert_rows(&self, first: usize, last: usize) { + pub fn begin_insert_rows(&mut self, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, first, last); } - pub fn end_insert_rows(&self) { + pub fn end_insert_rows(&mut self) { (self.end_insert_rows)(self.qobject); } - pub fn begin_move_rows(&self, first: usize, last: usize, destination: usize) { + pub fn begin_move_rows(&mut self, first: usize, last: usize, destination: usize) { (self.begin_move_rows)(self.qobject, first, last, destination); } - pub fn end_move_rows(&self) { + pub fn end_move_rows(&mut self) { (self.end_move_rows)(self.qobject); } - pub fn begin_remove_rows(&self, first: usize, last: usize) { + pub fn begin_remove_rows(&mut self, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, first, last); } - pub fn end_remove_rows(&self) { + pub fn end_remove_rows(&mut self) { (self.end_remove_rows)(self.qobject); } } pub trait FibonacciListTrait { fn new(emit: FibonacciListEmitter, model: FibonacciListList) -> Self; fn emit(&self) -> &FibonacciListEmitter; 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) {} fn fibonacci_number(&self, index: usize) -> u64; fn row(&self, index: usize) -> u64; } #[no_mangle] pub extern "C" fn fibonacci_list_new( fibonacci_list: *mut FibonacciListQObject, - fibonacci_list_new_data_ready: fn(*const FibonacciListQObject), - fibonacci_list_layout_about_to_be_changed: fn(*const FibonacciListQObject), - fibonacci_list_layout_changed: fn(*const FibonacciListQObject), - fibonacci_list_data_changed: fn(*const FibonacciListQObject, usize, usize), - fibonacci_list_begin_reset_model: fn(*const FibonacciListQObject), - fibonacci_list_end_reset_model: fn(*const FibonacciListQObject), - fibonacci_list_begin_insert_rows: fn(*const FibonacciListQObject, usize, usize), - fibonacci_list_end_insert_rows: fn(*const FibonacciListQObject), - fibonacci_list_begin_move_rows: fn(*const FibonacciListQObject, usize, usize, usize), - fibonacci_list_end_move_rows: fn(*const FibonacciListQObject), - fibonacci_list_begin_remove_rows: fn(*const FibonacciListQObject, usize, usize), - fibonacci_list_end_remove_rows: fn(*const FibonacciListQObject), + fibonacci_list_new_data_ready: fn(*mut FibonacciListQObject), + fibonacci_list_layout_about_to_be_changed: fn(*mut FibonacciListQObject), + fibonacci_list_layout_changed: fn(*mut FibonacciListQObject), + fibonacci_list_data_changed: fn(*mut FibonacciListQObject, usize, usize), + fibonacci_list_begin_reset_model: fn(*mut FibonacciListQObject), + fibonacci_list_end_reset_model: fn(*mut FibonacciListQObject), + fibonacci_list_begin_insert_rows: fn(*mut FibonacciListQObject, usize, usize), + fibonacci_list_end_insert_rows: fn(*mut FibonacciListQObject), + fibonacci_list_begin_move_rows: fn(*mut FibonacciListQObject, usize, usize, usize), + fibonacci_list_end_move_rows: fn(*mut FibonacciListQObject), + fibonacci_list_begin_remove_rows: fn(*mut FibonacciListQObject, usize, usize), + fibonacci_list_end_remove_rows: fn(*mut FibonacciListQObject), ) -> *mut FibonacciList { let fibonacci_list_emit = FibonacciListEmitter { qobject: Arc::new(AtomicPtr::new(fibonacci_list)), new_data_ready: fibonacci_list_new_data_ready, }; let model = FibonacciListList { qobject: fibonacci_list, layout_about_to_be_changed: fibonacci_list_layout_about_to_be_changed, layout_changed: fibonacci_list_layout_changed, data_changed: fibonacci_list_data_changed, begin_reset_model: fibonacci_list_begin_reset_model, end_reset_model: fibonacci_list_end_reset_model, begin_insert_rows: fibonacci_list_begin_insert_rows, end_insert_rows: fibonacci_list_end_insert_rows, begin_move_rows: fibonacci_list_begin_move_rows, end_move_rows: fibonacci_list_end_move_rows, begin_remove_rows: fibonacci_list_begin_remove_rows, end_remove_rows: fibonacci_list_end_remove_rows, }; let d_fibonacci_list = FibonacciList::new(fibonacci_list_emit, model); Box::into_raw(Box::new(d_fibonacci_list)) } #[no_mangle] pub unsafe extern "C" fn fibonacci_list_free(ptr: *mut FibonacciList) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn fibonacci_list_row_count(ptr: *const FibonacciList) -> c_int { to_c_int((&*ptr).row_count()) } #[no_mangle] pub unsafe extern "C" fn fibonacci_list_insert_rows(ptr: *mut FibonacciList, row: c_int, count: c_int) -> bool { (&mut *ptr).insert_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn fibonacci_list_remove_rows(ptr: *mut FibonacciList, row: c_int, count: c_int) -> bool { (&mut *ptr).remove_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn fibonacci_list_can_fetch_more(ptr: *const FibonacciList) -> bool { (&*ptr).can_fetch_more() } #[no_mangle] pub unsafe extern "C" fn fibonacci_list_fetch_more(ptr: *mut FibonacciList) { (&mut *ptr).fetch_more() } #[no_mangle] pub unsafe extern "C" fn fibonacci_list_sort( ptr: *mut FibonacciList, column: u8, order: SortOrder, ) { (&mut *ptr).sort(column, order) } #[no_mangle] pub unsafe extern "C" fn fibonacci_list_data_fibonacci_number(ptr: *const FibonacciList, row: c_int) -> u64 { let o = &*ptr; o.fibonacci_number(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn fibonacci_list_data_row(ptr: *const FibonacciList, row: c_int) -> u64 { let o = &*ptr; o.row(to_usize(row)).into() } pub struct FileSystemTreeQObject {} -#[derive(Clone)] pub struct FileSystemTreeEmitter { qobject: Arc>, - path_changed: fn(*const FileSystemTreeQObject), - new_data_ready: fn(*const FileSystemTreeQObject, index: COption), + path_changed: fn(*mut FileSystemTreeQObject), + new_data_ready: fn(*mut FileSystemTreeQObject, index: COption), } unsafe impl Send for FileSystemTreeEmitter {} impl FileSystemTreeEmitter { + /// 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) -> FileSystemTreeEmitter { + FileSystemTreeEmitter { + qobject: self.qobject.clone(), + path_changed: self.path_changed, + new_data_ready: self.new_data_ready, + } + } fn clear(&self) { let n: *const FileSystemTreeQObject = null(); self.qobject.store(n as *mut FileSystemTreeQObject, Ordering::SeqCst); } - pub fn path_changed(&self) { + pub fn path_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.path_changed)(ptr); } } - pub fn new_data_ready(&self, item: Option) { + 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()); } } } #[derive(Clone)] pub struct FileSystemTreeTree { - qobject: *const FileSystemTreeQObject, - layout_about_to_be_changed: fn(*const FileSystemTreeQObject), - layout_changed: fn(*const FileSystemTreeQObject), - data_changed: fn(*const FileSystemTreeQObject, usize, usize), - begin_reset_model: fn(*const FileSystemTreeQObject), - end_reset_model: fn(*const FileSystemTreeQObject), - begin_insert_rows: fn(*const FileSystemTreeQObject, index: COption, usize, usize), - end_insert_rows: fn(*const FileSystemTreeQObject), - begin_move_rows: fn(*const FileSystemTreeQObject, index: COption, usize, usize, dest: COption, usize), - end_move_rows: fn(*const FileSystemTreeQObject), - begin_remove_rows: fn(*const FileSystemTreeQObject, index: COption, usize, usize), - end_remove_rows: fn(*const FileSystemTreeQObject), + qobject: *mut FileSystemTreeQObject, + layout_about_to_be_changed: fn(*mut FileSystemTreeQObject), + layout_changed: fn(*mut FileSystemTreeQObject), + data_changed: fn(*mut FileSystemTreeQObject, usize, usize), + begin_reset_model: fn(*mut FileSystemTreeQObject), + end_reset_model: fn(*mut FileSystemTreeQObject), + begin_insert_rows: fn(*mut FileSystemTreeQObject, index: COption, usize, usize), + end_insert_rows: fn(*mut FileSystemTreeQObject), + begin_move_rows: fn(*mut FileSystemTreeQObject, index: COption, usize, usize, dest: COption, usize), + end_move_rows: fn(*mut FileSystemTreeQObject), + begin_remove_rows: fn(*mut FileSystemTreeQObject, index: COption, usize, usize), + end_remove_rows: fn(*mut FileSystemTreeQObject), } impl FileSystemTreeTree { - pub fn layout_about_to_be_changed(&self) { + pub fn layout_about_to_be_changed(&mut self) { (self.layout_about_to_be_changed)(self.qobject); } - pub fn layout_changed(&self) { + pub fn layout_changed(&mut self) { (self.layout_changed)(self.qobject); } - pub fn data_changed(&self, first: usize, last: usize) { + pub fn data_changed(&mut self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } - pub fn begin_reset_model(&self) { + pub fn begin_reset_model(&mut self) { (self.begin_reset_model)(self.qobject); } - pub fn end_reset_model(&self) { + pub fn end_reset_model(&mut self) { (self.end_reset_model)(self.qobject); } - pub fn begin_insert_rows(&self, index: Option, first: usize, last: usize) { + pub fn begin_insert_rows(&mut self, index: Option, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, index.into(), first, last); } - pub fn end_insert_rows(&self) { + pub fn end_insert_rows(&mut self) { (self.end_insert_rows)(self.qobject); } - pub fn begin_move_rows(&self, index: Option, first: usize, last: usize, dest: Option, destination: usize) { + pub fn begin_move_rows(&mut self, index: Option, first: usize, last: usize, dest: Option, destination: usize) { (self.begin_move_rows)(self.qobject, index.into(), first, last, dest.into(), destination); } - pub fn end_move_rows(&self) { + pub fn end_move_rows(&mut self) { (self.end_move_rows)(self.qobject); } - pub fn begin_remove_rows(&self, index: Option, first: usize, last: usize) { + pub fn begin_remove_rows(&mut self, index: Option, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, index.into(), first, last); } - pub fn end_remove_rows(&self) { + pub fn end_remove_rows(&mut self) { (self.end_remove_rows)(self.qobject); } } pub trait FileSystemTreeTrait { fn new(emit: FileSystemTreeEmitter, model: FileSystemTreeTree) -> Self; fn emit(&self) -> &FileSystemTreeEmitter; fn path(&self) -> Option<&str>; fn set_path(&mut self, value: Option); 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; fn file_icon(&self, index: usize) -> &[u8]; fn file_name(&self, index: usize) -> String; fn file_path(&self, index: usize) -> Option; fn file_permissions(&self, index: usize) -> i32; fn file_size(&self, index: usize) -> Option; fn file_type(&self, index: usize) -> i32; } #[no_mangle] pub extern "C" fn file_system_tree_new( file_system_tree: *mut FileSystemTreeQObject, - file_system_tree_path_changed: fn(*const FileSystemTreeQObject), - file_system_tree_new_data_ready: fn(*const FileSystemTreeQObject, index: COption), - file_system_tree_layout_about_to_be_changed: fn(*const FileSystemTreeQObject), - file_system_tree_layout_changed: fn(*const FileSystemTreeQObject), - file_system_tree_data_changed: fn(*const FileSystemTreeQObject, usize, usize), - file_system_tree_begin_reset_model: fn(*const FileSystemTreeQObject), - file_system_tree_end_reset_model: fn(*const FileSystemTreeQObject), - file_system_tree_begin_insert_rows: fn(*const FileSystemTreeQObject, index: COption, usize, usize), - file_system_tree_end_insert_rows: fn(*const FileSystemTreeQObject), - file_system_tree_begin_move_rows: fn(*const FileSystemTreeQObject, index: COption, usize, usize, index: COption, usize), - file_system_tree_end_move_rows: fn(*const FileSystemTreeQObject), - file_system_tree_begin_remove_rows: fn(*const FileSystemTreeQObject, index: COption, usize, usize), - file_system_tree_end_remove_rows: fn(*const FileSystemTreeQObject), + file_system_tree_path_changed: fn(*mut FileSystemTreeQObject), + file_system_tree_new_data_ready: fn(*mut FileSystemTreeQObject, index: COption), + file_system_tree_layout_about_to_be_changed: fn(*mut FileSystemTreeQObject), + file_system_tree_layout_changed: fn(*mut FileSystemTreeQObject), + file_system_tree_data_changed: fn(*mut FileSystemTreeQObject, usize, usize), + file_system_tree_begin_reset_model: fn(*mut FileSystemTreeQObject), + file_system_tree_end_reset_model: fn(*mut FileSystemTreeQObject), + file_system_tree_begin_insert_rows: fn(*mut FileSystemTreeQObject, index: COption, usize, usize), + file_system_tree_end_insert_rows: fn(*mut FileSystemTreeQObject), + file_system_tree_begin_move_rows: fn(*mut FileSystemTreeQObject, index: COption, usize, usize, index: COption, usize), + file_system_tree_end_move_rows: fn(*mut FileSystemTreeQObject), + file_system_tree_begin_remove_rows: fn(*mut FileSystemTreeQObject, index: COption, usize, usize), + file_system_tree_end_remove_rows: fn(*mut FileSystemTreeQObject), ) -> *mut FileSystemTree { let file_system_tree_emit = FileSystemTreeEmitter { qobject: Arc::new(AtomicPtr::new(file_system_tree)), path_changed: file_system_tree_path_changed, new_data_ready: file_system_tree_new_data_ready, }; let model = FileSystemTreeTree { qobject: file_system_tree, layout_about_to_be_changed: file_system_tree_layout_about_to_be_changed, layout_changed: file_system_tree_layout_changed, data_changed: file_system_tree_data_changed, begin_reset_model: file_system_tree_begin_reset_model, end_reset_model: file_system_tree_end_reset_model, begin_insert_rows: file_system_tree_begin_insert_rows, end_insert_rows: file_system_tree_end_insert_rows, begin_move_rows: file_system_tree_begin_move_rows, end_move_rows: file_system_tree_end_move_rows, begin_remove_rows: file_system_tree_begin_remove_rows, end_remove_rows: file_system_tree_end_remove_rows, }; let d_file_system_tree = FileSystemTree::new(file_system_tree_emit, model); Box::into_raw(Box::new(d_file_system_tree)) } #[no_mangle] pub unsafe extern "C" fn file_system_tree_free(ptr: *mut FileSystemTree) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn file_system_tree_path_get( ptr: *const FileSystemTree, p: *mut QString, set: fn(*mut QString, *const c_char, c_int), ) { let o = &*ptr; let v = o.path(); 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())); } } #[no_mangle] pub unsafe extern "C" fn file_system_tree_path_set(ptr: *mut FileSystemTree, 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_path(Some(s)); } #[no_mangle] pub unsafe extern "C" fn file_system_tree_path_set_none(ptr: *mut FileSystemTree) { let o = &mut *ptr; o.set_path(None); } #[no_mangle] pub unsafe extern "C" fn file_system_tree_row_count( ptr: *const FileSystemTree, index: COption, ) -> c_int { to_c_int((&*ptr).row_count(index.into())) } #[no_mangle] pub unsafe extern "C" fn file_system_tree_can_fetch_more( ptr: *const FileSystemTree, index: COption, ) -> bool { (&*ptr).can_fetch_more(index.into()) } #[no_mangle] pub unsafe extern "C" fn file_system_tree_fetch_more(ptr: *mut FileSystemTree, index: COption) { (&mut *ptr).fetch_more(index.into()) } #[no_mangle] pub unsafe extern "C" fn file_system_tree_sort( ptr: *mut FileSystemTree, column: u8, order: SortOrder ) { (&mut *ptr).sort(column, order) } #[no_mangle] pub unsafe extern "C" fn file_system_tree_check_row( ptr: *const FileSystemTree, index: usize, row: c_int, ) -> COption { (&*ptr).check_row(index.into(), to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn file_system_tree_index( ptr: *const FileSystemTree, index: COption, row: c_int, ) -> usize { (&*ptr).index(index.into(), to_usize(row)) } #[no_mangle] pub unsafe extern "C" fn file_system_tree_parent(ptr: *const FileSystemTree, 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 file_system_tree_row(ptr: *const FileSystemTree, index: usize) -> c_int { to_c_int((&*ptr).row(index)) } #[no_mangle] pub unsafe extern "C" fn file_system_tree_data_file_icon( ptr: *const FileSystemTree, index: usize, d: *mut QByteArray, set: fn(*mut QByteArray, *const c_char, len: c_int), ) { let o = &*ptr; let data = o.file_icon(index); let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, to_c_int(data.len())); } #[no_mangle] pub unsafe extern "C" fn file_system_tree_data_file_name( ptr: *const FileSystemTree, index: usize, d: *mut QString, set: fn(*mut QString, *const c_char, len: c_int), ) { let o = &*ptr; let data = o.file_name(index); let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, to_c_int(data.len())); } #[no_mangle] pub unsafe extern "C" fn file_system_tree_data_file_path( ptr: *const FileSystemTree, index: usize, d: *mut QString, set: fn(*mut QString, *const c_char, len: c_int), ) { let o = &*ptr; let data = o.file_path(index); 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())); } } #[no_mangle] pub unsafe extern "C" fn file_system_tree_data_file_permissions(ptr: *const FileSystemTree, index: usize) -> i32 { let o = &*ptr; o.file_permissions(index).into() } #[no_mangle] pub unsafe extern "C" fn file_system_tree_data_file_size(ptr: *const FileSystemTree, index: usize) -> COption { let o = &*ptr; o.file_size(index).into() } #[no_mangle] pub unsafe extern "C" fn file_system_tree_data_file_type(ptr: *const FileSystemTree, index: usize) -> i32 { let o = &*ptr; o.file_type(index).into() } pub struct ProcessesQObject {} -#[derive(Clone)] pub struct ProcessesEmitter { qobject: Arc>, - active_changed: fn(*const ProcessesQObject), - new_data_ready: fn(*const ProcessesQObject, index: COption), + active_changed: fn(*mut ProcessesQObject), + new_data_ready: fn(*mut ProcessesQObject, index: COption), } unsafe impl Send for ProcessesEmitter {} impl ProcessesEmitter { + /// 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) -> ProcessesEmitter { + ProcessesEmitter { + qobject: self.qobject.clone(), + active_changed: self.active_changed, + new_data_ready: self.new_data_ready, + } + } fn clear(&self) { let n: *const ProcessesQObject = null(); self.qobject.store(n as *mut ProcessesQObject, Ordering::SeqCst); } - pub fn active_changed(&self) { + pub fn active_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.active_changed)(ptr); } } - pub fn new_data_ready(&self, item: Option) { + 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()); } } } #[derive(Clone)] pub struct ProcessesTree { - qobject: *const ProcessesQObject, - layout_about_to_be_changed: fn(*const ProcessesQObject), - layout_changed: fn(*const ProcessesQObject), - data_changed: fn(*const ProcessesQObject, usize, usize), - begin_reset_model: fn(*const ProcessesQObject), - end_reset_model: fn(*const ProcessesQObject), - begin_insert_rows: fn(*const ProcessesQObject, index: COption, usize, usize), - end_insert_rows: fn(*const ProcessesQObject), - begin_move_rows: fn(*const ProcessesQObject, index: COption, usize, usize, dest: COption, usize), - end_move_rows: fn(*const ProcessesQObject), - begin_remove_rows: fn(*const ProcessesQObject, index: COption, usize, usize), - end_remove_rows: fn(*const ProcessesQObject), + qobject: *mut ProcessesQObject, + layout_about_to_be_changed: fn(*mut ProcessesQObject), + layout_changed: fn(*mut ProcessesQObject), + data_changed: fn(*mut ProcessesQObject, usize, usize), + begin_reset_model: fn(*mut ProcessesQObject), + end_reset_model: fn(*mut ProcessesQObject), + begin_insert_rows: fn(*mut ProcessesQObject, index: COption, usize, usize), + end_insert_rows: fn(*mut ProcessesQObject), + begin_move_rows: fn(*mut ProcessesQObject, index: COption, usize, usize, dest: COption, usize), + end_move_rows: fn(*mut ProcessesQObject), + begin_remove_rows: fn(*mut ProcessesQObject, index: COption, usize, usize), + end_remove_rows: fn(*mut ProcessesQObject), } impl ProcessesTree { - pub fn layout_about_to_be_changed(&self) { + pub fn layout_about_to_be_changed(&mut self) { (self.layout_about_to_be_changed)(self.qobject); } - pub fn layout_changed(&self) { + pub fn layout_changed(&mut self) { (self.layout_changed)(self.qobject); } - pub fn data_changed(&self, first: usize, last: usize) { + pub fn data_changed(&mut self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } - pub fn begin_reset_model(&self) { + pub fn begin_reset_model(&mut self) { (self.begin_reset_model)(self.qobject); } - pub fn end_reset_model(&self) { + pub fn end_reset_model(&mut self) { (self.end_reset_model)(self.qobject); } - pub fn begin_insert_rows(&self, index: Option, first: usize, last: usize) { + pub fn begin_insert_rows(&mut self, index: Option, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, index.into(), first, last); } - pub fn end_insert_rows(&self) { + pub fn end_insert_rows(&mut self) { (self.end_insert_rows)(self.qobject); } - pub fn begin_move_rows(&self, index: Option, first: usize, last: usize, dest: Option, destination: usize) { + pub fn begin_move_rows(&mut self, index: Option, first: usize, last: usize, dest: Option, destination: usize) { (self.begin_move_rows)(self.qobject, index.into(), first, last, dest.into(), destination); } - pub fn end_move_rows(&self) { + pub fn end_move_rows(&mut self) { (self.end_move_rows)(self.qobject); } - pub fn begin_remove_rows(&self, index: Option, first: usize, last: usize) { + pub fn begin_remove_rows(&mut self, index: Option, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, index.into(), first, last); } - pub fn end_remove_rows(&self) { + pub fn end_remove_rows(&mut self) { (self.end_remove_rows)(self.qobject); } } pub trait ProcessesTrait { fn new(emit: ProcessesEmitter, model: ProcessesTree) -> Self; fn emit(&self) -> &ProcessesEmitter; fn active(&self) -> bool; fn set_active(&mut self, value: bool); 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; fn cmd(&self, index: usize) -> String; fn cpu_percentage(&self, index: usize) -> u8; fn cpu_usage(&self, index: usize) -> f32; fn memory(&self, index: usize) -> u64; fn name(&self, index: usize) -> &str; fn pid(&self, index: usize) -> u32; fn uid(&self, index: usize) -> u32; } #[no_mangle] pub extern "C" fn processes_new( processes: *mut ProcessesQObject, - processes_active_changed: fn(*const ProcessesQObject), - processes_new_data_ready: fn(*const ProcessesQObject, index: COption), - processes_layout_about_to_be_changed: fn(*const ProcessesQObject), - processes_layout_changed: fn(*const ProcessesQObject), - processes_data_changed: fn(*const ProcessesQObject, usize, usize), - processes_begin_reset_model: fn(*const ProcessesQObject), - processes_end_reset_model: fn(*const ProcessesQObject), - processes_begin_insert_rows: fn(*const ProcessesQObject, index: COption, usize, usize), - processes_end_insert_rows: fn(*const ProcessesQObject), - processes_begin_move_rows: fn(*const ProcessesQObject, index: COption, usize, usize, index: COption, usize), - processes_end_move_rows: fn(*const ProcessesQObject), - processes_begin_remove_rows: fn(*const ProcessesQObject, index: COption, usize, usize), - processes_end_remove_rows: fn(*const ProcessesQObject), + processes_active_changed: fn(*mut ProcessesQObject), + processes_new_data_ready: fn(*mut ProcessesQObject, index: COption), + processes_layout_about_to_be_changed: fn(*mut ProcessesQObject), + processes_layout_changed: fn(*mut ProcessesQObject), + processes_data_changed: fn(*mut ProcessesQObject, usize, usize), + processes_begin_reset_model: fn(*mut ProcessesQObject), + processes_end_reset_model: fn(*mut ProcessesQObject), + processes_begin_insert_rows: fn(*mut ProcessesQObject, index: COption, usize, usize), + processes_end_insert_rows: fn(*mut ProcessesQObject), + processes_begin_move_rows: fn(*mut ProcessesQObject, index: COption, usize, usize, index: COption, usize), + processes_end_move_rows: fn(*mut ProcessesQObject), + processes_begin_remove_rows: fn(*mut ProcessesQObject, index: COption, usize, usize), + processes_end_remove_rows: fn(*mut ProcessesQObject), ) -> *mut Processes { let processes_emit = ProcessesEmitter { qobject: Arc::new(AtomicPtr::new(processes)), active_changed: processes_active_changed, new_data_ready: processes_new_data_ready, }; let model = ProcessesTree { qobject: processes, layout_about_to_be_changed: processes_layout_about_to_be_changed, layout_changed: processes_layout_changed, data_changed: processes_data_changed, begin_reset_model: processes_begin_reset_model, end_reset_model: processes_end_reset_model, begin_insert_rows: processes_begin_insert_rows, end_insert_rows: processes_end_insert_rows, begin_move_rows: processes_begin_move_rows, end_move_rows: processes_end_move_rows, begin_remove_rows: processes_begin_remove_rows, end_remove_rows: processes_end_remove_rows, }; let d_processes = Processes::new(processes_emit, model); Box::into_raw(Box::new(d_processes)) } #[no_mangle] pub unsafe extern "C" fn processes_free(ptr: *mut Processes) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn processes_active_get(ptr: *const Processes) -> bool { (&*ptr).active() } #[no_mangle] pub unsafe extern "C" fn processes_active_set(ptr: *mut Processes, v: bool) { (&mut *ptr).set_active(v); } #[no_mangle] pub unsafe extern "C" fn processes_row_count( ptr: *const Processes, index: COption, ) -> c_int { to_c_int((&*ptr).row_count(index.into())) } #[no_mangle] pub unsafe extern "C" fn processes_can_fetch_more( ptr: *const Processes, index: COption, ) -> bool { (&*ptr).can_fetch_more(index.into()) } #[no_mangle] pub unsafe extern "C" fn processes_fetch_more(ptr: *mut Processes, index: COption) { (&mut *ptr).fetch_more(index.into()) } #[no_mangle] pub unsafe extern "C" fn processes_sort( ptr: *mut Processes, column: u8, order: SortOrder ) { (&mut *ptr).sort(column, order) } #[no_mangle] pub unsafe extern "C" fn processes_check_row( ptr: *const Processes, index: usize, row: c_int, ) -> COption { (&*ptr).check_row(index.into(), to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn processes_index( ptr: *const Processes, index: COption, row: c_int, ) -> usize { (&*ptr).index(index.into(), to_usize(row)) } #[no_mangle] pub unsafe extern "C" fn processes_parent(ptr: *const Processes, 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 processes_row(ptr: *const Processes, index: usize) -> c_int { to_c_int((&*ptr).row(index)) } #[no_mangle] pub unsafe extern "C" fn processes_data_cmd( ptr: *const Processes, index: usize, d: *mut QString, set: fn(*mut QString, *const c_char, len: c_int), ) { let o = &*ptr; let data = o.cmd(index); let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, to_c_int(data.len())); } #[no_mangle] pub unsafe extern "C" fn processes_data_cpu_percentage(ptr: *const Processes, index: usize) -> u8 { let o = &*ptr; o.cpu_percentage(index).into() } #[no_mangle] pub unsafe extern "C" fn processes_data_cpu_usage(ptr: *const Processes, index: usize) -> f32 { let o = &*ptr; o.cpu_usage(index).into() } #[no_mangle] pub unsafe extern "C" fn processes_data_memory(ptr: *const Processes, index: usize) -> u64 { let o = &*ptr; o.memory(index).into() } #[no_mangle] pub unsafe extern "C" fn processes_data_name( ptr: *const Processes, index: usize, d: *mut QString, set: fn(*mut QString, *const c_char, len: c_int), ) { let o = &*ptr; let data = o.name(index); let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, to_c_int(data.len())); } #[no_mangle] pub unsafe extern "C" fn processes_data_pid(ptr: *const Processes, index: usize) -> u32 { let o = &*ptr; o.pid(index).into() } #[no_mangle] pub unsafe extern "C" fn processes_data_uid(ptr: *const Processes, index: usize) -> u32 { let o = &*ptr; o.uid(index).into() } pub struct TimeSeriesQObject {} -#[derive(Clone)] pub struct TimeSeriesEmitter { qobject: Arc>, - new_data_ready: fn(*const TimeSeriesQObject), + new_data_ready: fn(*mut TimeSeriesQObject), } unsafe impl Send for TimeSeriesEmitter {} impl TimeSeriesEmitter { + /// 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) -> TimeSeriesEmitter { + TimeSeriesEmitter { + qobject: self.qobject.clone(), + new_data_ready: self.new_data_ready, + } + } fn clear(&self) { let n: *const TimeSeriesQObject = null(); self.qobject.store(n as *mut TimeSeriesQObject, Ordering::SeqCst); } - pub fn new_data_ready(&self) { + pub fn new_data_ready(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.new_data_ready)(ptr); } } } #[derive(Clone)] pub struct TimeSeriesList { - qobject: *const TimeSeriesQObject, - layout_about_to_be_changed: fn(*const TimeSeriesQObject), - layout_changed: fn(*const TimeSeriesQObject), - data_changed: fn(*const TimeSeriesQObject, usize, usize), - begin_reset_model: fn(*const TimeSeriesQObject), - end_reset_model: fn(*const TimeSeriesQObject), - begin_insert_rows: fn(*const TimeSeriesQObject, usize, usize), - end_insert_rows: fn(*const TimeSeriesQObject), - begin_move_rows: fn(*const TimeSeriesQObject, usize, usize, usize), - end_move_rows: fn(*const TimeSeriesQObject), - begin_remove_rows: fn(*const TimeSeriesQObject, usize, usize), - end_remove_rows: fn(*const TimeSeriesQObject), + qobject: *mut TimeSeriesQObject, + layout_about_to_be_changed: fn(*mut TimeSeriesQObject), + layout_changed: fn(*mut TimeSeriesQObject), + data_changed: fn(*mut TimeSeriesQObject, usize, usize), + begin_reset_model: fn(*mut TimeSeriesQObject), + end_reset_model: fn(*mut TimeSeriesQObject), + begin_insert_rows: fn(*mut TimeSeriesQObject, usize, usize), + end_insert_rows: fn(*mut TimeSeriesQObject), + begin_move_rows: fn(*mut TimeSeriesQObject, usize, usize, usize), + end_move_rows: fn(*mut TimeSeriesQObject), + begin_remove_rows: fn(*mut TimeSeriesQObject, usize, usize), + end_remove_rows: fn(*mut TimeSeriesQObject), } impl TimeSeriesList { - pub fn layout_about_to_be_changed(&self) { + pub fn layout_about_to_be_changed(&mut self) { (self.layout_about_to_be_changed)(self.qobject); } - pub fn layout_changed(&self) { + pub fn layout_changed(&mut self) { (self.layout_changed)(self.qobject); } - pub fn data_changed(&self, first: usize, last: usize) { + pub fn data_changed(&mut self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } - pub fn begin_reset_model(&self) { + pub fn begin_reset_model(&mut self) { (self.begin_reset_model)(self.qobject); } - pub fn end_reset_model(&self) { + pub fn end_reset_model(&mut self) { (self.end_reset_model)(self.qobject); } - pub fn begin_insert_rows(&self, first: usize, last: usize) { + pub fn begin_insert_rows(&mut self, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, first, last); } - pub fn end_insert_rows(&self) { + pub fn end_insert_rows(&mut self) { (self.end_insert_rows)(self.qobject); } - pub fn begin_move_rows(&self, first: usize, last: usize, destination: usize) { + pub fn begin_move_rows(&mut self, first: usize, last: usize, destination: usize) { (self.begin_move_rows)(self.qobject, first, last, destination); } - pub fn end_move_rows(&self) { + pub fn end_move_rows(&mut self) { (self.end_move_rows)(self.qobject); } - pub fn begin_remove_rows(&self, first: usize, last: usize) { + pub fn begin_remove_rows(&mut self, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, first, last); } - pub fn end_remove_rows(&self) { + pub fn end_remove_rows(&mut self) { (self.end_remove_rows)(self.qobject); } } pub trait TimeSeriesTrait { fn new(emit: TimeSeriesEmitter, model: TimeSeriesList) -> Self; fn emit(&self) -> &TimeSeriesEmitter; 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) {} fn cos(&self, index: usize) -> f32; fn set_cos(&mut self, index: usize, f32) -> bool; fn sin(&self, index: usize) -> f32; fn set_sin(&mut self, index: usize, f32) -> bool; fn time(&self, index: usize) -> f32; fn set_time(&mut self, index: usize, f32) -> bool; } #[no_mangle] pub extern "C" fn time_series_new( time_series: *mut TimeSeriesQObject, - time_series_new_data_ready: fn(*const TimeSeriesQObject), - time_series_layout_about_to_be_changed: fn(*const TimeSeriesQObject), - time_series_layout_changed: fn(*const TimeSeriesQObject), - time_series_data_changed: fn(*const TimeSeriesQObject, usize, usize), - time_series_begin_reset_model: fn(*const TimeSeriesQObject), - time_series_end_reset_model: fn(*const TimeSeriesQObject), - time_series_begin_insert_rows: fn(*const TimeSeriesQObject, usize, usize), - time_series_end_insert_rows: fn(*const TimeSeriesQObject), - time_series_begin_move_rows: fn(*const TimeSeriesQObject, usize, usize, usize), - time_series_end_move_rows: fn(*const TimeSeriesQObject), - time_series_begin_remove_rows: fn(*const TimeSeriesQObject, usize, usize), - time_series_end_remove_rows: fn(*const TimeSeriesQObject), + time_series_new_data_ready: fn(*mut TimeSeriesQObject), + time_series_layout_about_to_be_changed: fn(*mut TimeSeriesQObject), + time_series_layout_changed: fn(*mut TimeSeriesQObject), + time_series_data_changed: fn(*mut TimeSeriesQObject, usize, usize), + time_series_begin_reset_model: fn(*mut TimeSeriesQObject), + time_series_end_reset_model: fn(*mut TimeSeriesQObject), + time_series_begin_insert_rows: fn(*mut TimeSeriesQObject, usize, usize), + time_series_end_insert_rows: fn(*mut TimeSeriesQObject), + time_series_begin_move_rows: fn(*mut TimeSeriesQObject, usize, usize, usize), + time_series_end_move_rows: fn(*mut TimeSeriesQObject), + time_series_begin_remove_rows: fn(*mut TimeSeriesQObject, usize, usize), + time_series_end_remove_rows: fn(*mut TimeSeriesQObject), ) -> *mut TimeSeries { let time_series_emit = TimeSeriesEmitter { qobject: Arc::new(AtomicPtr::new(time_series)), new_data_ready: time_series_new_data_ready, }; let model = TimeSeriesList { qobject: time_series, layout_about_to_be_changed: time_series_layout_about_to_be_changed, layout_changed: time_series_layout_changed, data_changed: time_series_data_changed, begin_reset_model: time_series_begin_reset_model, end_reset_model: time_series_end_reset_model, begin_insert_rows: time_series_begin_insert_rows, end_insert_rows: time_series_end_insert_rows, begin_move_rows: time_series_begin_move_rows, end_move_rows: time_series_end_move_rows, begin_remove_rows: time_series_begin_remove_rows, end_remove_rows: time_series_end_remove_rows, }; let d_time_series = TimeSeries::new(time_series_emit, model); Box::into_raw(Box::new(d_time_series)) } #[no_mangle] pub unsafe extern "C" fn time_series_free(ptr: *mut TimeSeries) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn time_series_row_count(ptr: *const TimeSeries) -> c_int { to_c_int((&*ptr).row_count()) } #[no_mangle] pub unsafe extern "C" fn time_series_insert_rows(ptr: *mut TimeSeries, row: c_int, count: c_int) -> bool { (&mut *ptr).insert_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn time_series_remove_rows(ptr: *mut TimeSeries, row: c_int, count: c_int) -> bool { (&mut *ptr).remove_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn time_series_can_fetch_more(ptr: *const TimeSeries) -> bool { (&*ptr).can_fetch_more() } #[no_mangle] pub unsafe extern "C" fn time_series_fetch_more(ptr: *mut TimeSeries) { (&mut *ptr).fetch_more() } #[no_mangle] pub unsafe extern "C" fn time_series_sort( ptr: *mut TimeSeries, column: u8, order: SortOrder, ) { (&mut *ptr).sort(column, order) } #[no_mangle] pub unsafe extern "C" fn time_series_data_cos(ptr: *const TimeSeries, row: c_int) -> f32 { let o = &*ptr; o.cos(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn time_series_set_data_cos( ptr: *mut TimeSeries, row: c_int, v: f32, ) -> bool { (&mut *ptr).set_cos(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn time_series_data_sin(ptr: *const TimeSeries, row: c_int) -> f32 { let o = &*ptr; o.sin(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn time_series_set_data_sin( ptr: *mut TimeSeries, row: c_int, v: f32, ) -> bool { (&mut *ptr).set_sin(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn time_series_data_time(ptr: *const TimeSeries, row: c_int) -> f32 { let o = &*ptr; o.time(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn time_series_set_data_time( ptr: *mut TimeSeries, row: c_int, v: f32, ) -> bool { (&mut *ptr).set_time(to_usize(row), v) } diff --git a/examples/todos/rust/src/interface.rs b/examples/todos/rust/src/interface.rs index da15b89..56aa27a 100644 --- a/examples/todos/rust/src/interface.rs +++ b/examples/todos/rust/src/interface.rs @@ -1,320 +1,368 @@ /* generated by rust_qt_binding_generator */ -#![allow(unknown_lints)] -#![allow(mutex_atomic, needless_pass_by_value)] use libc::{c_char, c_ushort, c_int}; use std::slice; use std::char::decode_utf16; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +use std::sync::atomic::{AtomicPtr, Ordering}; use std::ptr::null; use implementation::*; #[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, } } } } 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()) - .into_iter() .map(|r| r.unwrap()); s.clear(); s.extend(characters); } #[repr(C)] #[derive(PartialEq, Eq, Debug)] pub enum SortOrder { Ascending = 0, Descending = 1, } #[repr(C)] pub struct QModelIndex { row: c_int, internal_id: usize, } fn to_usize(n: c_int) -> usize { if n < 0 { panic!("Cannot cast {} to usize", n); } n as usize } 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 } pub struct TodosQObject {} -#[derive(Clone)] pub struct TodosEmitter { - qobject: Arc>, - active_count_changed: fn(*const TodosQObject), - count_changed: fn(*const TodosQObject), - new_data_ready: fn(*const TodosQObject), + qobject: Arc>, + active_count_changed: fn(*mut TodosQObject), + count_changed: fn(*mut TodosQObject), + new_data_ready: fn(*mut TodosQObject), } unsafe impl Send for TodosEmitter {} impl TodosEmitter { + /// 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) -> TodosEmitter { + TodosEmitter { + qobject: self.qobject.clone(), + active_count_changed: self.active_count_changed, + count_changed: self.count_changed, + new_data_ready: self.new_data_ready, + } + } fn clear(&self) { - *self.qobject.lock().unwrap() = null(); + let n: *const TodosQObject = null(); + self.qobject.store(n as *mut TodosQObject, Ordering::SeqCst); } - pub fn active_count_changed(&self) { - let ptr = *self.qobject.lock().unwrap(); + pub fn active_count_changed(&mut self) { + let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.active_count_changed)(ptr); } } - pub fn count_changed(&self) { - let ptr = *self.qobject.lock().unwrap(); + pub fn count_changed(&mut self) { + let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.count_changed)(ptr); } } - pub fn new_data_ready(&self) { - let ptr = *self.qobject.lock().unwrap(); + pub fn new_data_ready(&mut self) { + let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.new_data_ready)(ptr); } } } +#[derive(Clone)] pub struct TodosList { - qobject: *const TodosQObject, - data_changed: fn(*const TodosQObject, usize, usize), - begin_reset_model: fn(*const TodosQObject), - end_reset_model: fn(*const TodosQObject), - begin_insert_rows: fn(*const TodosQObject, usize, usize), - end_insert_rows: fn(*const TodosQObject), - begin_remove_rows: fn(*const TodosQObject, usize, usize), - end_remove_rows: fn(*const TodosQObject), + qobject: *mut TodosQObject, + layout_about_to_be_changed: fn(*mut TodosQObject), + layout_changed: fn(*mut TodosQObject), + data_changed: fn(*mut TodosQObject, usize, usize), + begin_reset_model: fn(*mut TodosQObject), + end_reset_model: fn(*mut TodosQObject), + begin_insert_rows: fn(*mut TodosQObject, usize, usize), + end_insert_rows: fn(*mut TodosQObject), + begin_move_rows: fn(*mut TodosQObject, usize, usize, usize), + end_move_rows: fn(*mut TodosQObject), + begin_remove_rows: fn(*mut TodosQObject, usize, usize), + end_remove_rows: fn(*mut TodosQObject), } impl TodosList { - pub fn data_changed(&self, first: usize, last: usize) { + 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(&self) { + pub fn begin_reset_model(&mut self) { (self.begin_reset_model)(self.qobject); } - pub fn end_reset_model(&self) { + pub fn end_reset_model(&mut self) { (self.end_reset_model)(self.qobject); } - pub fn begin_insert_rows(&self, first: usize, last: usize) { + pub fn begin_insert_rows(&mut self, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, first, last); } - pub fn end_insert_rows(&self) { + pub fn end_insert_rows(&mut self) { (self.end_insert_rows)(self.qobject); } - pub fn begin_remove_rows(&self, first: usize, last: usize) { + pub fn begin_move_rows(&mut self, first: usize, last: usize, destination: usize) { + (self.begin_move_rows)(self.qobject, first, last, destination); + } + pub fn end_move_rows(&mut self) { + (self.end_move_rows)(self.qobject); + } + pub fn begin_remove_rows(&mut self, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, first, last); } - pub fn end_remove_rows(&self) { + pub fn end_remove_rows(&mut self) { (self.end_remove_rows)(self.qobject); } } pub trait TodosTrait { fn new(emit: TodosEmitter, model: TodosList) -> Self; fn emit(&self) -> &TodosEmitter; fn active_count(&self) -> u64; fn count(&self) -> u64; fn add(&mut self, description: String) -> (); fn clear_completed(&mut self) -> (); fn remove(&mut self, index: u64) -> bool; fn set_all(&mut self, completed: bool) -> (); 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) {} fn completed(&self, index: usize) -> bool; fn set_completed(&mut self, index: usize, bool) -> bool; fn description(&self, index: usize) -> &str; fn set_description(&mut self, index: usize, String) -> bool; } #[no_mangle] pub extern "C" fn todos_new( todos: *mut TodosQObject, - todos_active_count_changed: fn(*const TodosQObject), - todos_count_changed: fn(*const TodosQObject), - todos_new_data_ready: fn(*const TodosQObject), - todos_data_changed: fn(*const TodosQObject, usize, usize), - todos_begin_reset_model: fn(*const TodosQObject), - todos_end_reset_model: fn(*const TodosQObject), - todos_begin_insert_rows: fn(*const TodosQObject, usize, usize), - todos_end_insert_rows: fn(*const TodosQObject), - todos_begin_remove_rows: fn(*const TodosQObject, usize, usize), - todos_end_remove_rows: fn(*const TodosQObject), + todos_active_count_changed: fn(*mut TodosQObject), + todos_count_changed: fn(*mut TodosQObject), + todos_new_data_ready: fn(*mut TodosQObject), + todos_layout_about_to_be_changed: fn(*mut TodosQObject), + todos_layout_changed: fn(*mut TodosQObject), + todos_data_changed: fn(*mut TodosQObject, usize, usize), + todos_begin_reset_model: fn(*mut TodosQObject), + todos_end_reset_model: fn(*mut TodosQObject), + todos_begin_insert_rows: fn(*mut TodosQObject, usize, usize), + todos_end_insert_rows: fn(*mut TodosQObject), + todos_begin_move_rows: fn(*mut TodosQObject, usize, usize, usize), + todos_end_move_rows: fn(*mut TodosQObject), + todos_begin_remove_rows: fn(*mut TodosQObject, usize, usize), + todos_end_remove_rows: fn(*mut TodosQObject), ) -> *mut Todos { let todos_emit = TodosEmitter { - qobject: Arc::new(Mutex::new(todos)), + qobject: Arc::new(AtomicPtr::new(todos)), active_count_changed: todos_active_count_changed, count_changed: todos_count_changed, new_data_ready: todos_new_data_ready, }; let model = TodosList { qobject: todos, + layout_about_to_be_changed: todos_layout_about_to_be_changed, + layout_changed: todos_layout_changed, data_changed: todos_data_changed, begin_reset_model: todos_begin_reset_model, end_reset_model: todos_end_reset_model, begin_insert_rows: todos_begin_insert_rows, end_insert_rows: todos_end_insert_rows, + begin_move_rows: todos_begin_move_rows, + end_move_rows: todos_end_move_rows, begin_remove_rows: todos_begin_remove_rows, end_remove_rows: todos_end_remove_rows, }; let d_todos = Todos::new(todos_emit, model); Box::into_raw(Box::new(d_todos)) } #[no_mangle] pub unsafe extern "C" fn todos_free(ptr: *mut Todos) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn todos_active_count_get(ptr: *const Todos) -> u64 { (&*ptr).active_count() } #[no_mangle] pub unsafe extern "C" fn todos_count_get(ptr: *const Todos) -> u64 { (&*ptr).count() } #[no_mangle] -pub extern "C" fn todos_add(ptr: *mut Todos, description_str: *const c_ushort, description_len: c_int) -> () { +pub unsafe extern "C" fn todos_add(ptr: *mut Todos, description_str: *const c_ushort, description_len: c_int) -> () { let mut description = String::new(); set_string_from_utf16(&mut description, description_str, description_len); - let o = unsafe { &mut *ptr }; + let o = &mut *ptr; let r = o.add(description); r } #[no_mangle] -pub extern "C" fn todos_clear_completed(ptr: *mut Todos) -> () { - let o = unsafe { &mut *ptr }; +pub unsafe extern "C" fn todos_clear_completed(ptr: *mut Todos) -> () { + let o = &mut *ptr; let r = o.clear_completed(); r } #[no_mangle] -pub extern "C" fn todos_remove(ptr: *mut Todos, index: u64) -> bool { - let o = unsafe { &mut *ptr }; +pub unsafe extern "C" fn todos_remove(ptr: *mut Todos, index: u64) -> bool { + let o = &mut *ptr; let r = o.remove(index); r } #[no_mangle] -pub extern "C" fn todos_set_all(ptr: *mut Todos, completed: bool) -> () { - let o = unsafe { &mut *ptr }; +pub unsafe extern "C" fn todos_set_all(ptr: *mut Todos, completed: bool) -> () { + let o = &mut *ptr; let r = o.set_all(completed); r } #[no_mangle] pub unsafe extern "C" fn todos_row_count(ptr: *const Todos) -> c_int { to_c_int((&*ptr).row_count()) } #[no_mangle] pub unsafe extern "C" fn todos_insert_rows(ptr: *mut Todos, row: c_int, count: c_int) -> bool { (&mut *ptr).insert_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn todos_remove_rows(ptr: *mut Todos, row: c_int, count: c_int) -> bool { (&mut *ptr).remove_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn todos_can_fetch_more(ptr: *const Todos) -> bool { (&*ptr).can_fetch_more() } #[no_mangle] pub unsafe extern "C" fn todos_fetch_more(ptr: *mut Todos) { (&mut *ptr).fetch_more() } #[no_mangle] pub unsafe extern "C" fn todos_sort( ptr: *mut Todos, column: u8, order: SortOrder, ) { (&mut *ptr).sort(column, order) } #[no_mangle] -pub extern "C" fn todos_data_completed(ptr: *const Todos, row: c_int) -> bool { - let o = unsafe { &*ptr }; +pub unsafe extern "C" fn todos_data_completed(ptr: *const Todos, row: c_int) -> bool { + let o = &*ptr; o.completed(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn todos_set_data_completed( ptr: *mut Todos, row: c_int, v: bool, ) -> bool { (&mut *ptr).set_completed(to_usize(row), v) } #[no_mangle] -pub extern "C" fn todos_data_description( +pub unsafe extern "C" fn todos_data_description( ptr: *const Todos, row: c_int, d: *mut QString, set: fn(*mut QString, *const c_char, len: c_int), ) { - let o = unsafe { &*ptr }; + let o = &*ptr; let data = o.description(to_usize(row)); let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, to_c_int(data.len())); } #[no_mangle] -pub extern "C" fn todos_set_data_description( +pub unsafe extern "C" fn todos_set_data_description( ptr: *mut Todos, row: c_int, s: *const c_ushort, len: c_int, ) -> bool { - let o = unsafe { &mut *ptr }; + let o = &mut *ptr; let mut v = String::new(); set_string_from_utf16(&mut v, s, len); o.set_description(to_usize(row), v) } diff --git a/examples/todos/src/Bindings.cpp b/examples/todos/src/Bindings.cpp index 2ca8fc1..e27779b 100644 --- a/examples/todos/src/Bindings.cpp +++ b/examples/todos/src/Bindings.cpp @@ -1,312 +1,331 @@ /* generated by rust_qt_binding_generator */ #include "Bindings.h" namespace { struct option_quintptr { public: quintptr value; bool some; operator QVariant() const { if (some) { return QVariant::fromValue(value); } return QVariant(); } }; static_assert(std::is_pod::value, "option_quintptr must be a POD type."); 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); } struct qmodelindex_t { int row; quintptr id; }; inline QVariant cleanNullQVariant(const QVariant& v) { return (v.isNull()) ?QVariant() :v; } inline void todosActiveCountChanged(Todos* o) { - emit o->activeCountChanged(); + Q_EMIT o->activeCountChanged(); } inline void todosCountChanged(Todos* o) { - emit o->countChanged(); + Q_EMIT o->countChanged(); } } extern "C" { bool todos_data_completed(const Todos::Private*, int); bool todos_set_data_completed(Todos::Private*, int, bool); void todos_data_description(const Todos::Private*, int, QString*, qstring_set); bool todos_set_data_description(Todos::Private*, int, const ushort* s, int len); void todos_sort(Todos::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int todos_row_count(const Todos::Private*); bool todos_insert_rows(Todos::Private*, int, int); bool todos_remove_rows(Todos::Private*, int, int); bool todos_can_fetch_more(const Todos::Private*); void todos_fetch_more(Todos::Private*); } int Todos::columnCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : 1; } bool Todos::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int Todos::rowCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : todos_row_count(m_d); } bool Todos::insertRows(int row, int count, const QModelIndex &) { return todos_insert_rows(m_d, row, count); } bool Todos::removeRows(int row, int count, const QModelIndex &) { return todos_remove_rows(m_d, row, count); } QModelIndex Todos::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid() && row >= 0 && row < rowCount(parent) && column >= 0 && column < 1) { return createIndex(row, column, (quintptr)row); } return QModelIndex(); } QModelIndex Todos::parent(const QModelIndex &) const { return QModelIndex(); } bool Todos::canFetchMore(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : todos_can_fetch_more(m_d); } void Todos::fetchMore(const QModelIndex &parent) { if (!parent.isValid()) { todos_fetch_more(m_d); } } +void Todos::updatePersistentIndexes() {} void Todos::sort(int column, Qt::SortOrder order) { todos_sort(m_d, column, order); } Qt::ItemFlags Todos::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); if (i.column() == 0) { flags |= Qt::ItemIsEditable; } return flags; } bool Todos::completed(int row) const { return todos_data_completed(m_d, row); } bool Todos::setCompleted(int row, bool value) { bool set = false; set = todos_set_data_completed(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); - emit dataChanged(index, index); + Q_EMIT dataChanged(index, index); } return set; } QString Todos::description(int row) const { QString s; todos_data_description(m_d, row, &s, set_qstring); return s; } bool Todos::setDescription(int row, const QString& value) { bool set = false; set = todos_set_data_description(m_d, row, value.utf16(), value.length()); if (set) { QModelIndex index = createIndex(row, 0, row); - emit dataChanged(index, index); + Q_EMIT dataChanged(index, index); } return set; } QVariant Todos::data(const QModelIndex &index, int role) const { Q_ASSERT(rowCount(index.parent()) > index.row()); switch (index.column()) { case 0: switch (role) { case Qt::UserRole + 0: return QVariant::fromValue(completed(index.row())); case Qt::UserRole + 1: return QVariant::fromValue(description(index.row())); } + break; } return QVariant(); } int Todos::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 Todos::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "completed"); names.insert(Qt::UserRole + 1, "description"); return names; } QVariant Todos::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 Todos::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; } bool Todos::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.column() == 0) { if (role == Qt::UserRole + 0) { if (value.canConvert(qMetaTypeId())) { return setCompleted(index.row(), value.value()); } } if (role == Qt::UserRole + 1) { if (value.canConvert(qMetaTypeId())) { return setDescription(index.row(), value.value()); } } } return false; } extern "C" { Todos::Private* todos_new(Todos*, void (*)(Todos*), void (*)(Todos*), void (*)(const Todos*), + void (*)(Todos*), + void (*)(Todos*), void (*)(Todos*, quintptr, quintptr), void (*)(Todos*), void (*)(Todos*), void (*)(Todos*, int, int), void (*)(Todos*), + void (*)(Todos*, int, int, int), + void (*)(Todos*), void (*)(Todos*, int, int), void (*)(Todos*)); void todos_free(Todos::Private*); quint64 todos_active_count_get(const Todos::Private*); quint64 todos_count_get(const Todos::Private*); void todos_add(Todos::Private*, const ushort*, int); void todos_clear_completed(Todos::Private*); bool todos_remove(Todos::Private*, quint64); void todos_set_all(Todos::Private*, bool); }; Todos::Todos(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), - m_d(0), + m_d(nullptr), m_ownsPrivate(false) { initHeaderData(); } Todos::Todos(QObject *parent): QAbstractItemModel(parent), m_d(todos_new(this, todosActiveCountChanged, todosCountChanged, [](const Todos* o) { - emit o->newDataReady(QModelIndex()); + Q_EMIT o->newDataReady(QModelIndex()); + }, + [](Todos* o) { + Q_EMIT o->layoutAboutToBeChanged(); + }, + [](Todos* o) { + o->updatePersistentIndexes(); + Q_EMIT o->layoutChanged(); }, [](Todos* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, 0, last)); }, [](Todos* o) { o->beginResetModel(); }, [](Todos* o) { o->endResetModel(); }, [](Todos* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](Todos* o) { o->endInsertRows(); }, + [](Todos* o, int first, int last, int destination) { + o->beginMoveRows(QModelIndex(), first, last, QModelIndex(), destination); + }, + [](Todos* o) { + o->endMoveRows(); + }, [](Todos* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](Todos* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &Todos::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } Todos::~Todos() { if (m_ownsPrivate) { todos_free(m_d); } } void Todos::initHeaderData() { } quint64 Todos::activeCount() const { return todos_active_count_get(m_d); } quint64 Todos::count() const { return todos_count_get(m_d); } void Todos::add(const QString& description) { return todos_add(m_d, description.utf16(), description.size()); } void Todos::clearCompleted() { return todos_clear_completed(m_d); } bool Todos::remove(quint64 index) { return todos_remove(m_d, index); } void Todos::setAll(bool completed) { return todos_set_all(m_d, completed); } diff --git a/examples/todos/src/Bindings.h b/examples/todos/src/Bindings.h index cbd6028..b10e08c 100644 --- a/examples/todos/src/Bindings.h +++ b/examples/todos/src/Bindings.h @@ -1,63 +1,64 @@ /* generated by rust_qt_binding_generator */ #ifndef BINDINGS_H #define BINDINGS_H -#include -#include +#include +#include class Todos; class Todos : public QAbstractItemModel { Q_OBJECT public: class Private; private: Private * m_d; bool m_ownsPrivate; Q_PROPERTY(quint64 activeCount READ activeCount NOTIFY activeCountChanged FINAL) Q_PROPERTY(quint64 count READ count NOTIFY countChanged FINAL) explicit Todos(bool owned, QObject *parent); public: explicit Todos(QObject *parent = nullptr); ~Todos(); quint64 activeCount() const; quint64 count() const; Q_INVOKABLE void add(const QString& description); Q_INVOKABLE void clearCompleted(); Q_INVOKABLE bool remove(quint64 index); Q_INVOKABLE void setAll(bool completed); 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; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; Q_INVOKABLE bool completed(int row) const; Q_INVOKABLE bool setCompleted(int row, bool value); Q_INVOKABLE QString description(int row) const; Q_INVOKABLE bool setDescription(int row, const QString& value); -signals: +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(); -signals: + void updatePersistentIndexes(); +Q_SIGNALS: void activeCountChanged(); void countChanged(); }; #endif // BINDINGS_H diff --git a/templates/qt_quick/rust/src/interface.rs b/templates/qt_quick/rust/src/interface.rs index 7040580..0a8f8c3 100644 --- a/templates/qt_quick/rust/src/interface.rs +++ b/templates/qt_quick/rust/src/interface.rs @@ -1,108 +1,118 @@ /* generated by rust_qt_binding_generator */ -#![allow(unknown_lints)] -#![allow(mutex_atomic, needless_pass_by_value)] use libc::{c_char, c_ushort, c_int}; use std::slice; use std::char::decode_utf16; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +use std::sync::atomic::{AtomicPtr, Ordering}; use std::ptr::null; use implementation::*; 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()) - .into_iter() .map(|r| r.unwrap()); s.clear(); s.extend(characters); } fn to_usize(n: c_int) -> usize { if n < 0 { panic!("Cannot cast {} to usize", n); } n as usize } 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 } pub struct SimpleQObject {} -#[derive(Clone)] pub struct SimpleEmitter { - qobject: Arc>, - message_changed: fn(*const SimpleQObject), + qobject: Arc>, + message_changed: fn(*mut SimpleQObject), } unsafe impl Send for SimpleEmitter {} impl SimpleEmitter { + /// 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) -> SimpleEmitter { + SimpleEmitter { + qobject: self.qobject.clone(), + message_changed: self.message_changed, + } + } fn clear(&self) { - *self.qobject.lock().unwrap() = null(); + let n: *const SimpleQObject = null(); + self.qobject.store(n as *mut SimpleQObject, Ordering::SeqCst); } - pub fn message_changed(&self) { - let ptr = *self.qobject.lock().unwrap(); + pub fn message_changed(&mut self) { + let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.message_changed)(ptr); } } } pub trait SimpleTrait { fn new(emit: SimpleEmitter) -> Self; fn emit(&self) -> &SimpleEmitter; fn message(&self) -> &str; fn set_message(&mut self, value: String); } #[no_mangle] pub extern "C" fn simple_new( simple: *mut SimpleQObject, - simple_message_changed: fn(*const SimpleQObject), + simple_message_changed: fn(*mut SimpleQObject), ) -> *mut Simple { let simple_emit = SimpleEmitter { - qobject: Arc::new(Mutex::new(simple)), + qobject: Arc::new(AtomicPtr::new(simple)), message_changed: simple_message_changed, }; let d_simple = Simple::new(simple_emit); Box::into_raw(Box::new(d_simple)) } #[no_mangle] pub unsafe extern "C" fn simple_free(ptr: *mut Simple) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] -pub extern "C" fn simple_message_get( +pub unsafe extern "C" fn simple_message_get( ptr: *const Simple, p: *mut QString, set: fn(*mut QString, *const c_char, c_int), ) { - let o = unsafe { &*ptr }; + let o = &*ptr; let v = o.message(); let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, to_c_int(v.len())); } #[no_mangle] -pub extern "C" fn simple_message_set(ptr: *mut Simple, v: *const c_ushort, len: c_int) { - let o = unsafe { &mut *ptr }; +pub unsafe extern "C" fn simple_message_set(ptr: *mut Simple, 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_message(s); } diff --git a/templates/qt_quick/src/Bindings.cpp b/templates/qt_quick/src/Bindings.cpp index 8178774..2ffb312 100644 --- a/templates/qt_quick/src/Bindings.cpp +++ b/templates/qt_quick/src/Bindings.cpp @@ -1,50 +1,50 @@ /* generated by rust_qt_binding_generator */ #include "Bindings.h" namespace { 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); } inline void simpleMessageChanged(Simple* o) { - emit o->messageChanged(); + Q_EMIT o->messageChanged(); } } extern "C" { Simple::Private* simple_new(Simple*, void (*)(Simple*)); void simple_free(Simple::Private*); void simple_message_get(const Simple::Private*, QString*, qstring_set); void simple_message_set(Simple::Private*, const ushort *str, int len); }; Simple::Simple(bool /*owned*/, QObject *parent): QObject(parent), - m_d(0), + m_d(nullptr), m_ownsPrivate(false) { } Simple::Simple(QObject *parent): QObject(parent), m_d(simple_new(this, simpleMessageChanged)), m_ownsPrivate(true) { } Simple::~Simple() { if (m_ownsPrivate) { simple_free(m_d); } } QString Simple::message() const { QString v; simple_message_get(m_d, &v, set_qstring); return v; } void Simple::setMessage(const QString& v) { simple_message_set(m_d, reinterpret_cast(v.data()), v.size()); } diff --git a/templates/qt_quick/src/Bindings.h b/templates/qt_quick/src/Bindings.h index 6d2c6df..1461ede 100644 --- a/templates/qt_quick/src/Bindings.h +++ b/templates/qt_quick/src/Bindings.h @@ -1,28 +1,28 @@ /* generated by rust_qt_binding_generator */ #ifndef BINDINGS_H #define BINDINGS_H -#include -#include +#include +#include class Simple; class Simple : public QObject { Q_OBJECT public: class Private; private: Private * m_d; bool m_ownsPrivate; Q_PROPERTY(QString message READ message WRITE setMessage NOTIFY messageChanged FINAL) explicit Simple(bool owned, QObject *parent); public: explicit Simple(QObject *parent = nullptr); ~Simple(); QString message() const; void setMessage(const QString& v); -signals: +Q_SIGNALS: void messageChanged(); }; #endif // BINDINGS_H diff --git a/templates/qt_widgets/rust/src/interface.rs b/templates/qt_widgets/rust/src/interface.rs index 7040580..0a8f8c3 100644 --- a/templates/qt_widgets/rust/src/interface.rs +++ b/templates/qt_widgets/rust/src/interface.rs @@ -1,108 +1,118 @@ /* generated by rust_qt_binding_generator */ -#![allow(unknown_lints)] -#![allow(mutex_atomic, needless_pass_by_value)] use libc::{c_char, c_ushort, c_int}; use std::slice; use std::char::decode_utf16; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +use std::sync::atomic::{AtomicPtr, Ordering}; use std::ptr::null; use implementation::*; 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()) - .into_iter() .map(|r| r.unwrap()); s.clear(); s.extend(characters); } fn to_usize(n: c_int) -> usize { if n < 0 { panic!("Cannot cast {} to usize", n); } n as usize } 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 } pub struct SimpleQObject {} -#[derive(Clone)] pub struct SimpleEmitter { - qobject: Arc>, - message_changed: fn(*const SimpleQObject), + qobject: Arc>, + message_changed: fn(*mut SimpleQObject), } unsafe impl Send for SimpleEmitter {} impl SimpleEmitter { + /// 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) -> SimpleEmitter { + SimpleEmitter { + qobject: self.qobject.clone(), + message_changed: self.message_changed, + } + } fn clear(&self) { - *self.qobject.lock().unwrap() = null(); + let n: *const SimpleQObject = null(); + self.qobject.store(n as *mut SimpleQObject, Ordering::SeqCst); } - pub fn message_changed(&self) { - let ptr = *self.qobject.lock().unwrap(); + pub fn message_changed(&mut self) { + let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.message_changed)(ptr); } } } pub trait SimpleTrait { fn new(emit: SimpleEmitter) -> Self; fn emit(&self) -> &SimpleEmitter; fn message(&self) -> &str; fn set_message(&mut self, value: String); } #[no_mangle] pub extern "C" fn simple_new( simple: *mut SimpleQObject, - simple_message_changed: fn(*const SimpleQObject), + simple_message_changed: fn(*mut SimpleQObject), ) -> *mut Simple { let simple_emit = SimpleEmitter { - qobject: Arc::new(Mutex::new(simple)), + qobject: Arc::new(AtomicPtr::new(simple)), message_changed: simple_message_changed, }; let d_simple = Simple::new(simple_emit); Box::into_raw(Box::new(d_simple)) } #[no_mangle] pub unsafe extern "C" fn simple_free(ptr: *mut Simple) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] -pub extern "C" fn simple_message_get( +pub unsafe extern "C" fn simple_message_get( ptr: *const Simple, p: *mut QString, set: fn(*mut QString, *const c_char, c_int), ) { - let o = unsafe { &*ptr }; + let o = &*ptr; let v = o.message(); let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, to_c_int(v.len())); } #[no_mangle] -pub extern "C" fn simple_message_set(ptr: *mut Simple, v: *const c_ushort, len: c_int) { - let o = unsafe { &mut *ptr }; +pub unsafe extern "C" fn simple_message_set(ptr: *mut Simple, 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_message(s); } diff --git a/templates/qt_widgets/src/Bindings.cpp b/templates/qt_widgets/src/Bindings.cpp index 8178774..2ffb312 100644 --- a/templates/qt_widgets/src/Bindings.cpp +++ b/templates/qt_widgets/src/Bindings.cpp @@ -1,50 +1,50 @@ /* generated by rust_qt_binding_generator */ #include "Bindings.h" namespace { 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); } inline void simpleMessageChanged(Simple* o) { - emit o->messageChanged(); + Q_EMIT o->messageChanged(); } } extern "C" { Simple::Private* simple_new(Simple*, void (*)(Simple*)); void simple_free(Simple::Private*); void simple_message_get(const Simple::Private*, QString*, qstring_set); void simple_message_set(Simple::Private*, const ushort *str, int len); }; Simple::Simple(bool /*owned*/, QObject *parent): QObject(parent), - m_d(0), + m_d(nullptr), m_ownsPrivate(false) { } Simple::Simple(QObject *parent): QObject(parent), m_d(simple_new(this, simpleMessageChanged)), m_ownsPrivate(true) { } Simple::~Simple() { if (m_ownsPrivate) { simple_free(m_d); } } QString Simple::message() const { QString v; simple_message_get(m_d, &v, set_qstring); return v; } void Simple::setMessage(const QString& v) { simple_message_set(m_d, reinterpret_cast(v.data()), v.size()); } diff --git a/templates/qt_widgets/src/Bindings.h b/templates/qt_widgets/src/Bindings.h index 6d2c6df..1461ede 100644 --- a/templates/qt_widgets/src/Bindings.h +++ b/templates/qt_widgets/src/Bindings.h @@ -1,28 +1,28 @@ /* generated by rust_qt_binding_generator */ #ifndef BINDINGS_H #define BINDINGS_H -#include -#include +#include +#include class Simple; class Simple : public QObject { Q_OBJECT public: class Private; private: Private * m_d; bool m_ownsPrivate; Q_PROPERTY(QString message READ message WRITE setMessage NOTIFY messageChanged FINAL) explicit Simple(bool owned, QObject *parent); public: explicit Simple(QObject *parent = nullptr); ~Simple(); QString message() const; void setMessage(const QString& v); -signals: +Q_SIGNALS: void messageChanged(); }; #endif // BINDINGS_H diff --git a/tests/rust_functions/src/interface.rs b/tests/rust_functions/src/interface.rs index 5d46e80..86b3694 100644 --- a/tests/rust_functions/src/interface.rs +++ b/tests/rust_functions/src/interface.rs @@ -1,171 +1,182 @@ /* 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 implementation::*; 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); } pub enum QByteArray {} fn to_usize(n: c_int) -> usize { if n < 0 { panic!("Cannot cast {} to usize", n); } n as usize } 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 } pub struct PersonQObject {} -#[derive(Clone)] pub struct PersonEmitter { qobject: Arc>, - user_name_changed: fn(*const PersonQObject), + user_name_changed: fn(*mut PersonQObject), } unsafe impl Send for PersonEmitter {} impl PersonEmitter { + /// 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) -> PersonEmitter { + PersonEmitter { + qobject: self.qobject.clone(), + user_name_changed: self.user_name_changed, + } + } fn clear(&self) { let n: *const PersonQObject = null(); self.qobject.store(n as *mut PersonQObject, Ordering::SeqCst); } - pub fn user_name_changed(&self) { + pub fn user_name_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.user_name_changed)(ptr); } } } pub trait PersonTrait { fn new(emit: PersonEmitter) -> Self; fn emit(&self) -> &PersonEmitter; fn user_name(&self) -> &str; fn set_user_name(&mut self, value: String); fn append(&mut self, suffix: String, amount: u32) -> (); fn double_name(&mut self) -> (); fn greet(&self, name: String) -> String; fn quote(&self, prefix: String, suffix: String) -> String; fn quote_bytes(&self, prefix: &[u8], suffix: &[u8]) -> Vec; fn vowels_in_name(&self) -> u8; } #[no_mangle] pub extern "C" fn person_new( person: *mut PersonQObject, - person_user_name_changed: fn(*const PersonQObject), + person_user_name_changed: fn(*mut PersonQObject), ) -> *mut Person { let person_emit = PersonEmitter { qobject: Arc::new(AtomicPtr::new(person)), user_name_changed: person_user_name_changed, }; let d_person = Person::new(person_emit); Box::into_raw(Box::new(d_person)) } #[no_mangle] pub unsafe extern "C" fn person_free(ptr: *mut Person) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn person_user_name_get( ptr: *const Person, p: *mut QString, set: fn(*mut QString, *const c_char, c_int), ) { let o = &*ptr; let v = o.user_name(); let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, to_c_int(v.len())); } #[no_mangle] pub unsafe extern "C" fn person_user_name_set(ptr: *mut Person, 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_user_name(s); } #[no_mangle] pub unsafe extern "C" fn person_append(ptr: *mut Person, suffix_str: *const c_ushort, suffix_len: c_int, amount: u32) -> () { let mut suffix = String::new(); set_string_from_utf16(&mut suffix, suffix_str, suffix_len); let o = &mut *ptr; let r = o.append(suffix, amount); r } #[no_mangle] pub unsafe extern "C" fn person_double_name(ptr: *mut Person) -> () { let o = &mut *ptr; let r = o.double_name(); r } #[no_mangle] pub unsafe extern "C" fn person_greet(ptr: *const Person, name_str: *const c_ushort, name_len: c_int, d: *mut QString, set: fn(*mut QString, str: *const c_char, len: c_int)) { let mut name = String::new(); set_string_from_utf16(&mut name, name_str, name_len); let o = &*ptr; let r = o.greet(name); let s: *const c_char = r.as_ptr() as (*const c_char); set(d, s, r.len() as i32); } #[no_mangle] pub unsafe extern "C" fn person_quote(ptr: *const Person, prefix_str: *const c_ushort, prefix_len: c_int, suffix_str: *const c_ushort, suffix_len: c_int, d: *mut QString, set: fn(*mut QString, str: *const c_char, len: c_int)) { let mut prefix = String::new(); set_string_from_utf16(&mut prefix, prefix_str, prefix_len); let mut suffix = String::new(); set_string_from_utf16(&mut suffix, suffix_str, suffix_len); let o = &*ptr; let r = o.quote(prefix, suffix); let s: *const c_char = r.as_ptr() as (*const c_char); set(d, s, r.len() as i32); } #[no_mangle] pub unsafe extern "C" fn person_quote_bytes(ptr: *const Person, prefix_str: *const c_char, prefix_len: c_int, suffix_str: *const c_char, suffix_len: c_int, d: *mut QByteArray, set: fn(*mut QByteArray, str: *const c_char, len: c_int)) { let prefix = { slice::from_raw_parts(prefix_str as *const u8, to_usize(prefix_len)) }; let suffix = { slice::from_raw_parts(suffix_str as *const u8, to_usize(suffix_len)) }; let o = &*ptr; let r = o.quote_bytes(prefix, suffix); let s: *const c_char = r.as_ptr() as (*const c_char); set(d, s, r.len() as i32); } #[no_mangle] pub unsafe extern "C" fn person_vowels_in_name(ptr: *const Person) -> u8 { let o = &*ptr; let r = o.vowels_in_name(); r } diff --git a/tests/rust_list/src/interface.rs b/tests/rust_list/src/interface.rs index a71ba68..df1e90c 100644 --- a/tests/rust_list/src/interface.rs +++ b/tests/rust_list/src/interface.rs @@ -1,476 +1,498 @@ /* 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 implementation::*; #[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, } } } } 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); } #[repr(C)] #[derive(PartialEq, Eq, Debug)] pub enum SortOrder { Ascending = 0, Descending = 1, } #[repr(C)] pub struct QModelIndex { row: c_int, internal_id: usize, } fn to_usize(n: c_int) -> usize { if n < 0 { panic!("Cannot cast {} to usize", n); } n as usize } 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 } pub struct NoRoleQObject {} -#[derive(Clone)] pub struct NoRoleEmitter { qobject: Arc>, - new_data_ready: fn(*const NoRoleQObject), + new_data_ready: fn(*mut NoRoleQObject), } unsafe impl Send for NoRoleEmitter {} impl NoRoleEmitter { + /// 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) -> NoRoleEmitter { + NoRoleEmitter { + qobject: self.qobject.clone(), + new_data_ready: self.new_data_ready, + } + } fn clear(&self) { let n: *const NoRoleQObject = null(); self.qobject.store(n as *mut NoRoleQObject, Ordering::SeqCst); } - pub fn new_data_ready(&self) { + pub fn new_data_ready(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.new_data_ready)(ptr); } } } #[derive(Clone)] pub struct NoRoleList { - qobject: *const NoRoleQObject, - layout_about_to_be_changed: fn(*const NoRoleQObject), - layout_changed: fn(*const NoRoleQObject), - data_changed: fn(*const NoRoleQObject, usize, usize), - begin_reset_model: fn(*const NoRoleQObject), - end_reset_model: fn(*const NoRoleQObject), - begin_insert_rows: fn(*const NoRoleQObject, usize, usize), - end_insert_rows: fn(*const NoRoleQObject), - begin_move_rows: fn(*const NoRoleQObject, usize, usize, usize), - end_move_rows: fn(*const NoRoleQObject), - begin_remove_rows: fn(*const NoRoleQObject, usize, usize), - end_remove_rows: fn(*const NoRoleQObject), + qobject: *mut NoRoleQObject, + layout_about_to_be_changed: fn(*mut NoRoleQObject), + layout_changed: fn(*mut NoRoleQObject), + data_changed: fn(*mut NoRoleQObject, usize, usize), + begin_reset_model: fn(*mut NoRoleQObject), + end_reset_model: fn(*mut NoRoleQObject), + begin_insert_rows: fn(*mut NoRoleQObject, usize, usize), + end_insert_rows: fn(*mut NoRoleQObject), + begin_move_rows: fn(*mut NoRoleQObject, usize, usize, usize), + end_move_rows: fn(*mut NoRoleQObject), + begin_remove_rows: fn(*mut NoRoleQObject, usize, usize), + end_remove_rows: fn(*mut NoRoleQObject), } impl NoRoleList { - pub fn layout_about_to_be_changed(&self) { + pub fn layout_about_to_be_changed(&mut self) { (self.layout_about_to_be_changed)(self.qobject); } - pub fn layout_changed(&self) { + pub fn layout_changed(&mut self) { (self.layout_changed)(self.qobject); } - pub fn data_changed(&self, first: usize, last: usize) { + pub fn data_changed(&mut self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } - pub fn begin_reset_model(&self) { + pub fn begin_reset_model(&mut self) { (self.begin_reset_model)(self.qobject); } - pub fn end_reset_model(&self) { + pub fn end_reset_model(&mut self) { (self.end_reset_model)(self.qobject); } - pub fn begin_insert_rows(&self, first: usize, last: usize) { + pub fn begin_insert_rows(&mut self, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, first, last); } - pub fn end_insert_rows(&self) { + pub fn end_insert_rows(&mut self) { (self.end_insert_rows)(self.qobject); } - pub fn begin_move_rows(&self, first: usize, last: usize, destination: usize) { + pub fn begin_move_rows(&mut self, first: usize, last: usize, destination: usize) { (self.begin_move_rows)(self.qobject, first, last, destination); } - pub fn end_move_rows(&self) { + pub fn end_move_rows(&mut self) { (self.end_move_rows)(self.qobject); } - pub fn begin_remove_rows(&self, first: usize, last: usize) { + pub fn begin_remove_rows(&mut self, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, first, last); } - pub fn end_remove_rows(&self) { + pub fn end_remove_rows(&mut self) { (self.end_remove_rows)(self.qobject); } } pub trait NoRoleTrait { fn new(emit: NoRoleEmitter, model: NoRoleList) -> Self; fn emit(&self) -> &NoRoleEmitter; 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) {} fn user_age(&self, index: usize) -> u8; fn set_user_age(&mut self, index: usize, u8) -> bool; fn user_name(&self, index: usize) -> &str; fn set_user_name(&mut self, index: usize, String) -> bool; } #[no_mangle] pub extern "C" fn no_role_new( no_role: *mut NoRoleQObject, - no_role_new_data_ready: fn(*const NoRoleQObject), - no_role_layout_about_to_be_changed: fn(*const NoRoleQObject), - no_role_layout_changed: fn(*const NoRoleQObject), - no_role_data_changed: fn(*const NoRoleQObject, usize, usize), - no_role_begin_reset_model: fn(*const NoRoleQObject), - no_role_end_reset_model: fn(*const NoRoleQObject), - no_role_begin_insert_rows: fn(*const NoRoleQObject, usize, usize), - no_role_end_insert_rows: fn(*const NoRoleQObject), - no_role_begin_move_rows: fn(*const NoRoleQObject, usize, usize, usize), - no_role_end_move_rows: fn(*const NoRoleQObject), - no_role_begin_remove_rows: fn(*const NoRoleQObject, usize, usize), - no_role_end_remove_rows: fn(*const NoRoleQObject), + no_role_new_data_ready: fn(*mut NoRoleQObject), + no_role_layout_about_to_be_changed: fn(*mut NoRoleQObject), + no_role_layout_changed: fn(*mut NoRoleQObject), + no_role_data_changed: fn(*mut NoRoleQObject, usize, usize), + no_role_begin_reset_model: fn(*mut NoRoleQObject), + no_role_end_reset_model: fn(*mut NoRoleQObject), + no_role_begin_insert_rows: fn(*mut NoRoleQObject, usize, usize), + no_role_end_insert_rows: fn(*mut NoRoleQObject), + no_role_begin_move_rows: fn(*mut NoRoleQObject, usize, usize, usize), + no_role_end_move_rows: fn(*mut NoRoleQObject), + no_role_begin_remove_rows: fn(*mut NoRoleQObject, usize, usize), + no_role_end_remove_rows: fn(*mut NoRoleQObject), ) -> *mut NoRole { let no_role_emit = NoRoleEmitter { qobject: Arc::new(AtomicPtr::new(no_role)), new_data_ready: no_role_new_data_ready, }; let model = NoRoleList { qobject: no_role, layout_about_to_be_changed: no_role_layout_about_to_be_changed, layout_changed: no_role_layout_changed, data_changed: no_role_data_changed, begin_reset_model: no_role_begin_reset_model, end_reset_model: no_role_end_reset_model, begin_insert_rows: no_role_begin_insert_rows, end_insert_rows: no_role_end_insert_rows, begin_move_rows: no_role_begin_move_rows, end_move_rows: no_role_end_move_rows, begin_remove_rows: no_role_begin_remove_rows, end_remove_rows: no_role_end_remove_rows, }; let d_no_role = NoRole::new(no_role_emit, model); Box::into_raw(Box::new(d_no_role)) } #[no_mangle] pub unsafe extern "C" fn no_role_free(ptr: *mut NoRole) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn no_role_row_count(ptr: *const NoRole) -> c_int { to_c_int((&*ptr).row_count()) } #[no_mangle] pub unsafe extern "C" fn no_role_insert_rows(ptr: *mut NoRole, row: c_int, count: c_int) -> bool { (&mut *ptr).insert_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn no_role_remove_rows(ptr: *mut NoRole, row: c_int, count: c_int) -> bool { (&mut *ptr).remove_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn no_role_can_fetch_more(ptr: *const NoRole) -> bool { (&*ptr).can_fetch_more() } #[no_mangle] pub unsafe extern "C" fn no_role_fetch_more(ptr: *mut NoRole) { (&mut *ptr).fetch_more() } #[no_mangle] pub unsafe extern "C" fn no_role_sort( ptr: *mut NoRole, column: u8, order: SortOrder, ) { (&mut *ptr).sort(column, order) } #[no_mangle] pub unsafe extern "C" fn no_role_data_user_age(ptr: *const NoRole, row: c_int) -> u8 { let o = &*ptr; o.user_age(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn no_role_set_data_user_age( ptr: *mut NoRole, row: c_int, v: u8, ) -> bool { (&mut *ptr).set_user_age(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn no_role_data_user_name( ptr: *const NoRole, row: c_int, d: *mut QString, set: fn(*mut QString, *const c_char, len: c_int), ) { let o = &*ptr; let data = o.user_name(to_usize(row)); let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, to_c_int(data.len())); } #[no_mangle] pub unsafe extern "C" fn no_role_set_data_user_name( ptr: *mut NoRole, row: c_int, 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_user_name(to_usize(row), v) } pub struct PersonsQObject {} -#[derive(Clone)] pub struct PersonsEmitter { qobject: Arc>, - new_data_ready: fn(*const PersonsQObject), + new_data_ready: fn(*mut PersonsQObject), } unsafe impl Send for PersonsEmitter {} impl PersonsEmitter { + /// 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) -> PersonsEmitter { + PersonsEmitter { + qobject: self.qobject.clone(), + new_data_ready: self.new_data_ready, + } + } fn clear(&self) { let n: *const PersonsQObject = null(); self.qobject.store(n as *mut PersonsQObject, Ordering::SeqCst); } - pub fn new_data_ready(&self) { + pub fn new_data_ready(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.new_data_ready)(ptr); } } } #[derive(Clone)] pub struct PersonsList { - qobject: *const PersonsQObject, - layout_about_to_be_changed: fn(*const PersonsQObject), - layout_changed: fn(*const PersonsQObject), - data_changed: fn(*const PersonsQObject, usize, usize), - begin_reset_model: fn(*const PersonsQObject), - end_reset_model: fn(*const PersonsQObject), - begin_insert_rows: fn(*const PersonsQObject, usize, usize), - end_insert_rows: fn(*const PersonsQObject), - begin_move_rows: fn(*const PersonsQObject, usize, usize, usize), - end_move_rows: fn(*const PersonsQObject), - begin_remove_rows: fn(*const PersonsQObject, usize, usize), - end_remove_rows: fn(*const PersonsQObject), + qobject: *mut PersonsQObject, + layout_about_to_be_changed: fn(*mut PersonsQObject), + layout_changed: fn(*mut PersonsQObject), + data_changed: fn(*mut PersonsQObject, usize, usize), + begin_reset_model: fn(*mut PersonsQObject), + end_reset_model: fn(*mut PersonsQObject), + begin_insert_rows: fn(*mut PersonsQObject, usize, usize), + end_insert_rows: fn(*mut PersonsQObject), + begin_move_rows: fn(*mut PersonsQObject, usize, usize, usize), + end_move_rows: fn(*mut PersonsQObject), + begin_remove_rows: fn(*mut PersonsQObject, usize, usize), + end_remove_rows: fn(*mut PersonsQObject), } impl PersonsList { - pub fn layout_about_to_be_changed(&self) { + pub fn layout_about_to_be_changed(&mut self) { (self.layout_about_to_be_changed)(self.qobject); } - pub fn layout_changed(&self) { + pub fn layout_changed(&mut self) { (self.layout_changed)(self.qobject); } - pub fn data_changed(&self, first: usize, last: usize) { + pub fn data_changed(&mut self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } - pub fn begin_reset_model(&self) { + pub fn begin_reset_model(&mut self) { (self.begin_reset_model)(self.qobject); } - pub fn end_reset_model(&self) { + pub fn end_reset_model(&mut self) { (self.end_reset_model)(self.qobject); } - pub fn begin_insert_rows(&self, first: usize, last: usize) { + pub fn begin_insert_rows(&mut self, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, first, last); } - pub fn end_insert_rows(&self) { + pub fn end_insert_rows(&mut self) { (self.end_insert_rows)(self.qobject); } - pub fn begin_move_rows(&self, first: usize, last: usize, destination: usize) { + pub fn begin_move_rows(&mut self, first: usize, last: usize, destination: usize) { (self.begin_move_rows)(self.qobject, first, last, destination); } - pub fn end_move_rows(&self) { + pub fn end_move_rows(&mut self) { (self.end_move_rows)(self.qobject); } - pub fn begin_remove_rows(&self, first: usize, last: usize) { + pub fn begin_remove_rows(&mut self, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, first, last); } - pub fn end_remove_rows(&self) { + pub fn end_remove_rows(&mut self) { (self.end_remove_rows)(self.qobject); } } pub trait PersonsTrait { fn new(emit: PersonsEmitter, model: PersonsList) -> Self; fn emit(&self) -> &PersonsEmitter; 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) {} fn user_name(&self, index: usize) -> &str; fn set_user_name(&mut self, index: usize, String) -> bool; } #[no_mangle] pub extern "C" fn persons_new( persons: *mut PersonsQObject, - persons_new_data_ready: fn(*const PersonsQObject), - persons_layout_about_to_be_changed: fn(*const PersonsQObject), - persons_layout_changed: fn(*const PersonsQObject), - persons_data_changed: fn(*const PersonsQObject, usize, usize), - persons_begin_reset_model: fn(*const PersonsQObject), - persons_end_reset_model: fn(*const PersonsQObject), - persons_begin_insert_rows: fn(*const PersonsQObject, usize, usize), - persons_end_insert_rows: fn(*const PersonsQObject), - persons_begin_move_rows: fn(*const PersonsQObject, usize, usize, usize), - persons_end_move_rows: fn(*const PersonsQObject), - persons_begin_remove_rows: fn(*const PersonsQObject, usize, usize), - persons_end_remove_rows: fn(*const PersonsQObject), + persons_new_data_ready: fn(*mut PersonsQObject), + persons_layout_about_to_be_changed: fn(*mut PersonsQObject), + persons_layout_changed: fn(*mut PersonsQObject), + persons_data_changed: fn(*mut PersonsQObject, usize, usize), + persons_begin_reset_model: fn(*mut PersonsQObject), + persons_end_reset_model: fn(*mut PersonsQObject), + persons_begin_insert_rows: fn(*mut PersonsQObject, usize, usize), + persons_end_insert_rows: fn(*mut PersonsQObject), + persons_begin_move_rows: fn(*mut PersonsQObject, usize, usize, usize), + persons_end_move_rows: fn(*mut PersonsQObject), + persons_begin_remove_rows: fn(*mut PersonsQObject, usize, usize), + persons_end_remove_rows: fn(*mut PersonsQObject), ) -> *mut Persons { let persons_emit = PersonsEmitter { qobject: Arc::new(AtomicPtr::new(persons)), new_data_ready: persons_new_data_ready, }; let model = PersonsList { qobject: persons, layout_about_to_be_changed: persons_layout_about_to_be_changed, layout_changed: persons_layout_changed, data_changed: persons_data_changed, begin_reset_model: persons_begin_reset_model, end_reset_model: persons_end_reset_model, begin_insert_rows: persons_begin_insert_rows, end_insert_rows: persons_end_insert_rows, begin_move_rows: persons_begin_move_rows, end_move_rows: persons_end_move_rows, begin_remove_rows: persons_begin_remove_rows, end_remove_rows: persons_end_remove_rows, }; let d_persons = Persons::new(persons_emit, model); Box::into_raw(Box::new(d_persons)) } #[no_mangle] pub unsafe extern "C" fn persons_free(ptr: *mut Persons) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn persons_row_count(ptr: *const Persons) -> c_int { to_c_int((&*ptr).row_count()) } #[no_mangle] pub unsafe extern "C" fn persons_insert_rows(ptr: *mut Persons, row: c_int, count: c_int) -> bool { (&mut *ptr).insert_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn persons_remove_rows(ptr: *mut Persons, row: c_int, count: c_int) -> bool { (&mut *ptr).remove_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn persons_can_fetch_more(ptr: *const Persons) -> bool { (&*ptr).can_fetch_more() } #[no_mangle] pub unsafe extern "C" fn persons_fetch_more(ptr: *mut Persons) { (&mut *ptr).fetch_more() } #[no_mangle] pub unsafe extern "C" fn persons_sort( ptr: *mut Persons, column: u8, order: SortOrder, ) { (&mut *ptr).sort(column, order) } #[no_mangle] pub unsafe extern "C" fn persons_data_user_name( ptr: *const Persons, row: c_int, d: *mut QString, set: fn(*mut QString, *const c_char, len: c_int), ) { let o = &*ptr; let data = o.user_name(to_usize(row)); let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, to_c_int(data.len())); } #[no_mangle] pub unsafe extern "C" fn persons_set_data_user_name( ptr: *mut Persons, row: c_int, 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_user_name(to_usize(row), v) } diff --git a/tests/rust_list_types/src/interface.rs b/tests/rust_list_types/src/interface.rs index cd91c84..c8be099 100644 --- a/tests/rust_list_types/src/interface.rs +++ b/tests/rust_list_types/src/interface.rs @@ -1,562 +1,573 @@ /* 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 implementation::*; #[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, } } } } 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); } pub enum QByteArray {} #[repr(C)] #[derive(PartialEq, Eq, Debug)] pub enum SortOrder { Ascending = 0, Descending = 1, } #[repr(C)] pub struct QModelIndex { row: c_int, internal_id: usize, } fn to_usize(n: c_int) -> usize { if n < 0 { panic!("Cannot cast {} to usize", n); } n as usize } 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 } pub struct ListQObject {} -#[derive(Clone)] pub struct ListEmitter { qobject: Arc>, - new_data_ready: fn(*const ListQObject), + new_data_ready: fn(*mut ListQObject), } unsafe impl Send for ListEmitter {} impl ListEmitter { + /// 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) -> ListEmitter { + ListEmitter { + qobject: self.qobject.clone(), + new_data_ready: self.new_data_ready, + } + } fn clear(&self) { let n: *const ListQObject = null(); self.qobject.store(n as *mut ListQObject, Ordering::SeqCst); } - pub fn new_data_ready(&self) { + pub fn new_data_ready(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.new_data_ready)(ptr); } } } #[derive(Clone)] pub struct ListList { - qobject: *const ListQObject, - layout_about_to_be_changed: fn(*const ListQObject), - layout_changed: fn(*const ListQObject), - data_changed: fn(*const ListQObject, usize, usize), - begin_reset_model: fn(*const ListQObject), - end_reset_model: fn(*const ListQObject), - begin_insert_rows: fn(*const ListQObject, usize, usize), - end_insert_rows: fn(*const ListQObject), - begin_move_rows: fn(*const ListQObject, usize, usize, usize), - end_move_rows: fn(*const ListQObject), - begin_remove_rows: fn(*const ListQObject, usize, usize), - end_remove_rows: fn(*const ListQObject), + qobject: *mut ListQObject, + layout_about_to_be_changed: fn(*mut ListQObject), + layout_changed: fn(*mut ListQObject), + data_changed: fn(*mut ListQObject, usize, usize), + begin_reset_model: fn(*mut ListQObject), + end_reset_model: fn(*mut ListQObject), + begin_insert_rows: fn(*mut ListQObject, usize, usize), + end_insert_rows: fn(*mut ListQObject), + begin_move_rows: fn(*mut ListQObject, usize, usize, usize), + end_move_rows: fn(*mut ListQObject), + begin_remove_rows: fn(*mut ListQObject, usize, usize), + end_remove_rows: fn(*mut ListQObject), } impl ListList { - pub fn layout_about_to_be_changed(&self) { + pub fn layout_about_to_be_changed(&mut self) { (self.layout_about_to_be_changed)(self.qobject); } - pub fn layout_changed(&self) { + pub fn layout_changed(&mut self) { (self.layout_changed)(self.qobject); } - pub fn data_changed(&self, first: usize, last: usize) { + pub fn data_changed(&mut self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } - pub fn begin_reset_model(&self) { + pub fn begin_reset_model(&mut self) { (self.begin_reset_model)(self.qobject); } - pub fn end_reset_model(&self) { + pub fn end_reset_model(&mut self) { (self.end_reset_model)(self.qobject); } - pub fn begin_insert_rows(&self, first: usize, last: usize) { + pub fn begin_insert_rows(&mut self, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, first, last); } - pub fn end_insert_rows(&self) { + pub fn end_insert_rows(&mut self) { (self.end_insert_rows)(self.qobject); } - pub fn begin_move_rows(&self, first: usize, last: usize, destination: usize) { + pub fn begin_move_rows(&mut self, first: usize, last: usize, destination: usize) { (self.begin_move_rows)(self.qobject, first, last, destination); } - pub fn end_move_rows(&self) { + pub fn end_move_rows(&mut self) { (self.end_move_rows)(self.qobject); } - pub fn begin_remove_rows(&self, first: usize, last: usize) { + pub fn begin_remove_rows(&mut self, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, first, last); } - pub fn end_remove_rows(&self) { + pub fn end_remove_rows(&mut self) { (self.end_remove_rows)(self.qobject); } } pub trait ListTrait { fn new(emit: ListEmitter, model: ListList) -> Self; fn emit(&self) -> &ListEmitter; 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) {} fn boolean(&self, index: usize) -> bool; fn set_boolean(&mut self, index: usize, bool) -> bool; fn bytearray(&self, index: usize) -> &[u8]; fn set_bytearray(&mut self, index: usize, &[u8]) -> bool; fn f32(&self, index: usize) -> f32; fn set_f32(&mut self, index: usize, f32) -> bool; fn f64(&self, index: usize) -> f64; fn set_f64(&mut self, index: usize, f64) -> bool; fn i16(&self, index: usize) -> i16; fn set_i16(&mut self, index: usize, i16) -> bool; fn i32(&self, index: usize) -> i32; fn set_i32(&mut self, index: usize, i32) -> bool; fn i64(&self, index: usize) -> i64; fn set_i64(&mut self, index: usize, i64) -> bool; fn i8(&self, index: usize) -> i8; fn set_i8(&mut self, index: usize, i8) -> bool; fn optional_boolean(&self, index: usize) -> Option; fn set_optional_boolean(&mut self, index: usize, Option) -> bool; fn optional_bytearray(&self, index: usize) -> Option<&[u8]>; fn set_optional_bytearray(&mut self, index: usize, Option<&[u8]>) -> bool; fn optional_string(&self, index: usize) -> Option<&str>; fn set_optional_string(&mut self, index: usize, Option) -> bool; fn string(&self, index: usize) -> &str; fn set_string(&mut self, index: usize, String) -> bool; fn u16(&self, index: usize) -> u16; fn set_u16(&mut self, index: usize, u16) -> bool; fn u32(&self, index: usize) -> u32; fn set_u32(&mut self, index: usize, u32) -> bool; fn u64(&self, index: usize) -> u64; fn set_u64(&mut self, index: usize, u64) -> bool; fn u8(&self, index: usize) -> u8; fn set_u8(&mut self, index: usize, u8) -> bool; } #[no_mangle] pub extern "C" fn list_new( list: *mut ListQObject, - list_new_data_ready: fn(*const ListQObject), - list_layout_about_to_be_changed: fn(*const ListQObject), - list_layout_changed: fn(*const ListQObject), - list_data_changed: fn(*const ListQObject, usize, usize), - list_begin_reset_model: fn(*const ListQObject), - list_end_reset_model: fn(*const ListQObject), - list_begin_insert_rows: fn(*const ListQObject, usize, usize), - list_end_insert_rows: fn(*const ListQObject), - list_begin_move_rows: fn(*const ListQObject, usize, usize, usize), - list_end_move_rows: fn(*const ListQObject), - list_begin_remove_rows: fn(*const ListQObject, usize, usize), - list_end_remove_rows: fn(*const ListQObject), + list_new_data_ready: fn(*mut ListQObject), + list_layout_about_to_be_changed: fn(*mut ListQObject), + list_layout_changed: fn(*mut ListQObject), + list_data_changed: fn(*mut ListQObject, usize, usize), + list_begin_reset_model: fn(*mut ListQObject), + list_end_reset_model: fn(*mut ListQObject), + list_begin_insert_rows: fn(*mut ListQObject, usize, usize), + list_end_insert_rows: fn(*mut ListQObject), + list_begin_move_rows: fn(*mut ListQObject, usize, usize, usize), + list_end_move_rows: fn(*mut ListQObject), + list_begin_remove_rows: fn(*mut ListQObject, usize, usize), + list_end_remove_rows: fn(*mut ListQObject), ) -> *mut List { let list_emit = ListEmitter { qobject: Arc::new(AtomicPtr::new(list)), new_data_ready: list_new_data_ready, }; let model = ListList { qobject: list, layout_about_to_be_changed: list_layout_about_to_be_changed, layout_changed: list_layout_changed, data_changed: list_data_changed, begin_reset_model: list_begin_reset_model, end_reset_model: list_end_reset_model, begin_insert_rows: list_begin_insert_rows, end_insert_rows: list_end_insert_rows, begin_move_rows: list_begin_move_rows, end_move_rows: list_end_move_rows, begin_remove_rows: list_begin_remove_rows, end_remove_rows: list_end_remove_rows, }; let d_list = List::new(list_emit, model); Box::into_raw(Box::new(d_list)) } #[no_mangle] pub unsafe extern "C" fn list_free(ptr: *mut List) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn list_row_count(ptr: *const List) -> c_int { to_c_int((&*ptr).row_count()) } #[no_mangle] pub unsafe extern "C" fn list_insert_rows(ptr: *mut List, row: c_int, count: c_int) -> bool { (&mut *ptr).insert_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn list_remove_rows(ptr: *mut List, row: c_int, count: c_int) -> bool { (&mut *ptr).remove_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn list_can_fetch_more(ptr: *const List) -> bool { (&*ptr).can_fetch_more() } #[no_mangle] pub unsafe extern "C" fn list_fetch_more(ptr: *mut List) { (&mut *ptr).fetch_more() } #[no_mangle] pub unsafe extern "C" fn list_sort( ptr: *mut List, column: u8, order: SortOrder, ) { (&mut *ptr).sort(column, order) } #[no_mangle] pub unsafe extern "C" fn list_data_boolean(ptr: *const List, row: c_int) -> bool { let o = &*ptr; o.boolean(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn list_set_data_boolean( ptr: *mut List, row: c_int, v: bool, ) -> bool { (&mut *ptr).set_boolean(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn list_data_bytearray( ptr: *const List, row: c_int, d: *mut QByteArray, set: fn(*mut QByteArray, *const c_char, len: c_int), ) { let o = &*ptr; let data = o.bytearray(to_usize(row)); let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, to_c_int(data.len())); } #[no_mangle] pub unsafe extern "C" fn list_set_data_bytearray( ptr: *mut List, row: c_int, 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_bytearray(to_usize(row), slice) } #[no_mangle] pub unsafe extern "C" fn list_data_f32(ptr: *const List, row: c_int) -> f32 { let o = &*ptr; o.f32(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn list_set_data_f32( ptr: *mut List, row: c_int, v: f32, ) -> bool { (&mut *ptr).set_f32(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn list_data_f64(ptr: *const List, row: c_int) -> f64 { let o = &*ptr; o.f64(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn list_set_data_f64( ptr: *mut List, row: c_int, v: f64, ) -> bool { (&mut *ptr).set_f64(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn list_data_i16(ptr: *const List, row: c_int) -> i16 { let o = &*ptr; o.i16(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn list_set_data_i16( ptr: *mut List, row: c_int, v: i16, ) -> bool { (&mut *ptr).set_i16(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn list_data_i32(ptr: *const List, row: c_int) -> i32 { let o = &*ptr; o.i32(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn list_set_data_i32( ptr: *mut List, row: c_int, v: i32, ) -> bool { (&mut *ptr).set_i32(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn list_data_i64(ptr: *const List, row: c_int) -> i64 { let o = &*ptr; o.i64(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn list_set_data_i64( ptr: *mut List, row: c_int, v: i64, ) -> bool { (&mut *ptr).set_i64(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn list_data_i8(ptr: *const List, row: c_int) -> i8 { let o = &*ptr; o.i8(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn list_set_data_i8( ptr: *mut List, row: c_int, v: i8, ) -> bool { (&mut *ptr).set_i8(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn list_data_optional_boolean(ptr: *const List, row: c_int) -> COption { let o = &*ptr; o.optional_boolean(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn list_set_data_optional_boolean( ptr: *mut List, row: c_int, v: bool, ) -> bool { (&mut *ptr).set_optional_boolean(to_usize(row), Some(v)) } #[no_mangle] pub unsafe extern "C" fn list_set_data_optional_boolean_none(ptr: *mut List, row: c_int) -> bool { (&mut *ptr).set_optional_boolean(to_usize(row), None) } #[no_mangle] pub unsafe extern "C" fn list_data_optional_bytearray( ptr: *const List, row: c_int, d: *mut QByteArray, set: fn(*mut QByteArray, *const c_char, len: c_int), ) { let o = &*ptr; let data = o.optional_bytearray(to_usize(row)); 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())); } } #[no_mangle] pub unsafe extern "C" fn list_set_data_optional_bytearray( ptr: *mut List, row: c_int, 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_optional_bytearray(to_usize(row), Some(slice)) } #[no_mangle] pub unsafe extern "C" fn list_set_data_optional_bytearray_none(ptr: *mut List, row: c_int) -> bool { (&mut *ptr).set_optional_bytearray(to_usize(row), None) } #[no_mangle] pub unsafe extern "C" fn list_data_optional_string( ptr: *const List, row: c_int, d: *mut QString, set: fn(*mut QString, *const c_char, len: c_int), ) { let o = &*ptr; let data = o.optional_string(to_usize(row)); 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())); } } #[no_mangle] pub unsafe extern "C" fn list_set_data_optional_string( ptr: *mut List, row: c_int, 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_optional_string(to_usize(row), Some(v)) } #[no_mangle] pub unsafe extern "C" fn list_set_data_optional_string_none(ptr: *mut List, row: c_int) -> bool { (&mut *ptr).set_optional_string(to_usize(row), None) } #[no_mangle] pub unsafe extern "C" fn list_data_string( ptr: *const List, row: c_int, d: *mut QString, set: fn(*mut QString, *const c_char, len: c_int), ) { let o = &*ptr; let data = o.string(to_usize(row)); let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, to_c_int(data.len())); } #[no_mangle] pub unsafe extern "C" fn list_set_data_string( ptr: *mut List, row: c_int, 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_string(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn list_data_u16(ptr: *const List, row: c_int) -> u16 { let o = &*ptr; o.u16(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn list_set_data_u16( ptr: *mut List, row: c_int, v: u16, ) -> bool { (&mut *ptr).set_u16(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn list_data_u32(ptr: *const List, row: c_int) -> u32 { let o = &*ptr; o.u32(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn list_set_data_u32( ptr: *mut List, row: c_int, v: u32, ) -> bool { (&mut *ptr).set_u32(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn list_data_u64(ptr: *const List, row: c_int) -> u64 { let o = &*ptr; o.u64(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn list_set_data_u64( ptr: *mut List, row: c_int, v: u64, ) -> bool { (&mut *ptr).set_u64(to_usize(row), v) } #[no_mangle] pub unsafe extern "C" fn list_data_u8(ptr: *const List, row: c_int) -> u8 { let o = &*ptr; o.u8(to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn list_set_data_u8( ptr: *mut List, row: c_int, v: u8, ) -> bool { (&mut *ptr).set_u8(to_usize(row), v) } diff --git a/tests/rust_object/src/interface.rs b/tests/rust_object/src/interface.rs index 7cfe940..583c151 100644 --- a/tests/rust_object/src/interface.rs +++ b/tests/rust_object/src/interface.rs @@ -1,107 +1,118 @@ /* 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 implementation::*; 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); } fn to_usize(n: c_int) -> usize { if n < 0 { panic!("Cannot cast {} to usize", n); } n as usize } 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 } pub struct PersonQObject {} -#[derive(Clone)] pub struct PersonEmitter { qobject: Arc>, - user_name_changed: fn(*const PersonQObject), + user_name_changed: fn(*mut PersonQObject), } unsafe impl Send for PersonEmitter {} impl PersonEmitter { + /// 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) -> PersonEmitter { + PersonEmitter { + qobject: self.qobject.clone(), + user_name_changed: self.user_name_changed, + } + } fn clear(&self) { let n: *const PersonQObject = null(); self.qobject.store(n as *mut PersonQObject, Ordering::SeqCst); } - pub fn user_name_changed(&self) { + pub fn user_name_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.user_name_changed)(ptr); } } } pub trait PersonTrait { fn new(emit: PersonEmitter) -> Self; fn emit(&self) -> &PersonEmitter; fn user_name(&self) -> &str; fn set_user_name(&mut self, value: String); } #[no_mangle] pub extern "C" fn person_new( person: *mut PersonQObject, - person_user_name_changed: fn(*const PersonQObject), + person_user_name_changed: fn(*mut PersonQObject), ) -> *mut Person { let person_emit = PersonEmitter { qobject: Arc::new(AtomicPtr::new(person)), user_name_changed: person_user_name_changed, }; let d_person = Person::new(person_emit); Box::into_raw(Box::new(d_person)) } #[no_mangle] pub unsafe extern "C" fn person_free(ptr: *mut Person) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn person_user_name_get( ptr: *const Person, p: *mut QString, set: fn(*mut QString, *const c_char, c_int), ) { let o = &*ptr; let v = o.user_name(); let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, to_c_int(v.len())); } #[no_mangle] pub unsafe extern "C" fn person_user_name_set(ptr: *mut Person, 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_user_name(s); } diff --git a/tests/rust_object_types/src/interface.rs b/tests/rust_object_types/src/interface.rs index 751c354..659f572 100644 --- a/tests/rust_object_types/src/interface.rs +++ b/tests/rust_object_types/src/interface.rs @@ -1,576 +1,604 @@ /* 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 implementation::*; #[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, } } } } 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); } pub enum QByteArray {} fn to_usize(n: c_int) -> usize { if n < 0 { panic!("Cannot cast {} to usize", n); } n as usize } 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 } pub struct ObjectQObject {} -#[derive(Clone)] pub struct ObjectEmitter { qobject: Arc>, - boolean_changed: fn(*const ObjectQObject), - bytearray_changed: fn(*const ObjectQObject), - f32_changed: fn(*const ObjectQObject), - f64_changed: fn(*const ObjectQObject), - i16_changed: fn(*const ObjectQObject), - i32_changed: fn(*const ObjectQObject), - i64_changed: fn(*const ObjectQObject), - i8_changed: fn(*const ObjectQObject), - optional_boolean_changed: fn(*const ObjectQObject), - optional_bytearray_changed: fn(*const ObjectQObject), - optional_string_changed: fn(*const ObjectQObject), - optional_u64_changed: fn(*const ObjectQObject), - string_changed: fn(*const ObjectQObject), - string_by_function_changed: fn(*const ObjectQObject), - u16_changed: fn(*const ObjectQObject), - u32_changed: fn(*const ObjectQObject), - u64_changed: fn(*const ObjectQObject), - u8_changed: fn(*const ObjectQObject), + boolean_changed: fn(*mut ObjectQObject), + bytearray_changed: fn(*mut ObjectQObject), + f32_changed: fn(*mut ObjectQObject), + f64_changed: fn(*mut ObjectQObject), + i16_changed: fn(*mut ObjectQObject), + i32_changed: fn(*mut ObjectQObject), + i64_changed: fn(*mut ObjectQObject), + i8_changed: fn(*mut ObjectQObject), + optional_boolean_changed: fn(*mut ObjectQObject), + optional_bytearray_changed: fn(*mut ObjectQObject), + optional_string_changed: fn(*mut ObjectQObject), + optional_u64_changed: fn(*mut ObjectQObject), + string_changed: fn(*mut ObjectQObject), + string_by_function_changed: fn(*mut ObjectQObject), + u16_changed: fn(*mut ObjectQObject), + u32_changed: fn(*mut ObjectQObject), + u64_changed: fn(*mut ObjectQObject), + u8_changed: fn(*mut ObjectQObject), } unsafe impl Send for ObjectEmitter {} impl ObjectEmitter { + /// 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) -> ObjectEmitter { + ObjectEmitter { + qobject: self.qobject.clone(), + boolean_changed: self.boolean_changed, + bytearray_changed: self.bytearray_changed, + f32_changed: self.f32_changed, + f64_changed: self.f64_changed, + i16_changed: self.i16_changed, + i32_changed: self.i32_changed, + i64_changed: self.i64_changed, + i8_changed: self.i8_changed, + optional_boolean_changed: self.optional_boolean_changed, + optional_bytearray_changed: self.optional_bytearray_changed, + optional_string_changed: self.optional_string_changed, + optional_u64_changed: self.optional_u64_changed, + string_changed: self.string_changed, + string_by_function_changed: self.string_by_function_changed, + u16_changed: self.u16_changed, + u32_changed: self.u32_changed, + u64_changed: self.u64_changed, + u8_changed: self.u8_changed, + } + } fn clear(&self) { let n: *const ObjectQObject = null(); self.qobject.store(n as *mut ObjectQObject, Ordering::SeqCst); } - pub fn boolean_changed(&self) { + pub fn boolean_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.boolean_changed)(ptr); } } - pub fn bytearray_changed(&self) { + pub fn bytearray_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.bytearray_changed)(ptr); } } - pub fn f32_changed(&self) { + pub fn f32_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.f32_changed)(ptr); } } - pub fn f64_changed(&self) { + pub fn f64_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.f64_changed)(ptr); } } - pub fn i16_changed(&self) { + pub fn i16_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.i16_changed)(ptr); } } - pub fn i32_changed(&self) { + pub fn i32_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.i32_changed)(ptr); } } - pub fn i64_changed(&self) { + pub fn i64_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.i64_changed)(ptr); } } - pub fn i8_changed(&self) { + pub fn i8_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.i8_changed)(ptr); } } - pub fn optional_boolean_changed(&self) { + pub fn optional_boolean_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.optional_boolean_changed)(ptr); } } - pub fn optional_bytearray_changed(&self) { + pub fn optional_bytearray_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.optional_bytearray_changed)(ptr); } } - pub fn optional_string_changed(&self) { + pub fn optional_string_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.optional_string_changed)(ptr); } } - pub fn optional_u64_changed(&self) { + pub fn optional_u64_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.optional_u64_changed)(ptr); } } - pub fn string_changed(&self) { + pub fn string_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.string_changed)(ptr); } } - pub fn string_by_function_changed(&self) { + pub fn string_by_function_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.string_by_function_changed)(ptr); } } - pub fn u16_changed(&self) { + pub fn u16_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.u16_changed)(ptr); } } - pub fn u32_changed(&self) { + pub fn u32_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.u32_changed)(ptr); } } - pub fn u64_changed(&self) { + pub fn u64_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.u64_changed)(ptr); } } - pub fn u8_changed(&self) { + pub fn u8_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.u8_changed)(ptr); } } } pub trait ObjectTrait { fn new(emit: ObjectEmitter) -> Self; fn emit(&self) -> &ObjectEmitter; fn boolean(&self) -> bool; fn set_boolean(&mut self, value: bool); fn bytearray(&self) -> &[u8]; fn set_bytearray(&mut self, value: &[u8]); fn f32(&self) -> f32; fn set_f32(&mut self, value: f32); fn f64(&self) -> f64; fn set_f64(&mut self, value: f64); fn i16(&self) -> i16; fn set_i16(&mut self, value: i16); fn i32(&self) -> i32; fn set_i32(&mut self, value: i32); fn i64(&self) -> i64; fn set_i64(&mut self, value: i64); fn i8(&self) -> i8; fn set_i8(&mut self, value: i8); fn optional_boolean(&self) -> Option; fn set_optional_boolean(&mut self, value: Option); fn optional_bytearray(&self) -> Option<&[u8]>; fn set_optional_bytearray(&mut self, value: Option<&[u8]>); fn optional_string(&self) -> Option<&str>; fn set_optional_string(&mut self, value: Option); fn optional_u64(&self) -> Option; fn set_optional_u64(&mut self, value: Option); fn string(&self) -> &str; fn set_string(&mut self, value: String); fn string_by_function(&self, getter: F) where F: FnOnce(&str); fn set_string_by_function(&mut self, value: String); fn u16(&self) -> u16; fn set_u16(&mut self, value: u16); fn u32(&self) -> u32; fn set_u32(&mut self, value: u32); fn u64(&self) -> u64; fn set_u64(&mut self, value: u64); fn u8(&self) -> u8; fn set_u8(&mut self, value: u8); } #[no_mangle] pub extern "C" fn object_new( object: *mut ObjectQObject, - object_boolean_changed: fn(*const ObjectQObject), - object_bytearray_changed: fn(*const ObjectQObject), - object_f32_changed: fn(*const ObjectQObject), - object_f64_changed: fn(*const ObjectQObject), - object_i16_changed: fn(*const ObjectQObject), - object_i32_changed: fn(*const ObjectQObject), - object_i64_changed: fn(*const ObjectQObject), - object_i8_changed: fn(*const ObjectQObject), - object_optional_boolean_changed: fn(*const ObjectQObject), - object_optional_bytearray_changed: fn(*const ObjectQObject), - object_optional_string_changed: fn(*const ObjectQObject), - object_optional_u64_changed: fn(*const ObjectQObject), - object_string_changed: fn(*const ObjectQObject), - object_string_by_function_changed: fn(*const ObjectQObject), - object_u16_changed: fn(*const ObjectQObject), - object_u32_changed: fn(*const ObjectQObject), - object_u64_changed: fn(*const ObjectQObject), - object_u8_changed: fn(*const ObjectQObject), + object_boolean_changed: fn(*mut ObjectQObject), + object_bytearray_changed: fn(*mut ObjectQObject), + object_f32_changed: fn(*mut ObjectQObject), + object_f64_changed: fn(*mut ObjectQObject), + object_i16_changed: fn(*mut ObjectQObject), + object_i32_changed: fn(*mut ObjectQObject), + object_i64_changed: fn(*mut ObjectQObject), + object_i8_changed: fn(*mut ObjectQObject), + object_optional_boolean_changed: fn(*mut ObjectQObject), + object_optional_bytearray_changed: fn(*mut ObjectQObject), + object_optional_string_changed: fn(*mut ObjectQObject), + object_optional_u64_changed: fn(*mut ObjectQObject), + object_string_changed: fn(*mut ObjectQObject), + object_string_by_function_changed: fn(*mut ObjectQObject), + object_u16_changed: fn(*mut ObjectQObject), + object_u32_changed: fn(*mut ObjectQObject), + object_u64_changed: fn(*mut ObjectQObject), + object_u8_changed: fn(*mut ObjectQObject), ) -> *mut Object { let object_emit = ObjectEmitter { qobject: Arc::new(AtomicPtr::new(object)), boolean_changed: object_boolean_changed, bytearray_changed: object_bytearray_changed, f32_changed: object_f32_changed, f64_changed: object_f64_changed, i16_changed: object_i16_changed, i32_changed: object_i32_changed, i64_changed: object_i64_changed, i8_changed: object_i8_changed, optional_boolean_changed: object_optional_boolean_changed, optional_bytearray_changed: object_optional_bytearray_changed, optional_string_changed: object_optional_string_changed, optional_u64_changed: object_optional_u64_changed, string_changed: object_string_changed, string_by_function_changed: object_string_by_function_changed, u16_changed: object_u16_changed, u32_changed: object_u32_changed, u64_changed: object_u64_changed, u8_changed: object_u8_changed, }; let d_object = Object::new(object_emit); Box::into_raw(Box::new(d_object)) } #[no_mangle] pub unsafe extern "C" fn object_free(ptr: *mut Object) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn object_boolean_get(ptr: *const Object) -> bool { (&*ptr).boolean() } #[no_mangle] pub unsafe extern "C" fn object_boolean_set(ptr: *mut Object, v: bool) { (&mut *ptr).set_boolean(v); } #[no_mangle] pub unsafe extern "C" fn object_bytearray_get( ptr: *const Object, p: *mut QByteArray, set: fn(*mut QByteArray, *const c_char, c_int), ) { let o = &*ptr; let v = o.bytearray(); let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, to_c_int(v.len())); } #[no_mangle] pub unsafe extern "C" fn object_bytearray_set(ptr: *mut Object, 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_bytearray(v); } #[no_mangle] pub unsafe extern "C" fn object_f32_get(ptr: *const Object) -> f32 { (&*ptr).f32() } #[no_mangle] pub unsafe extern "C" fn object_f32_set(ptr: *mut Object, v: f32) { (&mut *ptr).set_f32(v); } #[no_mangle] pub unsafe extern "C" fn object_f64_get(ptr: *const Object) -> f64 { (&*ptr).f64() } #[no_mangle] pub unsafe extern "C" fn object_f64_set(ptr: *mut Object, v: f64) { (&mut *ptr).set_f64(v); } #[no_mangle] pub unsafe extern "C" fn object_i16_get(ptr: *const Object) -> i16 { (&*ptr).i16() } #[no_mangle] pub unsafe extern "C" fn object_i16_set(ptr: *mut Object, v: i16) { (&mut *ptr).set_i16(v); } #[no_mangle] pub unsafe extern "C" fn object_i32_get(ptr: *const Object) -> i32 { (&*ptr).i32() } #[no_mangle] pub unsafe extern "C" fn object_i32_set(ptr: *mut Object, v: i32) { (&mut *ptr).set_i32(v); } #[no_mangle] pub unsafe extern "C" fn object_i64_get(ptr: *const Object) -> i64 { (&*ptr).i64() } #[no_mangle] pub unsafe extern "C" fn object_i64_set(ptr: *mut Object, v: i64) { (&mut *ptr).set_i64(v); } #[no_mangle] pub unsafe extern "C" fn object_i8_get(ptr: *const Object) -> i8 { (&*ptr).i8() } #[no_mangle] pub unsafe extern "C" fn object_i8_set(ptr: *mut Object, v: i8) { (&mut *ptr).set_i8(v); } #[no_mangle] pub unsafe extern "C" fn object_optional_boolean_get(ptr: *const Object) -> COption { match (&*ptr).optional_boolean() { Some(value) => COption { data: value, some: true }, None => COption { data: bool::default(), some: false} } } #[no_mangle] pub unsafe extern "C" fn object_optional_boolean_set(ptr: *mut Object, v: bool) { (&mut *ptr).set_optional_boolean(Some(v)); } #[no_mangle] pub unsafe extern "C" fn object_optional_boolean_set_none(ptr: *mut Object) { let o = &mut *ptr; o.set_optional_boolean(None); } #[no_mangle] pub unsafe extern "C" fn object_optional_bytearray_get( ptr: *const Object, p: *mut QByteArray, set: fn(*mut QByteArray, *const c_char, c_int), ) { let o = &*ptr; let v = o.optional_bytearray(); 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())); } } #[no_mangle] pub unsafe extern "C" fn object_optional_bytearray_set(ptr: *mut Object, 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_optional_bytearray(Some(v.into())); } #[no_mangle] pub unsafe extern "C" fn object_optional_bytearray_set_none(ptr: *mut Object) { let o = &mut *ptr; o.set_optional_bytearray(None); } #[no_mangle] pub unsafe extern "C" fn object_optional_string_get( ptr: *const Object, p: *mut QString, set: fn(*mut QString, *const c_char, c_int), ) { let o = &*ptr; let v = o.optional_string(); 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())); } } #[no_mangle] pub unsafe extern "C" fn object_optional_string_set(ptr: *mut Object, 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_optional_string(Some(s)); } #[no_mangle] pub unsafe extern "C" fn object_optional_string_set_none(ptr: *mut Object) { let o = &mut *ptr; o.set_optional_string(None); } #[no_mangle] pub unsafe extern "C" fn object_optional_u64_get(ptr: *const Object) -> COption { match (&*ptr).optional_u64() { Some(value) => COption { data: value, some: true }, None => COption { data: u64::default(), some: false} } } #[no_mangle] pub unsafe extern "C" fn object_optional_u64_set(ptr: *mut Object, v: u64) { (&mut *ptr).set_optional_u64(Some(v)); } #[no_mangle] pub unsafe extern "C" fn object_optional_u64_set_none(ptr: *mut Object) { let o = &mut *ptr; o.set_optional_u64(None); } #[no_mangle] pub unsafe extern "C" fn object_string_get( ptr: *const Object, p: *mut QString, set: fn(*mut QString, *const c_char, c_int), ) { let o = &*ptr; let v = o.string(); let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, to_c_int(v.len())); } #[no_mangle] pub unsafe extern "C" fn object_string_set(ptr: *mut Object, 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_string(s); } #[no_mangle] pub unsafe extern "C" fn object_string_by_function_get( ptr: *const Object, p: *mut QString, set: fn(*mut QString, *const c_char, c_int), ) { let o = &*ptr; o.string_by_function(|v| { let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, to_c_int(v.len())); }); } #[no_mangle] pub unsafe extern "C" fn object_string_by_function_set(ptr: *mut Object, 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_string_by_function(s); } #[no_mangle] pub unsafe extern "C" fn object_u16_get(ptr: *const Object) -> u16 { (&*ptr).u16() } #[no_mangle] pub unsafe extern "C" fn object_u16_set(ptr: *mut Object, v: u16) { (&mut *ptr).set_u16(v); } #[no_mangle] pub unsafe extern "C" fn object_u32_get(ptr: *const Object) -> u32 { (&*ptr).u32() } #[no_mangle] pub unsafe extern "C" fn object_u32_set(ptr: *mut Object, v: u32) { (&mut *ptr).set_u32(v); } #[no_mangle] pub unsafe extern "C" fn object_u64_get(ptr: *const Object) -> u64 { (&*ptr).u64() } #[no_mangle] pub unsafe extern "C" fn object_u64_set(ptr: *mut Object, v: u64) { (&mut *ptr).set_u64(v); } #[no_mangle] pub unsafe extern "C" fn object_u8_get(ptr: *const Object) -> u8 { (&*ptr).u8() } #[no_mangle] pub unsafe extern "C" fn object_u8_set(ptr: *mut Object, v: u8) { (&mut *ptr).set_u8(v); } diff --git a/tests/rust_objects/src/interface.rs b/tests/rust_objects/src/interface.rs index 8c445c8..f3f9efe 100644 --- a/tests/rust_objects/src/interface.rs +++ b/tests/rust_objects/src/interface.rs @@ -1,219 +1,250 @@ /* 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 implementation::*; 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); } fn to_usize(n: c_int) -> usize { if n < 0 { panic!("Cannot cast {} to usize", n); } n as usize } 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 } pub struct GroupQObject {} -#[derive(Clone)] pub struct GroupEmitter { qobject: Arc>, } unsafe impl Send for GroupEmitter {} impl GroupEmitter { + /// 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) -> GroupEmitter { + GroupEmitter { + qobject: self.qobject.clone(), + } + } fn clear(&self) { let n: *const GroupQObject = null(); self.qobject.store(n as *mut GroupQObject, Ordering::SeqCst); } } pub trait GroupTrait { fn new(emit: GroupEmitter, person: Person) -> Self; fn emit(&self) -> &GroupEmitter; fn person(&self) -> &Person; fn person_mut(&mut self) -> &mut Person; } #[no_mangle] pub extern "C" fn group_new( group: *mut GroupQObject, person: *mut PersonQObject, object: *mut InnerObjectQObject, - object_description_changed: fn(*const InnerObjectQObject), + object_description_changed: fn(*mut InnerObjectQObject), ) -> *mut Group { let object_emit = InnerObjectEmitter { qobject: Arc::new(AtomicPtr::new(object)), description_changed: object_description_changed, }; let d_object = InnerObject::new(object_emit); let person_emit = PersonEmitter { qobject: Arc::new(AtomicPtr::new(person)), }; let d_person = Person::new(person_emit, d_object); let group_emit = GroupEmitter { qobject: Arc::new(AtomicPtr::new(group)), }; let d_group = Group::new(group_emit, d_person); Box::into_raw(Box::new(d_group)) } #[no_mangle] pub unsafe extern "C" fn group_free(ptr: *mut Group) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn group_person_get(ptr: *mut Group) -> *mut Person { (&mut *ptr).person_mut() } pub struct InnerObjectQObject {} -#[derive(Clone)] pub struct InnerObjectEmitter { qobject: Arc>, - description_changed: fn(*const InnerObjectQObject), + description_changed: fn(*mut InnerObjectQObject), } unsafe impl Send for InnerObjectEmitter {} impl InnerObjectEmitter { + /// 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) -> InnerObjectEmitter { + InnerObjectEmitter { + qobject: self.qobject.clone(), + description_changed: self.description_changed, + } + } fn clear(&self) { let n: *const InnerObjectQObject = null(); self.qobject.store(n as *mut InnerObjectQObject, Ordering::SeqCst); } - pub fn description_changed(&self) { + pub fn description_changed(&mut self) { let ptr = self.qobject.load(Ordering::SeqCst); if !ptr.is_null() { (self.description_changed)(ptr); } } } pub trait InnerObjectTrait { fn new(emit: InnerObjectEmitter) -> Self; fn emit(&self) -> &InnerObjectEmitter; fn description(&self) -> &str; fn set_description(&mut self, value: String); } #[no_mangle] pub extern "C" fn inner_object_new( inner_object: *mut InnerObjectQObject, - inner_object_description_changed: fn(*const InnerObjectQObject), + inner_object_description_changed: fn(*mut InnerObjectQObject), ) -> *mut InnerObject { let inner_object_emit = InnerObjectEmitter { qobject: Arc::new(AtomicPtr::new(inner_object)), description_changed: inner_object_description_changed, }; let d_inner_object = InnerObject::new(inner_object_emit); Box::into_raw(Box::new(d_inner_object)) } #[no_mangle] pub unsafe extern "C" fn inner_object_free(ptr: *mut InnerObject) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn inner_object_description_get( ptr: *const InnerObject, p: *mut QString, set: fn(*mut QString, *const c_char, c_int), ) { let o = &*ptr; let v = o.description(); let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, to_c_int(v.len())); } #[no_mangle] pub unsafe extern "C" fn inner_object_description_set(ptr: *mut InnerObject, 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_description(s); } pub struct PersonQObject {} -#[derive(Clone)] pub struct PersonEmitter { qobject: Arc>, } unsafe impl Send for PersonEmitter {} impl PersonEmitter { + /// 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) -> PersonEmitter { + PersonEmitter { + qobject: self.qobject.clone(), + } + } fn clear(&self) { let n: *const PersonQObject = null(); self.qobject.store(n as *mut PersonQObject, Ordering::SeqCst); } } pub trait PersonTrait { fn new(emit: PersonEmitter, object: InnerObject) -> Self; fn emit(&self) -> &PersonEmitter; fn object(&self) -> &InnerObject; fn object_mut(&mut self) -> &mut InnerObject; } #[no_mangle] pub extern "C" fn person_new( person: *mut PersonQObject, object: *mut InnerObjectQObject, - object_description_changed: fn(*const InnerObjectQObject), + object_description_changed: fn(*mut InnerObjectQObject), ) -> *mut Person { let object_emit = InnerObjectEmitter { qobject: Arc::new(AtomicPtr::new(object)), description_changed: object_description_changed, }; let d_object = InnerObject::new(object_emit); let person_emit = PersonEmitter { qobject: Arc::new(AtomicPtr::new(person)), }; let d_person = Person::new(person_emit, d_object); Box::into_raw(Box::new(d_person)) } #[no_mangle] pub unsafe extern "C" fn person_free(ptr: *mut Person) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn person_object_get(ptr: *mut Person) -> *mut InnerObject { (&mut *ptr).object_mut() } diff --git a/tests/rust_tree/src/interface.rs b/tests/rust_tree/src/interface.rs index af227ca..79b18a4 100644 --- a/tests/rust_tree/src/interface.rs +++ b/tests/rust_tree/src/interface.rs @@ -1,309 +1,320 @@ /* 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 implementation::*; #[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, } } } } 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); } #[repr(C)] #[derive(PartialEq, Eq, Debug)] pub enum SortOrder { Ascending = 0, Descending = 1, } #[repr(C)] pub struct QModelIndex { row: c_int, internal_id: usize, } fn to_usize(n: c_int) -> usize { if n < 0 { panic!("Cannot cast {} to usize", n); } n as usize } 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 } pub struct PersonsQObject {} -#[derive(Clone)] pub struct PersonsEmitter { qobject: Arc>, - new_data_ready: fn(*const PersonsQObject, index: COption), + new_data_ready: fn(*mut PersonsQObject, index: COption), } unsafe impl Send for PersonsEmitter {} impl PersonsEmitter { + /// 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) -> PersonsEmitter { + PersonsEmitter { + qobject: self.qobject.clone(), + new_data_ready: self.new_data_ready, + } + } fn clear(&self) { let n: *const PersonsQObject = null(); self.qobject.store(n as *mut PersonsQObject, Ordering::SeqCst); } - pub fn new_data_ready(&self, item: Option) { + 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()); } } } #[derive(Clone)] pub struct PersonsTree { - qobject: *const PersonsQObject, - layout_about_to_be_changed: fn(*const PersonsQObject), - layout_changed: fn(*const PersonsQObject), - data_changed: fn(*const PersonsQObject, usize, usize), - begin_reset_model: fn(*const PersonsQObject), - end_reset_model: fn(*const PersonsQObject), - begin_insert_rows: fn(*const PersonsQObject, index: COption, usize, usize), - end_insert_rows: fn(*const PersonsQObject), - begin_move_rows: fn(*const PersonsQObject, index: COption, usize, usize, dest: COption, usize), - end_move_rows: fn(*const PersonsQObject), - begin_remove_rows: fn(*const PersonsQObject, index: COption, usize, usize), - end_remove_rows: fn(*const PersonsQObject), + qobject: *mut PersonsQObject, + layout_about_to_be_changed: fn(*mut PersonsQObject), + layout_changed: fn(*mut PersonsQObject), + data_changed: fn(*mut PersonsQObject, usize, usize), + begin_reset_model: fn(*mut PersonsQObject), + end_reset_model: fn(*mut PersonsQObject), + begin_insert_rows: fn(*mut PersonsQObject, index: COption, usize, usize), + end_insert_rows: fn(*mut PersonsQObject), + begin_move_rows: fn(*mut PersonsQObject, index: COption, usize, usize, dest: COption, usize), + end_move_rows: fn(*mut PersonsQObject), + begin_remove_rows: fn(*mut PersonsQObject, index: COption, usize, usize), + end_remove_rows: fn(*mut PersonsQObject), } impl PersonsTree { - pub fn layout_about_to_be_changed(&self) { + pub fn layout_about_to_be_changed(&mut self) { (self.layout_about_to_be_changed)(self.qobject); } - pub fn layout_changed(&self) { + pub fn layout_changed(&mut self) { (self.layout_changed)(self.qobject); } - pub fn data_changed(&self, first: usize, last: usize) { + pub fn data_changed(&mut self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } - pub fn begin_reset_model(&self) { + pub fn begin_reset_model(&mut self) { (self.begin_reset_model)(self.qobject); } - pub fn end_reset_model(&self) { + pub fn end_reset_model(&mut self) { (self.end_reset_model)(self.qobject); } - pub fn begin_insert_rows(&self, index: Option, first: usize, last: usize) { + pub fn begin_insert_rows(&mut self, index: Option, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, index.into(), first, last); } - pub fn end_insert_rows(&self) { + pub fn end_insert_rows(&mut self) { (self.end_insert_rows)(self.qobject); } - pub fn begin_move_rows(&self, index: Option, first: usize, last: usize, dest: Option, destination: usize) { + pub fn begin_move_rows(&mut self, index: Option, first: usize, last: usize, dest: Option, destination: usize) { (self.begin_move_rows)(self.qobject, index.into(), first, last, dest.into(), destination); } - pub fn end_move_rows(&self) { + pub fn end_move_rows(&mut self) { (self.end_move_rows)(self.qobject); } - pub fn begin_remove_rows(&self, index: Option, first: usize, last: usize) { + pub fn begin_remove_rows(&mut self, index: Option, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, index.into(), first, last); } - pub fn end_remove_rows(&self) { + pub fn end_remove_rows(&mut self) { (self.end_remove_rows)(self.qobject); } } pub trait PersonsTrait { fn new(emit: PersonsEmitter, model: PersonsTree) -> Self; fn emit(&self) -> &PersonsEmitter; 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; fn user_name(&self, index: usize) -> &str; fn set_user_name(&mut self, index: usize, String) -> bool; } #[no_mangle] pub extern "C" fn persons_new( persons: *mut PersonsQObject, - persons_new_data_ready: fn(*const PersonsQObject, index: COption), - persons_layout_about_to_be_changed: fn(*const PersonsQObject), - persons_layout_changed: fn(*const PersonsQObject), - persons_data_changed: fn(*const PersonsQObject, usize, usize), - persons_begin_reset_model: fn(*const PersonsQObject), - persons_end_reset_model: fn(*const PersonsQObject), - persons_begin_insert_rows: fn(*const PersonsQObject, index: COption, usize, usize), - persons_end_insert_rows: fn(*const PersonsQObject), - persons_begin_move_rows: fn(*const PersonsQObject, index: COption, usize, usize, index: COption, usize), - persons_end_move_rows: fn(*const PersonsQObject), - persons_begin_remove_rows: fn(*const PersonsQObject, index: COption, usize, usize), - persons_end_remove_rows: fn(*const PersonsQObject), + persons_new_data_ready: fn(*mut PersonsQObject, index: COption), + persons_layout_about_to_be_changed: fn(*mut PersonsQObject), + persons_layout_changed: fn(*mut PersonsQObject), + persons_data_changed: fn(*mut PersonsQObject, usize, usize), + persons_begin_reset_model: fn(*mut PersonsQObject), + persons_end_reset_model: fn(*mut PersonsQObject), + persons_begin_insert_rows: fn(*mut PersonsQObject, index: COption, usize, usize), + persons_end_insert_rows: fn(*mut PersonsQObject), + persons_begin_move_rows: fn(*mut PersonsQObject, index: COption, usize, usize, index: COption, usize), + persons_end_move_rows: fn(*mut PersonsQObject), + persons_begin_remove_rows: fn(*mut PersonsQObject, index: COption, usize, usize), + persons_end_remove_rows: fn(*mut PersonsQObject), ) -> *mut Persons { let persons_emit = PersonsEmitter { qobject: Arc::new(AtomicPtr::new(persons)), new_data_ready: persons_new_data_ready, }; let model = PersonsTree { qobject: persons, layout_about_to_be_changed: persons_layout_about_to_be_changed, layout_changed: persons_layout_changed, data_changed: persons_data_changed, begin_reset_model: persons_begin_reset_model, end_reset_model: persons_end_reset_model, begin_insert_rows: persons_begin_insert_rows, end_insert_rows: persons_end_insert_rows, begin_move_rows: persons_begin_move_rows, end_move_rows: persons_end_move_rows, begin_remove_rows: persons_begin_remove_rows, end_remove_rows: persons_end_remove_rows, }; let d_persons = Persons::new(persons_emit, model); Box::into_raw(Box::new(d_persons)) } #[no_mangle] pub unsafe extern "C" fn persons_free(ptr: *mut Persons) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn persons_row_count( ptr: *const Persons, index: COption, ) -> c_int { to_c_int((&*ptr).row_count(index.into())) } #[no_mangle] pub unsafe extern "C" fn persons_can_fetch_more( ptr: *const Persons, index: COption, ) -> bool { (&*ptr).can_fetch_more(index.into()) } #[no_mangle] pub unsafe extern "C" fn persons_fetch_more(ptr: *mut Persons, index: COption) { (&mut *ptr).fetch_more(index.into()) } #[no_mangle] pub unsafe extern "C" fn persons_sort( ptr: *mut Persons, column: u8, order: SortOrder ) { (&mut *ptr).sort(column, order) } #[no_mangle] pub unsafe extern "C" fn persons_check_row( ptr: *const Persons, index: usize, row: c_int, ) -> COption { (&*ptr).check_row(index.into(), to_usize(row)).into() } #[no_mangle] pub unsafe extern "C" fn persons_index( ptr: *const Persons, index: COption, row: c_int, ) -> usize { (&*ptr).index(index.into(), to_usize(row)) } #[no_mangle] pub unsafe extern "C" fn persons_parent(ptr: *const Persons, 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 persons_row(ptr: *const Persons, index: usize) -> c_int { to_c_int((&*ptr).row(index)) } #[no_mangle] pub unsafe extern "C" fn persons_data_user_name( ptr: *const Persons, index: usize, d: *mut QString, set: fn(*mut QString, *const c_char, len: c_int), ) { let o = &*ptr; let data = o.user_name(index); let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, to_c_int(data.len())); } #[no_mangle] pub unsafe extern "C" fn persons_set_data_user_name( ptr: *mut Persons, index: usize, 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_user_name(index, v) }