/*
* Copyright (C) 2015, 2017 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 as UC
import QtQuick.Controls 2.2 as QC
import "../components"
import "../data/suncalc.js" as SunCalc
import "../data/moonphase.js" as MoonPhase
import "../data/moment-with-locales.js" as Moment
import "../data/moment-timezone-with-data-10-year-range.js" as MomentTimezone
ListView {
id: mainPageWeekdayListView
height: parent.height
model: ListModel {
}
width: weatherApp.width
// do not set anchors here, seems to break things
/*
Data properties
*/
property string name
property string currentTemp
property string icon
property string iconName
property string currentCondition
property string currentFeelsLike
property string currentPrecipProp
property string currentHumidity
property string currentClouds
property string currentVisibility
property string currentWind
property string currentWindGusts
property string currentUV
property var hourlyForecastsData
property string hourlyTempUnit
property var todayData
property bool graphicVisible : false
property var lastFetch // don't store as int as reaches max int
property var extendedInfoMargin: units.gu(2.5) //needs to be greater than zero
delegate: DayDelegate {
width: parent.width
anchors {
left: parent.left
right: parent.right
leftMargin: extendedInfoMargin
rightMargin: extendedInfoMargin
}
day: checkToday(model.date) ? i18n.tr("Today") : model.day
high: model.high
image: model.image
low: model.low
modelData: model
}
header: UC.ListItem {
divider.visible: false
height: locationTop.height
width: parent.width
/* background rectangle to highlight todays info */
Rectangle {
id: coloredBackgroundRectangle
width: parent.width
height: units.gu(31.5)
color: settings.highlightToday ? UC.LomiriColors.graphite : "transparent"
opacity: 0.2
anchors {
top: locationTop.top
topMargin: units.gu(4) + headerRow.height + updatedLabel.height + locationsindicator.height
}
}
Column {
id: locationTop
width: parent.width
anchors {
left: parent.left
right: parent.right
margins: extendedInfoMargin // needs to be greater than 0 to attach properly to the page top
}
spacing: units.gu(1)
Row { // spacing at top = row height + column spacing value
height: units.gu(0.1)
width: parent.width
}
HeaderRow {
id: headerRow
locationName: mainPageWeekdayListView.name
}
property var updatedAt: mainPageWeekdayListView.lastFetch
onUpdatedAtChanged: diffTimer.restart()
UC.Label {
id: updatedLabel
font.weight: Font.Light
fontSize: "small"
text: i18n.tr("Today") + " - " + updatedAtText + " "
readonly property string updatedAtText: {
if (diffDays > 0) {
i18n.tr("updated %1 day ago", "updated %1 days ago", diffDays).arg(diffDays)
} else if (diffHours > 0) {
i18n.tr("updated %1 hour ago", "updated %1 hours ago", diffHours).arg(diffHours)
} else if (diffMinutes > 0) {
i18n.tr("updated %1 minute ago", "updated %1 minutes ago", diffMinutes).arg(diffMinutes)
} else {
i18n.tr("updated recently")
}
}
property var diff
property int diffMinutes: Math.floor(diff / 60)
property int diffHours: Math.floor(diffMinutes / 60)
property int diffDays: Math.floor(diffHours / 24)
// Check the time every 15 seconds
Timer {
id: diffTimer
interval: 15000
repeat: true
running: parent.visible
triggeredOnStart: true
onTriggered: parent.diff = ((new Date().getTime() - mainPageWeekdayListView.lastFetch) / 1000)
}
}
QC.PageIndicator {
id: locationsindicator
property int maxCount: 18
currentIndex: settings.current
count: weatherApp.locationsList.length
interactive: true
clip: true
anchors.horizontalCenter: parent.horizontalCenter
visible: weatherApp.locationsList.length > 1 ? true : false
height: weatherApp.locationsList.length > 1 ? units.gu(2) : -units.gu(1)
onCurrentIndexChanged: {settings.current = locationsindicator.currentIndex;}
delegate: Rectangle {
width: units.gu(1)
height: units.gu(1)
visible: locationsindicator.count > locationsindicator.maxCount ? false : true
radius: height/2
// uncomment to show location index inside of PageIndicator
// width: units.gu(1.8)
// radius: height/3.5
// UC.Label {
// anchors.horizontalCenter: parent.horizontalCenter
// anchors.verticalCenter: parent.verticalCenter
// text: index + 1 //adding one because index starts at zero
// font.pixelSize: units.gu(1.2)
// color: index === locationsindicator.currentIndex ? theme.palette.normal.background : theme.palette.normal.foregroundText
// }
color: theme.palette.normal.baseText
opacity: index === locationsindicator.currentIndex ? 0.90 : 0.4
Behavior on opacity {
OpacityAnimator {
duration: 100
}
}
}
// UC.Label {
// visible: locationsindicator.count > locationsindicator.maxCount ? true : false
// text: i18n.tr("too many locations to display page indicator") + " (> %1)".arg(locationsindicator.maxCount)
// font.weight: Font.Light
// font.pixelSize: units.gu(1.5)
// font.italic: true
// anchors.horizontalCenter: parent.horizontalCenter
// }
}
CurrentInfo {
id: currentInfo
width: parent.width
collapsedHeight: coloredBackgroundRectangle.height
modelData: todayData
now: mainPageWeekdayListView.currentTemp
icon: mainPageWeekdayListView.icon
conditionNow: mainPageWeekdayListView.currentCondition
feelsLike: mainPageWeekdayListView.currentFeelsLike
clouds: mainPageWeekdayListView.currentClouds
visibility: mainPageWeekdayListView.currentVisibility
wind: mainPageWeekdayListView.currentWind
windGusts: mainPageWeekdayListView.currentWindGusts
humidity: mainPageWeekdayListView.currentHumidity
precipitationPropability: mainPageWeekdayListView.currentPrecipProp
uvIndex: mainPageWeekdayListView.currentUV
}
Loader {
id: homeHourlyLoader
asynchronous: true
height: units.gu(23)
source: "../components/HomeHourly.qml"
visible: true
width: parent.width
}
// Row { // use this part of the code to add some space between hourly and daily forecast
// height: units.gu(1)
// width: parent.width
// }
NumberAnimation {
id: scrollToTopAnimation
target: mainPageWeekdayListView;
property: "contentY";
duration: 200;
easing.type: Easing.InOutQuad
to: -height
}
Connections {
target: locationPages
onCurrentIndexChanged: {
if (locationPages.currentIndex !== index) {
scrollToTopAnimation.start()
} else {
mainPageWeekdayListView.contentY = -locationTop.height
}
}
}
}
}
UC.PullToRefresh {
id: pullToRefresh
refreshing: false
onRefresh: {
if (networkError === false) {
locationPages.loaded = false
refreshing = true
refreshData(false, true)
} else {
mainPageStack.push(Qt.resolvedUrl("../components/NetworkErrorStateComponent.qml"));
refreshing = false
loading = false
refreshData(true, false)
}
}
}
//momentjs does not use dotted am/pm notation like a.m./p.m.
//this is edited here if needed
function dottify(ampmTime) {
var timeString = ampmTime
if (Qt.locale().amText.search(".") !== -1 && (timeString.search("m") !== -1 || timeString.search("M") !== -1)) {
timeString = timeString.replace("am","a.m.").replace("pm","p.m.").replace("AM","A.M.").replace("PM","P.M.")
}
return timeString
}
function getDayData(data) {
/*
Depending on weather data provider, the date is generally provided in local time
(including daylightsaving) of given day, BUT with different hours (00:00,11:59,...)
and also CAN BE in UTC.
To correctly calculate sunrise and sunset times and moonphase fraction,
we need to
- ensure to convert dates/times to local time including daylighsaving shifts
(using moment.js backed by IANA timezone data for that)
- set hours to fixed values we can work with
*/
// calculate sunrise and sunset times using suncalc.js
moment.locale(Qt.locale().name); //initialize moment.js with the systems locale
var sunrise = SunCalc.SunCalc.getTimes(getDate(data.date), data.location.coord.lat, data.location.coord.lon).sunrise.getTime();
sunrise = moment(sunrise).tz(data.location.timezone.timeZoneId).format("LT"); //use locale time format for hours + minutes
var sunset = SunCalc.SunCalc.getTimes(getDate(data.date), data.location.coord.lat, data.location.coord.lon).sunset.getTime();
sunset = moment(sunset).tz(data.location.timezone.timeZoneId).format("LT"); //use locale time format for hours + minutes
// calculate moonphase fraction for start of day and end of day using suncalc.js
// moon label and image are determined based on the moonphase fraction in moonphase.js
var zeroHoursDate = new Date(data.date.year, data.date.month, data.date.date,0,0,0)
var dayEndHoursDate = new Date(data.date.year, data.date.month, data.date.date,23,59,59)
var moonPhaseString = MoonPhase.getMoonPhaseString(zeroHoursDate,dayEndHoursDate).moonphase;
var moonPhaseImage = MoonPhase.getMoonPhaseString(zeroHoursDate,dayEndHoursDate).moonimage;
return {
// for undefined values -255 is returned, as specified for checkUndefined() in lomiri-weather-app.qml
day: formatTimestampLocaleShort(data.date) + " " + formatTimestamp(data.date,"ddd"),
date: data.date, // used for today check in DayDelegate
low: getTemp(data["metric"].tempMin, true),
high: getTemp(data["metric"].tempMax, true),
image: (data.icon !== undefined && iconMap[data.icon] !== undefined) ? iconMap[data.icon] : "",
condition: emptyIfUndefined(data.condition),
// on extended day info only show rain and snow if there is a value greater than zero
rain: data.rain !== -255 ? getRain(data.rain) : "", //'undefined' will cause an "can't convert undefined as QString" error //-> set in homepage.qml
snow: data.snow !== -255 ? getSnow(data.snow) : "", //'undefined' will cause an "can't convert undefined as QString" error //-> set in homepage.qml
//humidity forecast only provided for 15 days, other days -255 returned -> omit those values
//TRANSLATORS: % (percent) is the unit for humidity or chance or precipitation, add a space before the unit according to your language specifications
humidity: data.humidity !== -255 ? i18n.ctr("%1 will be replaced with the value, unit % for humidity, daily forecast", "%1%").arg(data.humidity) : "",
clouds: data.clouds,
sunrise: dottify(sunrise),
sunset: dottify(sunset),
moonPhase: moonPhaseString,
moonImage: moonPhaseImage,
//pressure forecast only provided for 15 days, other days -255 returned -> omit those values
//TRANSLATORS: hectopascal, unit for air pressure, only use abbreviated
pressure: data.pressure !== -255 ? i18n.ctr("pressure, daily forecast","%1 hPa").arg(data.pressure) : "",
windSpeed: data.windSpeed, //for current wind
windDir: data.windDir, //for current wind
wind: data.windSpeed === undefined || data.windDir === undefined //used for daily forecast wind info
//TRANSLATORS: first value is wind speed, second value is wind bearing, reorder and keep/remove space as suitable
? "" : i18n.ctr("wind data, daily forecast","%1 %2").arg(getWindSpeed(data.windSpeed)).arg(getWindBearing(data.windDir)),
uvIndexDay: localeDezimalSeparator(data.uvIndexDay) + getUVLevel(data.uvIndexDay),
//TRANSLATORS: % (percent) is the unit for humidity or chance or precipitation, add a space before the unit according to your language specifications
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) : "",
sunshinetime: data.sunshinetime
};
}
/*
Extracts values from the location weather data and puts them into the appropriate components
to display them.
Attention: Data access happens through "weatherApp.locationList[]" by index, since complex
data in models will lead to type problems.
*/
function renderData(index) {
var data = weatherApp.locationsList[index],
current = data.data[0].current,
forecasts = data.data,
forecastsLength = forecasts.length,
hourlyForecasts = [];
// set general location data
name = data.location.name;
// set current temps and condition
iconName = (current.icon) ? current.icon : "";
icon = (imageMap[iconName] !== undefined) ? imageMap[iconName] : "";
currentTemp = getTemp(current["metric"].temp,false) + "°"; //without unit to save space
currentCondition = current.condition;
//TRANSLATORS: feels like refers to the current temperature as how it feels adjusted e.g. by wind
currentFeelsLike = current["metric"].feels_like !== undefined ? i18n.ctr("current weather","feels like %1").arg(getTemp(current["metric"].feels_like,true)) : "";
//TRANSLATORS: %1 is cloud coverage in percent, keep/remove the space before the unit according to your language specifications
currentClouds = current.clouds !== undefined ? i18n.ctr("current weather","Clouds: %1 %").arg(current.clouds) : "";
//TRANSLATORS: %1 is wind speed including unit and %2 is wind direction
currentWind = i18n.ctr("current weather","Wind: %1 %2").arg(getWindSpeed(current.windSpeed)).arg(getWindBearing(current.windDir));
currentWindGusts = i18n.ctr("current weather","Wind gusts: %1").arg(getWindSpeed(current.windGusts));
//TRANSLATORS: humidity in percent, keep/remove the space before the unit according to your language specifications
currentHumidity = current.humidity !== undefined ? i18n.ctr("humidity, current weather","Humidity: %1 %").arg(current.humidity) : "";
currentUV = i18n.ctr("current weather","UV Index: %1").arg(localeDezimalSeparator(current.uvIndex ) + getUVLevel(current.uvIndex ));
currentPrecipProp = current.precipProp !== undefined ? i18n.ctr("current weather chance of precipitation","%1 %").arg(current.precipProp) : "";
currentVisibility = i18n.ctr("current weather","Visibility: %1").arg(getVisibility(current.visibility));
// reset days list
mainPageWeekdayListView.model.clear()
// set daily forecasts
if(forecastsLength > 0) {
for(var x=0;x 0) {
hourlyForecasts = hourlyForecasts.concat(forecasts[x].hourly)
}
// Copy the coords and timezone of the location
// so that sun{rise,set} work with OWM
forecasts[x].location = {
coord: data.location.coord,
timezone: data.location.timezone
};
if (x === 0) {
// store today's data for later use
todayData = getDayData(forecasts[x]);
// mainPageWeekdayListView.model.append(getDayData(forecasts[x])); //uncomment to add todays data to forecast list
} else {
// set daydata
mainPageWeekdayListView.model.append(getDayData(forecasts[x]));
}
}
}
// set data for hourly forecasts
if(hourlyForecasts.length > 0) {
hourlyForecastsData = hourlyForecasts;
}
// Set last updated time
mainPageWeekdayListView.lastFetch = data.updated;
}
function checkToday(datadate) {
var day = Qt.formatDate(new Date(datadate.year, datadate.month, datadate.date, datadate.hours, datadate.minutes))
var today = Qt.formatDate(new Date())
return today === day ? true : false
}
Component.onCompleted: renderData(index)
}