Skip to content

Simplify the qmlextensionplugins example a bit #208

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 18 additions & 30 deletions examples/qmlextensionplugins/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
use std::ffi::CStr;
use std::sync::{Arc, Condvar, Mutex};
use std::thread::JoinHandle;
use std::sync::mpsc::SyncSender;
use std::sync::mpsc::{self, RecvTimeoutError};

use chrono::Timelike;
use cstr::cstr;

use qmetaobject::prelude::*;

#[derive(Default)]
struct AbortCondVar {
is_aborted: Mutex<bool>,
abort_condvar: Condvar,
}

#[allow(non_snake_case)]
#[derive(Default, QObject)]
struct TimeModel {
Expand All @@ -21,43 +15,37 @@ struct TimeModel {
minute: qt_property!(u32; NOTIFY timeChanged READ get_minute),
timeChanged: qt_signal!(),

thread: Option<(JoinHandle<()>, Arc<AbortCondVar>)>,
drop_notification: Option<SyncSender<()>>,
}

impl Drop for TimeModel {
fn drop(&mut self) {
self.thread.as_ref().map(|x| {
let mut lock = x.1.is_aborted.lock().unwrap();
*lock = true;
x.1.abort_condvar.notify_one();
// tell the timer thread to stop
self.drop_notification.as_ref().map(|x| {
let _ignored_result = x.send(());
});
}
}

impl TimeModel {
fn lazy_init(&mut self) {
if self.thread.is_none() {
if self.drop_notification.is_none() {
let ptr = QPointer::from(&*self);
let cb = qmetaobject::queued_callback(move |()| {
let notify_time_changed = qmetaobject::queued_callback(move |()| {
ptr.as_ref().map(|x| x.timeChanged());
});
let arc = Arc::<AbortCondVar>::new(Default::default());
let arc2 = arc.clone();
let thread = std::thread::spawn(move || loop {
let lock = arc2.is_aborted.lock().unwrap();
if *lock {
break;

let (drop_notification_tx, drop_notification_rx) = mpsc::sync_channel(1);
std::thread::spawn(move || {
// We just wait on the channel for 1 second to simulate a one second timer
while drop_notification_rx.recv_timeout(std::time::Duration::from_millis(1000))
== Err(RecvTimeoutError::Timeout)
{
notify_time_changed(());
}
// We just wait on the condition variable for 1 second to simulate a one second timer
let lock = arc2
.abort_condvar
.wait_timeout(lock, std::time::Duration::from_millis(1000))
.unwrap()
.0;
std::mem::drop(lock);
cb(());
});
self.thread = Some((thread, arc));

self.drop_notification = Some(drop_notification_tx);
}
}
fn get_hour(&mut self) -> u32 {
Expand Down