QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
LoopState.h
Go to the documentation of this file.
1#pragma once
2
3#include "QGCState.h"
4
5#include <functional>
6
25template<typename T>
26class LoopState : public QGCState
27{
28public:
29 using ItemAction = std::function<void(const T& item, int index)>;
30 using ItemPredicate = std::function<bool(const T& item, int index)>;
31
37 LoopState(const QString& stateName, QState* parent,
38 const QList<T>& items, ItemAction action)
39 : QGCState(stateName, parent)
40 , _items(items)
41 , _action(std::move(action))
42 {
43 }
44
46 void setFilter(ItemPredicate filter) { _filter = std::move(filter); }
47
49 int currentIndex() const { return _currentIndex; }
50
52 T currentItem() const { return _currentIndex >= 0 && _currentIndex < _items.size()
53 ? _items[_currentIndex] : T(); }
54
56 int totalItems() const { return _items.size(); }
57
59 int processedCount() const { return _processedCount; }
60
61protected:
62 void onEnter() override
63 {
64 _currentIndex = -1;
65 _processedCount = 0;
66 _processNextItem();
67 }
68
69private:
70 void _processNextItem()
71 {
72 _currentIndex++;
73
74 // Skip filtered items
75 while (_currentIndex < _items.size() && _filter && !_filter(_items[_currentIndex], _currentIndex)) {
76 _currentIndex++;
77 }
78
79 if (_currentIndex >= _items.size()) {
80 // All items processed
81 emit advance();
82 return;
83 }
84
85 // Process current item
86 if (_action) {
87 _action(_items[_currentIndex], _currentIndex);
88 }
89 _processedCount++;
90
91 // Schedule next item processing (allow event loop to process)
92 QMetaObject::invokeMethod(this, &LoopState::_processNextItem, Qt::QueuedConnection);
93 }
94
95 QList<T> _items;
96 ItemAction _action;
97 ItemPredicate _filter;
98 int _currentIndex = -1;
99 int _processedCount = 0;
100};
void onEnter() override
Override to perform actions on state entry.
Definition LoopState.h:62
void setFilter(ItemPredicate filter)
Set a predicate to filter items (only items where predicate returns true are processed)
Definition LoopState.h:46
std::function< bool(const T &item, int index)> ItemPredicate
Definition LoopState.h:30
int currentIndex() const
Get the current index being processed.
Definition LoopState.h:49
T currentItem() const
Get the current item being processed.
Definition LoopState.h:52
int totalItems() const
Get the total number of items.
Definition LoopState.h:56
int processedCount() const
Get the number of items processed so far.
Definition LoopState.h:59
LoopState(const QString &stateName, QState *parent, const QList< T > &items, ItemAction action)
Definition LoopState.h:37
std::function< void(const T &item, int index)> ItemAction
Definition LoopState.h:29
QString stateName() const