Debian Codegraph @

src/app/qml/ui/LocationPane.qml

raw
1 /*
2 * Copyright (C) 2015, 2017 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 as UC
21 import QtQuick.Controls 2.2 as QC
22 import "../components"
23 import "../data/suncalc.js" as SunCalc
24 import "../data/moonphase.js" as MoonPhase
25 import "../data/moment-with-locales.js" as Moment
26 import "../data/moment-timezone-with-data-10-year-range.js" as MomentTimezone
27
28
29 ListView {
30 id: mainPageWeekdayListView
31 height: parent.height
32 model: ListModel {
33
34 }
35 width: weatherApp.width
36 // do not set anchors here, seems to break things
37
38 /*
39 Data properties
40 */
41 property string name
42 property string currentTemp
43 property string icon
44 property string iconName
45 property string currentCondition
46 property string currentFeelsLike
47 property string currentPrecipProp
48 property string currentHumidity
49 property string currentClouds
50 property string currentVisibility
51 property string currentWind
52 property string currentWindGusts
53 property string currentUV
54
55 property var hourlyForecastsData
56 property string hourlyTempUnit
57
58 property var todayData
59 property bool graphicVisible : false
60
61 property var lastFetch // don't store as int as reaches max int
62
63 property var extendedInfoMargin: units.gu(2.5) //needs to be greater than zero
64
65 delegate: DayDelegate {
66 width: parent.width
67 anchors {
68 left: parent.left
69 right: parent.right
70 leftMargin: extendedInfoMargin
71 rightMargin: extendedInfoMargin
72 }
73 day: checkToday(model.date) ? i18n.tr("Today") : model.day
74 high: model.high
75 image: model.image
76 low: model.low
77
78 modelData: model
79 }
80 header: UC.ListItem {
81 divider.visible: false
82 height: locationTop.height
83 width: parent.width
84
85 /* background rectangle to highlight todays info */
86 Rectangle {
87 id: coloredBackgroundRectangle
88 width: parent.width
89 height: units.gu(31.5)
90 color: settings.highlightToday ? UC.LomiriColors.graphite : "transparent"
91 opacity: 0.2
92
93 anchors {
94 top: locationTop.top
95 topMargin: units.gu(4) + headerRow.height + updatedLabel.height + locationsindicator.height
96 }
97 }
98
99 Column {
100 id: locationTop
101 width: parent.width
102
103 anchors {
104 left: parent.left
105 right: parent.right
106 margins: extendedInfoMargin // needs to be greater than 0 to attach properly to the page top
107 }
108 spacing: units.gu(1)
109
110 Row { // spacing at top = row height + column spacing value
111 height: units.gu(0.1)
112 width: parent.width
113 }
114
115 HeaderRow {
116 id: headerRow
117 locationName: mainPageWeekdayListView.name
118 }
119
120 property var updatedAt: mainPageWeekdayListView.lastFetch
121 onUpdatedAtChanged: diffTimer.restart()
122
123 UC.Label {
124 id: updatedLabel
125 font.weight: Font.Light
126 fontSize: "small"
127 text: i18n.tr("Today") + " - " + updatedAtText + " "
128
129 readonly property string updatedAtText: {
130 if (diffDays > 0) {
131 i18n.tr("updated %1 day ago", "updated %1 days ago", diffDays).arg(diffDays)
132 } else if (diffHours > 0) {
133 i18n.tr("updated %1 hour ago", "updated %1 hours ago", diffHours).arg(diffHours)
134 } else if (diffMinutes > 0) {
135 i18n.tr("updated %1 minute ago", "updated %1 minutes ago", diffMinutes).arg(diffMinutes)
136 } else {
137 i18n.tr("updated recently")
138 }
139 }
140
141 property var diff
142 property int diffMinutes: Math.floor(diff / 60)
143 property int diffHours: Math.floor(diffMinutes / 60)
144 property int diffDays: Math.floor(diffHours / 24)
145
146 // Check the time every 15 seconds
147 Timer {
148 id: diffTimer
149 interval: 15000
150 repeat: true
151 running: parent.visible
152 triggeredOnStart: true
153
154 onTriggered: parent.diff = ((new Date().getTime() - mainPageWeekdayListView.lastFetch) / 1000)
155 }
156 }
157
158 QC.PageIndicator {
159 id: locationsindicator
160 property int maxCount: 18
161 currentIndex: settings.current
162 count: weatherApp.locationsList.length
163 interactive: true
164 clip: true
165 anchors.horizontalCenter: parent.horizontalCenter
166
167 visible: weatherApp.locationsList.length > 1 ? true : false
168 height: weatherApp.locationsList.length > 1 ? units.gu(2) : -units.gu(1)
169 onCurrentIndexChanged: {settings.current = locationsindicator.currentIndex;}
170
171 delegate: Rectangle {
172 width: units.gu(1)
173 height: units.gu(1)
174 visible: locationsindicator.count > locationsindicator.maxCount ? false : true
175 radius: height/2
176 // uncomment to show location index inside of PageIndicator
177 // width: units.gu(1.8)
178 // radius: height/3.5
179 // UC.Label {
180 // anchors.horizontalCenter: parent.horizontalCenter
181 // anchors.verticalCenter: parent.verticalCenter
182 // text: index + 1 //adding one because index starts at zero
183 // font.pixelSize: units.gu(1.2)
184 // color: index === locationsindicator.currentIndex ? theme.palette.normal.background : theme.palette.normal.foregroundText
185 // }
186 color: theme.palette.normal.baseText
187 opacity: index === locationsindicator.currentIndex ? 0.90 : 0.4
188 Behavior on opacity {
189 OpacityAnimator {
190 duration: 100
191 }
192 }
193 }
194
195 // UC.Label {
196 // visible: locationsindicator.count > locationsindicator.maxCount ? true : false
197 // text: i18n.tr("too many locations to display page indicator") + " (> %1)".arg(locationsindicator.maxCount)
198 // font.weight: Font.Light
199 // font.pixelSize: units.gu(1.5)
200 // font.italic: true
201 // anchors.horizontalCenter: parent.horizontalCenter
202 // }
203 }
204
205 CurrentInfo {
206 id: currentInfo
207 width: parent.width
208 collapsedHeight: coloredBackgroundRectangle.height
209 modelData: todayData
210 now: mainPageWeekdayListView.currentTemp
211 icon: mainPageWeekdayListView.icon
212 conditionNow: mainPageWeekdayListView.currentCondition
213 feelsLike: mainPageWeekdayListView.currentFeelsLike
214 clouds: mainPageWeekdayListView.currentClouds
215 visibility: mainPageWeekdayListView.currentVisibility
216 wind: mainPageWeekdayListView.currentWind
217 windGusts: mainPageWeekdayListView.currentWindGusts
218 humidity: mainPageWeekdayListView.currentHumidity
219 precipitationPropability: mainPageWeekdayListView.currentPrecipProp
220 uvIndex: mainPageWeekdayListView.currentUV
221 }
222
223 Loader {
224 id: homeHourlyLoader
225 asynchronous: true
226 height: units.gu(23)
227 source: "../components/HomeHourly.qml"
228 visible: true
229 width: parent.width
230 }
231
232 // Row { // use this part of the code to add some space between hourly and daily forecast
233 // height: units.gu(1)
234 // width: parent.width
235 // }
236
237 NumberAnimation {
238 id: scrollToTopAnimation
239 target: mainPageWeekdayListView;
240 property: "contentY";
241 duration: 200;
242 easing.type: Easing.InOutQuad
243 to: -height
244 }
245
246 Connections {
247 target: locationPages
248 onCurrentIndexChanged: {
249 if (locationPages.currentIndex !== index) {
250 scrollToTopAnimation.start()
251 } else {
252 mainPageWeekdayListView.contentY = -locationTop.height
253 }
254 }
255 }
256 }
257 }
258
259 UC.PullToRefresh {
260 id: pullToRefresh
261 refreshing: false
262
263 onRefresh: {
264 if (networkError === false) {
265 locationPages.loaded = false
266 refreshing = true
267 refreshData(false, true)
268 } else {
269 mainPageStack.push(Qt.resolvedUrl("../components/NetworkErrorStateComponent.qml"));
270 refreshing = false
271 loading = false
272 refreshData(true, false)
273 }
274 }
275 }
276
277 //momentjs does not use dotted am/pm notation like a.m./p.m.
278 //this is edited here if needed
279 function dottify(ampmTime) {
280 var timeString = ampmTime
281 if (Qt.locale().amText.search(".") !== -1 && (timeString.search("m") !== -1 || timeString.search("M") !== -1)) {
282 timeString = timeString.replace("am","a.m.").replace("pm","p.m.").replace("AM","A.M.").replace("PM","P.M.")
283 }
284 return timeString
285 }
286
287 function getDayData(data) {
288 /*
289 Depending on weather data provider, the date is generally provided in local time
290 (including daylightsaving) of given day, BUT with different hours (00:00,11:59,...)
291 and also CAN BE in UTC.
292 To correctly calculate sunrise and sunset times and moonphase fraction,
293 we need to
294 - ensure to convert dates/times to local time including daylighsaving shifts
295 (using moment.js backed by IANA timezone data for that)
296 - set hours to fixed values we can work with
297 */
298
299 // calculate sunrise and sunset times using suncalc.js
300 moment.locale(Qt.locale().name); //initialize moment.js with the systems locale
301 var sunrise = SunCalc.SunCalc.getTimes(getDate(data.date), data.location.coord.lat, data.location.coord.lon).sunrise.getTime();
302 sunrise = moment(sunrise).tz(data.location.timezone.timeZoneId).format("LT"); //use locale time format for hours + minutes
303 var sunset = SunCalc.SunCalc.getTimes(getDate(data.date), data.location.coord.lat, data.location.coord.lon).sunset.getTime();
304 sunset = moment(sunset).tz(data.location.timezone.timeZoneId).format("LT"); //use locale time format for hours + minutes
305 // calculate moonphase fraction for start of day and end of day using suncalc.js
306 // moon label and image are determined based on the moonphase fraction in moonphase.js
307 var zeroHoursDate = new Date(data.date.year, data.date.month, data.date.date,0,0,0)
308 var dayEndHoursDate = new Date(data.date.year, data.date.month, data.date.date,23,59,59)
309 var moonPhaseString = MoonPhase.getMoonPhaseString(zeroHoursDate,dayEndHoursDate).moonphase;
310 var moonPhaseImage = MoonPhase.getMoonPhaseString(zeroHoursDate,dayEndHoursDate).moonimage;
311 return {
312 // for undefined values -255 is returned, as specified for checkUndefined() in lomiri-weather-app.qml
313 day: formatTimestampLocaleShort(data.date) + " " + formatTimestamp(data.date,"ddd"),
314 date: data.date, // used for today check in DayDelegate
315 low: getTemp(data["metric"].tempMin, true),
316 high: getTemp(data["metric"].tempMax, true),
317 image: (data.icon !== undefined && iconMap[data.icon] !== undefined) ? iconMap[data.icon] : "",
318 condition: emptyIfUndefined(data.condition),
319 // on extended day info only show rain and snow if there is a value greater than zero
320 rain: data.rain !== -255 ? getRain(data.rain) : "", //'undefined' will cause an "can't convert undefined as QString" error //-> set in homepage.qml
321 snow: data.snow !== -255 ? getSnow(data.snow) : "", //'undefined' will cause an "can't convert undefined as QString" error //-> set in homepage.qml
322 //humidity forecast only provided for 15 days, other days -255 returned -> omit those values
323 //TRANSLATORS: % (percent) is the unit for humidity or chance or precipitation, add a space before the unit according to your language specifications
324 humidity: data.humidity !== -255 ? i18n.ctr("%1 will be replaced with the value, unit % for humidity, daily forecast", "%1%").arg(data.humidity) : "",
325 clouds: data.clouds,
326 sunrise: dottify(sunrise),
327 sunset: dottify(sunset),
328 moonPhase: moonPhaseString,
329 moonImage: moonPhaseImage,
330 //pressure forecast only provided for 15 days, other days -255 returned -> omit those values
331 //TRANSLATORS: hectopascal, unit for air pressure, only use abbreviated
332 pressure: data.pressure !== -255 ? i18n.ctr("pressure, daily forecast","%1 hPa").arg(data.pressure) : "",
333 windSpeed: data.windSpeed, //for current wind
334 windDir: data.windDir, //for current wind
335 wind: data.windSpeed === undefined || data.windDir === undefined //used for daily forecast wind info
336 //TRANSLATORS: first value is wind speed, second value is wind bearing, reorder and keep/remove space as suitable
337 ? "" : i18n.ctr("wind data, daily forecast","%1 %2").arg(getWindSpeed(data.windSpeed)).arg(getWindBearing(data.windDir)),
338 uvIndexDay: localeDezimalSeparator(data.uvIndexDay) + getUVLevel(data.uvIndexDay),
339 //TRANSLATORS: % (percent) is the unit for humidity or chance or precipitation, add a space before the unit according to your language specifications
340 chanceOfPrecip: data.pop !== -255 ? i18n.ctr("%1 will be replaced with the value, unit % for chance of precipitation, daily forecast", "%1%").arg(data.pop*100) : "",
341 sunshinetime: data.sunshinetime
342 };
343 }
344
345 /*
346 Extracts values from the location weather data and puts them into the appropriate components
347 to display them.
348
349 Attention: Data access happens through "weatherApp.locationList[]" by index, since complex
350 data in models will lead to type problems.
351 */
352 function renderData(index) {
353 var data = weatherApp.locationsList[index],
354 current = data.data[0].current,
355 forecasts = data.data,
356 forecastsLength = forecasts.length,
357 hourlyForecasts = [];
358
359 // set general location data
360 name = data.location.name;
361
362 // set current temps and condition
363 iconName = (current.icon) ? current.icon : "";
364 icon = (imageMap[iconName] !== undefined) ? imageMap[iconName] : "";
365 currentTemp = getTemp(current["metric"].temp,false) + "°"; //without unit to save space
366 currentCondition = current.condition;
367 //TRANSLATORS: feels like refers to the current temperature as how it feels adjusted e.g. by wind
368 currentFeelsLike = current["metric"].feels_like !== undefined ? i18n.ctr("current weather","feels like %1").arg(getTemp(current["metric"].feels_like,true)) : "";
369 //TRANSLATORS: %1 is cloud coverage in percent, keep/remove the space before the unit according to your language specifications
370 currentClouds = current.clouds !== undefined ? i18n.ctr("current weather","Clouds: %1 %").arg(current.clouds) : "";
371 //TRANSLATORS: %1 is wind speed including unit and %2 is wind direction
372 currentWind = i18n.ctr("current weather","Wind: %1 %2").arg(getWindSpeed(current.windSpeed)).arg(getWindBearing(current.windDir));
373 currentWindGusts = i18n.ctr("current weather","Wind gusts: %1").arg(getWindSpeed(current.windGusts));
374 //TRANSLATORS: humidity in percent, keep/remove the space before the unit according to your language specifications
375 currentHumidity = current.humidity !== undefined ? i18n.ctr("humidity, current weather","Humidity: %1 %").arg(current.humidity) : "";
376 currentUV = i18n.ctr("current weather","UV Index: %1").arg(localeDezimalSeparator(current.uvIndex ) + getUVLevel(current.uvIndex ));
377 currentPrecipProp = current.precipProp !== undefined ? i18n.ctr("current weather chance of precipitation","%1 %").arg(current.precipProp) : "";
378 currentVisibility = i18n.ctr("current weather","Visibility: %1").arg(getVisibility(current.visibility));
379
380 // reset days list
381 mainPageWeekdayListView.model.clear()
382
383 // set daily forecasts
384 if(forecastsLength > 0) {
385 for(var x=0;x<forecastsLength;x++) {
386 // collect hourly forecasts if available
387 if(forecasts[x].hourly !== undefined && forecasts[x].hourly.length > 0) {
388 hourlyForecasts = hourlyForecasts.concat(forecasts[x].hourly)
389 }
390
391 // Copy the coords and timezone of the location
392 // so that sun{rise,set} work with OWM
393 forecasts[x].location = {
394 coord: data.location.coord,
395 timezone: data.location.timezone
396 };
397
398 if (x === 0) {
399 // store today's data for later use
400 todayData = getDayData(forecasts[x]);
401 // mainPageWeekdayListView.model.append(getDayData(forecasts[x])); //uncomment to add todays data to forecast list
402 } else {
403 // set daydata
404 mainPageWeekdayListView.model.append(getDayData(forecasts[x]));
405 }
406 }
407 }
408
409 // set data for hourly forecasts
410 if(hourlyForecasts.length > 0) {
411 hourlyForecastsData = hourlyForecasts;
412 }
413
414 // Set last updated time
415 mainPageWeekdayListView.lastFetch = data.updated;
416 }
417
418 function checkToday(datadate) {
419 var day = Qt.formatDate(new Date(datadate.year, datadate.month, datadate.date, datadate.hours, datadate.minutes))
420 var today = Qt.formatDate(new Date())
421 return today === day ? true : false
422 }
423
424 Component.onCompleted: renderData(index)
425 }