summaryrefslogtreecommitdiff
path: root/lib/astal/io/time.vala
diff options
context:
space:
mode:
authorAylur <[email protected]>2024-10-14 16:01:36 +0000
committerAylur <[email protected]>2024-10-14 16:44:51 +0000
commit6a8c41cd1d5e218d0dacffb836fdd7d4ec6333dd (patch)
tree7e027d39940838b10c742ef0d5a7aeddad6ef884 /lib/astal/io/time.vala
parentbdb23e20f171da7c769cba9e393d7e406e563a78 (diff)
feat: astal-io
Diffstat (limited to 'lib/astal/io/time.vala')
-rw-r--r--lib/astal/io/time.vala71
1 files changed, 71 insertions, 0 deletions
diff --git a/lib/astal/io/time.vala b/lib/astal/io/time.vala
new file mode 100644
index 0000000..1446441
--- /dev/null
+++ b/lib/astal/io/time.vala
@@ -0,0 +1,71 @@
+public class AstalIO.Time : Object {
+ public signal void now ();
+ public signal void cancelled ();
+ private Cancellable cancellable;
+ private uint timeout_id;
+ private bool fulfilled = false;
+
+ construct {
+ cancellable = new Cancellable();
+ cancellable.cancelled.connect(() => {
+ if (!fulfilled) {
+ Source.remove(timeout_id);
+ cancelled();
+ dispose();
+ }
+ });
+ }
+
+ private void connect_closure(Closure? closure) {
+ if (closure == null)
+ return;
+
+ now.connect(() => {
+ Value ret = Value(Type.POINTER); // void
+ closure.invoke(ref ret, {});
+ });
+ }
+
+ public Time.interval_prio(uint interval, int prio = Priority.DEFAULT, Closure? fn) {
+ connect_closure(fn);
+ Idle.add_once(() => now());
+ timeout_id = Timeout.add(interval, () => {
+ now();
+ return Source.CONTINUE;
+ }, prio);
+ }
+
+ public Time.timeout_prio(uint timeout, int prio = Priority.DEFAULT, Closure? fn) {
+ connect_closure(fn);
+ timeout_id = Timeout.add(timeout, () => {
+ now();
+ fulfilled = true;
+ return Source.REMOVE;
+ }, prio);
+ }
+
+ public Time.idle_prio(int prio = Priority.DEFAULT_IDLE, Closure? fn) {
+ connect_closure(fn);
+ timeout_id = Idle.add(() => {
+ now();
+ fulfilled = true;
+ return Source.REMOVE;
+ }, prio);
+ }
+
+ public static Time interval(uint interval, Closure? fn) {
+ return new Time.interval_prio(interval, Priority.DEFAULT, fn);
+ }
+
+ public static Time timeout(uint timeout, Closure? fn) {
+ return new Time.timeout_prio(timeout, Priority.DEFAULT, fn);
+ }
+
+ public static Time idle(Closure? fn) {
+ return new Time.idle_prio(Priority.DEFAULT_IDLE, fn);
+ }
+
+ public void cancel() {
+ cancellable.cancel();
+ }
+}