aboutsummaryrefslogtreecommitdiff
path: root/libdino
diff options
context:
space:
mode:
Diffstat (limited to 'libdino')
-rw-r--r--libdino/CMakeLists.txt1
-rw-r--r--libdino/meson.build1
-rw-r--r--libdino/src/util/weak_timeout.vala40
3 files changed, 42 insertions, 0 deletions
diff --git a/libdino/CMakeLists.txt b/libdino/CMakeLists.txt
index d52f9184..e4d786c9 100644
--- a/libdino/CMakeLists.txt
+++ b/libdino/CMakeLists.txt
@@ -70,6 +70,7 @@ SOURCES
src/util/display_name.vala
src/util/util.vala
src/util/weak_map.vala
+ src/util/weak_timeout.vala
CUSTOM_VAPIS
"${CMAKE_BINARY_DIR}/exports/xmpp-vala.vapi"
"${CMAKE_BINARY_DIR}/exports/qlite.vapi"
diff --git a/libdino/meson.build b/libdino/meson.build
index 356c15d3..17804d23 100644
--- a/libdino/meson.build
+++ b/libdino/meson.build
@@ -76,6 +76,7 @@ sources = files(
'src/util/display_name.vala',
'src/util/util.vala',
'src/util/weak_map.vala',
+ 'src/util/weak_timeout.vala',
)
sources += [version_vala]
c_args = [
diff --git a/libdino/src/util/weak_timeout.vala b/libdino/src/util/weak_timeout.vala
new file mode 100644
index 00000000..28894ed3
--- /dev/null
+++ b/libdino/src/util/weak_timeout.vala
@@ -0,0 +1,40 @@
+public class Dino.WeakTimeout {
+ // XXX: If you get an error saying your function doesn't match the delegate, make sure it's static!
+ // These are marked as "has_target=false" so you can't close over "this" and leak it in your lambda.
+ [CCode (has_target = false, instance_pos = 0)]
+ public delegate bool SourceFunc<T> (T object);
+
+ [CCode (has_target = false, instance_pos = 0)]
+ public delegate void SourceOnceFunc<T> (T object);
+
+ public static uint add<T>(uint interval, T object, owned SourceFunc<T> function, int priority = GLib.Priority.DEFAULT) {
+ var weak = WeakRef((Object)object);
+ return GLib.Timeout.add(interval, () => {
+ var strong = weak.get();
+ if (strong == null) return false;
+
+ return function(strong);
+ }, priority);
+ }
+
+ public static uint add_once<T>(uint interval, T object, owned SourceOnceFunc<T> function, int priority = GLib.Priority.DEFAULT) {
+ var weak = WeakRef((Object)object);
+ return GLib.Timeout.add(interval, () => {
+ var strong = weak.get();
+ if (strong == null) return false;
+
+ function(strong);
+ return false;
+ }, priority);
+ }
+
+ public static uint add_seconds<T>(uint interval, T object, owned SourceFunc<T> function, int priority = GLib.Priority.DEFAULT) {
+ return add(interval * 1000, object, (owned) function, priority);
+ }
+
+ // This one doesn't have an upstream equivalent, but it seems pretty obvious to me
+ public static uint add_seconds_once<T>(uint interval, T object, owned SourceOnceFunc<T> function, int priority = GLib.Priority.DEFAULT) {
+ return add_once(interval * 1000, object, (owned) function, priority);
+ }
+
+}