/* * Copyright (C) 2015-2016 Canonical Ltd. * * This file is part of Lomiri Weather App * * Lomiri Weather App is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * Lomiri Weather App is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ import QtQuick 2.12 import Lomiri.Components 1.3 import Lomiri.Components.Popups 1.3 import "../components" import "../data/CitiesList.js" as Cities import "../data/WeatherApi.js" as WeatherApi Page { id: addLocationPage objectName: "addLocationPage" visible: false header: PageHeader { id: searchHeader visible: true leadingActionBar { actions: [ Action { iconName: "back" objectName: "pagestack_back_action_button" text: i18n.tr("Back") onTriggered: pop() } ] } contents: Loader { id: searchComponentLoader sourceComponent: searchComponent anchors { left: parent ? parent.left : undefined right: parent ? parent.right : undefined verticalCenter: parent ? parent.verticalCenter : undefined } } } Component.onCompleted: searchComponentLoader.item.forceActiveFocus() // Outside component so property can bind to for autopilot Timer { id: searchTimer interval: 250 onTriggered: { if (searchComponentLoader.item) { // check component exists if (searchComponentLoader.item.text.trim() === "") { loadEmpty() } else { loadFromProvider(searchComponentLoader.item.text,"searchByName") } } else { loadEmpty() } } } Component { id: searchComponent TextField { id: searchField objectName: "searchField" inputMethodHints: Qt.ImhNoPredictiveText placeholderText: i18n.tr("Search city or select below") hasClearButton: true onTextChanged: searchTimer.restart() } } // Builds a area label for the location, depending on the uniqueness of name, adminName1 and country function buildAreaLabel(loc, a1Counts,a2Counts) { var label = ""; label += ((loc.adminName1) ? loc.adminName1.replace(/ Region$/,''):""); if (loc.adminName2 && a1Counts[loc.name+loc.adminName1] > 1) { // even name and adminName1 are multiple, add adminName2 label += ", "+loc.adminName2; } if (loc.adminName3 && a2Counts[loc.name+loc.adminName1+loc.adminName2] > 1) { // even name and adminName1 and adminName2 are multiple, add adminName3 label += ", "+loc.adminName3; } label += ((label !== "") ? ", " : "") + loc.countryName return label; } // Builds a station details label for the location function buildStationDetailLabel(loc) { var label = ""; label += i18n.ctr("location ID from geonames.org","geonames.org ID: %1").arg(loc.services.geonames) label += "\n" + i18n.ctr("Latitude and longitude (coordinates)","lat: %1, lon: %2").arg(localeDezimalSeparator(loc.coord.lat)).arg(localeDezimalSeparator(loc.coord.lon)) return label; } function appendCities(list) { var a1Counts = {}; // count occurrences of name+adminName1 list.forEach(function(loc) { a1Counts[loc.name+loc.adminName1] = (!a1Counts[loc.name+loc.adminName1]) ? 1 : a1Counts[loc.name+loc.adminName1]+1; }); var a2Counts = {}; // count occurrences of name+adminName1+adminName2 list.forEach(function(loc) { a2Counts[loc.name+loc.adminName1+loc.adminName2] = (!a2Counts[loc.name+loc.adminName1+loc.adminName2]) ? 1 : a2Counts[loc.name+loc.adminName1+loc.adminName2]+1; }); // build area labels and add locations to listmodel list.forEach(function(loc) { loc.areaLabel = buildAreaLabel(loc, a1Counts, a2Counts); loc.stationdetails = buildStationDetailLabel(loc); citiesModel.append(loc); }); sortModel(); } function clearModelForLoading() { citiesModel.clear() citiesModel.loading = true citiesModel.httpError = false } function sortModel() { // sort model data by name attribute var n; var i; for (n=0; n < citiesModel.count; n++) { for (i=n+1; i < citiesModel.count; i++) { if (citiesModel.get(n).name > citiesModel.get(i).name) { citiesModel.move(i, n, 1); n=0; } } } } function loadEmpty() { clearModelForLoading() //retrieve data for each predefined city by coordinate Cities.megacities.forEach(function(citydata) { loadFromProvider(citydata,"searchByPoint") }); sortModel(); citiesModel.loading = false; } function loadFromProvider(searchstring, searchtype) { clearModelForLoading() var parameters //format parameters depending on search type to pass either coords or name if (searchtype === "searchByPoint") { parameters = { coords: searchstring, units: "metric", lang: getLocale() } } else { parameters = { name: searchstring, units: "metric", lang: getLocale() } } WeatherApi.sendRequest({ action: searchtype, params: parameters, }, searchResponseHandler) } function searchResponseHandler(msgObject) { if (!msgObject.error) { appendCities(msgObject.result.locations) } else { citiesModel.httpError = true //always set citiesModel to invisible, then provide an error message var errorCode = parseInt(msgObject.error.msg.replace("wrong response http code, got ", "")); console.log("location request error code: " + errorCode + "\n" + msgObject.error) if (errorCode == undefined || errorCode < 500) { 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 } else if (errorCode > 499) { requestFail.text = i18n.tr("Could not load data. Provider server unavailable. Please ensure you are connected to the Internet.") } } citiesModel.loading = false } ListView { id: locationList anchors { top: addLocationPage.header.bottom topMargin: units.gu(2) left: parent.left right: parent.right rightMargin: fastScroll.showing ? fastScroll.width - units.gu(1) : 0 bottom: parent.bottom } objectName: "locationList" clip: true currentIndex: -1 function getSectionText(index) { return citiesModel.get(index).name.substring(0,1) } onFlickStarted: forceActiveFocus() section.property: "name" section.criteria: ViewSection.FirstCharacter section.labelPositioning: ViewSection.InlineLabels section.delegate: ListItem { height: headerText.implicitHeight + units.gu(1) Label { id: headerText text: section anchors { left: parent.left; right: parent.right; margins: units.gu(2) } font.weight: Font.DemiBold } } model: ListModel { id: citiesModel property bool loading: true property bool httpError: false onRowsAboutToBeInserted: loading = false } delegate: ListItem { divider.visible: false objectName: "addLocation" + index height: listDelegateLayout.height ListItemLayout { id: listDelegateLayout title.text: name subtitle.text: areaLabel subtitle.textSize: Label.Small summary.text: stationdetails summary.textSize: Label.Small } onClicked: { if (storage.addLocation(citiesModel.get(index))) { mainPageStack.pop() } else { PopupUtils.open(locationExistsComponent, addLocationPage) } } } Component.onCompleted: loadEmpty() Behavior on anchors.rightMargin { LomiriNumberAnimation {} } } FastScroll { id: fastScroll listView: locationList enabled: (locationList.contentHeight > (locationList.height * 2)) && (locationList.height >= minimumHeight) anchors { top: locationList.top topMargin: units.gu(1.5) bottom: locationList.bottom right: parent.right } } ActivityIndicator { anchors { centerIn: parent } running: visible visible: citiesModel.loading } Label { id: noCity objectName: "noCity" anchors { centerIn: parent } text: i18n.tr("No city found") visible: citiesModel.count === 0 && !citiesModel.loading } Label { id: requestFail anchors { left: parent.left margins: units.gu(1) right: parent.right top: noCity.bottom } horizontalAlignment: Text.AlignHCenter visible: citiesModel.httpError wrapMode: Text.Wrap } Component { id: locationExistsComponent Dialog { id: locationExists title: i18n.tr("Location already added.") Button { text: i18n.tr("OK") onClicked: PopupUtils.close(locationExists) } } } }