slint icon indicating copy to clipboard operation
slint copied to clipboard

Separating provision of `Timer` callback and starting it

Open Enyium opened this issue 1 year ago • 2 comments

I use Rust.

The way the Timer API is structured, I must do some noisy extra work to be able to access what's needed in its callback. I have an App struct that holds a Slint window component along with other data that I need for my app's business. Its new() function returns a type very similar to Rc<RefCell<App>> (including borrow() and borrow_mut(); for the sake of this issue, the concrete type deviation is irrelevant). new() sets up callbacks by cloning the Rc and passing the clones into closures that call borrow() or borrow_mut() to call through to App's methods, so they have nice &self or &mut self parameters. In some App methods, I need to start timers and must, as it stands, redefine their callbacks there everytime, because Timer::start() works that way. Of course, I can't move &self or &mut self into the timer closure; so I have to pass an extra Rc clone into the App methods that start Timers and do closure definition work there that should happen in new().

I wish Timer would allow to pass its callback once on creation, and then provide the means to start, restart and stop the timer at will. I would then just have dedicated App methods that are called on Timer expiration, just like with all other callbacks. I would need a single Timer method to start or restart it, no matter whether it was started before (in my app, certain code should run after user actions subsided for a while, which means constant restarts on user actions).

If this accepted: While you're at it, breaking Timer's API:

  • set_interval() could be named restart_with_interval().
  • There should perhaps be a way to change the TimerMode, maybe with restart_with_details() with parameters for TimerMode and interval.
  • Googling "one-shot timer" yields more results than "single-shot timer" and is shorter, which could justify adopting the first term in the crate (Rust's API guidelines say, "contractions of compound words count as one word: use [...] Stdin rather than StdIn", which may mean that it should be oneshot rather than one_shot, which would be written with a hyphen in a natural-language context).

Enyium avatar Aug 22 '24 12:08 Enyium

For reference, in C++, there is a constructor that takes an interval and callback: https://releases.slint.dev/1.7.2/docs/cpp/api/structslint_1_1timer#_CPPv4I_NSt9invocableEEN5slint5Timer5TimerENSt6chrono12millisecondsE1F (but it will then be running) We could have also a rust consturctor function that creates a started timer.

ogoffart avatar Aug 22 '24 15:08 ogoffart

We could have also a rust consturctor function that creates a started timer.

If it created a started Timer, I'd have to stop() it right away. Seems like a quirk to me.

Enyium avatar Aug 22 '24 15:08 Enyium