Debian Codegraph @

src/GUI/RecentLocationsModel.cxx

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