FlightGear next
RecentLocationsModel.cxx
Go to the documentation of this file.
2
3#include <QSettings>
4#include <QDebug>
5
6
7const int MAX_RECENT_LOCATIONS = 20;
8
9// avoid clashng with previous versions, with incompatible data
10const QString recentLocationsKey = "recent-locations-2020";
11
13 QAbstractListModel(pr)
14{
15 QSettings settings;
16 m_data = settings.value(recentLocationsKey).toList();
17}
18
20{
21 QSettings settings;
22 settings.setValue(recentLocationsKey, m_data);
23}
24
25QVariantMap RecentLocationsModel::locationAt(int index) const
26{
27 return m_data.at(index).toMap();
28}
29
31{
32 return m_data.empty();
33}
34
35QVariant RecentLocationsModel::data(const QModelIndex &index, int role) const
36{
37 const QVariantMap loc = m_data.at(index.row()).toMap();
38 if (role == Qt::DisplayRole) {
39 return loc.value("text");
40 } else if (role == Qt::UserRole) {
41 return loc;
42 }
43
44 return {};
45}
46
47int RecentLocationsModel::rowCount(const QModelIndex &parent) const
48{
49 return m_data.size();
50}
51
52QHash<int, QByteArray> RecentLocationsModel::roleNames() const
53{
54 QHash<int, QByteArray> result = QAbstractListModel::roleNames();
55 result[Qt::DisplayRole] = "display";
56 // result[Qt::UserRole] = "uri";
57 return result;
58}
59
61{
62 if (m_data.empty()) {
63 return {};
64 }
65
66 return m_data.front().toMap();
67}
68
69void RecentLocationsModel::insert(QVariant location)
70{
71 if (location.toMap().isEmpty())
72 return;
73
74 QVariant locDesc = location.toMap().value("text");
75 auto it = std::find_if(m_data.begin(), m_data.end(),
76 [locDesc](QVariant v) { return v.toMap().value("text") == locDesc; });
77 if (!m_data.empty() && (it == m_data.begin())) {
78 // special, common case - nothing to do
79 // we use the description to determine equality,
80 // but it doesn't mention altitude/speed/heading so always
81 // update the actual stored value
82 *it = location;
83 return;
84 }
85
86 if (it != m_data.end()) {
87 int existingIndex = std::distance(m_data.begin(), it);
88 beginRemoveRows(QModelIndex(), existingIndex, existingIndex);
89 m_data.erase(it);
90 endRemoveRows();
91 }
92
93 beginInsertRows(QModelIndex(), 0, 0);
94 m_data.push_front(location);
95 endInsertRows();
96
97 if (m_data.size() > MAX_RECENT_LOCATIONS) {
98 beginRemoveRows(QModelIndex(), MAX_RECENT_LOCATIONS, m_data.size() - 1);
99 // truncate the data at the correct size
100 m_data = m_data.mid(0, MAX_RECENT_LOCATIONS);
101 endRemoveRows();
102 }
103
104 emit isEmptyChanged();
105}
const unsigned int MAX_RECENT_LOCATIONS
const QString recentLocationsKey
Q_INVOKABLE QVariantMap locationAt(int index) const
int rowCount(const QModelIndex &parent) const override
QHash< int, QByteArray > roleNames() const override
void insert(QVariant location)
RecentLocationsModel(QObject *pr=nullptr)
QVariantMap mostRecent() const
QVariant data(const QModelIndex &index, int role) const override