Program Listing for File slint_timer.h

Return to documentation for file (/home/runner/work/slint/slint/api/cpp/include/slint_timer.h)

// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0

// cSpell: ignore singleshot

#pragma once

#include <chrono>

#include <optional>
#include <slint_timer_internal.h>

namespace slint {

using cbindgen_private::TimerMode;

struct Timer
{
    Timer() = default;
    template<std::invocable F>
    Timer(std::chrono::milliseconds interval, F callback)
        : id(cbindgen_private::slint_timer_start(
                  0, TimerMode::Repeated, interval.count(),
                  [](void *data) { (*reinterpret_cast<F *>(data))(); }, new F(std::move(callback)),
                  [](void *data) { delete reinterpret_cast<F *>(data); }))
    {
    }
    Timer(const Timer &) = delete;
    Timer &operator=(const Timer &) = delete;
    ~Timer() { cbindgen_private::slint_timer_destroy(id); }

    template<std::invocable F>
    void start(TimerMode mode, std::chrono::milliseconds interval, F callback)
    {
        id = cbindgen_private::slint_timer_start(
                id, mode, interval.count(), [](void *data) { (*reinterpret_cast<F *>(data))(); },
                new F(std::move(callback)), [](void *data) { delete reinterpret_cast<F *>(data); });
    }
    void stop() { cbindgen_private::slint_timer_stop(id); }
    void restart() { cbindgen_private::slint_timer_restart(id); }
    bool running() const { return cbindgen_private::slint_timer_running(id); }
    std::optional<std::chrono::milliseconds> interval() const
    {
        int64_t val = cbindgen_private::slint_timer_interval(id);
        if (val < 0) {
            return std::nullopt;
        }
        return std::chrono::milliseconds(val);
    }

    template<std::invocable F>
    static void single_shot(std::chrono::milliseconds duration, F callback)
    {
        cbindgen_private::slint_timer_singleshot(
                duration.count(), [](void *data) { (*reinterpret_cast<F *>(data))(); },
                new F(std::move(callback)), [](void *data) { delete reinterpret_cast<F *>(data); });
    }

private:
    uint64_t id = 0;
};

} // namespace slint