Debian Codegraph @

src/app/qml/ui/AddLocationPage.qml

raw
1 /*
2 * Copyright (C) 2015-2016 Canonical Ltd.
3 *
4 * This file is part of Lomiri Weather App
5 *
6 * Lomiri Weather App is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 3 as
8 * published by the Free Software Foundation.
9 *
10 * Lomiri Weather App is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 import QtQuick 2.12
20 import Lomiri.Components 1.3
21 import Lomiri.Components.Popups 1.3
22 import "../components"
23 import "../data/CitiesList.js" as Cities
24 import "../data/WeatherApi.js" as WeatherApi
25
26 Page {
27 id: addLocationPage
28 objectName: "addLocationPage"
29
30 visible: false
31
32 header: PageHeader {
33 id: searchHeader
34 visible: true
35
36 leadingActionBar {
37 actions: [
38 Action {
39 iconName: "back"
40 objectName: "pagestack_back_action_button"
41 text: i18n.tr("Back")
42 onTriggered: pop()
43 }
44 ]
45 }
46 contents: Loader {
47 id: searchComponentLoader
48 sourceComponent: searchComponent
49 anchors {
50 left: parent ? parent.left : undefined
51 right: parent ? parent.right : undefined
52 verticalCenter: parent ? parent.verticalCenter : undefined
53 }
54 }
55 }
56
57 Component.onCompleted: searchComponentLoader.item.forceActiveFocus()
58
59 // Outside component so property can bind to for autopilot
60 Timer {
61 id: searchTimer
62 interval: 250
63 onTriggered: {
64 if (searchComponentLoader.item) { // check component exists
65 if (searchComponentLoader.item.text.trim() === "") {
66 loadEmpty()
67 } else {
68 loadFromProvider(searchComponentLoader.item.text,"searchByName")
69 }
70 } else {
71 loadEmpty()
72 }
73 }
74 }
75
76 Component {
77 id: searchComponent
78 TextField {
79 id: searchField
80 objectName: "searchField"
81
82 inputMethodHints: Qt.ImhNoPredictiveText
83 placeholderText: i18n.tr("Search city or select below")
84 hasClearButton: true
85
86 onTextChanged: searchTimer.restart()
87 }
88 }
89
90 // Builds a area label for the location, depending on the uniqueness of name, adminName1 and country
91 function buildAreaLabel(loc, a1Counts,a2Counts) {
92 var label = "";
93 label += ((loc.adminName1) ? loc.adminName1.replace(/ Region$/,''):"");
94 if (loc.adminName2 && a1Counts[loc.name+loc.adminName1] > 1) {
95 // even name and adminName1 are multiple, add adminName2
96 label += ", "+loc.adminName2;
97 }
98 if (loc.adminName3 && a2Counts[loc.name+loc.adminName1+loc.adminName2] > 1) {
99 // even name and adminName1 and adminName2 are multiple, add adminName3
100 label += ", "+loc.adminName3;
101 }
102 label += ((label !== "") ? ", " : "") + loc.countryName
103 return label;
104 }
105
106 // Builds a station details label for the location
107 function buildStationDetailLabel(loc) {
108 var label = "";
109 label += i18n.ctr("location ID from geonames.org","geonames.org ID: %1").arg(loc.services.geonames)
110 label += "\n" + i18n.ctr("Latitude and longitude (coordinates)","lat: %1, lon: %2").arg(localeDezimalSeparator(loc.coord.lat)).arg(localeDezimalSeparator(loc.coord.lon))
111 return label;
112 }
113
114 function appendCities(list) {
115 var a1Counts = {};
116 // count occurrences of name+adminName1
117 list.forEach(function(loc) {
118 a1Counts[loc.name+loc.adminName1] = (!a1Counts[loc.name+loc.adminName1]) ? 1 : a1Counts[loc.name+loc.adminName1]+1;
119 });
120 var a2Counts = {};
121 // count occurrences of name+adminName1+adminName2
122 list.forEach(function(loc) {
123 a2Counts[loc.name+loc.adminName1+loc.adminName2] = (!a2Counts[loc.name+loc.adminName1+loc.adminName2]) ? 1 : a2Counts[loc.name+loc.adminName1+loc.adminName2]+1;
124 });
125 // build area labels and add locations to listmodel
126 list.forEach(function(loc) {
127 loc.areaLabel = buildAreaLabel(loc, a1Counts, a2Counts);
128 loc.stationdetails = buildStationDetailLabel(loc);
129 citiesModel.append(loc);
130 });
131 sortModel();
132 }
133
134 function clearModelForLoading() {
135 citiesModel.clear()
136 citiesModel.loading = true
137 citiesModel.httpError = false
138 }
139
140 function sortModel() {
141 // sort model data by name attribute
142 var n;
143 var i;
144 for (n=0; n < citiesModel.count; n++) {
145 for (i=n+1; i < citiesModel.count; i++) {
146 if (citiesModel.get(n).name > citiesModel.get(i).name)
147 {
148 citiesModel.move(i, n, 1);
149 n=0;
150 }
151 }
152 }
153 }
154
155 function loadEmpty() {
156 clearModelForLoading()
157 //retrieve data for each predefined city by coordinate
158 Cities.megacities.forEach(function(citydata) {
159 loadFromProvider(citydata,"searchByPoint")
160 });
161 sortModel();
162 citiesModel.loading = false;
163 }
164
165 function loadFromProvider(searchstring, searchtype) {
166 clearModelForLoading()
167 var parameters
168 //format parameters depending on search type to pass either coords or name
169 if (searchtype === "searchByPoint") {
170 parameters = {
171 coords: searchstring,
172 units: "metric",
173 lang: getLocale()
174 }
175 } else {
176 parameters = {
177 name: searchstring,
178 units: "metric",
179 lang: getLocale()
180 }
181 }
182
183 WeatherApi.sendRequest({
184 action: searchtype,
185 params: parameters,
186 }, searchResponseHandler)
187 }
188
189 function searchResponseHandler(msgObject) {
190 if (!msgObject.error) {
191 appendCities(msgObject.result.locations)
192 } else {
193 citiesModel.httpError = true //always set citiesModel to invisible, then provide an error message
194 var errorCode = parseInt(msgObject.error.msg.replace("wrong response http code, got ", ""));
195 console.log("location request error code: " + errorCode + "\n" + msgObject.error)
196 if (errorCode == undefined || errorCode < 500) {
197 requestFail.text = i18n.tr("Could not load data. Please open an issue and provide the following error message:") + "\n\n" + JSON.stringify(msgObject.error) //.msg + "\n" + msgObject.error.request
198 } else if (errorCode > 499) {
199 requestFail.text = i18n.tr("Could not load data. Provider server unavailable. Please ensure you are connected to the Internet.")
200 }
201 }
202 citiesModel.loading = false
203 }
204
205 ListView {
206 id: locationList
207 anchors {
208 top: addLocationPage.header.bottom
209 topMargin: units.gu(2)
210 left: parent.left
211 right: parent.right
212 rightMargin: fastScroll.showing ? fastScroll.width - units.gu(1) : 0
213 bottom: parent.bottom
214 }
215
216 objectName: "locationList"
217 clip: true
218 currentIndex: -1
219
220 function getSectionText(index) {
221 return citiesModel.get(index).name.substring(0,1)
222 }
223
224 onFlickStarted: forceActiveFocus()
225
226 section.property: "name"
227 section.criteria: ViewSection.FirstCharacter
228 section.labelPositioning: ViewSection.InlineLabels
229
230 section.delegate: ListItem {
231 height: headerText.implicitHeight + units.gu(1)
232 Label {
233 id: headerText
234 text: section
235 anchors { left: parent.left; right: parent.right; margins: units.gu(2) }
236 font.weight: Font.DemiBold
237 }
238 }
239
240 model: ListModel {
241 id: citiesModel
242
243 property bool loading: true
244 property bool httpError: false
245
246 onRowsAboutToBeInserted: loading = false
247 }
248
249 delegate: ListItem {
250 divider.visible: false
251 objectName: "addLocation" + index
252
253 height: listDelegateLayout.height
254
255 ListItemLayout {
256 id: listDelegateLayout
257 title.text: name
258 subtitle.text: areaLabel
259 subtitle.textSize: Label.Small
260 summary.text: stationdetails
261 summary.textSize: Label.Small
262 }
263
264 onClicked: {
265 if (storage.addLocation(citiesModel.get(index))) {
266 mainPageStack.pop()
267 } else {
268 PopupUtils.open(locationExistsComponent, addLocationPage)
269 }
270 }
271 }
272
273 Component.onCompleted: loadEmpty()
274
275 Behavior on anchors.rightMargin {
276 LomiriNumberAnimation {}
277 }
278 }
279
280 FastScroll {
281 id: fastScroll
282
283 listView: locationList
284
285 enabled: (locationList.contentHeight > (locationList.height * 2)) &&
286 (locationList.height >= minimumHeight)
287
288 anchors {
289 top: locationList.top
290 topMargin: units.gu(1.5)
291 bottom: locationList.bottom
292 right: parent.right
293 }
294 }
295
296 ActivityIndicator {
297 anchors {
298 centerIn: parent
299 }
300 running: visible
301 visible: citiesModel.loading
302 }
303
304 Label {
305 id: noCity
306 objectName: "noCity"
307 anchors {
308 centerIn: parent
309 }
310 text: i18n.tr("No city found")
311 visible: citiesModel.count === 0 && !citiesModel.loading
312 }
313
314 Label {
315 id: requestFail
316 anchors {
317 left: parent.left
318 margins: units.gu(1)
319 right: parent.right
320 top: noCity.bottom
321 }
322 horizontalAlignment: Text.AlignHCenter
323 visible: citiesModel.httpError
324 wrapMode: Text.Wrap
325 }
326
327 Component {
328 id: locationExistsComponent
329
330 Dialog {
331 id: locationExists
332 title: i18n.tr("Location already added.")
333
334 Button {
335 text: i18n.tr("OK")
336 onClicked: PopupUtils.close(locationExists)
337 }
338 }
339 }
340
341 }