1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-1.1 OR LicenseRef-Slint-commercial
3
4use pyo3::prelude::*;
5
6#[derive(Copy, Clone)]
7#[pyclass(name = "TimerMode")]
8pub enum PyTimerMode {
9 /// A SingleShot timer is fired only once.
10 SingleShot,
11 /// A Repeated timer is fired repeatedly until it is stopped or dropped.
12 Repeated,
13}
14
15impl From<PyTimerMode> for i_slint_core::timers::TimerMode {
16 fn from(value: PyTimerMode) -> Self {
17 match value {
18 PyTimerMode::SingleShot => i_slint_core::timers::TimerMode::SingleShot,
19 PyTimerMode::Repeated => i_slint_core::timers::TimerMode::Repeated,
20 }
21 }
22}
23
24#[pyclass(name = "Timer")]
25pub struct PyTimer {
26 timer: i_slint_core::timers::Timer,
27}
28
29#[pymethods]
30impl PyTimer {
31 #[new]
32 fn py_new() -> Self {
33 PyTimer { timer: Default::default() }
34 }
35
36 fn start(
37 &self,
38 mode: PyTimerMode,
39 interval: chrono::Duration,
40 callback: PyObject,
41 ) -> PyResult<()> {
42 let interval = interval
43 .to_std()
44 .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;
45 self.timer.start(mode.into(), interval, move || {
46 Python::with_gil(|py| {
47 callback.call0(py).expect("unexpected failure running python timer callback");
48 });
49 });
50 Ok(())
51 }
52
53 #[staticmethod]
54 fn single_shot(duration: chrono::Duration, callback: PyObject) -> PyResult<()> {
55 let duration = duration
56 .to_std()
57 .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;
58 i_slint_core::timers::Timer::single_shot(duration, move || {
59 Python::with_gil(|py| {
60 callback.call0(py).expect("unexpected failure running python timer callback");
61 });
62 });
63 Ok(())
64 }
65
66 fn stop(&self) {
67 self.timer.stop();
68 }
69
70 fn restart(&self) {
71 self.timer.restart();
72 }
73
74 fn running(&self) -> bool {
75 self.timer.running()
76 }
77
78 fn set_interval(&self, interval: chrono::Duration) -> PyResult<()> {
79 let interval = interval
80 .to_std()
81 .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;
82 self.timer.set_interval(interval);
83 Ok(())
84 }
85}
86