Skip to content

Commit 6ff9442

Browse files
mjhanninenNoraCodes
authored andcommitted
fix: throttle UI::run_delay
To trigger `on_tick` on every `delay_ms` milliseconds (as advertised) and not to consume a whole core. A workaround but works for now.
1 parent e76abf6 commit 6ff9442

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ compliance.
4242
* `ui-sys` now builds on modern macOS.
4343
* `inputs` and `inputs-grid` examples no longer erroneously start at 0 for inputs starting at 1.
4444
* Text no longer uses incorrect newlines per platform.
45+
* `UI::run_delay` no longer spins on the callback, but actually calls it at the
46+
appropriate interval
4547

4648
### Security
4749

iui/src/ui.rs

100644100755
Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ use std::ffi::CStr;
88
use std::marker::PhantomData;
99
use std::mem;
1010
use std::rc::Rc;
11-
use std::thread::sleep;
12-
use std::time::Duration;
11+
use std::thread;
12+
use std::time::{Duration, SystemTime};
1313

1414
use controls::Window;
1515

@@ -222,11 +222,27 @@ impl<'s> EventLoop<'s> {
222222
/// running the callback given with `on_tick` approximately every
223223
/// `delay` milliseconds.
224224
pub fn run_delay(&mut self, ctx: &UI, delay_ms: u32) {
225-
loop {
226-
if !self.next_tick(ctx) {
227-
break;
225+
if let Some(ref mut c) = self.callback {
226+
let delay_ms = delay_ms as u128;
227+
let mut t0 = SystemTime::now();
228+
'event_loop: loop {
229+
for _ in 0..5 {
230+
if !unsafe { ui_sys::uiMainStep(false as c_int) == 1 } {
231+
break 'event_loop;
232+
}
233+
}
234+
if let Ok(duration) = t0.elapsed() {
235+
if duration.as_millis() >= delay_ms {
236+
c();
237+
t0 = SystemTime::now();
238+
}
239+
} else {
240+
t0 = SystemTime::now();
241+
}
242+
thread::sleep(Duration::from_millis(5));
228243
}
244+
} else {
245+
self.run(ctx)
229246
}
230-
sleep(Duration::new(0, delay_ms * 1000000))
231247
}
232248
}

0 commit comments

Comments
 (0)