diff --git a/demo/rust/src/implementation/file_system_tree.rs b/demo/rust/src/implementation/file_system_tree.rs index 5bee76f..a405cbb 100644 --- a/demo/rust/src/implementation/file_system_tree.rs +++ b/demo/rust/src/implementation/file_system_tree.rs @@ -1,302 +1,309 @@ // 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::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() } } 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(); let path: PathBuf = parents.into_iter().map(|e| &e.name).collect(); thread::spawn(move || { 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)); } }); } } 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 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, } 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) { let parents = self.get_parents(index); let incoming = self.incoming.clone(); T::retrieve(index, parents, incoming, self.emit.clone()); } 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, ); } } self.entries[id].children = Some(children); if !new_entries.is_empty() { 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 { emit: emit, model: model, entries: Vec::new(), path: None, incoming: Arc::new(Mutex::new(HashMap::new())), }; tree.reset(); tree } fn emit(&self) -> &FileSystemTreeEmitter { &self.emit } fn path(&self) -> Option<&str> { 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 } } 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); } } 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); } 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 f975963..29fbefa 100644 --- a/demo/rust/src/implementation/processes.rs +++ b/demo/rust/src/implementation/processes.rs @@ -1,434 +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_none() { 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, 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, 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, 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 { 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, 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 { let (tx, rx) = channel(); let p = Processes { emit: emit.clone(), model: 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); } } } } 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 f565d3a..3ceed02 100644 --- a/demo/rust/src/interface.rs +++ b/demo/rust/src/interface.rs @@ -1,1320 +1,1338 @@ /* 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::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); } 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 { fn clear(&self) { *self.qobject.lock().unwrap() = null(); } } 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_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), 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), 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), 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), ) -> *mut Demo { let fibonacci_emit = FibonacciEmitter { qobject: Arc::new(Mutex::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(Mutex::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(Mutex::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(Mutex::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(Mutex::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(Mutex::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), } unsafe impl Send for FibonacciEmitter {} impl FibonacciEmitter { fn clear(&self) { *self.qobject.lock().unwrap() = null(); } pub fn input_changed(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.input_changed)(ptr); } } pub fn result_changed(&self) { let ptr = *self.qobject.lock().unwrap(); 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), ) -> *mut Fibonacci { let fibonacci_emit = FibonacciEmitter { qobject: Arc::new(Mutex::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), } unsafe impl Send for FibonacciListEmitter {} impl FibonacciListEmitter { fn clear(&self) { *self.qobject.lock().unwrap() = null(); } pub fn new_data_ready(&self) { let ptr = *self.qobject.lock().unwrap(); 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), } impl FibonacciListList { pub fn layout_about_to_be_changed(&self) { (self.layout_about_to_be_changed)(self.qobject); } pub fn layout_changed(&self) { (self.layout_changed)(self.qobject); } pub fn data_changed(&self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } pub fn begin_reset_model(&self) { (self.begin_reset_model)(self.qobject); } pub fn end_reset_model(&self) { (self.end_reset_model)(self.qobject); } pub fn begin_insert_rows(&self, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, first, last); } pub fn end_insert_rows(&self) { (self.end_insert_rows)(self.qobject); } pub fn begin_move_rows(&self, first: usize, last: usize, destination: usize) { (self.begin_move_rows)(self.qobject, first, last, destination); } pub fn end_move_rows(&self) { (self.end_move_rows)(self.qobject); } pub fn begin_remove_rows(&self, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, first, last); } pub fn end_remove_rows(&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), ) -> *mut FibonacciList { let fibonacci_list_emit = FibonacciListEmitter { qobject: Arc::new(Mutex::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 extern "C" fn fibonacci_list_data_fibonacci_number(ptr: *const FibonacciList, row: c_int) -> u64 { let o = unsafe { &*ptr }; o.fibonacci_number(to_usize(row)).into() } #[no_mangle] pub extern "C" fn fibonacci_list_data_row(ptr: *const FibonacciList, row: c_int) -> u64 { let o = unsafe { &*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), } unsafe impl Send for FileSystemTreeEmitter {} impl FileSystemTreeEmitter { fn clear(&self) { *self.qobject.lock().unwrap() = null(); } pub fn path_changed(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.path_changed)(ptr); } } pub fn new_data_ready(&self, item: Option) { let ptr = *self.qobject.lock().unwrap(); 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), } impl FileSystemTreeTree { pub fn layout_about_to_be_changed(&self) { (self.layout_about_to_be_changed)(self.qobject); } pub fn layout_changed(&self) { (self.layout_changed)(self.qobject); } pub fn data_changed(&self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } pub fn begin_reset_model(&self) { (self.begin_reset_model)(self.qobject); } pub fn end_reset_model(&self) { (self.end_reset_model)(self.qobject); } pub fn begin_insert_rows(&self, index: Option, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, index.into(), first, last); } pub fn end_insert_rows(&self) { (self.end_insert_rows)(self.qobject); } pub fn begin_move_rows(&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) { (self.end_move_rows)(self.qobject); } pub fn begin_remove_rows(&self, index: Option, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, index.into(), first, last); } pub fn end_remove_rows(&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), ) -> *mut FileSystemTree { let file_system_tree_emit = FileSystemTreeEmitter { qobject: Arc::new(Mutex::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 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 = unsafe { &*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 extern "C" fn file_system_tree_path_set(ptr: *mut FileSystemTree, v: *const c_ushort, len: c_int) { let o = unsafe { &mut *ptr }; let mut s = String::new(); set_string_from_utf16(&mut s, v, len); o.set_path(Some(s)); } #[no_mangle] pub extern "C" fn file_system_tree_path_set_none(ptr: *mut FileSystemTree) { let o = unsafe { &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 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 = unsafe { &*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 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 = unsafe { &*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 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 = unsafe { &*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 extern "C" fn file_system_tree_data_file_permissions(ptr: *const FileSystemTree, index: usize) -> i32 { let o = unsafe { &*ptr }; o.file_permissions(index).into() } #[no_mangle] pub extern "C" fn file_system_tree_data_file_size(ptr: *const FileSystemTree, index: usize) -> COption { let o = unsafe { &*ptr }; o.file_size(index).into() } #[no_mangle] pub extern "C" fn file_system_tree_data_file_type(ptr: *const FileSystemTree, index: usize) -> i32 { let o = unsafe { &*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), } unsafe impl Send for ProcessesEmitter {} impl ProcessesEmitter { fn clear(&self) { *self.qobject.lock().unwrap() = null(); } pub fn active_changed(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.active_changed)(ptr); } } pub fn new_data_ready(&self, item: Option) { let ptr = *self.qobject.lock().unwrap(); 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), } impl ProcessesTree { pub fn layout_about_to_be_changed(&self) { (self.layout_about_to_be_changed)(self.qobject); } pub fn layout_changed(&self) { (self.layout_changed)(self.qobject); } pub fn data_changed(&self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } pub fn begin_reset_model(&self) { (self.begin_reset_model)(self.qobject); } pub fn end_reset_model(&self) { (self.end_reset_model)(self.qobject); } pub fn begin_insert_rows(&self, index: Option, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, index.into(), first, last); } pub fn end_insert_rows(&self) { (self.end_insert_rows)(self.qobject); } pub fn begin_move_rows(&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) { (self.end_move_rows)(self.qobject); } pub fn begin_remove_rows(&self, index: Option, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, index.into(), first, last); } pub fn end_remove_rows(&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), ) -> *mut Processes { let processes_emit = ProcessesEmitter { qobject: Arc::new(Mutex::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 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 = unsafe { &*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 extern "C" fn processes_data_cpu_percentage(ptr: *const Processes, index: usize) -> u8 { let o = unsafe { &*ptr }; o.cpu_percentage(index).into() } #[no_mangle] pub extern "C" fn processes_data_cpu_usage(ptr: *const Processes, index: usize) -> f32 { let o = unsafe { &*ptr }; o.cpu_usage(index).into() } #[no_mangle] pub extern "C" fn processes_data_memory(ptr: *const Processes, index: usize) -> u64 { let o = unsafe { &*ptr }; o.memory(index).into() } #[no_mangle] pub 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 = unsafe { &*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 extern "C" fn processes_data_pid(ptr: *const Processes, index: usize) -> u32 { let o = unsafe { &*ptr }; o.pid(index).into() } #[no_mangle] pub extern "C" fn processes_data_uid(ptr: *const Processes, index: usize) -> u32 { let o = unsafe { &*ptr }; o.uid(index).into() } pub struct TimeSeriesQObject {} #[derive(Clone)] pub struct TimeSeriesEmitter { qobject: Arc>, new_data_ready: fn(*const TimeSeriesQObject), } unsafe impl Send for TimeSeriesEmitter {} impl TimeSeriesEmitter { fn clear(&self) { *self.qobject.lock().unwrap() = null(); } pub fn new_data_ready(&self) { let ptr = *self.qobject.lock().unwrap(); 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), } impl TimeSeriesList { pub fn layout_about_to_be_changed(&self) { (self.layout_about_to_be_changed)(self.qobject); } pub fn layout_changed(&self) { (self.layout_changed)(self.qobject); } pub fn data_changed(&self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } pub fn begin_reset_model(&self) { (self.begin_reset_model)(self.qobject); } pub fn end_reset_model(&self) { (self.end_reset_model)(self.qobject); } pub fn begin_insert_rows(&self, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, first, last); } pub fn end_insert_rows(&self) { (self.end_insert_rows)(self.qobject); } pub fn begin_move_rows(&self, first: usize, last: usize, destination: usize) { (self.begin_move_rows)(self.qobject, first, last, destination); } pub fn end_move_rows(&self) { (self.end_move_rows)(self.qobject); } pub fn begin_remove_rows(&self, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, first, last); } pub fn end_remove_rows(&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), ) -> *mut TimeSeries { let time_series_emit = TimeSeriesEmitter { qobject: Arc::new(Mutex::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 extern "C" fn time_series_data_cos(ptr: *const TimeSeries, row: c_int) -> f32 { let o = unsafe { &*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 extern "C" fn time_series_data_sin(ptr: *const TimeSeries, row: c_int) -> f32 { let o = unsafe { &*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 extern "C" fn time_series_data_time(ptr: *const TimeSeries, row: c_int) -> f32 { let o = unsafe { &*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/demo/src/Bindings.cpp b/demo/src/Bindings.cpp index 7eb64cb..562ff65 100644 --- a/demo/src/Bindings.cpp +++ b/demo/src/Bindings.cpp @@ -1,1712 +1,1754 @@ /* 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."); struct option_quint64 { public: quint64 value; bool some; operator QVariant() const { if (some) { return QVariant::fromValue(value); } return QVariant(); } }; static_assert(std::is_pod::value, "option_quint64 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); } typedef void (*qbytearray_set)(QByteArray* val, const char* bytes, int nbytes); void set_qbytearray(QByteArray* v, const char* bytes, int nbytes) { if (v->isNull() && nbytes == 0) { *v = QByteArray(bytes, nbytes); } else { v->truncate(0); v->append(bytes, nbytes); } } struct qmodelindex_t { int row; quintptr id; }; inline QVariant cleanNullQVariant(const QVariant& v) { return (v.isNull()) ?QVariant() :v; } inline void fibonacciInputChanged(Fibonacci* o) { emit o->inputChanged(); } inline void fibonacciResultChanged(Fibonacci* o) { emit o->resultChanged(); } inline void fileSystemTreePathChanged(FileSystemTree* o) { emit o->pathChanged(); } inline void processesActiveChanged(Processes* o) { emit o->activeChanged(); } } extern "C" { Demo::Private* demo_new(Demo*, Fibonacci*, void (*)(Fibonacci*), void (*)(Fibonacci*), FibonacciList*, void (*)(const FibonacciList*), void (*)(FibonacciList*), void (*)(FibonacciList*), void (*)(FibonacciList*, quintptr, quintptr), void (*)(FibonacciList*), void (*)(FibonacciList*), void (*)(FibonacciList*, int, int), void (*)(FibonacciList*), void (*)(FibonacciList*, int, int, int), void (*)(FibonacciList*), void (*)(FibonacciList*, int, int), void (*)(FibonacciList*), FileSystemTree*, void (*)(FileSystemTree*), void (*)(const FileSystemTree*, option_quintptr), void (*)(FileSystemTree*), void (*)(FileSystemTree*), void (*)(FileSystemTree*, quintptr, quintptr), void (*)(FileSystemTree*), void (*)(FileSystemTree*), void (*)(FileSystemTree*, option_quintptr, int, int), void (*)(FileSystemTree*), void (*)(FileSystemTree*, option_quintptr, int, int, option_quintptr, int), void (*)(FileSystemTree*), void (*)(FileSystemTree*, option_quintptr, int, int), void (*)(FileSystemTree*), Processes*, void (*)(Processes*), void (*)(const Processes*, option_quintptr), void (*)(Processes*), void (*)(Processes*), void (*)(Processes*, quintptr, quintptr), void (*)(Processes*), void (*)(Processes*), void (*)(Processes*, option_quintptr, int, int), void (*)(Processes*), void (*)(Processes*, option_quintptr, int, int, option_quintptr, int), void (*)(Processes*), void (*)(Processes*, option_quintptr, int, int), void (*)(Processes*), TimeSeries*, void (*)(const TimeSeries*), void (*)(TimeSeries*), void (*)(TimeSeries*), void (*)(TimeSeries*, quintptr, quintptr), void (*)(TimeSeries*), void (*)(TimeSeries*), void (*)(TimeSeries*, int, int), void (*)(TimeSeries*), void (*)(TimeSeries*, int, int, int), void (*)(TimeSeries*), void (*)(TimeSeries*, int, int), void (*)(TimeSeries*)); void demo_free(Demo::Private*); Fibonacci::Private* demo_fibonacci_get(const Demo::Private*); FibonacciList::Private* demo_fibonacci_list_get(const Demo::Private*); FileSystemTree::Private* demo_file_system_tree_get(const Demo::Private*); Processes::Private* demo_processes_get(const Demo::Private*); TimeSeries::Private* demo_time_series_get(const Demo::Private*); }; extern "C" { Fibonacci::Private* fibonacci_new(Fibonacci*, void (*)(Fibonacci*), void (*)(Fibonacci*)); void fibonacci_free(Fibonacci::Private*); quint32 fibonacci_input_get(const Fibonacci::Private*); void fibonacci_input_set(Fibonacci::Private*, quint32); quint64 fibonacci_result_get(const Fibonacci::Private*); }; extern "C" { quint64 fibonacci_list_data_fibonacci_number(const FibonacciList::Private*, int); quint64 fibonacci_list_data_row(const FibonacciList::Private*, int); void fibonacci_list_sort(FibonacciList::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int fibonacci_list_row_count(const FibonacciList::Private*); bool fibonacci_list_insert_rows(FibonacciList::Private*, int, int); bool fibonacci_list_remove_rows(FibonacciList::Private*, int, int); bool fibonacci_list_can_fetch_more(const FibonacciList::Private*); void fibonacci_list_fetch_more(FibonacciList::Private*); } int FibonacciList::columnCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : 2; } bool FibonacciList::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int FibonacciList::rowCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : fibonacci_list_row_count(m_d); } bool FibonacciList::insertRows(int row, int count, const QModelIndex &) { return fibonacci_list_insert_rows(m_d, row, count); } bool FibonacciList::removeRows(int row, int count, const QModelIndex &) { return fibonacci_list_remove_rows(m_d, row, count); } QModelIndex FibonacciList::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid() && row >= 0 && row < rowCount(parent) && column >= 0 && column < 2) { return createIndex(row, column, (quintptr)row); } return QModelIndex(); } QModelIndex FibonacciList::parent(const QModelIndex &) const { return QModelIndex(); } bool FibonacciList::canFetchMore(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : fibonacci_list_can_fetch_more(m_d); } void FibonacciList::fetchMore(const QModelIndex &parent) { if (!parent.isValid()) { fibonacci_list_fetch_more(m_d); } } +void FibonacciList::updatePersistentIndexes() {} void FibonacciList::sort(int column, Qt::SortOrder order) { fibonacci_list_sort(m_d, column, order); } Qt::ItemFlags FibonacciList::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); return flags; } quint64 FibonacciList::fibonacciNumber(int row) const { return fibonacci_list_data_fibonacci_number(m_d, row); } quint64 FibonacciList::row(int row) const { return fibonacci_list_data_row(m_d, row); } QVariant FibonacciList::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(fibonacciNumber(index.row())); case Qt::DisplayRole: case Qt::UserRole + 1: return QVariant::fromValue(row(index.row())); } case 1: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 0: return QVariant::fromValue(fibonacciNumber(index.row())); } } return QVariant(); } int FibonacciList::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 FibonacciList::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "fibonacciNumber"); names.insert(Qt::UserRole + 1, "row"); return names; } QVariant FibonacciList::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 FibonacciList::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; } extern "C" { FibonacciList::Private* fibonacci_list_new(FibonacciList*, void (*)(const FibonacciList*), void (*)(FibonacciList*), void (*)(FibonacciList*), void (*)(FibonacciList*, quintptr, quintptr), void (*)(FibonacciList*), void (*)(FibonacciList*), void (*)(FibonacciList*, int, int), void (*)(FibonacciList*), void (*)(FibonacciList*, int, int, int), void (*)(FibonacciList*), void (*)(FibonacciList*, int, int), void (*)(FibonacciList*)); void fibonacci_list_free(FibonacciList::Private*); }; extern "C" { void file_system_tree_data_file_icon(const FileSystemTree::Private*, quintptr, QByteArray*, qbytearray_set); void file_system_tree_data_file_name(const FileSystemTree::Private*, quintptr, QString*, qstring_set); void file_system_tree_data_file_path(const FileSystemTree::Private*, quintptr, QString*, qstring_set); qint32 file_system_tree_data_file_permissions(const FileSystemTree::Private*, quintptr); option_quint64 file_system_tree_data_file_size(const FileSystemTree::Private*, quintptr); qint32 file_system_tree_data_file_type(const FileSystemTree::Private*, quintptr); void file_system_tree_sort(FileSystemTree::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int file_system_tree_row_count(const FileSystemTree::Private*, option_quintptr); bool file_system_tree_can_fetch_more(const FileSystemTree::Private*, option_quintptr); void file_system_tree_fetch_more(FileSystemTree::Private*, option_quintptr); quintptr file_system_tree_index(const FileSystemTree::Private*, option_quintptr, int); qmodelindex_t file_system_tree_parent(const FileSystemTree::Private*, quintptr); int file_system_tree_row(const FileSystemTree::Private*, quintptr); + option_quintptr file_system_tree_check_row(const FileSystemTree::Private*, quintptr, int); } int FileSystemTree::columnCount(const QModelIndex &) const { return 5; } bool FileSystemTree::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int FileSystemTree::rowCount(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return 0; } const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; return file_system_tree_row_count(m_d, rust_parent); } bool FileSystemTree::insertRows(int, int, const QModelIndex &) { return false; // not supported yet } bool FileSystemTree::removeRows(int, int, const QModelIndex &) { return false; // not supported yet } QModelIndex FileSystemTree::index(int row, int column, const QModelIndex &parent) const { if (row < 0 || column < 0 || column >= 5) { return QModelIndex(); } if (parent.isValid() && parent.column() != 0) { return QModelIndex(); } if (row >= rowCount(parent)) { return QModelIndex(); } const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; const quintptr id = file_system_tree_index(m_d, rust_parent, row); return createIndex(row, column, id); } QModelIndex FileSystemTree::parent(const QModelIndex &index) const { if (!index.isValid()) { return QModelIndex(); } const qmodelindex_t parent = file_system_tree_parent(m_d, index.internalId()); return parent.row >= 0 ?createIndex(parent.row, 0, parent.id) :QModelIndex(); } bool FileSystemTree::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return false; } const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; return file_system_tree_can_fetch_more(m_d, rust_parent); } void FileSystemTree::fetchMore(const QModelIndex &parent) { const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; file_system_tree_fetch_more(m_d, rust_parent); } +void FileSystemTree::updatePersistentIndexes() { + const auto from = persistentIndexList(); + auto to = from; + auto len = to.size(); + for (int i = 0; i < len; ++i) { + auto index = to.at(i); + auto row = file_system_tree_check_row(m_d, index.internalId(), index.row()); + if (row.some) { + to[i] = createIndex(row.value, index.column(), index.internalId()); + } else { + to[i] = QModelIndex(); + } + } + changePersistentIndexList(from, to); +} void FileSystemTree::sort(int column, Qt::SortOrder order) { file_system_tree_sort(m_d, column, order); } Qt::ItemFlags FileSystemTree::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); return flags; } QByteArray FileSystemTree::fileIcon(const QModelIndex& index) const { QByteArray b; file_system_tree_data_file_icon(m_d, index.internalId(), &b, set_qbytearray); return b; } QString FileSystemTree::fileName(const QModelIndex& index) const { QString s; file_system_tree_data_file_name(m_d, index.internalId(), &s, set_qstring); return s; } QString FileSystemTree::filePath(const QModelIndex& index) const { QString s; file_system_tree_data_file_path(m_d, index.internalId(), &s, set_qstring); return s; } qint32 FileSystemTree::filePermissions(const QModelIndex& index) const { return file_system_tree_data_file_permissions(m_d, index.internalId()); } QVariant FileSystemTree::fileSize(const QModelIndex& index) const { QVariant v; v = file_system_tree_data_file_size(m_d, index.internalId()); return v; } qint32 FileSystemTree::fileType(const QModelIndex& index) const { return file_system_tree_data_file_type(m_d, index.internalId()); } QVariant FileSystemTree::data(const QModelIndex &index, int role) const { Q_ASSERT(rowCount(index.parent()) > index.row()); switch (index.column()) { case 0: switch (role) { case Qt::DecorationRole: case Qt::UserRole + 0: return QVariant::fromValue(fileIcon(index)); case Qt::DisplayRole: case Qt::UserRole + 1: return QVariant::fromValue(fileName(index)); case Qt::UserRole + 2: return cleanNullQVariant(QVariant::fromValue(filePath(index))); case Qt::UserRole + 3: return QVariant::fromValue(filePermissions(index)); case Qt::UserRole + 4: return fileSize(index); case Qt::UserRole + 5: return QVariant::fromValue(fileType(index)); } case 1: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 4: return fileSize(index); } case 2: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 2: return cleanNullQVariant(QVariant::fromValue(filePath(index))); } case 3: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 3: return QVariant::fromValue(filePermissions(index)); } case 4: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 5: return QVariant::fromValue(fileType(index)); } } return QVariant(); } int FileSystemTree::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 FileSystemTree::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "fileIcon"); names.insert(Qt::UserRole + 1, "fileName"); names.insert(Qt::UserRole + 2, "filePath"); names.insert(Qt::UserRole + 3, "filePermissions"); names.insert(Qt::UserRole + 4, "fileSize"); names.insert(Qt::UserRole + 5, "fileType"); return names; } QVariant FileSystemTree::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 FileSystemTree::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; } extern "C" { FileSystemTree::Private* file_system_tree_new(FileSystemTree*, void (*)(FileSystemTree*), void (*)(const FileSystemTree*, option_quintptr), void (*)(FileSystemTree*), void (*)(FileSystemTree*), void (*)(FileSystemTree*, quintptr, quintptr), void (*)(FileSystemTree*), void (*)(FileSystemTree*), void (*)(FileSystemTree*, option_quintptr, int, int), void (*)(FileSystemTree*), void (*)(FileSystemTree*, option_quintptr, int, int, option_quintptr, int), void (*)(FileSystemTree*), void (*)(FileSystemTree*, option_quintptr, int, int), void (*)(FileSystemTree*)); void file_system_tree_free(FileSystemTree::Private*); void file_system_tree_path_get(const FileSystemTree::Private*, QString*, qstring_set); void file_system_tree_path_set(FileSystemTree::Private*, const ushort *str, int len); void file_system_tree_path_set_none(FileSystemTree::Private*); }; extern "C" { void processes_data_cmd(const Processes::Private*, quintptr, QString*, qstring_set); quint8 processes_data_cpu_percentage(const Processes::Private*, quintptr); float processes_data_cpu_usage(const Processes::Private*, quintptr); quint64 processes_data_memory(const Processes::Private*, quintptr); void processes_data_name(const Processes::Private*, quintptr, QString*, qstring_set); quint32 processes_data_pid(const Processes::Private*, quintptr); quint32 processes_data_uid(const Processes::Private*, quintptr); void processes_sort(Processes::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int processes_row_count(const Processes::Private*, option_quintptr); bool processes_can_fetch_more(const Processes::Private*, option_quintptr); void processes_fetch_more(Processes::Private*, option_quintptr); quintptr processes_index(const Processes::Private*, option_quintptr, int); qmodelindex_t processes_parent(const Processes::Private*, quintptr); int processes_row(const Processes::Private*, quintptr); + option_quintptr processes_check_row(const Processes::Private*, quintptr, int); } int Processes::columnCount(const QModelIndex &) const { return 3; } bool Processes::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int Processes::rowCount(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return 0; } const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; return processes_row_count(m_d, rust_parent); } bool Processes::insertRows(int, int, const QModelIndex &) { return false; // not supported yet } bool Processes::removeRows(int, int, const QModelIndex &) { return false; // not supported yet } QModelIndex Processes::index(int row, int column, const QModelIndex &parent) const { if (row < 0 || column < 0 || column >= 3) { return QModelIndex(); } if (parent.isValid() && parent.column() != 0) { return QModelIndex(); } if (row >= rowCount(parent)) { return QModelIndex(); } const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; const quintptr id = processes_index(m_d, rust_parent, row); return createIndex(row, column, id); } QModelIndex Processes::parent(const QModelIndex &index) const { if (!index.isValid()) { return QModelIndex(); } const qmodelindex_t parent = processes_parent(m_d, index.internalId()); return parent.row >= 0 ?createIndex(parent.row, 0, parent.id) :QModelIndex(); } bool Processes::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return false; } const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; return processes_can_fetch_more(m_d, rust_parent); } void Processes::fetchMore(const QModelIndex &parent) { const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; processes_fetch_more(m_d, rust_parent); } +void Processes::updatePersistentIndexes() { + const auto from = persistentIndexList(); + auto to = from; + auto len = to.size(); + for (int i = 0; i < len; ++i) { + auto index = to.at(i); + auto row = processes_check_row(m_d, index.internalId(), index.row()); + if (row.some) { + to[i] = createIndex(row.value, index.column(), index.internalId()); + } else { + to[i] = QModelIndex(); + } + } + changePersistentIndexList(from, to); +} void Processes::sort(int column, Qt::SortOrder order) { processes_sort(m_d, column, order); } Qt::ItemFlags Processes::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); return flags; } QString Processes::cmd(const QModelIndex& index) const { QString s; processes_data_cmd(m_d, index.internalId(), &s, set_qstring); return s; } quint8 Processes::cpuPercentage(const QModelIndex& index) const { return processes_data_cpu_percentage(m_d, index.internalId()); } float Processes::cpuUsage(const QModelIndex& index) const { return processes_data_cpu_usage(m_d, index.internalId()); } quint64 Processes::memory(const QModelIndex& index) const { return processes_data_memory(m_d, index.internalId()); } QString Processes::name(const QModelIndex& index) const { QString s; processes_data_name(m_d, index.internalId(), &s, set_qstring); return s; } quint32 Processes::pid(const QModelIndex& index) const { return processes_data_pid(m_d, index.internalId()); } quint32 Processes::uid(const QModelIndex& index) const { return processes_data_uid(m_d, index.internalId()); } QVariant Processes::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(cmd(index)); case Qt::UserRole + 1: return QVariant::fromValue(cpuPercentage(index)); case Qt::UserRole + 2: return QVariant::fromValue(cpuUsage(index)); case Qt::UserRole + 3: return QVariant::fromValue(memory(index)); case Qt::DisplayRole: case Qt::UserRole + 4: return QVariant::fromValue(name(index)); case Qt::ToolTipRole: case Qt::UserRole + 5: return QVariant::fromValue(pid(index)); case Qt::UserRole + 6: return QVariant::fromValue(uid(index)); } case 1: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 2: return QVariant::fromValue(cpuUsage(index)); } case 2: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 3: return QVariant::fromValue(memory(index)); } } return QVariant(); } int Processes::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 Processes::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "cmd"); names.insert(Qt::UserRole + 1, "cpuPercentage"); names.insert(Qt::UserRole + 2, "cpuUsage"); names.insert(Qt::UserRole + 3, "memory"); names.insert(Qt::UserRole + 4, "name"); names.insert(Qt::UserRole + 5, "pid"); names.insert(Qt::UserRole + 6, "uid"); return names; } QVariant Processes::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 Processes::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; } extern "C" { Processes::Private* processes_new(Processes*, void (*)(Processes*), void (*)(const Processes*, option_quintptr), void (*)(Processes*), void (*)(Processes*), void (*)(Processes*, quintptr, quintptr), void (*)(Processes*), void (*)(Processes*), void (*)(Processes*, option_quintptr, int, int), void (*)(Processes*), void (*)(Processes*, option_quintptr, int, int, option_quintptr, int), void (*)(Processes*), void (*)(Processes*, option_quintptr, int, int), void (*)(Processes*)); void processes_free(Processes::Private*); bool processes_active_get(const Processes::Private*); void processes_active_set(Processes::Private*, bool); }; extern "C" { float time_series_data_cos(const TimeSeries::Private*, int); bool time_series_set_data_cos(TimeSeries::Private*, int, float); float time_series_data_sin(const TimeSeries::Private*, int); bool time_series_set_data_sin(TimeSeries::Private*, int, float); float time_series_data_time(const TimeSeries::Private*, int); bool time_series_set_data_time(TimeSeries::Private*, int, float); void time_series_sort(TimeSeries::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int time_series_row_count(const TimeSeries::Private*); bool time_series_insert_rows(TimeSeries::Private*, int, int); bool time_series_remove_rows(TimeSeries::Private*, int, int); bool time_series_can_fetch_more(const TimeSeries::Private*); void time_series_fetch_more(TimeSeries::Private*); } int TimeSeries::columnCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : 3; } bool TimeSeries::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int TimeSeries::rowCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : time_series_row_count(m_d); } bool TimeSeries::insertRows(int row, int count, const QModelIndex &) { return time_series_insert_rows(m_d, row, count); } bool TimeSeries::removeRows(int row, int count, const QModelIndex &) { return time_series_remove_rows(m_d, row, count); } QModelIndex TimeSeries::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid() && row >= 0 && row < rowCount(parent) && column >= 0 && column < 3) { return createIndex(row, column, (quintptr)row); } return QModelIndex(); } QModelIndex TimeSeries::parent(const QModelIndex &) const { return QModelIndex(); } bool TimeSeries::canFetchMore(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : time_series_can_fetch_more(m_d); } void TimeSeries::fetchMore(const QModelIndex &parent) { if (!parent.isValid()) { time_series_fetch_more(m_d); } } +void TimeSeries::updatePersistentIndexes() {} void TimeSeries::sort(int column, Qt::SortOrder order) { time_series_sort(m_d, column, order); } Qt::ItemFlags TimeSeries::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); if (i.column() == 0) { flags |= Qt::ItemIsEditable; } if (i.column() == 1) { flags |= Qt::ItemIsEditable; } if (i.column() == 2) { flags |= Qt::ItemIsEditable; } return flags; } float TimeSeries::cos(int row) const { return time_series_data_cos(m_d, row); } bool TimeSeries::setCos(int row, float value) { bool set = false; set = time_series_set_data_cos(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } float TimeSeries::sin(int row) const { return time_series_data_sin(m_d, row); } bool TimeSeries::setSin(int row, float value) { bool set = false; set = time_series_set_data_sin(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } float TimeSeries::time(int row) const { return time_series_data_time(m_d, row); } bool TimeSeries::setTime(int row, float value) { bool set = false; set = time_series_set_data_time(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QVariant TimeSeries::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(cos(index.row())); case Qt::UserRole + 1: return QVariant::fromValue(sin(index.row())); case Qt::DisplayRole: case Qt::EditRole: case Qt::UserRole + 2: return QVariant::fromValue(time(index.row())); } case 1: switch (role) { case Qt::DisplayRole: case Qt::EditRole: case Qt::UserRole + 1: return QVariant::fromValue(sin(index.row())); } case 2: switch (role) { case Qt::DisplayRole: case Qt::EditRole: case Qt::UserRole + 0: return QVariant::fromValue(cos(index.row())); } } return QVariant(); } int TimeSeries::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 TimeSeries::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "cos"); names.insert(Qt::UserRole + 1, "sin"); names.insert(Qt::UserRole + 2, "time"); return names; } QVariant TimeSeries::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 TimeSeries::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 TimeSeries::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.column() == 0) { if (role == Qt::UserRole + 0) { if (value.canConvert(qMetaTypeId())) { return setCos(index.row(), value.value()); } } if (role == Qt::UserRole + 1) { if (value.canConvert(qMetaTypeId())) { return setSin(index.row(), value.value()); } } if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole + 2) { if (value.canConvert(qMetaTypeId())) { return setTime(index.row(), value.value()); } } } if (index.column() == 1) { if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole + 1) { if (value.canConvert(qMetaTypeId())) { return setSin(index.row(), value.value()); } } } if (index.column() == 2) { if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole + 0) { if (value.canConvert(qMetaTypeId())) { return setCos(index.row(), value.value()); } } } return false; } extern "C" { TimeSeries::Private* time_series_new(TimeSeries*, void (*)(const TimeSeries*), void (*)(TimeSeries*), void (*)(TimeSeries*), void (*)(TimeSeries*, quintptr, quintptr), void (*)(TimeSeries*), void (*)(TimeSeries*), void (*)(TimeSeries*, int, int), void (*)(TimeSeries*), void (*)(TimeSeries*, int, int, int), void (*)(TimeSeries*), void (*)(TimeSeries*, int, int), void (*)(TimeSeries*)); void time_series_free(TimeSeries::Private*); }; Demo::Demo(bool /*owned*/, QObject *parent): QObject(parent), m_fibonacci(new Fibonacci(false, this)), m_fibonacciList(new FibonacciList(false, this)), m_fileSystemTree(new FileSystemTree(false, this)), m_processes(new Processes(false, this)), m_timeSeries(new TimeSeries(false, this)), m_d(0), m_ownsPrivate(false) { } Demo::Demo(QObject *parent): QObject(parent), m_fibonacci(new Fibonacci(false, this)), m_fibonacciList(new FibonacciList(false, this)), m_fileSystemTree(new FileSystemTree(false, this)), m_processes(new Processes(false, this)), m_timeSeries(new TimeSeries(false, this)), m_d(demo_new(this, m_fibonacci, fibonacciInputChanged, fibonacciResultChanged, m_fibonacciList, [](const FibonacciList* o) { emit o->newDataReady(QModelIndex()); }, [](FibonacciList* o) { emit o->layoutAboutToBeChanged(); }, [](FibonacciList* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](FibonacciList* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, 1, last)); }, [](FibonacciList* o) { o->beginResetModel(); }, [](FibonacciList* o) { o->endResetModel(); }, [](FibonacciList* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](FibonacciList* o) { o->endInsertRows(); }, [](FibonacciList* o, int first, int last, int destination) { o->beginMoveRows(QModelIndex(), first, last, QModelIndex(), destination); }, [](FibonacciList* o) { o->endMoveRows(); }, [](FibonacciList* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](FibonacciList* o) { o->endRemoveRows(); } , m_fileSystemTree, fileSystemTreePathChanged, [](const FileSystemTree* o, option_quintptr id) { if (id.some) { int row = file_system_tree_row(o->m_d, id.value); emit o->newDataReady(o->createIndex(row, 0, id.value)); } else { emit o->newDataReady(QModelIndex()); } }, [](FileSystemTree* o) { emit o->layoutAboutToBeChanged(); }, [](FileSystemTree* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](FileSystemTree* o, quintptr first, quintptr last) { quintptr frow = file_system_tree_row(o->m_d, first); quintptr lrow = file_system_tree_row(o->m_d, first); o->dataChanged(o->createIndex(frow, 0, first), o->createIndex(lrow, 4, last)); }, [](FileSystemTree* o) { o->beginResetModel(); }, [](FileSystemTree* o) { o->endResetModel(); }, [](FileSystemTree* o, option_quintptr id, int first, int last) { if (id.some) { int row = file_system_tree_row(o->m_d, id.value); o->beginInsertRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginInsertRows(QModelIndex(), first, last); } }, [](FileSystemTree* o) { o->endInsertRows(); }, [](FileSystemTree* o, option_quintptr sourceParent, int first, int last, option_quintptr destinationParent, int destination) { QModelIndex s; if (sourceParent.some) { int row = file_system_tree_row(o->m_d, sourceParent.value); s = o->createIndex(row, 0, sourceParent.value); } QModelIndex d; if (destinationParent.some) { int row = file_system_tree_row(o->m_d, destinationParent.value); d = o->createIndex(row, 0, destinationParent.value); } o->beginMoveRows(s, first, last, d, destination); }, [](FileSystemTree* o) { o->endMoveRows(); }, [](FileSystemTree* o, option_quintptr id, int first, int last) { if (id.some) { int row = file_system_tree_row(o->m_d, id.value); o->beginRemoveRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginRemoveRows(QModelIndex(), first, last); } }, [](FileSystemTree* o) { o->endRemoveRows(); } , m_processes, processesActiveChanged, [](const Processes* o, option_quintptr id) { if (id.some) { int row = processes_row(o->m_d, id.value); emit o->newDataReady(o->createIndex(row, 0, id.value)); } else { emit o->newDataReady(QModelIndex()); } }, [](Processes* o) { emit o->layoutAboutToBeChanged(); }, [](Processes* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](Processes* o, quintptr first, quintptr last) { quintptr frow = processes_row(o->m_d, first); quintptr lrow = processes_row(o->m_d, first); o->dataChanged(o->createIndex(frow, 0, first), o->createIndex(lrow, 2, last)); }, [](Processes* o) { o->beginResetModel(); }, [](Processes* o) { o->endResetModel(); }, [](Processes* o, option_quintptr id, int first, int last) { if (id.some) { int row = processes_row(o->m_d, id.value); o->beginInsertRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginInsertRows(QModelIndex(), first, last); } }, [](Processes* o) { o->endInsertRows(); }, [](Processes* o, option_quintptr sourceParent, int first, int last, option_quintptr destinationParent, int destination) { QModelIndex s; if (sourceParent.some) { int row = processes_row(o->m_d, sourceParent.value); s = o->createIndex(row, 0, sourceParent.value); } QModelIndex d; if (destinationParent.some) { int row = processes_row(o->m_d, destinationParent.value); d = o->createIndex(row, 0, destinationParent.value); } o->beginMoveRows(s, first, last, d, destination); }, [](Processes* o) { o->endMoveRows(); }, [](Processes* o, option_quintptr id, int first, int last) { if (id.some) { int row = processes_row(o->m_d, id.value); o->beginRemoveRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginRemoveRows(QModelIndex(), first, last); } }, [](Processes* o) { o->endRemoveRows(); } , m_timeSeries, [](const TimeSeries* o) { emit o->newDataReady(QModelIndex()); }, [](TimeSeries* o) { emit o->layoutAboutToBeChanged(); }, [](TimeSeries* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](TimeSeries* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, 2, last)); }, [](TimeSeries* o) { o->beginResetModel(); }, [](TimeSeries* o) { o->endResetModel(); }, [](TimeSeries* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](TimeSeries* o) { o->endInsertRows(); }, [](TimeSeries* o, int first, int last, int destination) { o->beginMoveRows(QModelIndex(), first, last, QModelIndex(), destination); }, [](TimeSeries* o) { o->endMoveRows(); }, [](TimeSeries* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](TimeSeries* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { m_fibonacci->m_d = demo_fibonacci_get(m_d); m_fibonacciList->m_d = demo_fibonacci_list_get(m_d); m_fileSystemTree->m_d = demo_file_system_tree_get(m_d); m_processes->m_d = demo_processes_get(m_d); m_timeSeries->m_d = demo_time_series_get(m_d); connect(this->m_fibonacciList, &FibonacciList::newDataReady, this->m_fibonacciList, [this](const QModelIndex& i) { this->m_fibonacciList->fetchMore(i); }, Qt::QueuedConnection); connect(this->m_fileSystemTree, &FileSystemTree::newDataReady, this->m_fileSystemTree, [this](const QModelIndex& i) { this->m_fileSystemTree->fetchMore(i); }, Qt::QueuedConnection); connect(this->m_processes, &Processes::newDataReady, this->m_processes, [this](const QModelIndex& i) { this->m_processes->fetchMore(i); }, Qt::QueuedConnection); connect(this->m_timeSeries, &TimeSeries::newDataReady, this->m_timeSeries, [this](const QModelIndex& i) { this->m_timeSeries->fetchMore(i); }, Qt::QueuedConnection); } Demo::~Demo() { if (m_ownsPrivate) { demo_free(m_d); } } const Fibonacci* Demo::fibonacci() const { return m_fibonacci; } Fibonacci* Demo::fibonacci() { return m_fibonacci; } const FibonacciList* Demo::fibonacciList() const { return m_fibonacciList; } FibonacciList* Demo::fibonacciList() { return m_fibonacciList; } const FileSystemTree* Demo::fileSystemTree() const { return m_fileSystemTree; } FileSystemTree* Demo::fileSystemTree() { return m_fileSystemTree; } const Processes* Demo::processes() const { return m_processes; } Processes* Demo::processes() { return m_processes; } const TimeSeries* Demo::timeSeries() const { return m_timeSeries; } TimeSeries* Demo::timeSeries() { return m_timeSeries; } Fibonacci::Fibonacci(bool /*owned*/, QObject *parent): QObject(parent), m_d(0), m_ownsPrivate(false) { } Fibonacci::Fibonacci(QObject *parent): QObject(parent), m_d(fibonacci_new(this, fibonacciInputChanged, fibonacciResultChanged)), m_ownsPrivate(true) { } Fibonacci::~Fibonacci() { if (m_ownsPrivate) { fibonacci_free(m_d); } } quint32 Fibonacci::input() const { return fibonacci_input_get(m_d); } void Fibonacci::setInput(quint32 v) { fibonacci_input_set(m_d, v); } quint64 Fibonacci::result() const { return fibonacci_result_get(m_d); } FibonacciList::FibonacciList(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } FibonacciList::FibonacciList(QObject *parent): QAbstractItemModel(parent), m_d(fibonacci_list_new(this, [](const FibonacciList* o) { emit o->newDataReady(QModelIndex()); }, [](FibonacciList* o) { emit o->layoutAboutToBeChanged(); }, [](FibonacciList* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](FibonacciList* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, 1, last)); }, [](FibonacciList* o) { o->beginResetModel(); }, [](FibonacciList* o) { o->endResetModel(); }, [](FibonacciList* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](FibonacciList* o) { o->endInsertRows(); }, [](FibonacciList* o, int first, int last, int destination) { o->beginMoveRows(QModelIndex(), first, last, QModelIndex(), destination); }, [](FibonacciList* o) { o->endMoveRows(); }, [](FibonacciList* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](FibonacciList* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &FibonacciList::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } FibonacciList::~FibonacciList() { if (m_ownsPrivate) { fibonacci_list_free(m_d); } } void FibonacciList::initHeaderData() { m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("row")); m_headerData.insert(qMakePair(1, Qt::DisplayRole), QVariant("fibonacciNumber")); } FileSystemTree::FileSystemTree(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } FileSystemTree::FileSystemTree(QObject *parent): QAbstractItemModel(parent), m_d(file_system_tree_new(this, fileSystemTreePathChanged, [](const FileSystemTree* o, option_quintptr id) { if (id.some) { int row = file_system_tree_row(o->m_d, id.value); emit o->newDataReady(o->createIndex(row, 0, id.value)); } else { emit o->newDataReady(QModelIndex()); } }, [](FileSystemTree* o) { emit o->layoutAboutToBeChanged(); }, [](FileSystemTree* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](FileSystemTree* o, quintptr first, quintptr last) { quintptr frow = file_system_tree_row(o->m_d, first); quintptr lrow = file_system_tree_row(o->m_d, first); o->dataChanged(o->createIndex(frow, 0, first), o->createIndex(lrow, 4, last)); }, [](FileSystemTree* o) { o->beginResetModel(); }, [](FileSystemTree* o) { o->endResetModel(); }, [](FileSystemTree* o, option_quintptr id, int first, int last) { if (id.some) { int row = file_system_tree_row(o->m_d, id.value); o->beginInsertRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginInsertRows(QModelIndex(), first, last); } }, [](FileSystemTree* o) { o->endInsertRows(); }, [](FileSystemTree* o, option_quintptr sourceParent, int first, int last, option_quintptr destinationParent, int destination) { QModelIndex s; if (sourceParent.some) { int row = file_system_tree_row(o->m_d, sourceParent.value); s = o->createIndex(row, 0, sourceParent.value); } QModelIndex d; if (destinationParent.some) { int row = file_system_tree_row(o->m_d, destinationParent.value); d = o->createIndex(row, 0, destinationParent.value); } o->beginMoveRows(s, first, last, d, destination); }, [](FileSystemTree* o) { o->endMoveRows(); }, [](FileSystemTree* o, option_quintptr id, int first, int last) { if (id.some) { int row = file_system_tree_row(o->m_d, id.value); o->beginRemoveRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginRemoveRows(QModelIndex(), first, last); } }, [](FileSystemTree* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &FileSystemTree::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } FileSystemTree::~FileSystemTree() { if (m_ownsPrivate) { file_system_tree_free(m_d); } } void FileSystemTree::initHeaderData() { m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("fileName")); m_headerData.insert(qMakePair(1, Qt::DisplayRole), QVariant("fileSize")); m_headerData.insert(qMakePair(2, Qt::DisplayRole), QVariant("filePath")); m_headerData.insert(qMakePair(3, Qt::DisplayRole), QVariant("filePermissions")); m_headerData.insert(qMakePair(4, Qt::DisplayRole), QVariant("fileType")); } QString FileSystemTree::path() const { QString v; file_system_tree_path_get(m_d, &v, set_qstring); return v; } void FileSystemTree::setPath(const QString& v) { if (v.isNull()) { file_system_tree_path_set_none(m_d); } else { file_system_tree_path_set(m_d, reinterpret_cast(v.data()), v.size()); } } Processes::Processes(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } Processes::Processes(QObject *parent): QAbstractItemModel(parent), m_d(processes_new(this, processesActiveChanged, [](const Processes* o, option_quintptr id) { if (id.some) { int row = processes_row(o->m_d, id.value); emit o->newDataReady(o->createIndex(row, 0, id.value)); } else { emit o->newDataReady(QModelIndex()); } }, [](Processes* o) { emit o->layoutAboutToBeChanged(); }, [](Processes* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](Processes* o, quintptr first, quintptr last) { quintptr frow = processes_row(o->m_d, first); quintptr lrow = processes_row(o->m_d, first); o->dataChanged(o->createIndex(frow, 0, first), o->createIndex(lrow, 2, last)); }, [](Processes* o) { o->beginResetModel(); }, [](Processes* o) { o->endResetModel(); }, [](Processes* o, option_quintptr id, int first, int last) { if (id.some) { int row = processes_row(o->m_d, id.value); o->beginInsertRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginInsertRows(QModelIndex(), first, last); } }, [](Processes* o) { o->endInsertRows(); }, [](Processes* o, option_quintptr sourceParent, int first, int last, option_quintptr destinationParent, int destination) { QModelIndex s; if (sourceParent.some) { int row = processes_row(o->m_d, sourceParent.value); s = o->createIndex(row, 0, sourceParent.value); } QModelIndex d; if (destinationParent.some) { int row = processes_row(o->m_d, destinationParent.value); d = o->createIndex(row, 0, destinationParent.value); } o->beginMoveRows(s, first, last, d, destination); }, [](Processes* o) { o->endMoveRows(); }, [](Processes* o, option_quintptr id, int first, int last) { if (id.some) { int row = processes_row(o->m_d, id.value); o->beginRemoveRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginRemoveRows(QModelIndex(), first, last); } }, [](Processes* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &Processes::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } Processes::~Processes() { if (m_ownsPrivate) { processes_free(m_d); } } void Processes::initHeaderData() { m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("name")); m_headerData.insert(qMakePair(1, Qt::DisplayRole), QVariant("cpuUsage")); m_headerData.insert(qMakePair(2, Qt::DisplayRole), QVariant("memory")); } bool Processes::active() const { return processes_active_get(m_d); } void Processes::setActive(bool v) { processes_active_set(m_d, v); } TimeSeries::TimeSeries(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } TimeSeries::TimeSeries(QObject *parent): QAbstractItemModel(parent), m_d(time_series_new(this, [](const TimeSeries* o) { emit o->newDataReady(QModelIndex()); }, [](TimeSeries* o) { emit o->layoutAboutToBeChanged(); }, [](TimeSeries* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](TimeSeries* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, 2, last)); }, [](TimeSeries* o) { o->beginResetModel(); }, [](TimeSeries* o) { o->endResetModel(); }, [](TimeSeries* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](TimeSeries* o) { o->endInsertRows(); }, [](TimeSeries* o, int first, int last, int destination) { o->beginMoveRows(QModelIndex(), first, last, QModelIndex(), destination); }, [](TimeSeries* o) { o->endMoveRows(); }, [](TimeSeries* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](TimeSeries* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &TimeSeries::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } TimeSeries::~TimeSeries() { if (m_ownsPrivate) { time_series_free(m_d); } } void TimeSeries::initHeaderData() { m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("time")); m_headerData.insert(qMakePair(1, Qt::DisplayRole), QVariant("sin")); m_headerData.insert(qMakePair(2, Qt::DisplayRole), QVariant("cos")); } diff --git a/demo/src/Bindings.h b/demo/src/Bindings.h index 5acdef5..c536e02 100644 --- a/demo/src/Bindings.h +++ b/demo/src/Bindings.h @@ -1,267 +1,271 @@ /* generated by rust_qt_binding_generator */ #ifndef BINDINGS_H #define BINDINGS_H #include #include class Demo; class Fibonacci; class FibonacciList; class FileSystemTree; class Processes; class TimeSeries; class Demo : public QObject { Q_OBJECT public: class Private; private: Fibonacci* const m_fibonacci; FibonacciList* const m_fibonacciList; FileSystemTree* const m_fileSystemTree; Processes* const m_processes; TimeSeries* const m_timeSeries; Private * m_d; bool m_ownsPrivate; Q_PROPERTY(Fibonacci* fibonacci READ fibonacci NOTIFY fibonacciChanged FINAL) Q_PROPERTY(FibonacciList* fibonacciList READ fibonacciList NOTIFY fibonacciListChanged FINAL) Q_PROPERTY(FileSystemTree* fileSystemTree READ fileSystemTree NOTIFY fileSystemTreeChanged FINAL) Q_PROPERTY(Processes* processes READ processes NOTIFY processesChanged FINAL) Q_PROPERTY(TimeSeries* timeSeries READ timeSeries NOTIFY timeSeriesChanged FINAL) explicit Demo(bool owned, QObject *parent); public: explicit Demo(QObject *parent = nullptr); ~Demo(); const Fibonacci* fibonacci() const; Fibonacci* fibonacci(); const FibonacciList* fibonacciList() const; FibonacciList* fibonacciList(); const FileSystemTree* fileSystemTree() const; FileSystemTree* fileSystemTree(); const Processes* processes() const; Processes* processes(); const TimeSeries* timeSeries() const; TimeSeries* timeSeries(); signals: void fibonacciChanged(); void fibonacciListChanged(); void fileSystemTreeChanged(); void processesChanged(); void timeSeriesChanged(); }; class Fibonacci : public QObject { Q_OBJECT friend class Demo; public: class Private; private: Private * m_d; bool m_ownsPrivate; Q_PROPERTY(quint32 input READ input WRITE setInput NOTIFY inputChanged FINAL) Q_PROPERTY(quint64 result READ result NOTIFY resultChanged FINAL) explicit Fibonacci(bool owned, QObject *parent); public: explicit Fibonacci(QObject *parent = nullptr); ~Fibonacci(); quint32 input() const; void setInput(quint32 v); quint64 result() const; signals: void inputChanged(); void resultChanged(); }; class FibonacciList : public QAbstractItemModel { Q_OBJECT friend class Demo; public: class Private; private: Private * m_d; bool m_ownsPrivate; explicit FibonacciList(bool owned, QObject *parent); public: explicit FibonacciList(QObject *parent = nullptr); ~FibonacciList(); 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; Q_INVOKABLE quint64 fibonacciNumber(int row) const; Q_INVOKABLE quint64 row(int row) const; signals: // new data is ready to be made available to the model with fetchMore() void newDataReady(const QModelIndex &parent) const; private: QHash, QVariant> m_headerData; void initHeaderData(); + void updatePersistentIndexes(); signals: }; class FileSystemTree : public QAbstractItemModel { Q_OBJECT friend class Demo; public: class Private; private: Private * m_d; bool m_ownsPrivate; Q_PROPERTY(QString path READ path WRITE setPath NOTIFY pathChanged FINAL) explicit FileSystemTree(bool owned, QObject *parent); public: explicit FileSystemTree(QObject *parent = nullptr); ~FileSystemTree(); QString path() const; void setPath(const QString& v); 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; Q_INVOKABLE QByteArray fileIcon(const QModelIndex& index) const; Q_INVOKABLE QString fileName(const QModelIndex& index) const; Q_INVOKABLE QString filePath(const QModelIndex& index) const; Q_INVOKABLE qint32 filePermissions(const QModelIndex& index) const; Q_INVOKABLE QVariant fileSize(const QModelIndex& index) const; Q_INVOKABLE qint32 fileType(const QModelIndex& index) const; signals: // new data is ready to be made available to the model with fetchMore() void newDataReady(const QModelIndex &parent) const; private: QHash, QVariant> m_headerData; void initHeaderData(); + void updatePersistentIndexes(); signals: void pathChanged(); }; class Processes : public QAbstractItemModel { Q_OBJECT friend class Demo; public: class Private; private: Private * m_d; bool m_ownsPrivate; Q_PROPERTY(bool active READ active WRITE setActive NOTIFY activeChanged FINAL) explicit Processes(bool owned, QObject *parent); public: explicit Processes(QObject *parent = nullptr); ~Processes(); bool active() const; void setActive(bool v); 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; Q_INVOKABLE QString cmd(const QModelIndex& index) const; Q_INVOKABLE quint8 cpuPercentage(const QModelIndex& index) const; Q_INVOKABLE float cpuUsage(const QModelIndex& index) const; Q_INVOKABLE quint64 memory(const QModelIndex& index) const; Q_INVOKABLE QString name(const QModelIndex& index) const; Q_INVOKABLE quint32 pid(const QModelIndex& index) const; Q_INVOKABLE quint32 uid(const QModelIndex& index) const; signals: // new data is ready to be made available to the model with fetchMore() void newDataReady(const QModelIndex &parent) const; private: QHash, QVariant> m_headerData; void initHeaderData(); + void updatePersistentIndexes(); signals: void activeChanged(); }; class TimeSeries : public QAbstractItemModel { Q_OBJECT friend class Demo; public: class Private; private: Private * m_d; bool m_ownsPrivate; explicit TimeSeries(bool owned, QObject *parent); public: explicit TimeSeries(QObject *parent = nullptr); ~TimeSeries(); 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 float cos(int row) const; Q_INVOKABLE bool setCos(int row, float value); Q_INVOKABLE float sin(int row) const; Q_INVOKABLE bool setSin(int row, float value); Q_INVOKABLE float time(int row) const; Q_INVOKABLE bool setTime(int row, float value); signals: // new data is ready to be made available to the model with fetchMore() void newDataReady(const QModelIndex &parent) const; private: QHash, QVariant> m_headerData; void initHeaderData(); + void updatePersistentIndexes(); signals: }; #endif // BINDINGS_H diff --git a/src/cpp.cpp b/src/cpp.cpp index a113e22..34f660d 100644 --- a/src/cpp.cpp +++ b/src/cpp.cpp @@ -1,1174 +1,1194 @@ /* * 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 . */ #include "structs.h" #include "cpp.h" #include "helper.h" #include #include template QString cppSetType(const T& p) { if (p.optional) { return "option_" + p.type.cppSetType; } return p.type.cppSetType; } template QString propertyType(const T& p) { return (p.optional && !p.type.isComplex()) ?"QVariant" :p.type.name; } QString upperInitial(const QString& name) { return name.left(1).toUpper() + name.mid(1); } QString lowerInitial(const QString& name) { return name.left(1).toLower() + name.mid(1); } QString writeProperty(const QString& name) { return "WRITE set" + upperInitial(name) + " "; } QString baseType(const Object& o) { if (o.type != ObjectType::Object) { return "QAbstractItemModel"; } return "QObject"; } QString cGetType(const BindingTypeProperties& type) { return type.name + "*, " + type.name.toLower() + "_set"; } bool modelIsWritable(const Object& o) { bool write = false; for (auto ip: o.itemProperties) { write |= ip.write; } return write; } void writeHeaderItemModel(QTextStream& h, const Object& o) { h << QString(R"( int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &index) const override; bool hasChildren(const QModelIndex &parent = QModelIndex()) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; bool canFetchMore(const QModelIndex &parent) const override; void fetchMore(const QModelIndex &parent) override; Qt::ItemFlags flags(const QModelIndex &index) const override; void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override; int role(const char* name) const; QHash roleNames() const override; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::EditRole) override; Q_INVOKABLE bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; Q_INVOKABLE bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; )"); if (modelIsWritable(o)) { h << " bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;\n"; } for (auto ip: o.itemProperties) { auto r = propertyType(ip); auto rw = r; if (r == "QVariant" || ip.type.isComplex()) { rw = "const " + r + "&"; } if (o.type == ObjectType::List) { h << QString(" Q_INVOKABLE %2 %1(int row) const;\n").arg(ip.name, r); if (ip.write) { h << QString(" Q_INVOKABLE bool set%1(int row, %2 value);\n").arg(upperInitial(ip.name), rw); } } else { h << QString(" Q_INVOKABLE %2 %1(const QModelIndex& index) const;\n").arg(ip.name, r); if (ip.write) { h << QString(" Q_INVOKABLE bool set%1(const QModelIndex& index, %2 value);\n").arg(upperInitial(ip.name), rw); } } } h << R"( signals: // new data is ready to be made available to the model with fetchMore() void newDataReady(const QModelIndex &parent) const; private: QHash, QVariant> m_headerData; void initHeaderData(); + void updatePersistentIndexes(); )"; } bool isColumnWrite(const Object& o, int col) { for (auto ip: o.itemProperties) { if (ip.write && (col == 0 || (ip.roles.size() > col && ip.roles[col].size() > 0))) { return true; } } return false; } void writeModelGetterSetter(QTextStream& cpp, const QString& index, const ItemProperty& ip, const Object& o) { const QString lcname(snakeCase(o.name)); QString idx = index; // getter auto r = propertyType(ip); if (o.type == ObjectType::List) { idx = ", row"; cpp << QString("%3 %1::%2(int row) const\n{\n") .arg(o.name, ip.name, r); } else { cpp << QString("%3 %1::%2(const QModelIndex& index) const\n{\n") .arg(o.name, ip.name, r); } if (ip.type.name == "QString") { cpp << " QString s;\n"; cpp << QString(" %1_data_%2(m_d%4, &s, set_%3);\n") .arg(lcname, snakeCase(ip.name), ip.type.name.toLower(), idx); cpp << " return s;\n"; } else if (ip.type.name == "QByteArray") { cpp << " QByteArray b;\n"; cpp << QString(" %1_data_%2(m_d%4, &b, set_%3);\n") .arg(lcname, snakeCase(ip.name), ip.type.name.toLower(), idx); cpp << " return b;\n"; } else if (ip.optional) { cpp << " QVariant v;\n"; cpp << QString(" v = %1_data_%2(m_d%3);\n") .arg(lcname, snakeCase(ip.name), idx); cpp << " return v;\n"; } else { cpp << QString(" return %1_data_%2(m_d%3);\n") .arg(lcname, snakeCase(ip.name), idx); } cpp << "}\n\n"; if (!ip.write) { return; } // setter if (r == "QVariant" || ip.type.isComplex()) { r = "const " + r + "&"; } if (o.type == ObjectType::List) { idx = ", row"; cpp << QString("bool %1::set%2(int row, %3 value)\n{\n") .arg(o.name, upperInitial(ip.name), r); } else { cpp << QString("bool %1::set%2(const QModelIndex& index, %3 value)\n{\n") .arg(o.name, upperInitial(ip.name), r); } cpp << " bool set = false;\n"; if (ip.optional) { QString test = "value.isNull()"; if (!ip.type.isComplex()) { test += " || !value.isValid()"; } cpp << " if (" << test << ") {\n"; cpp << QString(" set = %1_set_data_%2_none(m_d%3);") .arg(lcname, snakeCase(ip.name), idx) << endl; cpp << " } else {\n"; } if (ip.optional && !ip.type.isComplex()) { cpp << QString(" if (!value.canConvert(qMetaTypeId<%1>())) {\n return false;\n }\n").arg(ip.type.name); cpp << QString(" set = %1_set_data_%2(m_d%3, value.value<%4>());") .arg(lcname, snakeCase(ip.name), idx, ip.type.name) << endl; } else { QString val = "value"; if (ip.type.isComplex()) { if (ip.type.name == "QString") { val = "value.utf16(), value.length()"; } else { val = "value.data(), value.length()"; } } cpp << QString(" set = %1_set_data_%2(m_d%3, %4);") .arg(lcname, snakeCase(ip.name), idx, val) << endl; } if (ip.optional) { cpp << " }\n"; } if (o.type == ObjectType::List) { cpp << R"( if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } )"; } else { cpp << R"( if (set) { emit dataChanged(index, index); } return set; } )"; } } void writeCppModel(QTextStream& cpp, const Object& o) { const QString lcname(snakeCase(o.name)); QString indexDecl = ", int"; QString index = ", index.row()"; if (o.type == ObjectType::Tree) { indexDecl = ", quintptr"; index = ", index.internalId()"; } cpp << "extern \"C\" {\n"; for (auto ip: o.itemProperties) { if (ip.type.isComplex()) { cpp << QString(" void %2_data_%3(const %1::Private*%5, %4);\n") .arg(o.name, lcname, snakeCase(ip.name), cGetType(ip.type), indexDecl); } else { cpp << QString(" %4 %2_data_%3(const %1::Private*%5);\n") .arg(o.name, lcname, snakeCase(ip.name), cppSetType(ip), indexDecl); } if (ip.write) { if (ip.type.name == "QString") { cpp << QString(" bool %2_set_data_%3(%1::Private*%4, const ushort* s, int len);") .arg(o.name, lcname, snakeCase(ip.name), indexDecl) << endl; } else if (ip.type.name == "QByteArray") { cpp << QString(" bool %2_set_data_%3(%1::Private*%4, const char* s, int len);") .arg(o.name, lcname, snakeCase(ip.name), indexDecl) << endl; } else { cpp << QString(" bool %2_set_data_%3(%1::Private*%5, %4);") .arg(o.name, lcname, snakeCase(ip.name), ip.type.cSetType, indexDecl) << endl; } if (ip.optional) { cpp << QString(" bool %2_set_data_%3_none(%1::Private*%4);") .arg(o.name, lcname, snakeCase(ip.name), indexDecl) << endl; } } } cpp << QString(" void %2_sort(%1::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder);\n").arg(o.name, lcname); if (o.type == ObjectType::List) { cpp << QString(R"( int %2_row_count(const %1::Private*); bool %2_insert_rows(%1::Private*, int, int); bool %2_remove_rows(%1::Private*, int, int); bool %2_can_fetch_more(const %1::Private*); void %2_fetch_more(%1::Private*); } int %1::columnCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : %3; } bool %1::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int %1::rowCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : %2_row_count(m_d); } bool %1::insertRows(int row, int count, const QModelIndex &) { return %2_insert_rows(m_d, row, count); } bool %1::removeRows(int row, int count, const QModelIndex &) { return %2_remove_rows(m_d, row, count); } QModelIndex %1::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid() && row >= 0 && row < rowCount(parent) && column >= 0 && column < %3) { return createIndex(row, column, (quintptr)row); } return QModelIndex(); } QModelIndex %1::parent(const QModelIndex &) const { return QModelIndex(); } bool %1::canFetchMore(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : %2_can_fetch_more(m_d); } void %1::fetchMore(const QModelIndex &parent) { if (!parent.isValid()) { %2_fetch_more(m_d); } } +void %1::updatePersistentIndexes() {} )").arg(o.name, lcname, QString::number(o.columnCount)); } else { cpp << QString(R"( int %2_row_count(const %1::Private*, option_quintptr); bool %2_can_fetch_more(const %1::Private*, option_quintptr); void %2_fetch_more(%1::Private*, option_quintptr); quintptr %2_index(const %1::Private*, option_quintptr, int); qmodelindex_t %2_parent(const %1::Private*, quintptr); int %2_row(const %1::Private*, quintptr); + option_quintptr %2_check_row(const %1::Private*, quintptr, int); } int %1::columnCount(const QModelIndex &) const { return %3; } bool %1::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int %1::rowCount(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return 0; } const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; return %2_row_count(m_d, rust_parent); } bool %1::insertRows(int, int, const QModelIndex &) { return false; // not supported yet } bool %1::removeRows(int, int, const QModelIndex &) { return false; // not supported yet } QModelIndex %1::index(int row, int column, const QModelIndex &parent) const { if (row < 0 || column < 0 || column >= %3) { return QModelIndex(); } if (parent.isValid() && parent.column() != 0) { return QModelIndex(); } if (row >= rowCount(parent)) { return QModelIndex(); } const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; const quintptr id = %2_index(m_d, rust_parent, row); return createIndex(row, column, id); } QModelIndex %1::parent(const QModelIndex &index) const { if (!index.isValid()) { return QModelIndex(); } const qmodelindex_t parent = %2_parent(m_d, index.internalId()); return parent.row >= 0 ?createIndex(parent.row, 0, parent.id) :QModelIndex(); } bool %1::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return false; } const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; return %2_can_fetch_more(m_d, rust_parent); } void %1::fetchMore(const QModelIndex &parent) { const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; %2_fetch_more(m_d, rust_parent); } +void %1::updatePersistentIndexes() { + const auto from = persistentIndexList(); + auto to = from; + auto len = to.size(); + for (int i = 0; i < len; ++i) { + auto index = to.at(i); + auto row = %2_check_row(m_d, index.internalId(), index.row()); + if (row.some) { + to[i] = createIndex(row.value, index.column(), index.internalId()); + } else { + to[i] = QModelIndex(); + } + } + changePersistentIndexList(from, to); +} )").arg(o.name, lcname, QString::number(o.columnCount)); } cpp << QString(R"( void %1::sort(int column, Qt::SortOrder order) { %2_sort(m_d, column, order); } Qt::ItemFlags %1::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); )").arg(o.name, lcname); for (int col = 0; col < o.columnCount; ++col) { if (isColumnWrite(o, col)) { cpp << " if (i.column() == " << col << ") {\n"; cpp << " flags |= Qt::ItemIsEditable;\n }\n"; } } cpp << " return flags;\n}\n\n"; for (auto ip: o.itemProperties) { writeModelGetterSetter(cpp, index, ip, o); } cpp << QString(R"(QVariant %1::data(const QModelIndex &index, int role) const { Q_ASSERT(rowCount(index.parent()) > index.row()); switch (index.column()) { )").arg(o.name); auto metaRoles = QMetaEnum::fromType(); for (int col = 0; col < o.columnCount; ++col) { cpp << QString(" case %1:\n").arg(col); cpp << QString(" switch (role) {\n"); for (int i = 0; i < o.itemProperties.size(); ++i) { auto ip = o.itemProperties[i]; auto roles = ip.roles.value(col); if (col > 0 && roles.size() == 0) { continue; } for (auto role: roles) { cpp << QString(" case Qt::%1:\n").arg(metaRoles.valueToKey(role)); } cpp << QString(" case Qt::UserRole + %1:\n").arg(i); auto ii = (o.type == ObjectType::List) ?".row()" :""; if (ip.optional && !ip.type.isComplex()) { cpp << QString(" return %1(index%2);\n").arg(ip.name, ii); } else if (ip.optional) { cpp << QString(" return cleanNullQVariant(QVariant::fromValue(%1(index%2)));\n").arg(ip.name, ii); } else { cpp << QString(" return QVariant::fromValue(%1(index%2));\n").arg(ip.name, ii); } } cpp << " }\n"; } cpp << " }\n return QVariant();\n}\n\n"; cpp << "int " << o.name << "::role(const char* name) const {\n"; cpp << " auto names = roleNames();\n"; cpp << " auto i = names.constBegin();\n"; cpp << " while (i != names.constEnd()) {\n"; cpp << " if (i.value() == name) {\n"; cpp << " return i.key();\n"; cpp << " }\n"; cpp << " ++i;\n"; cpp << " }\n"; cpp << " return -1;\n"; cpp << "}\n"; cpp << "QHash " << o.name << "::roleNames() const {\n"; cpp << " QHash names = QAbstractItemModel::roleNames();\n"; for (int i = 0; i < o.itemProperties.size(); ++i) { auto ip = o.itemProperties[i]; cpp << " names.insert(Qt::UserRole + " << i << ", \"" << ip.name << "\");\n"; } cpp << " return names;\n"; cpp << QString(R"(} QVariant %1::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 %1::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; } )").arg(o.name); if (modelIsWritable(o)) { cpp << QString("bool %1::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n").arg(o.name); for (int col = 0; col < o.columnCount; ++col) { if (!isColumnWrite(o, col)) { continue; } cpp << " if (index.column() == " << col << ") {\n"; for (int i = 0; i < o.itemProperties.size(); ++i) { auto ip = o.itemProperties[i]; if (!ip.write) { continue; } auto roles = ip.roles.value(col); if (col > 0 && roles.size() == 0) { continue; } cpp << " if ("; for (auto role: roles) { cpp << QString("role == Qt::%1 || ").arg(metaRoles.valueToKey(role)); } cpp << "role == Qt::UserRole + " << i << ") {\n"; auto ii = (o.type == ObjectType::List) ?".row()" :""; if (ip.optional && !ip.type.isComplex()) { cpp << QString(" return set%1(index%2, value);\n") .arg(upperInitial(ip.name), ii); } else { QString pre = ""; if (ip.optional) { pre = "!value.isValid() || value.isNull() ||"; } cpp << QString(" if (%2value.canConvert(qMetaTypeId<%1>())) {\n").arg(ip.type.name, pre); cpp << QString(" return set%1(index%2, value.value<%3>());\n").arg(upperInitial(ip.name), ii, ip.type.name); cpp << QString(" }\n"); } cpp << " }\n"; } cpp << " }\n"; } cpp << " return false;\n}\n\n"; } } void writeHeaderObject(QTextStream& h, const Object& o, const Configuration& conf) { h << QString(R"( class %1 : public %3 { Q_OBJEC%2 )").arg(o.name, "T", baseType(o)); for (auto object: conf.objects) { if (object.containsObject() && o.name != object.name) { h << " friend class " << object.name << ";\n"; } } h << R"(public: class Private; private: )"; for (auto p: o.properties) { if (p.type.type == BindingType::Object) { h << " " << p.type.name << "* const m_" << p.name << ";\n"; } } h << R"( Private * m_d; bool m_ownsPrivate; )"; for (auto p: o.properties) { bool obj = p.type.type == BindingType::Object; auto t = p.type.name; if (p.optional && !p.type.isComplex()) { t = "QVariant"; } h << QString(" Q_PROPERTY(%1 %2 READ %2 %3NOTIFY %2Changed FINAL)") .arg(t + (obj ?"*" :""), p.name, p.write ? writeProperty(p.name) :"") << endl; } h << QString(R"( explicit %1(bool owned, QObject *parent); public: explicit %1(QObject *parent = nullptr); ~%1(); )").arg(o.name); for (auto p: o.properties) { if (p.type.type == BindingType::Object) { h << " const " << p.type.name << "* " << p.name << "() const;" << endl; h << " " << p.type.name << "* " << p.name << "();" << endl; } else { auto t = p.type.name; auto t2 = p.type.cppSetType; if (p.optional && !p.type.isComplex()) { t = "QVariant"; t2 = "const QVariant&"; } h << " " << t << " " << p.name << "() const;" << endl; if (p.write) { h << " void set" << upperInitial(p.name) << "(" << t2 << " v);" << endl; } } } for (auto f: o.functions) { h << " Q_INVOKABLE " << f.type.name << " " << f.name << "("; for (auto a = f.args.begin(); a < f.args.end(); a++) { if (a != f.args.begin()) { h << ", "; } h << QString("%1 %2").arg(a->type.cppSetType, a->name); } h << QString(")%1;").arg(f.mut ? "" : " const"); h << endl; } if (baseType(o) == "QAbstractItemModel") { writeHeaderItemModel(h, o); } h << "signals:" << endl; for (auto p: o.properties) { h << " void " << p.name << "Changed();" << endl; } h << "};" << endl; } void constructorArgsDecl(QTextStream& cpp, const Object& o, const Configuration& conf) { cpp << o.name << "*"; for (auto p: o.properties) { if (p.type.type == BindingType::Object) { cpp << QString(", "); constructorArgsDecl(cpp, conf.findObject(p.type.name), conf); } else { cpp << QString(", void (*)(%1*)").arg(o.name); } } if (o.type == ObjectType::List) { cpp << QString(R"(, void (*)(const %1*), void (*)(%1*), void (*)(%1*), void (*)(%1*, quintptr, quintptr), void (*)(%1*), void (*)(%1*), void (*)(%1*, int, int), void (*)(%1*), void (*)(%1*, int, int, int), void (*)(%1*), void (*)(%1*, int, int), void (*)(%1*))").arg(o.name); } if (o.type == ObjectType::Tree) { cpp << QString(R"(, void (*)(const %1*, option_quintptr), void (*)(%1*), void (*)(%1*), void (*)(%1*, quintptr, quintptr), void (*)(%1*), void (*)(%1*), void (*)(%1*, option_quintptr, int, int), void (*)(%1*), void (*)(%1*, option_quintptr, int, int, option_quintptr, int), void (*)(%1*), void (*)(%1*, option_quintptr, int, int), void (*)(%1*))").arg(o.name); } } QString changedF(const Object& o, const Property& p) { return lowerInitial(o.name) + upperInitial(p.name) + "Changed"; } void constructorArgs(QTextStream& cpp, const QString& prefix, const Object& o, const Configuration& conf) { const QString lcname(snakeCase(o.name)); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { cpp << ", " << prefix << "m_" << p.name; constructorArgs(cpp, "m_" + p.name + "->", conf.findObject(p.type.name), conf); } else { cpp << ",\n " << changedF(o, p); } } if (o.type == ObjectType::List) { cpp << QString(R"(, [](const %1* o) { emit o->newDataReady(QModelIndex()); }, [](%1* o) { emit o->layoutAboutToBeChanged(); }, [](%1* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](%1* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, %2, last)); }, [](%1* o) { o->beginResetModel(); }, [](%1* o) { o->endResetModel(); }, [](%1* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](%1* o) { o->endInsertRows(); }, [](%1* o, int first, int last, int destination) { o->beginMoveRows(QModelIndex(), first, last, QModelIndex(), destination); }, [](%1* o) { o->endMoveRows(); }, [](%1* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](%1* o) { o->endRemoveRows(); } )").arg(o.name, QString::number(o.columnCount - 1)); } if (o.type == ObjectType::Tree) { cpp << QString(R"(, [](const %1* o, option_quintptr id) { if (id.some) { int row = %2_row(o->m_d, id.value); emit o->newDataReady(o->createIndex(row, 0, id.value)); } else { emit o->newDataReady(QModelIndex()); } }, [](%1* o) { emit o->layoutAboutToBeChanged(); }, [](%1* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](%1* o, quintptr first, quintptr last) { quintptr frow = %2_row(o->m_d, first); quintptr lrow = %2_row(o->m_d, first); o->dataChanged(o->createIndex(frow, 0, first), o->createIndex(lrow, %3, last)); }, [](%1* o) { o->beginResetModel(); }, [](%1* o) { o->endResetModel(); }, [](%1* o, option_quintptr id, int first, int last) { if (id.some) { int row = %2_row(o->m_d, id.value); o->beginInsertRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginInsertRows(QModelIndex(), first, last); } }, [](%1* o) { o->endInsertRows(); }, [](%1* o, option_quintptr sourceParent, int first, int last, option_quintptr destinationParent, int destination) { QModelIndex s; if (sourceParent.some) { int row = %2_row(o->m_d, sourceParent.value); s = o->createIndex(row, 0, sourceParent.value); } QModelIndex d; if (destinationParent.some) { int row = %2_row(o->m_d, destinationParent.value); d = o->createIndex(row, 0, destinationParent.value); } o->beginMoveRows(s, first, last, d, destination); }, [](%1* o) { o->endMoveRows(); }, [](%1* o, option_quintptr id, int first, int last) { if (id.some) { int row = %2_row(o->m_d, id.value); o->beginRemoveRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginRemoveRows(QModelIndex(), first, last); } }, [](%1* o) { o->endRemoveRows(); } )").arg(o.name, lcname, QString::number(o.columnCount - 1)); } } void writeFunctionCDecl(QTextStream& cpp, const Function& f, const QString& lcname, const Object& o) { const QString lc(snakeCase(f.name)); cpp << " "; if (f.type.isComplex()) { cpp << "void"; } else { cpp << f.type.name; } const QString name = QString("%1_%2").arg(lcname, lc); cpp << QString(" %1(%3%2::Private*").arg(name, o.name, f.mut ? "" : "const "); // write all the input arguments, for QString and QByteArray, write // pointers to their content and the length for (auto a = f.args.begin(); a < f.args.end(); a++) { if (a->type.name == "QString") { cpp << ", const ushort*, int"; } else if (a->type.name == "QByteArray") { cpp << ", const char*, int"; } else { cpp << ", " << a->type.name; } } // If the return type is QString or QByteArray, append a pointer to the // variable that will be set to the argument list. Also add a setter // function. if (f.type.name == "QString") { cpp << ", QString*, qstring_set"; } else if (f.type.name == "QByteArray") { cpp << ", QByteArray*, qbytearray_set"; } cpp << ");\n"; } void writeObjectCDecl(QTextStream& cpp, const Object& o, const Configuration& conf) { const QString lcname(snakeCase(o.name)); cpp << QString(" %1::Private* %2_new(").arg(o.name, lcname); constructorArgsDecl(cpp, o, conf); cpp << ");" << endl; cpp << QString(" void %2_free(%1::Private*);").arg(o.name, lcname) << endl; for (const Property& p: o.properties) { const QString base = QString("%1_%2").arg(lcname, snakeCase(p.name)); if (p.type.type == BindingType::Object) { cpp << QString(" %3::Private* %2_get(const %1::Private*);") .arg(o.name, base, p.type.name) << endl; } else if (p.type.isComplex()) { cpp << QString(" void %2_get(const %1::Private*, %3);") .arg(o.name, base, cGetType(p.type)) << endl; } else if (p.optional) { cpp << QString(" option_%3 %2_get(const %1::Private*);") .arg(o.name, base, p.type.name) << endl; } else { cpp << QString(" %3 %2_get(const %1::Private*);") .arg(o.name, base, p.type.name) << endl; } if (p.write) { QString t = p.type.cSetType; if (t == "qstring_t") { t = "const ushort *str, int len"; } else if (t == "qbytearray_t") { t = "const char* bytes, int len"; } cpp << QString(" void %2_set(%1::Private*, %3);") .arg(o.name, base, t) << endl; if (p.optional) { cpp << QString(" void %2_set_none(%1::Private*);") .arg(o.name, base) << endl; } } } for (const Function& f: o.functions) { writeFunctionCDecl(cpp, f, lcname, o); } } void initializeMembersEmpty(QTextStream& cpp, const Object& o, const Configuration& conf) { for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { initializeMembersEmpty(cpp, conf.findObject(p.type.name), conf); cpp << QString(" %1m_%2(new %3(false, this)),\n") .arg(p.name, p.type.name); } } } void initializeMembersZero(QTextStream& cpp, const Object& o) { for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { cpp << QString(" m_%1(new %2(false, this)),\n") .arg(p.name, p.type.name); } } } void initializeMembers(QTextStream& cpp, const QString& prefix, const Object& o, const Configuration& conf) { for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { cpp << QString(" %1m_%2->m_d = %3_%4_get(%1m_d);\n") .arg(prefix, p.name, snakeCase(o.name), snakeCase(p.name)); initializeMembers(cpp, "m_" + p.name + "->", conf.findObject(p.type.name), conf); } } } void connect(QTextStream& cpp, const QString& d, const Object& o, const Configuration& conf) { for (auto p: o.properties) { if (p.type.type == BindingType::Object) { connect(cpp, d + "->m_" + p.name, conf.findObject(p.type.name), conf); } } if (o.type != ObjectType::Object) { cpp << QString(R"( connect(%2, &%1::newDataReady, %2, [this](const QModelIndex& i) { %2->fetchMore(i); }, Qt::QueuedConnection); )").arg(o.name, d); } } void writeCppObject(QTextStream& cpp, const Object& o, const Configuration& conf) { const QString lcname(snakeCase(o.name)); cpp << QString("%1::%1(bool /*owned*/, QObject *parent):\n %2(parent),") .arg(o.name, baseType(o)) << endl; for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { cpp << QString(" m_%1(new %2(false, this)),\n") .arg(p.name, p.type.name); } } cpp << " m_d(0),\n m_ownsPrivate(false)\n{\n"; if (o.type != ObjectType::Object) { cpp << " initHeaderData();\n"; } cpp << QString("}\n\n%1::%1(QObject *parent):\n %2(parent),") .arg(o.name, baseType(o)) << endl; initializeMembersZero(cpp, o); cpp << QString(" m_d(%1_new(this").arg(lcname); constructorArgs(cpp, "", o, conf); cpp << ")),\n m_ownsPrivate(true)\n{\n"; initializeMembers(cpp, "", o, conf); connect(cpp, "this", o, conf); if (o.type != ObjectType::Object) { cpp << " initHeaderData();\n"; } cpp << QString(R"(} %1::~%1() { if (m_ownsPrivate) { %2_free(m_d); } } )").arg(o.name, lcname); if (o.type != ObjectType::Object) { cpp << QString("void %1::initHeaderData() {\n").arg(o.name); for (int col = 0; col < o.columnCount; ++col) { for (auto ip: o.itemProperties) { auto roles = ip.roles.value(col); if (roles.contains(Qt::DisplayRole)) { cpp << QString(" m_headerData.insert(qMakePair(%1, Qt::DisplayRole), QVariant(\"%2\"));\n").arg(QString::number(col), ip.name); } } } cpp << "}\n"; } for (const Property& p: o.properties) { const QString base = QString("%1_%2").arg(lcname, snakeCase(p.name)); if (p.type.type == BindingType::Object) { cpp << QString(R"(const %3* %1::%2() const { return m_%2; } %3* %1::%2() { return m_%2; } )").arg(o.name, p.name, p.type.name); } else if (p.type.isComplex()) { cpp << QString("%3 %1::%2() const\n{\n").arg(o.name, p.name, p.type.name); cpp << " " << p.type.name << " v;\n"; cpp << " " << base << "_get(m_d, &v, set_" << p.type.name.toLower() << ");\n"; cpp << " return v;\n}\n"; } else if (p.optional) { cpp << QString("QVariant %1::%2() const\n{\n").arg(o.name, p.name); cpp << " QVariant v;\n"; cpp << QString(" auto r = %1_get(m_d);\n").arg(base); cpp << " if (r.some) {\n"; cpp << " v.setValue(r.value);\n"; cpp << " }\n"; cpp << " return r;\n"; cpp << "}\n"; } else { cpp << QString("%3 %1::%2() const\n{\n").arg(o.name, p.name, p.type.name); cpp << QString(" return %1_get(m_d);\n}\n").arg(base); } if (p.write) { auto t = p.type.cppSetType; if (p.optional && !p.type.isComplex()) { t = "const QVariant&"; } cpp << "void " << o.name << "::set" << upperInitial(p.name) << "(" << t << " v) {" << endl; if (p.optional) { if (p.type.isComplex()) { cpp << " if (v.isNull()) {" << endl; } else { cpp << QString(" if (v.isNull() || !v.canConvert<%1>()) {").arg(p.type.name) << endl; } cpp << QString(" %1_set_none(m_d);").arg(base) << endl; cpp << QString(" } else {") << endl; if (p.type.name == "QString") { cpp << QString(" %1_set(m_d, reinterpret_cast(v.data()), v.size());").arg(base) << endl; } else if (p.type.name == "QByteArray") { cpp << QString(" %1_set(m_d, v.data(), v.size());").arg(base) << endl; } else if (p.optional) { cpp << QString(" %1_set(m_d, v.value<%2>());").arg(base, p.type.name) << endl; } else { cpp << QString(" %1_set(m_d, v);").arg(base) << endl; } cpp << QString(" }") << endl; } else if (p.type.name == "QString") { cpp << QString(" %1_set(m_d, reinterpret_cast(v.data()), v.size());").arg(base) << endl; } else if (p.type.name == "QByteArray") { cpp << QString(" %1_set(m_d, v.data(), v.size());").arg(base) << endl; } else { cpp << QString(" %1_set(m_d, v);").arg(base) << endl; } cpp << "}" << endl; } } for (const Function& f: o.functions) { const QString base = QString("%1_%2") .arg(lcname, snakeCase(f.name)); cpp << QString("%1 %2::%3(").arg(f.type.name, o.name, f.name); for (auto a = f.args.begin(); a < f.args.end(); a++) { cpp << QString("%1 %2%3").arg(a->type.cppSetType, a->name, a + 1 < f.args.end() ? ", " : ""); } cpp << QString(")%1\n{\n").arg(f.mut ? "" : " const"); QString argList; for (auto a = f.args.begin(); a < f.args.end(); a++) { if (a->type.name == "QString") { argList.append(QString(", %1.utf16(), %1.size()").arg(a->name)); } else if (a->type.name == "QByteArray") { argList.append(QString(", %1.data(), %1.size()").arg(a->name)); } else { argList.append(QString(", %1").arg(a->name)); } } if (f.type.name == "QString") { cpp << QString(" %1 s;").arg(f.type.name) << endl; cpp << QString(" %1(m_d%2, &s, set_qstring);") .arg(base, argList) << endl; cpp << " return s;" << endl; } else if (f.type.name == "QByteArray") { cpp << QString(" %1 s;").arg(f.type.name) << endl; cpp << QString(" %1(m_d%2, &s, set_qbytearray);") .arg(base, argList) << endl; cpp << " return s;" << endl; } else { cpp << QString(" return %1(m_d%2);") .arg(base, argList) << endl; } cpp << "}" << endl; } } void writeHeader(const Configuration& conf) { DifferentFileWriter w(conf.hFile.absoluteFilePath()); QTextStream h(&w.buffer); const QString guard(conf.hFile.fileName().replace('.', '_').toUpper()); h << QString(R"(/* generated by rust_qt_binding_generator */ #ifndef %1 #define %1 #include #include )").arg(guard); for (auto object: conf.objects) { h << "class " << object.name << ";\n"; } for (auto object: conf.objects) { writeHeaderObject(h, object, conf); } h << QString("#endif // %1\n").arg(guard); } void writeCpp(const Configuration& conf) { DifferentFileWriter w(conf.cppFile.absoluteFilePath()); QTextStream cpp(&w.buffer); cpp << QString(R"(/* generated by rust_qt_binding_generator */ #include "%1" namespace { )").arg(conf.hFile.fileName()); for (auto option: conf.optionalTypes()) { if (option != "QString" && option != "QByteArray") { cpp << QString(R"( struct option_%1 { public: %1 value; bool some; operator QVariant() const { if (some) { return QVariant::fromValue(value); } return QVariant(); } }; static_assert(std::is_pod::value, "option_%1 must be a POD type."); )").arg(option); } } if (conf.types().contains("QString")) { cpp << R"( typedef void (*qstring_set)(QString* val, const char* utf8, int nbytes); void set_qstring(QString* val, const char* utf8, int nbytes) { *val = QString::fromUtf8(utf8, nbytes); } )"; } if (conf.types().contains("QByteArray")) { cpp << R"( typedef void (*qbytearray_set)(QByteArray* val, const char* bytes, int nbytes); void set_qbytearray(QByteArray* v, const char* bytes, int nbytes) { if (v->isNull() && nbytes == 0) { *v = QByteArray(bytes, nbytes); } else { v->truncate(0); v->append(bytes, nbytes); } } )"; } if (conf.hasListOrTree()) { cpp << R"( struct qmodelindex_t { int row; quintptr id; }; inline QVariant cleanNullQVariant(const QVariant& v) { return (v.isNull()) ?QVariant() :v; } )"; } for (auto o: conf.objects) { for (auto p: o.properties) { if (p.type.type == BindingType::Object) { continue; } cpp << " inline void " << changedF(o, p) << "(" << o.name << "* o)\n"; cpp << " {\n emit o->" << p.name << "Changed();\n }\n"; } } cpp << "}\n"; for (auto object: conf.objects) { if (object.type != ObjectType::Object) { writeCppModel(cpp, object); } cpp << "extern \"C\" {\n"; writeObjectCDecl(cpp, object, conf); cpp << "};\n" << endl; } for (auto object: conf.objects) { writeCppObject(cpp, object, conf); } } diff --git a/src/rust.cpp b/src/rust.cpp index 5658679..b8237ef 100644 --- a/src/rust.cpp +++ b/src/rust.cpp @@ -1,1108 +1,1117 @@ /* * 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 . */ #include "structs.h" #include "helper.h" template QString rustType(const T& p) { if (p.optional) { return "Option<" + p.type.rustType + ">"; } return p.type.rustType; } template QString rustReturnType(const T& p) { QString type = p.type.rustType; if (type == "String" && !p.rustByValue) { type = "str"; } if (type == "Vec" && !p.rustByValue) { type = "[u8]"; } if (p.type.isComplex() && !p.rustByValue) { type = "&" + type; } if (p.optional) { return "Option<" + type + ">"; } return type; } template QString rustCType(const T& p) { if (p.optional) { return "COption<" + p.type.rustType + ">"; } return p.type.rustType; } template QString rustTypeInit(const T& p) { if (p.optional) { return "None"; } return p.type.rustTypeInit; } void rConstructorArgsDecl(QTextStream& r, const QString& name, const Object& o, const Configuration& conf) { r << QString(" %2: *mut %1QObject").arg(o.name, snakeCase(name)); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { r << QString(",\n"); rConstructorArgsDecl(r, p.name, conf.findObject(p.type.name), conf); } else { r << QString(",\n %3_%2_changed: fn(*const %1QObject)") .arg(o.name, snakeCase(p.name), snakeCase(name)); } } if (o.type == ObjectType::List) { r << QString(",\n %2_new_data_ready: fn(*const %1QObject)") .arg(o.name, snakeCase(name)); } else if (o.type == ObjectType::Tree) { r << QString(",\n %2_new_data_ready: fn(*const %1QObject, index: COption)") .arg(o.name, snakeCase(name)); } if (o.type != ObjectType::Object) { QString indexDecl; if (o.type == ObjectType::Tree) { indexDecl = " index: COption,"; } QString destDecl; if (o.type == ObjectType::Tree) { destDecl = " index: COption,"; } r << QString(R"(, %3_layout_about_to_be_changed: fn(*const %1QObject), %3_layout_changed: fn(*const %1QObject), %3_data_changed: fn(*const %1QObject, usize, usize), %3_begin_reset_model: fn(*const %1QObject), %3_end_reset_model: fn(*const %1QObject), %3_begin_insert_rows: fn(*const %1QObject,%2 usize, usize), %3_end_insert_rows: fn(*const %1QObject), %3_begin_move_rows: fn(*const %1QObject,%2 usize, usize,%4 usize), %3_end_move_rows: fn(*const %1QObject), %3_begin_remove_rows: fn(*const %1QObject,%2 usize, usize), %3_end_remove_rows: fn(*const %1QObject))").arg(o.name, indexDecl, snakeCase(name), destDecl); } } void rConstructorArgs(QTextStream& r, const QString& name, const Object& o, const Configuration& conf) { const QString lcname(snakeCase(o.name)); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { rConstructorArgs(r, p.name, conf.findObject(p.type.name), conf); } } r << QString(R"( let %2_emit = %1Emitter { qobject: Arc::new(Mutex::new(%2)), )").arg(o.name, snakeCase(name)); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) continue; r << QString(" %1_changed: %2_%1_changed,\n").arg(snakeCase(p.name), snakeCase(name)); } if (o.type != ObjectType::Object) { r << QString(" new_data_ready: %1_new_data_ready,\n") .arg(snakeCase(name)); } QString model = ""; if (o.type != ObjectType::Object) { const QString type = o.type == ObjectType::List ? "List" : "Tree"; model = ", model"; r << QString(R"( }; let model = %1%2 { qobject: %3, layout_about_to_be_changed: %4_layout_about_to_be_changed, layout_changed: %4_layout_changed, data_changed: %4_data_changed, begin_reset_model: %4_begin_reset_model, end_reset_model: %4_end_reset_model, begin_insert_rows: %4_begin_insert_rows, end_insert_rows: %4_end_insert_rows, begin_move_rows: %4_begin_move_rows, end_move_rows: %4_end_move_rows, begin_remove_rows: %4_begin_remove_rows, end_remove_rows: %4_end_remove_rows, )").arg(o.name, type, snakeCase(name), snakeCase(name)); } r << QString(" };\n let d_%3 = %1::new(%3_emit%2") .arg(o.name, model, snakeCase(name)); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { r << ",\n d_" << snakeCase(p.name); } } r << ");\n"; } void writeFunction(QTextStream& r, const Function& f, const QString& lcname, const Object& o) { const QString lc(snakeCase(f.name)); r << QString(R"( #[no_mangle] pub extern "C" fn %1_%2(ptr: *%3 %4)").arg(lcname, lc, f.mut ? "mut" : "const", o.name); // write all the input arguments, for QString and QByteArray, write // pointers to their content and the length which is int in Qt for (auto a = f.args.begin(); a < f.args.end(); a++) { r << ", "; if (a->type.name == "QString") { r << QString("%1_str: *const c_ushort, %1_len: c_int").arg(a->name); } else if (a->type.name == "QByteArray") { r << QString("%1_str: *const c_char, %1_len: c_int").arg(a->name); } else { r << a->name << ": " << a->type.rustType; } } // If the return type is QString or QByteArray, append a pointer to the // variable that will be set to the argument list. Also add a setter // function. if (f.type.isComplex()) { r << QString(", d: *mut %1, set: fn(*mut %1, str: *const c_char, len: c_int)) {\n").arg(f.type.name); } else { r << ") -> " << f.type.rustType << " {\n"; } for (auto a = f.args.begin(); a < f.args.end(); a++) { if (a->type.name == "QString") { r << " let mut " << a->name << " = String::new();\n"; r << QString(" set_string_from_utf16(&mut %1, %1_str, %1_len);\n").arg(a->name); } else if (a->type.name == "QByteArray") { r << QString(" let %1 = unsafe { slice::from_raw_parts(%1_str as *const u8, to_usize(%1_len)) };\n").arg(a->name); } } if (f.mut) { r << " let o = unsafe { &mut *ptr };\n"; } else { r << " let o = unsafe { &*ptr };\n"; } r << " let r = o." << lc << "("; for (auto a = f.args.begin(); a < f.args.end(); a++) { if (a != f.args.begin()) { r << ", "; } r << a->name; } r << ");\n"; if (f.type.isComplex()) { r << " let s: *const c_char = r.as_ptr() as (*const c_char);\n"; r << " set(d, s, r.len() as i32);\n"; } else { r << " r\n"; } r << "}\n"; } void writeRustInterfaceObject(QTextStream& r, const Object& o, const Configuration& conf) { const QString lcname(snakeCase(o.name)); r << QString(R"( pub struct %1QObject {} #[derive(Clone)] pub struct %1Emitter { qobject: Arc>, )").arg(o.name); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { continue; } r << QString(" %2_changed: fn(*const %1QObject),\n") .arg(o.name, snakeCase(p.name)); } if (o.type == ObjectType::List) { r << QString(" new_data_ready: fn(*const %1QObject),\n") .arg(o.name); } else if (o.type == ObjectType::Tree) { r << QString(" new_data_ready: fn(*const %1QObject, index: COption),\n") .arg(o.name); } r << QString(R"(} unsafe impl Send for %1Emitter {} impl %1Emitter { fn clear(&self) { *self.qobject.lock().unwrap() = null(); } )").arg(o.name); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { continue; } r << QString(R"( pub fn %1_changed(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.%1_changed)(ptr); } } )").arg(snakeCase(p.name)); } if (o.type == ObjectType::List) { r << R"( pub fn new_data_ready(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.new_data_ready)(ptr); } } )"; } else if (o.type == ObjectType::Tree) { r << R"( pub fn new_data_ready(&self, item: Option) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.new_data_ready)(ptr, item.into()); } } )"; } QString modelStruct = ""; if (o.type != ObjectType::Object) { QString type = o.type == ObjectType::List ? "List" : "Tree"; modelStruct = ", model: " + o.name + type; QString index; QString indexDecl; QString indexCDecl; QString dest; QString destDecl; QString destCDecl; if (o.type == ObjectType::Tree) { indexDecl = " index: Option,"; indexCDecl = " index: COption,"; index = " index.into(),"; destDecl = " dest: Option,"; destCDecl = " dest: COption,"; dest = " dest.into(),"; } r << QString(R"(} #[derive(Clone)] pub struct %1%2 { qobject: *const %1QObject, layout_about_to_be_changed: fn(*const %1QObject), layout_changed: fn(*const %1QObject), data_changed: fn(*const %1QObject, usize, usize), begin_reset_model: fn(*const %1QObject), end_reset_model: fn(*const %1QObject), begin_insert_rows: fn(*const %1QObject,%5 usize, usize), end_insert_rows: fn(*const %1QObject), begin_move_rows: fn(*const %1QObject,%5 usize, usize,%8 usize), end_move_rows: fn(*const %1QObject), begin_remove_rows: fn(*const %1QObject,%5 usize, usize), end_remove_rows: fn(*const %1QObject), } impl %1%2 { pub fn layout_about_to_be_changed(&self) { (self.layout_about_to_be_changed)(self.qobject); } pub fn layout_changed(&self) { (self.layout_changed)(self.qobject); } pub fn data_changed(&self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } pub fn begin_reset_model(&self) { (self.begin_reset_model)(self.qobject); } pub fn end_reset_model(&self) { (self.end_reset_model)(self.qobject); } pub fn begin_insert_rows(&self,%3 first: usize, last: usize) { (self.begin_insert_rows)(self.qobject,%4 first, last); } pub fn end_insert_rows(&self) { (self.end_insert_rows)(self.qobject); } pub fn begin_move_rows(&self,%3 first: usize, last: usize,%6 destination: usize) { (self.begin_move_rows)(self.qobject,%4 first, last,%7 destination); } pub fn end_move_rows(&self) { (self.end_move_rows)(self.qobject); } pub fn begin_remove_rows(&self,%3 first: usize, last: usize) { (self.begin_remove_rows)(self.qobject,%4 first, last); } pub fn end_remove_rows(&self) { (self.end_remove_rows)(self.qobject); } )").arg(o.name, type, indexDecl, index, indexCDecl, destDecl, dest, destCDecl); } r << QString(R"(} pub trait %1Trait { fn new(emit: %1Emitter%2)").arg(o.name, modelStruct); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { r << ",\n " << snakeCase(p.name) << ": " << p.type.name; } } r << QString(R"() -> Self; fn emit(&self) -> &%1Emitter; )").arg(o.name); for (const Property& p: o.properties) { const QString lc(snakeCase(p.name)); if (p.type.type == BindingType::Object) { r << QString(" fn %1(&self) -> &%2;\n").arg(lc, rustType(p)); r << QString(" fn %1_mut(&mut self) -> &mut %2;\n").arg(lc, rustType(p)); } else { if (p.rustByFunction) { r << QString(" fn %1(&self, getter: F) where F: FnOnce(%2);").arg(lc, rustReturnType(p)); } else { r << QString(" fn %1(&self) -> %2;\n").arg(lc, rustReturnType(p)); } if (p.write) { if (p.type.name == "QByteArray") { if (p.optional) { r << QString(" fn set_%1(&mut self, value: Option<&[u8]>);\n").arg(lc); } else { r << QString(" fn set_%1(&mut self, value: &[u8]);\n").arg(lc); } } else { r << QString(" fn set_%1(&mut self, value: %2);\n").arg(lc, rustType(p)); } } } } for (const Function& f: o.functions) { const QString lc(snakeCase(f.name)); QString argList; if (f.args.size() > 0) { for (auto a = f.args.begin(); a < f.args.end(); a++) { auto t = a->type.name == "QByteArray" ?"&[u8]" :a->type.rustType; argList.append(QString(", %1: %2").arg(a->name, t)); } } r << QString(" fn %1(&%2self%4) -> %3;\n") .arg(lc, f.mut ? "mut " : "", f.type.rustType, argList); } if (o.type == ObjectType::List) { r << R"( fn row_count(&self) -> usize; fn insert_rows(&mut self, _row: usize, _count: usize) -> bool { false } fn remove_rows(&mut self, _row: usize, _count: usize) -> bool { false } fn can_fetch_more(&self) -> bool { false } fn fetch_more(&mut self) {} fn sort(&mut self, u8, SortOrder) {} )"; } else if (o.type == ObjectType::Tree) { r << R"( fn row_count(&self, Option) -> usize; fn can_fetch_more(&self, Option) -> bool { false } fn fetch_more(&mut self, Option) {} fn sort(&mut self, u8, SortOrder) {} + fn check_row(&self, index: usize, row: usize) -> Option; fn index(&self, item: Option, row: usize) -> usize; fn parent(&self, index: usize) -> Option; fn row(&self, index: usize) -> usize; )"; } if (o.type != ObjectType::Object) { for (auto ip: o.itemProperties) { r << QString(" fn %1(&self, index: usize) -> %2;\n") .arg(snakeCase(ip.name), rustReturnType(ip)); if (ip.write) { if (ip.type.name == "QByteArray") { if (ip.optional) { r << QString(" fn set_%1(&mut self, index: usize, Option<&[u8]>) -> bool;\n") .arg(snakeCase(ip.name)); } else { r << QString(" fn set_%1(&mut self, index: usize, &[u8]) -> bool;\n") .arg(snakeCase(ip.name)); } } else { r << QString(" fn set_%1(&mut self, index: usize, %2) -> bool;\n") .arg(snakeCase(ip.name), rustType(ip)); } } } } r << QString(R"(} #[no_mangle] pub extern "C" fn %1_new( )").arg(lcname); rConstructorArgsDecl(r, lcname, o, conf); r << QString(",\n) -> *mut %1 {\n").arg(o.name); rConstructorArgs(r, lcname, o, conf); r << QString(R"( Box::into_raw(Box::new(d_%2)) } #[no_mangle] pub unsafe extern "C" fn %2_free(ptr: *mut %1) { Box::from_raw(ptr).emit().clear(); } )").arg(o.name, lcname); for (const Property& p: o.properties) { const QString base = QString("%1_%2").arg(lcname, snakeCase(p.name)); QString ret = ") -> " + rustType(p); if (p.type.type == BindingType::Object) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_get(ptr: *mut %1) -> *mut %4 { (&mut *ptr).%3_mut() } )").arg(o.name, base, snakeCase(p.name), rustType(p)); } else if (p.type.isComplex() && !p.optional) { if (p.rustByFunction) { r << QString(R"( #[no_mangle] pub extern "C" fn %2_get( ptr: *const %1, p: *mut %4, set: fn(*mut %4, *const c_char, c_int), ) { let o = unsafe { &*ptr }; o.%3(|v| { let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, to_c_int(v.len())); }); } )").arg(o.name, base, snakeCase(p.name), p.type.name); } else { r << QString(R"( #[no_mangle] pub extern "C" fn %2_get( ptr: *const %1, p: *mut %4, set: fn(*mut %4, *const c_char, c_int), ) { let o = unsafe { &*ptr }; let v = o.%3(); let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, to_c_int(v.len())); } )").arg(o.name, base, snakeCase(p.name), p.type.name); } if (p.write && p.type.name == "QString") { r << QString(R"( #[no_mangle] pub extern "C" fn %2_set(ptr: *mut %1, v: *const c_ushort, len: c_int) { let o = unsafe { &mut *ptr }; let mut s = String::new(); set_string_from_utf16(&mut s, v, len); o.set_%3(s); } )").arg(o.name, base, snakeCase(p.name)); } else if (p.write) { r << QString(R"( #[no_mangle] pub extern "C" fn %2_set(ptr: *mut %1, v: *const c_char, len: c_int) { let o = unsafe { &mut *ptr }; let v = unsafe { slice::from_raw_parts(v as *const u8, to_usize(len)) }; o.set_%3(v); } )").arg(o.name, base, snakeCase(p.name)); } } else if (p.type.isComplex()) { r << QString(R"( #[no_mangle] pub extern "C" fn %2_get( ptr: *const %1, p: *mut %4, set: fn(*mut %4, *const c_char, c_int), ) { let o = unsafe { &*ptr }; let v = o.%3(); 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())); } } )").arg(o.name, base, snakeCase(p.name), p.type.name); if (p.write && p.type.name == "QString") { r << QString(R"( #[no_mangle] pub extern "C" fn %2_set(ptr: *mut %1, v: *const c_ushort, len: c_int) { let o = unsafe { &mut *ptr }; let mut s = String::new(); set_string_from_utf16(&mut s, v, len); o.set_%3(Some(s)); } )").arg(o.name, base, snakeCase(p.name)); } else if (p.write) { r << QString(R"( #[no_mangle] pub extern "C" fn %2_set(ptr: *mut %1, v: *const c_char, len: c_int) { let o = unsafe { &mut *ptr }; let v = unsafe { slice::from_raw_parts(v as *const u8, to_usize(len)) }; o.set_%3(Some(v.into())); } )").arg(o.name, base, snakeCase(p.name)); } } else if (p.optional) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_get(ptr: *const %1) -> COption<%4> { match (&*ptr).%3() { Some(value) => COption { data: value, some: true }, None => COption { data: %4::default(), some: false} } } )").arg(o.name, base, snakeCase(p.name), p.type.rustType); if (p.write) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_set(ptr: *mut %1, v: %4) { (&mut *ptr).set_%3(Some(v)); } )").arg(o.name, base, snakeCase(p.name), p.type.rustType); } } else { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_get(ptr: *const %1) -> %4 { (&*ptr).%3() } )").arg(o.name, base, snakeCase(p.name), rustType(p)); if (p.write) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_set(ptr: *mut %1, v: %4) { (&mut *ptr).set_%3(v); } )").arg(o.name, base, snakeCase(p.name), rustType(p)); } } if (p.write && p.optional) { r << QString(R"( #[no_mangle] pub extern "C" fn %2_set_none(ptr: *mut %1) { let o = unsafe { &mut *ptr }; o.set_%3(None); } )").arg(o.name, base, snakeCase(p.name)); } } for (const Function& f: o.functions) { writeFunction(r, f, lcname, o); } if (o.type == ObjectType::List) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_row_count(ptr: *const %1) -> c_int { to_c_int((&*ptr).row_count()) } #[no_mangle] pub unsafe extern "C" fn %2_insert_rows(ptr: *mut %1, row: c_int, count: c_int) -> bool { (&mut *ptr).insert_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn %2_remove_rows(ptr: *mut %1, row: c_int, count: c_int) -> bool { (&mut *ptr).remove_rows(to_usize(row), to_usize(count)) } #[no_mangle] pub unsafe extern "C" fn %2_can_fetch_more(ptr: *const %1) -> bool { (&*ptr).can_fetch_more() } #[no_mangle] pub unsafe extern "C" fn %2_fetch_more(ptr: *mut %1) { (&mut *ptr).fetch_more() } #[no_mangle] pub unsafe extern "C" fn %2_sort( ptr: *mut %1, column: u8, order: SortOrder, ) { (&mut *ptr).sort(column, order) } )").arg(o.name, lcname); } else if (o.type == ObjectType::Tree) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_row_count( ptr: *const %1, index: COption, ) -> c_int { to_c_int((&*ptr).row_count(index.into())) } #[no_mangle] pub unsafe extern "C" fn %2_can_fetch_more( ptr: *const %1, index: COption, ) -> bool { (&*ptr).can_fetch_more(index.into()) } #[no_mangle] pub unsafe extern "C" fn %2_fetch_more(ptr: *mut %1, index: COption) { (&mut *ptr).fetch_more(index.into()) } #[no_mangle] pub unsafe extern "C" fn %2_sort( ptr: *mut %1, column: u8, order: SortOrder ) { (&mut *ptr).sort(column, order) } #[no_mangle] +pub unsafe extern "C" fn %2_check_row( + ptr: *const %1, + index: usize, + row: c_int, +) -> COption { + (&*ptr).check_row(index.into(), to_usize(row)).into() +} +#[no_mangle] pub unsafe extern "C" fn %2_index( ptr: *const %1, index: COption, row: c_int, ) -> usize { (&*ptr).index(index.into(), to_usize(row)) } #[no_mangle] pub unsafe extern "C" fn %2_parent(ptr: *const %1, 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 %2_row(ptr: *const %1, index: usize) -> c_int { to_c_int((&*ptr).row(index)) } )").arg(o.name, lcname); } if (o.type != ObjectType::Object) { QString indexDecl = ", row: c_int"; QString index = "to_usize(row)"; if (o.type == ObjectType::Tree) { indexDecl = ", index: usize"; index = "index"; } for (auto ip: o.itemProperties) { if (ip.type.isComplex() && !ip.optional) { r << QString(R"( #[no_mangle] pub extern "C" fn %2_data_%3( ptr: *const %1%4, d: *mut %6, set: fn(*mut %6, *const c_char, len: c_int), ) { let o = unsafe { &*ptr }; let data = o.%3(%5); let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, to_c_int(data.len())); } )").arg(o.name, lcname, snakeCase(ip.name), indexDecl, index, ip.type.name); } else if (ip.type.isComplex()) { r << QString(R"( #[no_mangle] pub extern "C" fn %2_data_%3( ptr: *const %1%4, d: *mut %6, set: fn(*mut %6, *const c_char, len: c_int), ) { let o = unsafe { &*ptr }; let data = o.%3(%5); 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())); } } )").arg(o.name, lcname, snakeCase(ip.name), indexDecl, index, ip.type.name); } else { r << QString(R"( #[no_mangle] pub extern "C" fn %2_data_%3(ptr: *const %1%5) -> %4 { let o = unsafe { &*ptr }; o.%3(%6).into() } )").arg(o.name, lcname, snakeCase(ip.name), rustCType(ip), indexDecl, index); } if (ip.write) { QString val = "v"; if (ip.optional) { val = "Some(" + val + ")"; } if (ip.type.name == "QString") { r << QString(R"( #[no_mangle] pub extern "C" fn %2_set_data_%3( ptr: *mut %1%4, s: *const c_ushort, len: c_int, ) -> bool { let o = unsafe { &mut *ptr }; let mut v = String::new(); set_string_from_utf16(&mut v, s, len); o.set_%3(%5, %6) } )").arg(o.name, lcname, snakeCase(ip.name), indexDecl, index, val); } else if (ip.type.name == "QByteArray") { r << QString(R"( #[no_mangle] pub extern "C" fn %2_set_data_%3( ptr: *mut %1%4, s: *const c_char, len: c_int, ) -> bool { let o = unsafe { &mut *ptr }; let slice = unsafe { ::std::slice::from_raw_parts(s as *const u8, to_usize(len)) }; o.set_%3(%5, %6) } )").arg(o.name, lcname, snakeCase(ip.name), indexDecl, index, ip.optional ?"Some(slice)" :"slice"); } else { const QString type = ip.type.rustType; r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_set_data_%3( ptr: *mut %1%4, v: %6, ) -> bool { (&mut *ptr).set_%3(%5, %7) } )").arg(o.name, lcname, snakeCase(ip.name), indexDecl, index, type, val); } } if (ip.write && ip.optional) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_set_data_%3_none(ptr: *mut %1%4) -> bool { (&mut *ptr).set_%3(%5, None) } )").arg(o.name, lcname, snakeCase(ip.name), indexDecl, index); } } } } QString rustFile(const QDir rustdir, const QString& module) { QDir src(rustdir.absoluteFilePath("src")); QString modulePath = src.absoluteFilePath(module + "/mod.rs"); if (QFile::exists(modulePath)) { return modulePath; } return src.absoluteFilePath(module + ".rs"); } void writeRustTypes(const Configuration& conf, QTextStream& r) { bool hasOption = false; bool hasString = false; bool hasByteArray = false; bool hasListOrTree = false; for (auto o: conf.objects) { hasListOrTree |= o.type != ObjectType::Object; for (auto p: o.properties) { hasOption |= p.optional; hasString |= p.type.type == BindingType::QString; hasByteArray |= p.type.type == BindingType::QByteArray; } for (auto p: o.itemProperties) { hasOption |= p.optional; hasString |= p.type.type == BindingType::QString; hasByteArray |= p.type.type == BindingType::QByteArray; } for (auto f: o.functions) { hasString |= f.type.type == BindingType::QString; hasByteArray |= f.type.type == BindingType::QByteArray; for (auto a: f.args) { hasString |= a.type.type == BindingType::QString; hasByteArray |= a.type.type == BindingType::QByteArray; } } } if (hasOption || hasListOrTree) { r << R"( #[repr(C)] pub struct COption { data: T, some: bool, } impl COption { #![allow(dead_code)] fn into(self) -> Option { if self.some { Some(self.data) } else { None } } } impl From> for COption where T: Default, { fn from(t: Option) -> COption { if let Some(v) = t { COption { data: v, some: true, } } else { COption { data: T::default(), some: false, } } } } )"; } if (hasString) { r << R"( pub enum QString {} fn set_string_from_utf16(s: &mut String, str: *const c_ushort, len: c_int) { let utf16 = unsafe { slice::from_raw_parts(str, to_usize(len)) }; let characters = decode_utf16(utf16.iter().cloned()) .into_iter() .map(|r| r.unwrap()); s.clear(); s.extend(characters); } )"; } if (hasByteArray) { r << R"( pub enum QByteArray {} )"; } if (hasListOrTree) { r << R"( #[repr(C)] #[derive(PartialEq, Eq, Debug)] pub enum SortOrder { Ascending = 0, Descending = 1, } #[repr(C)] pub struct QModelIndex { row: c_int, internal_id: usize, } )"; } if (hasString || hasByteArray || hasListOrTree) { r << R"( fn to_usize(n: c_int) -> usize { if n < 0 { panic!("Cannot cast {} to usize", n); } n as usize } )"; } if (hasString || hasByteArray || hasListOrTree) { r << R"( fn to_c_int(n: usize) -> c_int { if n > c_int::max_value() as usize { panic!("Cannot cast {} to c_int", n); } n as c_int } )"; } } void writeRustInterface(const Configuration& conf) { DifferentFileWriter w(rustFile(conf.rustdir, conf.interfaceModule)); QTextStream r(&w.buffer); r << QString(R"(/* 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::ptr::null; use %1::*; )").arg(conf.implementationModule); writeRustTypes(conf, r); for (auto object: conf.objects) { writeRustInterfaceObject(r, object, conf); } } void writeRustImplementationObject(QTextStream& r, const Object& o) { const QString lcname(snakeCase(o.name)); if (o.type != ObjectType::Object) { r << "#[derive(Default, Clone)]\n"; r << QString("struct %1Item {\n").arg(o.name); for (auto ip: o.itemProperties) { const QString lc(snakeCase(ip.name)); r << QString(" %1: %2,\n").arg(lc, ip.type.rustType); } r << "}\n\n"; } QString modelStruct = ""; r << QString("pub struct %1 {\n emit: %1Emitter,\n").arg((o.name)); if (o.type == ObjectType::List) { modelStruct = ", model: " + o.name + "List"; r << QString(" model: %1List,\n").arg(o.name); } else if (o.type == ObjectType::Tree) { modelStruct = ", model: " + o.name + "Tree"; r << QString(" model: %1Tree,\n").arg(o.name); } for (const Property& p: o.properties) { const QString lc(snakeCase(p.name)); r << QString(" %1: %2,\n").arg(lc, rustType(p)); } if (o.type != ObjectType::Object) { r << QString(" list: Vec<%1Item>,\n").arg(o.name); } r << "}\n\n"; for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { modelStruct += ", " + p.name + ": " + p.type.name; } } r << QString(R"(impl %1Trait for %1 { fn new(emit: %1Emitter%2) -> %1 { %1 { emit: emit, )").arg(o.name, modelStruct); if (o.type != ObjectType::Object) { r << QString(" model: model,\n"); } for (const Property& p: o.properties) { const QString lc(snakeCase(p.name)); if (p.type.type == BindingType::Object) { r << QString(" %1: %1,\n").arg(lc); } else { r << QString(" %1: %2,\n").arg(lc, rustTypeInit(p)); } } r << QString(R"( } } fn emit(&self) -> &%1Emitter { &self.emit } )").arg(o.name); for (const Property& p: o.properties) { const QString lc(snakeCase(p.name)); if (p.type.type == BindingType::Object) { r << QString(R"( fn %1(&self) -> &%2 { &self.%1 } fn %1_mut(&mut self) -> &mut %2 { &mut self.%1 } )").arg(lc, rustReturnType(p)); } else { r << QString(" fn %1(&self) -> %2 {\n").arg(lc, rustReturnType(p)); if (p.type.isComplex()) { if (p.optional) { /* if (rustType(p) == "Option") { r << QString(" self.%1.as_ref().map(|p|p.as_str())\n").arg(lc); } else { } */ r << QString(" self.%1.as_ref().map(|p|&p[..])\n").arg(lc); } else { r << QString(" &self.%1\n").arg(lc); } } else { r << QString(" self.%1\n").arg(lc); } r << " }\n"; if (p.write) { r << QString(R"( fn set_%1(&mut self, value: %2) { self.%1 = value; self.emit.%1_changed(); } )").arg(lc, rustType(p)); } } } if (o.type == ObjectType::List) { r << " fn row_count(&self) -> usize {\n self.list.len()\n }\n"; } else if (o.type == ObjectType::Tree) { r << R"( fn row_count(&self, item: Option) -> usize { self.list.len() } fn index(&self, item: Option, row: usize) -> usize { 0 } fn parent(&self, index: usize) -> Option { None } fn row(&self, index: usize) -> usize { item } )"; } if (o.type != ObjectType::Object) { QString index; if (o.type == ObjectType::Tree) { index = ", index: usize"; } for (auto ip: o.itemProperties) { const QString lc(snakeCase(ip.name)); r << QString(" fn %1(&self, index: usize) -> %2 {\n") .arg(lc, rustReturnType(ip)); if (ip.type.isComplex()) { r << " &self.list[index]." << lc << "\n"; } else { r << " self.list[index]." << lc << "\n"; } r << " }\n"; if (ip.write) { r << QString(" fn set_%1(&mut self, index: usize, v: %2) -> bool {\n") .arg(snakeCase(ip.name), rustType(ip)); r << " self.list[index]." << lc << " = v;\n"; r << " true\n"; r << " }\n"; } } } r << "}\n\n"; } void writeRustImplementation(const Configuration& conf) { DifferentFileWriter w(rustFile(conf.rustdir, conf.implementationModule), conf.overwriteImplementation); QTextStream r(&w.buffer); r << QString(R"(#![allow(unused_imports)] #![allow(unused_variables)] #![allow(dead_code)] use %1::*; )").arg(conf.interfaceModule); for (auto object: conf.objects) { writeRustImplementationObject(r, object); } } diff --git a/tests/rust_tree/src/implementation.rs b/tests/rust_tree/src/implementation.rs index 47c1c9b..09d4f4f 100644 --- a/tests/rust_tree/src/implementation.rs +++ b/tests/rust_tree/src/implementation.rs @@ -1,48 +1,55 @@ #![allow(unused_imports)] #![allow(unused_variables)] #![allow(dead_code)] use interface::*; #[derive(Default, Clone)] struct PersonsItem { user_name: String, } pub struct Persons { emit: PersonsEmitter, model: PersonsTree, list: Vec, } impl PersonsTrait for Persons { fn new(emit: PersonsEmitter, model: PersonsTree) -> Persons { Persons { emit: emit, model: model, list: vec![PersonsItem::default(); 10], } } fn emit(&self) -> &PersonsEmitter { &self.emit } fn row_count(&self, index: Option) -> usize { self.list.len() } fn index(&self, index: Option, row: usize) -> usize { 0 } fn parent(&self, index: usize) -> Option { None } fn row(&self, index: usize) -> usize { index } + fn check_row(&self, index: usize, _row: usize) -> Option { + if index < self.list.len() { + Some(index) + } else { + None + } + } fn user_name(&self, index: usize) -> &str { &self.list[index].user_name } fn set_user_name(&mut self, index: usize, v: String) -> bool { self.list[index].user_name = v; true } } diff --git a/tests/rust_tree/src/interface.rs b/tests/rust_tree/src/interface.rs index e2c0b2b..d32faa8 100644 --- a/tests/rust_tree/src/interface.rs +++ b/tests/rust_tree/src/interface.rs @@ -1,301 +1,310 @@ /* 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::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 PersonsQObject {} #[derive(Clone)] pub struct PersonsEmitter { qobject: Arc>, new_data_ready: fn(*const PersonsQObject, index: COption), } unsafe impl Send for PersonsEmitter {} impl PersonsEmitter { fn clear(&self) { *self.qobject.lock().unwrap() = null(); } pub fn new_data_ready(&self, item: Option) { let ptr = *self.qobject.lock().unwrap(); 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), } impl PersonsTree { pub fn layout_about_to_be_changed(&self) { (self.layout_about_to_be_changed)(self.qobject); } pub fn layout_changed(&self) { (self.layout_changed)(self.qobject); } pub fn data_changed(&self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } pub fn begin_reset_model(&self) { (self.begin_reset_model)(self.qobject); } pub fn end_reset_model(&self) { (self.end_reset_model)(self.qobject); } pub fn begin_insert_rows(&self, index: Option, first: usize, last: usize) { (self.begin_insert_rows)(self.qobject, index.into(), first, last); } pub fn end_insert_rows(&self) { (self.end_insert_rows)(self.qobject); } pub fn begin_move_rows(&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) { (self.end_move_rows)(self.qobject); } pub fn begin_remove_rows(&self, index: Option, first: usize, last: usize) { (self.begin_remove_rows)(self.qobject, index.into(), first, last); } pub fn end_remove_rows(&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), ) -> *mut Persons { let persons_emit = PersonsEmitter { qobject: Arc::new(Mutex::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 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 = unsafe { &*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 extern "C" fn persons_set_data_user_name( ptr: *mut Persons, index: usize, s: *const c_ushort, len: c_int, ) -> bool { let o = unsafe { &mut *ptr }; let mut v = String::new(); set_string_from_utf16(&mut v, s, len); o.set_user_name(index, v) } diff --git a/tests/test_list_rust.cpp b/tests/test_list_rust.cpp index 9d8e4b6..758e5fd 100644 --- a/tests/test_list_rust.cpp +++ b/tests/test_list_rust.cpp @@ -1,522 +1,526 @@ /* generated by rust_qt_binding_generator */ #include "test_list_rust.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; } } extern "C" { quint8 no_role_data_user_age(const NoRole::Private*, int); bool no_role_set_data_user_age(NoRole::Private*, int, quint8); void no_role_data_user_name(const NoRole::Private*, int, QString*, qstring_set); bool no_role_set_data_user_name(NoRole::Private*, int, const ushort* s, int len); void no_role_sort(NoRole::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int no_role_row_count(const NoRole::Private*); bool no_role_insert_rows(NoRole::Private*, int, int); bool no_role_remove_rows(NoRole::Private*, int, int); bool no_role_can_fetch_more(const NoRole::Private*); void no_role_fetch_more(NoRole::Private*); } int NoRole::columnCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : 1; } bool NoRole::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int NoRole::rowCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : no_role_row_count(m_d); } bool NoRole::insertRows(int row, int count, const QModelIndex &) { return no_role_insert_rows(m_d, row, count); } bool NoRole::removeRows(int row, int count, const QModelIndex &) { return no_role_remove_rows(m_d, row, count); } QModelIndex NoRole::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 NoRole::parent(const QModelIndex &) const { return QModelIndex(); } bool NoRole::canFetchMore(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : no_role_can_fetch_more(m_d); } void NoRole::fetchMore(const QModelIndex &parent) { if (!parent.isValid()) { no_role_fetch_more(m_d); } } +void NoRole::updatePersistentIndexes() {} void NoRole::sort(int column, Qt::SortOrder order) { no_role_sort(m_d, column, order); } Qt::ItemFlags NoRole::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); if (i.column() == 0) { flags |= Qt::ItemIsEditable; } return flags; } quint8 NoRole::userAge(int row) const { return no_role_data_user_age(m_d, row); } bool NoRole::setUserAge(int row, quint8 value) { bool set = false; set = no_role_set_data_user_age(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QString NoRole::userName(int row) const { QString s; no_role_data_user_name(m_d, row, &s, set_qstring); return s; } bool NoRole::setUserName(int row, const QString& value) { bool set = false; set = no_role_set_data_user_name(m_d, row, value.utf16(), value.length()); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QVariant NoRole::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(userAge(index.row())); case Qt::UserRole + 1: return QVariant::fromValue(userName(index.row())); } } return QVariant(); } int NoRole::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 NoRole::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "userAge"); names.insert(Qt::UserRole + 1, "userName"); return names; } QVariant NoRole::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 NoRole::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 NoRole::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.column() == 0) { if (role == Qt::UserRole + 0) { if (value.canConvert(qMetaTypeId())) { return setUserAge(index.row(), value.value()); } } if (role == Qt::UserRole + 1) { if (value.canConvert(qMetaTypeId())) { return setUserName(index.row(), value.value()); } } } return false; } extern "C" { NoRole::Private* no_role_new(NoRole*, void (*)(const NoRole*), void (*)(NoRole*), void (*)(NoRole*), void (*)(NoRole*, quintptr, quintptr), void (*)(NoRole*), void (*)(NoRole*), void (*)(NoRole*, int, int), void (*)(NoRole*), void (*)(NoRole*, int, int, int), void (*)(NoRole*), void (*)(NoRole*, int, int), void (*)(NoRole*)); void no_role_free(NoRole::Private*); }; extern "C" { void persons_data_user_name(const Persons::Private*, int, QString*, qstring_set); bool persons_set_data_user_name(Persons::Private*, int, const ushort* s, int len); void persons_sort(Persons::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int persons_row_count(const Persons::Private*); bool persons_insert_rows(Persons::Private*, int, int); bool persons_remove_rows(Persons::Private*, int, int); bool persons_can_fetch_more(const Persons::Private*); void persons_fetch_more(Persons::Private*); } int Persons::columnCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : 1; } bool Persons::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int Persons::rowCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : persons_row_count(m_d); } bool Persons::insertRows(int row, int count, const QModelIndex &) { return persons_insert_rows(m_d, row, count); } bool Persons::removeRows(int row, int count, const QModelIndex &) { return persons_remove_rows(m_d, row, count); } QModelIndex Persons::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 Persons::parent(const QModelIndex &) const { return QModelIndex(); } bool Persons::canFetchMore(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : persons_can_fetch_more(m_d); } void Persons::fetchMore(const QModelIndex &parent) { if (!parent.isValid()) { persons_fetch_more(m_d); } } +void Persons::updatePersistentIndexes() {} void Persons::sort(int column, Qt::SortOrder order) { persons_sort(m_d, column, order); } Qt::ItemFlags Persons::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); if (i.column() == 0) { flags |= Qt::ItemIsEditable; } return flags; } QString Persons::userName(int row) const { QString s; persons_data_user_name(m_d, row, &s, set_qstring); return s; } bool Persons::setUserName(int row, const QString& value) { bool set = false; set = persons_set_data_user_name(m_d, row, value.utf16(), value.length()); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QVariant Persons::data(const QModelIndex &index, int role) const { Q_ASSERT(rowCount(index.parent()) > index.row()); switch (index.column()) { case 0: switch (role) { case Qt::DisplayRole: case Qt::EditRole: case Qt::UserRole + 0: return QVariant::fromValue(userName(index.row())); } } return QVariant(); } int Persons::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 Persons::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "userName"); return names; } QVariant Persons::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 Persons::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 Persons::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.column() == 0) { if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole + 0) { if (value.canConvert(qMetaTypeId())) { return setUserName(index.row(), value.value()); } } } return false; } extern "C" { Persons::Private* persons_new(Persons*, void (*)(const Persons*), void (*)(Persons*), void (*)(Persons*), void (*)(Persons*, quintptr, quintptr), void (*)(Persons*), void (*)(Persons*), void (*)(Persons*, int, int), void (*)(Persons*), void (*)(Persons*, int, int, int), void (*)(Persons*), void (*)(Persons*, int, int), void (*)(Persons*)); void persons_free(Persons::Private*); }; NoRole::NoRole(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } NoRole::NoRole(QObject *parent): QAbstractItemModel(parent), m_d(no_role_new(this, [](const NoRole* o) { emit o->newDataReady(QModelIndex()); }, [](NoRole* o) { emit o->layoutAboutToBeChanged(); }, [](NoRole* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](NoRole* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, 0, last)); }, [](NoRole* o) { o->beginResetModel(); }, [](NoRole* o) { o->endResetModel(); }, [](NoRole* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](NoRole* o) { o->endInsertRows(); }, [](NoRole* o, int first, int last, int destination) { o->beginMoveRows(QModelIndex(), first, last, QModelIndex(), destination); }, [](NoRole* o) { o->endMoveRows(); }, [](NoRole* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](NoRole* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &NoRole::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } NoRole::~NoRole() { if (m_ownsPrivate) { no_role_free(m_d); } } void NoRole::initHeaderData() { } Persons::Persons(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } Persons::Persons(QObject *parent): QAbstractItemModel(parent), m_d(persons_new(this, [](const Persons* o) { emit o->newDataReady(QModelIndex()); }, [](Persons* o) { emit o->layoutAboutToBeChanged(); }, [](Persons* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](Persons* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, 0, last)); }, [](Persons* o) { o->beginResetModel(); }, [](Persons* o) { o->endResetModel(); }, [](Persons* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](Persons* o) { o->endInsertRows(); }, [](Persons* o, int first, int last, int destination) { o->beginMoveRows(QModelIndex(), first, last, QModelIndex(), destination); }, [](Persons* o) { o->endMoveRows(); }, [](Persons* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](Persons* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &Persons::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } Persons::~Persons() { if (m_ownsPrivate) { persons_free(m_d); } } void Persons::initHeaderData() { m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("userName")); } diff --git a/tests/test_list_rust.h b/tests/test_list_rust.h index 6088a66..cc1e99e 100644 --- a/tests/test_list_rust.h +++ b/tests/test_list_rust.h @@ -1,96 +1,98 @@ /* generated by rust_qt_binding_generator */ #ifndef TEST_LIST_RUST_H #define TEST_LIST_RUST_H #include #include class NoRole; class Persons; class NoRole : public QAbstractItemModel { Q_OBJECT public: class Private; private: Private * m_d; bool m_ownsPrivate; explicit NoRole(bool owned, QObject *parent); public: explicit NoRole(QObject *parent = nullptr); ~NoRole(); 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 quint8 userAge(int row) const; Q_INVOKABLE bool setUserAge(int row, quint8 value); Q_INVOKABLE QString userName(int row) const; Q_INVOKABLE bool setUserName(int row, const QString& value); signals: // new data is ready to be made available to the model with fetchMore() void newDataReady(const QModelIndex &parent) const; private: QHash, QVariant> m_headerData; void initHeaderData(); + void updatePersistentIndexes(); signals: }; class Persons : public QAbstractItemModel { Q_OBJECT public: class Private; private: Private * m_d; bool m_ownsPrivate; explicit Persons(bool owned, QObject *parent); public: explicit Persons(QObject *parent = nullptr); ~Persons(); 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 QString userName(int row) const; Q_INVOKABLE bool setUserName(int row, const QString& value); signals: // new data is ready to be made available to the model with fetchMore() void newDataReady(const QModelIndex &parent) const; private: QHash, QVariant> m_headerData; void initHeaderData(); + void updatePersistentIndexes(); signals: }; #endif // TEST_LIST_RUST_H diff --git a/tests/test_list_types_rust.cpp b/tests/test_list_types_rust.cpp index cd36f88..d202492 100644 --- a/tests/test_list_types_rust.cpp +++ b/tests/test_list_types_rust.cpp @@ -1,702 +1,704 @@ /* generated by rust_qt_binding_generator */ #include "test_list_types_rust.h" namespace { struct option_bool { public: bool value; bool some; operator QVariant() const { if (some) { return QVariant::fromValue(value); } return QVariant(); } }; static_assert(std::is_pod::value, "option_bool must be a POD type."); 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); } typedef void (*qbytearray_set)(QByteArray* val, const char* bytes, int nbytes); void set_qbytearray(QByteArray* v, const char* bytes, int nbytes) { if (v->isNull() && nbytes == 0) { *v = QByteArray(bytes, nbytes); } else { v->truncate(0); v->append(bytes, nbytes); } } struct qmodelindex_t { int row; quintptr id; }; inline QVariant cleanNullQVariant(const QVariant& v) { return (v.isNull()) ?QVariant() :v; } } extern "C" { bool list_data_boolean(const List::Private*, int); bool list_set_data_boolean(List::Private*, int, bool); void list_data_bytearray(const List::Private*, int, QByteArray*, qbytearray_set); bool list_set_data_bytearray(List::Private*, int, const char* s, int len); float list_data_f32(const List::Private*, int); bool list_set_data_f32(List::Private*, int, float); double list_data_f64(const List::Private*, int); bool list_set_data_f64(List::Private*, int, double); qint16 list_data_i16(const List::Private*, int); bool list_set_data_i16(List::Private*, int, qint16); qint32 list_data_i32(const List::Private*, int); bool list_set_data_i32(List::Private*, int, qint32); qint64 list_data_i64(const List::Private*, int); bool list_set_data_i64(List::Private*, int, qint64); qint8 list_data_i8(const List::Private*, int); bool list_set_data_i8(List::Private*, int, qint8); option_bool list_data_optional_boolean(const List::Private*, int); bool list_set_data_optional_boolean(List::Private*, int, bool); bool list_set_data_optional_boolean_none(List::Private*, int); void list_data_optional_bytearray(const List::Private*, int, QByteArray*, qbytearray_set); bool list_set_data_optional_bytearray(List::Private*, int, const char* s, int len); bool list_set_data_optional_bytearray_none(List::Private*, int); void list_data_optional_string(const List::Private*, int, QString*, qstring_set); bool list_set_data_optional_string(List::Private*, int, const ushort* s, int len); bool list_set_data_optional_string_none(List::Private*, int); void list_data_string(const List::Private*, int, QString*, qstring_set); bool list_set_data_string(List::Private*, int, const ushort* s, int len); quint16 list_data_u16(const List::Private*, int); bool list_set_data_u16(List::Private*, int, quint16); quint32 list_data_u32(const List::Private*, int); bool list_set_data_u32(List::Private*, int, quint32); quint64 list_data_u64(const List::Private*, int); bool list_set_data_u64(List::Private*, int, quint64); quint8 list_data_u8(const List::Private*, int); bool list_set_data_u8(List::Private*, int, quint8); void list_sort(List::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int list_row_count(const List::Private*); bool list_insert_rows(List::Private*, int, int); bool list_remove_rows(List::Private*, int, int); bool list_can_fetch_more(const List::Private*); void list_fetch_more(List::Private*); } int List::columnCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : 1; } bool List::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int List::rowCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : list_row_count(m_d); } bool List::insertRows(int row, int count, const QModelIndex &) { return list_insert_rows(m_d, row, count); } bool List::removeRows(int row, int count, const QModelIndex &) { return list_remove_rows(m_d, row, count); } QModelIndex List::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 List::parent(const QModelIndex &) const { return QModelIndex(); } bool List::canFetchMore(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : list_can_fetch_more(m_d); } void List::fetchMore(const QModelIndex &parent) { if (!parent.isValid()) { list_fetch_more(m_d); } } +void List::updatePersistentIndexes() {} void List::sort(int column, Qt::SortOrder order) { list_sort(m_d, column, order); } Qt::ItemFlags List::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); if (i.column() == 0) { flags |= Qt::ItemIsEditable; } return flags; } bool List::boolean(int row) const { return list_data_boolean(m_d, row); } bool List::setBoolean(int row, bool value) { bool set = false; set = list_set_data_boolean(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QByteArray List::bytearray(int row) const { QByteArray b; list_data_bytearray(m_d, row, &b, set_qbytearray); return b; } bool List::setBytearray(int row, const QByteArray& value) { bool set = false; set = list_set_data_bytearray(m_d, row, value.data(), value.length()); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } float List::f32(int row) const { return list_data_f32(m_d, row); } bool List::setF32(int row, float value) { bool set = false; set = list_set_data_f32(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } double List::f64(int row) const { return list_data_f64(m_d, row); } bool List::setF64(int row, double value) { bool set = false; set = list_set_data_f64(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } qint16 List::i16(int row) const { return list_data_i16(m_d, row); } bool List::setI16(int row, qint16 value) { bool set = false; set = list_set_data_i16(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } qint32 List::i32(int row) const { return list_data_i32(m_d, row); } bool List::setI32(int row, qint32 value) { bool set = false; set = list_set_data_i32(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } qint64 List::i64(int row) const { return list_data_i64(m_d, row); } bool List::setI64(int row, qint64 value) { bool set = false; set = list_set_data_i64(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } qint8 List::i8(int row) const { return list_data_i8(m_d, row); } bool List::setI8(int row, qint8 value) { bool set = false; set = list_set_data_i8(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QVariant List::optionalBoolean(int row) const { QVariant v; v = list_data_optional_boolean(m_d, row); return v; } bool List::setOptionalBoolean(int row, const QVariant& value) { bool set = false; if (value.isNull() || !value.isValid()) { set = list_set_data_optional_boolean_none(m_d, row); } else { if (!value.canConvert(qMetaTypeId())) { return false; } set = list_set_data_optional_boolean(m_d, row, value.value()); } if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QByteArray List::optionalBytearray(int row) const { QByteArray b; list_data_optional_bytearray(m_d, row, &b, set_qbytearray); return b; } bool List::setOptionalBytearray(int row, const QByteArray& value) { bool set = false; if (value.isNull()) { set = list_set_data_optional_bytearray_none(m_d, row); } else { set = list_set_data_optional_bytearray(m_d, row, value.data(), value.length()); } if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QString List::optionalString(int row) const { QString s; list_data_optional_string(m_d, row, &s, set_qstring); return s; } bool List::setOptionalString(int row, const QString& value) { bool set = false; if (value.isNull()) { set = list_set_data_optional_string_none(m_d, row); } else { set = list_set_data_optional_string(m_d, row, value.utf16(), value.length()); } if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QString List::string(int row) const { QString s; list_data_string(m_d, row, &s, set_qstring); return s; } bool List::setString(int row, const QString& value) { bool set = false; set = list_set_data_string(m_d, row, value.utf16(), value.length()); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } quint16 List::u16(int row) const { return list_data_u16(m_d, row); } bool List::setU16(int row, quint16 value) { bool set = false; set = list_set_data_u16(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } quint32 List::u32(int row) const { return list_data_u32(m_d, row); } bool List::setU32(int row, quint32 value) { bool set = false; set = list_set_data_u32(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } quint64 List::u64(int row) const { return list_data_u64(m_d, row); } bool List::setU64(int row, quint64 value) { bool set = false; set = list_set_data_u64(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } quint8 List::u8(int row) const { return list_data_u8(m_d, row); } bool List::setU8(int row, quint8 value) { bool set = false; set = list_set_data_u8(m_d, row, value); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QVariant List::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(boolean(index.row())); case Qt::UserRole + 1: return QVariant::fromValue(bytearray(index.row())); case Qt::UserRole + 2: return QVariant::fromValue(f32(index.row())); case Qt::UserRole + 3: return QVariant::fromValue(f64(index.row())); case Qt::UserRole + 4: return QVariant::fromValue(i16(index.row())); case Qt::UserRole + 5: return QVariant::fromValue(i32(index.row())); case Qt::UserRole + 6: return QVariant::fromValue(i64(index.row())); case Qt::UserRole + 7: return QVariant::fromValue(i8(index.row())); case Qt::UserRole + 8: return optionalBoolean(index.row()); case Qt::UserRole + 9: return cleanNullQVariant(QVariant::fromValue(optionalBytearray(index.row()))); case Qt::UserRole + 10: return cleanNullQVariant(QVariant::fromValue(optionalString(index.row()))); case Qt::DisplayRole: case Qt::EditRole: case Qt::UserRole + 11: return QVariant::fromValue(string(index.row())); case Qt::UserRole + 12: return QVariant::fromValue(u16(index.row())); case Qt::UserRole + 13: return QVariant::fromValue(u32(index.row())); case Qt::UserRole + 14: return QVariant::fromValue(u64(index.row())); case Qt::UserRole + 15: return QVariant::fromValue(u8(index.row())); } } return QVariant(); } int List::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 List::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "boolean"); names.insert(Qt::UserRole + 1, "bytearray"); names.insert(Qt::UserRole + 2, "f32"); names.insert(Qt::UserRole + 3, "f64"); names.insert(Qt::UserRole + 4, "i16"); names.insert(Qt::UserRole + 5, "i32"); names.insert(Qt::UserRole + 6, "i64"); names.insert(Qt::UserRole + 7, "i8"); names.insert(Qt::UserRole + 8, "optionalBoolean"); names.insert(Qt::UserRole + 9, "optionalBytearray"); names.insert(Qt::UserRole + 10, "optionalString"); names.insert(Qt::UserRole + 11, "string"); names.insert(Qt::UserRole + 12, "u16"); names.insert(Qt::UserRole + 13, "u32"); names.insert(Qt::UserRole + 14, "u64"); names.insert(Qt::UserRole + 15, "u8"); return names; } QVariant List::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 List::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 List::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.column() == 0) { if (role == Qt::UserRole + 0) { if (value.canConvert(qMetaTypeId())) { return setBoolean(index.row(), value.value()); } } if (role == Qt::UserRole + 1) { if (value.canConvert(qMetaTypeId())) { return setBytearray(index.row(), value.value()); } } if (role == Qt::UserRole + 2) { if (value.canConvert(qMetaTypeId())) { return setF32(index.row(), value.value()); } } if (role == Qt::UserRole + 3) { if (value.canConvert(qMetaTypeId())) { return setF64(index.row(), value.value()); } } if (role == Qt::UserRole + 4) { if (value.canConvert(qMetaTypeId())) { return setI16(index.row(), value.value()); } } if (role == Qt::UserRole + 5) { if (value.canConvert(qMetaTypeId())) { return setI32(index.row(), value.value()); } } if (role == Qt::UserRole + 6) { if (value.canConvert(qMetaTypeId())) { return setI64(index.row(), value.value()); } } if (role == Qt::UserRole + 7) { if (value.canConvert(qMetaTypeId())) { return setI8(index.row(), value.value()); } } if (role == Qt::UserRole + 8) { return setOptionalBoolean(index.row(), value); } if (role == Qt::UserRole + 9) { if (!value.isValid() || value.isNull() ||value.canConvert(qMetaTypeId())) { return setOptionalBytearray(index.row(), value.value()); } } if (role == Qt::UserRole + 10) { if (!value.isValid() || value.isNull() ||value.canConvert(qMetaTypeId())) { return setOptionalString(index.row(), value.value()); } } if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole + 11) { if (value.canConvert(qMetaTypeId())) { return setString(index.row(), value.value()); } } if (role == Qt::UserRole + 12) { if (value.canConvert(qMetaTypeId())) { return setU16(index.row(), value.value()); } } if (role == Qt::UserRole + 13) { if (value.canConvert(qMetaTypeId())) { return setU32(index.row(), value.value()); } } if (role == Qt::UserRole + 14) { if (value.canConvert(qMetaTypeId())) { return setU64(index.row(), value.value()); } } if (role == Qt::UserRole + 15) { if (value.canConvert(qMetaTypeId())) { return setU8(index.row(), value.value()); } } } return false; } extern "C" { List::Private* list_new(List*, void (*)(const List*), void (*)(List*), void (*)(List*), void (*)(List*, quintptr, quintptr), void (*)(List*), void (*)(List*), void (*)(List*, int, int), void (*)(List*), void (*)(List*, int, int, int), void (*)(List*), void (*)(List*, int, int), void (*)(List*)); void list_free(List::Private*); }; List::List(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } List::List(QObject *parent): QAbstractItemModel(parent), m_d(list_new(this, [](const List* o) { emit o->newDataReady(QModelIndex()); }, [](List* o) { emit o->layoutAboutToBeChanged(); }, [](List* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](List* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, 0, last)); }, [](List* o) { o->beginResetModel(); }, [](List* o) { o->endResetModel(); }, [](List* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](List* o) { o->endInsertRows(); }, [](List* o, int first, int last, int destination) { o->beginMoveRows(QModelIndex(), first, last, QModelIndex(), destination); }, [](List* o) { o->endMoveRows(); }, [](List* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](List* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &List::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } List::~List() { if (m_ownsPrivate) { list_free(m_d); } } void List::initHeaderData() { m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("string")); } diff --git a/tests/test_list_types_rust.h b/tests/test_list_types_rust.h index b73b788..ee9d0a4 100644 --- a/tests/test_list_types_rust.h +++ b/tests/test_list_types_rust.h @@ -1,81 +1,82 @@ /* generated by rust_qt_binding_generator */ #ifndef TEST_LIST_TYPES_RUST_H #define TEST_LIST_TYPES_RUST_H #include #include class List; class List : public QAbstractItemModel { Q_OBJECT public: class Private; private: Private * m_d; bool m_ownsPrivate; explicit List(bool owned, QObject *parent); public: explicit List(QObject *parent = nullptr); ~List(); 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 boolean(int row) const; Q_INVOKABLE bool setBoolean(int row, bool value); Q_INVOKABLE QByteArray bytearray(int row) const; Q_INVOKABLE bool setBytearray(int row, const QByteArray& value); Q_INVOKABLE float f32(int row) const; Q_INVOKABLE bool setF32(int row, float value); Q_INVOKABLE double f64(int row) const; Q_INVOKABLE bool setF64(int row, double value); Q_INVOKABLE qint16 i16(int row) const; Q_INVOKABLE bool setI16(int row, qint16 value); Q_INVOKABLE qint32 i32(int row) const; Q_INVOKABLE bool setI32(int row, qint32 value); Q_INVOKABLE qint64 i64(int row) const; Q_INVOKABLE bool setI64(int row, qint64 value); Q_INVOKABLE qint8 i8(int row) const; Q_INVOKABLE bool setI8(int row, qint8 value); Q_INVOKABLE QVariant optionalBoolean(int row) const; Q_INVOKABLE bool setOptionalBoolean(int row, const QVariant& value); Q_INVOKABLE QByteArray optionalBytearray(int row) const; Q_INVOKABLE bool setOptionalBytearray(int row, const QByteArray& value); Q_INVOKABLE QString optionalString(int row) const; Q_INVOKABLE bool setOptionalString(int row, const QString& value); Q_INVOKABLE QString string(int row) const; Q_INVOKABLE bool setString(int row, const QString& value); Q_INVOKABLE quint16 u16(int row) const; Q_INVOKABLE bool setU16(int row, quint16 value); Q_INVOKABLE quint32 u32(int row) const; Q_INVOKABLE bool setU32(int row, quint32 value); Q_INVOKABLE quint64 u64(int row) const; Q_INVOKABLE bool setU64(int row, quint64 value); Q_INVOKABLE quint8 u8(int row) const; Q_INVOKABLE bool setU8(int row, quint8 value); signals: // new data is ready to be made available to the model with fetchMore() void newDataReady(const QModelIndex &parent) const; private: QHash, QVariant> m_headerData; void initHeaderData(); + void updatePersistentIndexes(); signals: }; #endif // TEST_LIST_TYPES_RUST_H diff --git a/tests/test_tree_rust.cpp b/tests/test_tree_rust.cpp index fc34a92..4d747a5 100644 --- a/tests/test_tree_rust.cpp +++ b/tests/test_tree_rust.cpp @@ -1,323 +1,340 @@ /* generated by rust_qt_binding_generator */ #include "test_tree_rust.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; } } extern "C" { void persons_data_user_name(const Persons::Private*, quintptr, QString*, qstring_set); bool persons_set_data_user_name(Persons::Private*, quintptr, const ushort* s, int len); void persons_sort(Persons::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int persons_row_count(const Persons::Private*, option_quintptr); bool persons_can_fetch_more(const Persons::Private*, option_quintptr); void persons_fetch_more(Persons::Private*, option_quintptr); quintptr persons_index(const Persons::Private*, option_quintptr, int); qmodelindex_t persons_parent(const Persons::Private*, quintptr); int persons_row(const Persons::Private*, quintptr); + option_quintptr persons_check_row(const Persons::Private*, quintptr, int); } int Persons::columnCount(const QModelIndex &) const { return 1; } bool Persons::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int Persons::rowCount(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return 0; } const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; return persons_row_count(m_d, rust_parent); } bool Persons::insertRows(int, int, const QModelIndex &) { return false; // not supported yet } bool Persons::removeRows(int, int, const QModelIndex &) { return false; // not supported yet } QModelIndex Persons::index(int row, int column, const QModelIndex &parent) const { if (row < 0 || column < 0 || column >= 1) { return QModelIndex(); } if (parent.isValid() && parent.column() != 0) { return QModelIndex(); } if (row >= rowCount(parent)) { return QModelIndex(); } const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; const quintptr id = persons_index(m_d, rust_parent, row); return createIndex(row, column, id); } QModelIndex Persons::parent(const QModelIndex &index) const { if (!index.isValid()) { return QModelIndex(); } const qmodelindex_t parent = persons_parent(m_d, index.internalId()); return parent.row >= 0 ?createIndex(parent.row, 0, parent.id) :QModelIndex(); } bool Persons::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return false; } const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; return persons_can_fetch_more(m_d, rust_parent); } void Persons::fetchMore(const QModelIndex &parent) { const option_quintptr rust_parent = { parent.internalId(), parent.isValid() }; persons_fetch_more(m_d, rust_parent); } +void Persons::updatePersistentIndexes() { + const auto from = persistentIndexList(); + auto to = from; + auto len = to.size(); + for (int i = 0; i < len; ++i) { + auto index = to.at(i); + auto row = persons_check_row(m_d, index.internalId(), index.row()); + if (row.some) { + to[i] = createIndex(row.value, index.column(), index.internalId()); + } else { + to[i] = QModelIndex(); + } + } + changePersistentIndexList(from, to); +} void Persons::sort(int column, Qt::SortOrder order) { persons_sort(m_d, column, order); } Qt::ItemFlags Persons::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); if (i.column() == 0) { flags |= Qt::ItemIsEditable; } return flags; } QString Persons::userName(const QModelIndex& index) const { QString s; persons_data_user_name(m_d, index.internalId(), &s, set_qstring); return s; } bool Persons::setUserName(const QModelIndex& index, const QString& value) { bool set = false; set = persons_set_data_user_name(m_d, index.internalId(), value.utf16(), value.length()); if (set) { emit dataChanged(index, index); } return set; } QVariant Persons::data(const QModelIndex &index, int role) const { Q_ASSERT(rowCount(index.parent()) > index.row()); switch (index.column()) { case 0: switch (role) { case Qt::DisplayRole: case Qt::EditRole: case Qt::UserRole + 0: return QVariant::fromValue(userName(index)); } } return QVariant(); } int Persons::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 Persons::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "userName"); return names; } QVariant Persons::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 Persons::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 Persons::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.column() == 0) { if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole + 0) { if (value.canConvert(qMetaTypeId())) { return setUserName(index, value.value()); } } } return false; } extern "C" { Persons::Private* persons_new(Persons*, void (*)(const Persons*, option_quintptr), void (*)(Persons*), void (*)(Persons*), void (*)(Persons*, quintptr, quintptr), void (*)(Persons*), void (*)(Persons*), void (*)(Persons*, option_quintptr, int, int), void (*)(Persons*), void (*)(Persons*, option_quintptr, int, int, option_quintptr, int), void (*)(Persons*), void (*)(Persons*, option_quintptr, int, int), void (*)(Persons*)); void persons_free(Persons::Private*); }; Persons::Persons(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } Persons::Persons(QObject *parent): QAbstractItemModel(parent), m_d(persons_new(this, [](const Persons* o, option_quintptr id) { if (id.some) { int row = persons_row(o->m_d, id.value); emit o->newDataReady(o->createIndex(row, 0, id.value)); } else { emit o->newDataReady(QModelIndex()); } }, [](Persons* o) { emit o->layoutAboutToBeChanged(); }, [](Persons* o) { + o->updatePersistentIndexes(); emit o->layoutChanged(); }, [](Persons* o, quintptr first, quintptr last) { quintptr frow = persons_row(o->m_d, first); quintptr lrow = persons_row(o->m_d, first); o->dataChanged(o->createIndex(frow, 0, first), o->createIndex(lrow, 0, last)); }, [](Persons* o) { o->beginResetModel(); }, [](Persons* o) { o->endResetModel(); }, [](Persons* o, option_quintptr id, int first, int last) { if (id.some) { int row = persons_row(o->m_d, id.value); o->beginInsertRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginInsertRows(QModelIndex(), first, last); } }, [](Persons* o) { o->endInsertRows(); }, [](Persons* o, option_quintptr sourceParent, int first, int last, option_quintptr destinationParent, int destination) { QModelIndex s; if (sourceParent.some) { int row = persons_row(o->m_d, sourceParent.value); s = o->createIndex(row, 0, sourceParent.value); } QModelIndex d; if (destinationParent.some) { int row = persons_row(o->m_d, destinationParent.value); d = o->createIndex(row, 0, destinationParent.value); } o->beginMoveRows(s, first, last, d, destination); }, [](Persons* o) { o->endMoveRows(); }, [](Persons* o, option_quintptr id, int first, int last) { if (id.some) { int row = persons_row(o->m_d, id.value); o->beginRemoveRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginRemoveRows(QModelIndex(), first, last); } }, [](Persons* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &Persons::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } Persons::~Persons() { if (m_ownsPrivate) { persons_free(m_d); } } void Persons::initHeaderData() { m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("userName")); } diff --git a/tests/test_tree_rust.h b/tests/test_tree_rust.h index ee45939..0eabbd9 100644 --- a/tests/test_tree_rust.h +++ b/tests/test_tree_rust.h @@ -1,51 +1,52 @@ /* generated by rust_qt_binding_generator */ #ifndef TEST_TREE_RUST_H #define TEST_TREE_RUST_H #include #include class Persons; class Persons : public QAbstractItemModel { Q_OBJECT public: class Private; private: Private * m_d; bool m_ownsPrivate; explicit Persons(bool owned, QObject *parent); public: explicit Persons(QObject *parent = nullptr); ~Persons(); 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 QString userName(const QModelIndex& index) const; Q_INVOKABLE bool setUserName(const QModelIndex& index, const QString& value); signals: // new data is ready to be made available to the model with fetchMore() void newDataReady(const QModelIndex &parent) const; private: QHash, QVariant> m_headerData; void initHeaderData(); + void updatePersistentIndexes(); signals: }; #endif // TEST_TREE_RUST_H