Fix the Rust/C++ Timer API to be more convenient to use

Allow calling restart() on a repeated timer if it has been previously stopped.
This commit is contained in:
Simon Hausmann 2022-01-05 11:15:15 +01:00 committed by Simon Hausmann
parent ced05732a8
commit 083ae5692b
4 changed files with 83 additions and 16 deletions

View file

@ -374,7 +374,7 @@ struct Timer
}
Timer(const Timer &) = delete;
Timer &operator=(const Timer &) = delete;
~Timer() { cbindgen_private::sixtyfps_timer_stop(id); }
~Timer() { cbindgen_private::sixtyfps_timer_destroy(id); }
/// Starts the timer with the given \a mode and \a interval, in order for the \a callback to
/// called when the timer fires. If the timer has been started previously and not fired yet,
@ -388,12 +388,12 @@ struct Timer
}
/// Stops the previously started timer. Does nothing if the timer has never been started. A
/// stopped timer cannot be restarted with restart() -- instead you need to call start().
void stop()
{
cbindgen_private::sixtyfps_timer_stop(id);
id = -1;
}
/// Restarts the timer, if it was previously started.
void stop() { cbindgen_private::sixtyfps_timer_stop(id); }
/// Restarts the timer. If the timer was previously started by calling [`Self::start()`]
/// with a duration and callback, then the time when the callback will be next invoked
/// is re-calculated to be in the specified duration relative to when this function is called.
///
/// Does nothing if the timer was never started.
void restart() { cbindgen_private::sixtyfps_timer_restart(id); }
/// Returns true if the timer is running; false otherwise.
bool running() const { return cbindgen_private::sixtyfps_timer_running(id); }

View file

@ -77,6 +77,57 @@ TEST_CASE("C++ Restart Singleshot Timer")
REQUIRE(timer_was_running);
}
TEST_CASE("C++ Restart Repeated Timer")
{
int timer_triggered = 0;
sixtyfps::Timer timer;
timer.start(sixtyfps::TimerMode::Repeated, std::chrono::milliseconds(30),
[&]() { timer_triggered++; });
REQUIRE(timer_triggered == 0);
bool timer_was_running = false;
sixtyfps::Timer::single_shot(std::chrono::milliseconds(500), [&]() {
timer_was_running = timer.running();
sixtyfps::quit_event_loop();
});
sixtyfps::run_event_loop();
REQUIRE(timer_triggered > 1);
REQUIRE(timer_was_running);
timer_was_running = false;
timer_triggered = 0;
timer.stop();
sixtyfps::Timer::single_shot(std::chrono::milliseconds(500), [&]() {
timer_was_running = timer.running();
sixtyfps::quit_event_loop();
});
sixtyfps::run_event_loop();
REQUIRE(timer_triggered == 0);
REQUIRE(!timer_was_running);
timer_was_running = false;
timer_triggered = 0;
timer.restart();
sixtyfps::Timer::single_shot(std::chrono::milliseconds(500), [&]() {
timer_was_running = timer.running();
sixtyfps::quit_event_loop();
});
sixtyfps::run_event_loop();
REQUIRE(timer_triggered > 1);
REQUIRE(timer_was_running);
}
TEST_CASE("Quit from event")
{
int called = 0;