|
| 1 | +/* |
| 2 | +* Copyright (C) 2025 Fastly, Inc. |
| 3 | +* |
| 4 | +* This file is part of Pushpin. |
| 5 | +* |
| 6 | +* $FANOUT_BEGIN_LICENSE:APACHE2$ |
| 7 | +* |
| 8 | +* Licensed under the Apache License, Version 2.0 (the "License"); |
| 9 | +* you may not use this file except in compliance with the License. |
| 10 | +* You may obtain a copy of the License at |
| 11 | +* |
| 12 | +* http://www.apache.org/licenses/LICENSE-2.0 |
| 13 | +* |
| 14 | +* Unless required by applicable law or agreed to in writing, software |
| 15 | +* distributed under the License is distributed on an "AS IS" BASIS, |
| 16 | +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 17 | +* See the License for the specific language governing permissions and |
| 18 | +* limitations under the License. |
| 19 | +* |
| 20 | +* $FANOUT_END_LICENSE$ |
| 21 | +*/ |
| 22 | + |
| 23 | +#ifndef DEFERCALL_H |
| 24 | +#define DEFERCALL_H |
| 25 | + |
| 26 | +#include <QObject> |
| 27 | + |
| 28 | +// queues calls to be run after returning to the event loop |
| 29 | +class DeferCall : public QObject |
| 30 | +{ |
| 31 | + Q_OBJECT |
| 32 | + |
| 33 | +public: |
| 34 | + DeferCall(); |
| 35 | + ~DeferCall(); |
| 36 | + |
| 37 | + // queue handler to be called after returning to the event loop. if |
| 38 | + // handler contains references, they must outlive DeferCall. the |
| 39 | + // recommended usage is for each object needing to perform deferred calls |
| 40 | + // to keep a DeferCall as a member variable, and only refer to the |
| 41 | + // object's own data in the handler. that way, any references are |
| 42 | + // guaranteed to live long enough. |
| 43 | + void defer(std::function<void ()> handler); |
| 44 | + |
| 45 | + static DeferCall *global(); |
| 46 | + static void cleanup(); |
| 47 | + |
| 48 | + template <typename T> |
| 49 | + static void deleteLater(T *p) |
| 50 | + { |
| 51 | + global()->defer([=]() { delete p; }); |
| 52 | + } |
| 53 | + |
| 54 | +private slots: |
| 55 | + void callNext(); |
| 56 | + |
| 57 | +private: |
| 58 | + class Call |
| 59 | + { |
| 60 | + public: |
| 61 | + std::function<void ()> handler; |
| 62 | + }; |
| 63 | + |
| 64 | + std::list<Call> deferredCalls_; |
| 65 | +}; |
| 66 | + |
| 67 | +#endif |
0 commit comments