kdeplasma-addons: reimplement weather applet and move it to kde-workspace repo

the weather wallpaper plugin needed overhaul to make it work
out-of-the-box properly but I am not into it so it is simply dropped

Signed-off-by: Ivailo Monev <xakepa10@gmail.com>
This commit is contained in:
Ivailo Monev 2023-09-23 14:46:21 +03:00
parent 41110f2399
commit 69dcd67699
61 changed files with 0 additions and 7408 deletions

View file

@ -21,7 +21,6 @@ include_directories(
${CMAKE_CURRENT_SOURCE_DIR}/libs
)
add_subdirectory(libs)
add_subdirectory(applets)
add_subdirectory(dataengines)
add_subdirectory(runners)

View file

@ -1,5 +1,3 @@
# this works also for the weatherutils include dir, but should be done properly, Alex
include_directories(${PLASMACLOCK_INCLUDE_DIR})
add_subdirectory(bball)
@ -19,7 +17,6 @@ add_subdirectory(spellcheck)
add_subdirectory(timer)
add_subdirectory(eyes)
add_subdirectory(unitconverter)
add_subdirectory(weatherstation)
add_subdirectory(dict)
add_subdirectory(incomingmsg)
add_subdirectory(showdesktop)
@ -29,6 +26,5 @@ add_subdirectory(systemloadviewer)
if(KDE4WORKSPACE_FOUND)
add_subdirectory(binary-clock)
add_subdirectory(fuzzy-clock)
add_subdirectory(weather)
add_subdirectory(icontasks)
endif()

View file

@ -1,36 +0,0 @@
project(weatherapplet)
include_directories(
# for plasmaweather_export.h
${kdeplasma-addons_BINARY_DIR}/libs/plasmaweather
)
set(weatherapplet_SRCS
weatherapplet.cpp)
kde4_add_plugin(plasma_applet_weather ${weatherapplet_SRCS})
target_link_libraries(plasma_applet_weather
KDE4::plasma
KDE4::kio
KDE4::kdeui
KDE4Workspace::weather_ion
${QT_QTDECLARATIVE_LIBRARY}
plasmaweather
)
install(
TARGETS plasma_applet_weather
DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}
)
install(
FILES plasma-applet-weather.desktop
DESTINATION ${KDE4_SERVICES_INSTALL_DIR}
)
install(
FILES wind-arrows.svgz
DESTINATION ${KDE4_DATA_INSTALL_DIR}/desktoptheme/default/weather/
)
install(
DIRECTORY package/
DESTINATION ${KDE4_DATA_INSTALL_DIR}/plasma/packages/org.kde.weather
)

View file

@ -1,2 +0,0 @@
#! /usr/bin/env bash
$XGETTEXT *.cpp -o $podir/plasma_applet_weather.pot

View file

@ -1,59 +0,0 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*/
import QtQuick 1.1
import org.kde.plasma.core 0.1 as PlasmaCore
import org.kde.qtextracomponents 0.1 as QtExtraComponents
WeatherListView {
id: root
roundedRows: false
delegate: Item {
anchors.fill: parent
Item {
anchors.centerIn: parent
height: parent.height
width: childrenRect.width
QtExtraComponents.QPixmapItem {
id: icon
pixmap: svg.pixmap(rowData.icon)
height: nativeHeight
width: nativeWidth
visible: rowData.icon.length > 0
}
Text {
anchors {
left: icon.right
leftMargin: 2
verticalCenter: parent.verticalCenter
}
color: theme.textColor
text: rowData.text
}
}
}
PlasmaCore.Svg {
id: svg
imagePath: "weather/wind-arrows"
}
}

View file

@ -1,88 +0,0 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*/
import QtQuick 1.1
import org.kde.plasma.core 0.1 as PlasmaCore
import org.kde.qtextracomponents 0.1 as QtExtraComponents
import "Utils.js" as Utils
WeatherListView {
id: root
delegate: Row {
anchors.fill: parent
Repeater {
id: rowRepeater
model: rowData
Loader {
height: rowIndex == 1 ? parent.height + root.spacing : parent.height
width: parent.width / rowRepeater.count
sourceComponent: rowIndex == 1 ? iconDelegate : textDelegate
onLoaded: {
if (rowIndex == 1) {
var values = modelData.split("|");
item.icon = values[0];
item.toolTip = values[1];
} else {
var txt = modelData;
if (txt.indexOf("nt") != -1)
txt = txt.replace(" nt", "");
item.text = txt;
}
if (rowIndex == 0)
item.font.bold = true;
}
}
}
}
Component {
id: textDelegate
Text {
function checkTitle(txt) {
return txt.indexOf("ight") != -1 || txt.indexOf("nite") != -1;
}
width: parent.width
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
color: theme.textColor
opacity: font.bold && checkTitle(text) ? 0.5 : 1
}
}
Component {
id: iconDelegate
QtExtraComponents.QIconItem {
property alias toolTip: iconToolTip.mainText
anchors.centerIn: parent
anchors.verticalCenterOffset: -root.spacing/2
PlasmaCore.ToolTip {
id: iconToolTip
target: parent
}
}
}
}

View file

@ -1,47 +0,0 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*/
import QtQuick 1.1
Column {
property alias model: repeater.model
property alias title: title.text
anchors.left: parent.left
anchors.right: parent.right
Text {
id: title
font.bold: true
color: theme.textColor
}
Repeater {
id: repeater
Text {
font.underline: true
color: theme.linkColor
text: modelData.description
MouseArea {
anchors.fill: parent
onClicked: weatherApplet.invokeBrowser(modelData.info);
}
}
}
}

View file

@ -1,38 +0,0 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*/
import QtQuick 1.1
Column {
id: root
property variant model
spacing: 10
visible: model.length > 0 && model[0].length > 0 && model[1].length > 0
clip: true
Notice {
title: i18nc("weather warnings", "Warnings Issued:")
model: root.model[0]
}
Notice {
title: i18nc("weather watches" ,"Watches Issued:")
model: root.model[1]
}
}

View file

@ -1,85 +0,0 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*/
import QtQuick 1.1
import org.kde.plasma.core 0.1 as PlasmaCore
import org.kde.qtextracomponents 0.1 as QtExtraComponents
PlasmaCore.FrameSvgItem {
property variant model
imagePath: "widgets/frame"
prefix: "plain"
visible: model.location.length > 0
QtExtraComponents.QIconItem {
icon: model.conditionIcon
height: parent.height
width: height
}
Text {
id: locationLabel
anchors {
top: parent.top
left: parent.left
right: tempLabel.visible ? forecastTempsLabel.left : parent.right
topMargin: 5
leftMargin: parent.width * 0.21
}
font.bold: true
color: theme.textColor
text: model.location
elide: Text.ElideRight
Component.onCompleted: font.pointSize = Math.floor(font.pointSize * 1.4);
}
Text {
id: conditionLabel
anchors {
top: parent.top
left: locationLabel.left
topMargin: parent.height * 0.6
}
color: theme.textColor
text: model.conditions
}
Text {
id: tempLabel
anchors {
right: parent.right
top: locationLabel.top
rightMargin: 5
}
font: locationLabel.font
color: theme.textColor
text: model.temp
}
Text{
id: forecastTempsLabel
anchors {
right: tempLabel.right
top: conditionLabel.top
}
font.pointSize: theme.smallestFont.pointSize
color: theme.textColor
text: model.forecastTemps
}
}

View file

@ -1,11 +0,0 @@
.pragma library
function setAlphaF(solidColor, alpha) {
var solid = String(solidColor);
var alphaHex = Math.round(alpha * 255).toString(16);
if (alphaHex.length === 1)
alphaHex = "0" + alphaHex;
return "#" + alphaHex + solid.slice(1);
}

View file

@ -1,49 +0,0 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*/
import QtQuick 1.1
import "Utils.js" as Utils
Column {
id: root
property alias model: repeater.model
property Component delegate
property bool roundedRows: true
property int rowHeight: 18
spacing: (root.height - (repeater.count*rowHeight)) / (repeater.count-1)
Repeater {
id: repeater
Rectangle {
id: rect
height: root.rowHeight
width: root.width
radius: root.roundedRows ? 5 : 0
color: Utils.setAlphaF(theme.textColor, ((index+1)/repeater.count)*0.3);
Loader {
property int rowIndex: index
property variant rowData: modelData
anchors.fill: parent
sourceComponent: root.delegate
}
}
}
}

View file

@ -1,121 +0,0 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*/
import QtQuick 1.1
import org.kde.plasma.core 0.1 as PlasmaCore
import org.kde.plasma.components 0.1 as PlasmaComponents
Item {
id: root
property int minimumWidth: 373
property int minimumHeight: 272
anchors.fill: parent
clip: true
PlasmaCore.Theme {
id: theme
}
TopPanel {
id: panel
anchors {
top: parent.top
left: parent.left
right: parent.right
margins: 5
}
height: parent.height * 0.21
model: weatherApplet.panelModel
}
PlasmaComponents.TabBar {
id: tabBar
anchors {
top: panel.bottom
topMargin: 5
horizontalCenter: parent.horizontalCenter
}
visible: detailsView.model.length > 0
PlasmaComponents.TabButton {
text: weatherApplet.panelModel.totalDays
tab: fiveDaysView
}
PlasmaComponents.TabButton {
text: i18n("Details")
tab: detailsView
}
PlasmaComponents.TabButton {
text: i18n("Notices")
visible: noticesView.visible
onClicked: noticesView
}
}
PlasmaComponents.TabGroup {
id: mainTabGroup
anchors {
top: tabBar.visible ? tabBar.bottom : tabBar.top
bottom: courtesyLabel.top
topMargin: 12
bottomMargin: 15
}
width: panel.width
FiveDaysView {
id: fiveDaysView
anchors.fill: parent
model: weatherApplet.fiveDaysModel
}
DetailsView {
id: detailsView
anchors.fill: parent
model: weatherApplet.detailsModel
}
NoticesView {
id: noticesView
anchors.fill: parent
model: weatherApplet.noticesModel
}
}
Text {
id: courtesyLabel
anchors {
bottom: parent.bottom
right: parent.right
bottomMargin: 7
}
font {
pointSize: theme.smallestFont.pointSize
underline: mouseArea.enabled
}
color: theme.textColor
text: weatherApplet.panelModel.courtesy
MouseArea {
id: mouseArea
anchors.fill: parent
enabled: weatherApplet.panelModel.enableLink
onClicked: weatherApplet.invokeBrowser();
}
}
}

View file

@ -1,60 +0,0 @@
[Desktop Entry]
Encoding=UTF-8
Name=Weather Forecast (QML)
Name[ar]=تنبؤات الطقس (QML)
Name[bs]=Vremenska prognoza (QML)
Name[ca]=Previsió meteorològica (QML)
Name[ca@valencia]=Previsió meteorològica (QML)
Name[cs]=Předpověď počasí (QML)
Name[da]=Vejrudsigt (QML)
Name[de]=Wettervorhersage (QML)
Name[el]=Πρόγνωση καιρού (QML)
Name[en_GB]=Weather Forecast (QML)
Name[es]=Previsión meteorológica (QML)
Name[et]=Ilmateade (QML)
Name[fi]=Sääennuste (QML)
Name[fr]=Bulletin météorologique (QML)
Name[ga]=Réamhaisnéis Aimsire (QML)
Name[gl]=Prognóstico meteorolóxico (QML)
Name[hu]=Időjárás-előrejelzés (QML)
Name[it]=Previsioni meteo (QML)
Name[kk]=Ауа райын болжау (QML)
Name[ko]= (QML)
Name[lt]=Orų prognozė (QML)
Name[mr]= (QML)
Name[nb]=Værmelding (QML)
Name[nds]=Wederbericht (QML)
Name[nl]=Weersvoorspelling (QML)
Name[pa]= (QML)
Name[pl]=Prognoza pogody (QML)
Name[pt]=Boletim Meteorológico (QML)
Name[pt_BR]=Previsão meteorológica (QML)
Name[ro]=Prognoza vremii (QML)
Name[ru]=Прогноз погоды (порт на QML)
Name[sk]=Predpoveď počasia (QML)
Name[sl]=Vremenska napoved (QML)
Name[sr]=временска прогноза (КуМЛ)
Name[sr@ijekavian]=временска прогноза (КуМЛ)
Name[sr@ijekavianlatin]=vremenska prognoza (QML)
Name[sr@latin]=vremenska prognoza (QML)
Name[sv]=Väderprognos (QML)
Name[tr]=Hava Tahmini (QML)
Name[uk]=Прогноз погоди (QML)
Name[x-test]=xxWeather Forecast (QML)xx
Name[zh_CN]= (QML)
Name[zh_TW]= (QML)
Type=Service
ServiceTypes=Plasma/Applet,Plasma/PopupApplet
Icon=weather-clear
X-Plasma-MainScript=ui/main.qml
X-Plasma-DefaultSize=250,350
X-Plasma-NotificationArea=true
X-KDE-PluginInfo-Author=Luís Gabriel Lima
X-KDE-PluginInfo-Email=lampih@gmail.com
X-KDE-PluginInfo-Name=org.kde.weather
X-KDE-PluginInfo-Version=1.0
X-KDE-PluginInfo-Website=
X-KDE-PluginInfo-Category=Examples
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPLv2+
X-KDE-PluginInfo-EnabledByDefault=true

View file

@ -1,128 +0,0 @@
[Desktop Entry]
Encoding=UTF-8
Name=Weather Forecast
Name[ar]=تنبؤات الطقس
Name[ast]=Previsión meteorolóxica
Name[bs]=Vremenska prognoza
Name[ca]=Previsió meteorològica
Name[ca@valencia]=Previsió meteorològica
Name[cs]=Předpověď počasí
Name[da]=Vejrudsigt
Name[de]=Wetterbericht
Name[el]=Πρόγνωση καιρού
Name[en_GB]=Weather Forecast
Name[es]=Previsión meteorológica
Name[et]=Ilmateade
Name[eu]=Eguraldi iragarpena
Name[fi]=Sääennuste
Name[fr]=Bulletin météorologique
Name[ga]=Réamhaisnéis Aimsire
Name[gl]=Prognóstico meteorolóxico
Name[hr]=Prognoza vremena
Name[hu]=Időjárás-előrejelzés
Name[is]=Veðurspá
Name[it]=Previsioni meteo
Name[ja]=
Name[kk]=Ауа райын болжау
Name[km]=
Name[ko]=
Name[lt]=Orų prognozė
Name[lv]=Laika prognoze
Name[mr]=
Name[nb]=Værmelding
Name[nds]=Wederbericht
Name[nl]=Weersvoorspelling
Name[nn]=Vêrmelding
Name[pa]=
Name[pl]=Prognoza pogody
Name[pt]=Boletim Meteorológico
Name[pt_BR]=Previsão meteorológica
Name[ro]=Prognoza vremii
Name[ru]=Прогноз погоды
Name[sk]=Predpoveď počasia
Name[sl]=Vremenska napoved
Name[sq]=Parashikimi i Motit
Name[sr]=временска прогноза
Name[sr@ijekavian]=временска прогноза
Name[sr@ijekavianlatin]=vremenska prognoza
Name[sr@latin]=vremenska prognoza
Name[sv]=Väderprognos
Name[th]=
Name[tr]=Hava Tahmini
Name[ug]=ھاۋارايىدىن مەلۇمات
Name[uk]=Прогноз погоди
Name[wa]=Prédijhaedjes del meteyo
Name[x-test]=xxWeather Forecastxx
Name[zh_CN]=
Name[zh_TW]=
Comment=Displays Weather information
Comment[ar]=تعرض معلومات الطقس
Comment[ast]=Amuesa información meteorolóxica
Comment[bs]=Prikazi Informacije o vremenu
Comment[ca]=Mostra informació meteorològica
Comment[ca@valencia]=Mostra informació meteorològica
Comment[cs]=Zobrazuje informace o počasí
Comment[da]=Viser vejrinformation.
Comment[de]=Zeigt Wetterinformationen an
Comment[el]=Εμφάνιση πληροφοριών καιρού
Comment[en_GB]=Displays Weather information
Comment[es]=Muestra información meteorológica
Comment[et]=Ilmateade
Comment[eu]=Eguraldiaren gaineko informazioa bistaratu
Comment[fi]=Näyttää säätietoja
Comment[fr]=Affiche des informations météorologiques
Comment[ga]=Taispeáin faisnéis aimsire
Comment[gl]=Mostra información meteorolóxica
Comment[hr]=Prikazuje informacije o vremenu
Comment[hu]=Időjárás-információk megjelenítése
Comment[is]=Sýnir veðurupplýsingar
Comment[it]=Mostra informazioni meteo
Comment[ja]=
Comment[kk]=Ауа райы мәліметін көрсету
Comment[km]=
Comment[ko]=
Comment[lt]=Rodo orų prognozės informaciją
Comment[lv]=Rāda laikapstākļu informāciju
Comment[mr]= ि ि
Comment[nb]=Viser værinformasjon
Comment[nds]=Wiest Weder-Informatschonen
Comment[nl]=Toont weerinformatie
Comment[nn]=Vis vêrinformasjon
Comment[pa]=
Comment[pl]=Wyświetla informacje o pogodzie
Comment[pt]=Mostra informações meteorológicas
Comment[pt_BR]=Exibe informações meteorológicas
Comment[ro]=Afișează informații meteorologice
Comment[ru]=Отображение сведений о погоде
Comment[sk]=Zobrazuje informácie o počasí
Comment[sl]=Prikazuje vremenske podatke
Comment[sr]=Информације о времену
Comment[sr@ijekavian]=Информације о времену
Comment[sr@ijekavianlatin]=Informacije o vremenu
Comment[sr@latin]=Informacije o vremenu
Comment[sv]=Visar väderinformation
Comment[th]=
Comment[tr]=Hava durumu bilgisini görüntüler
Comment[uk]=Показує відомості про погоду
Comment[wa]=Håyene les informåcions del meteyo
Comment[x-test]=xxDisplays Weather informationxx
Comment[zh_CN]=
Comment[zh_TW]=
Icon=weather-clear
Type=Service
ServiceTypes=Plasma/Applet
X-KDE-Library=plasma_applet_weather
X-KDE-PluginInfo-Author=Shawn Starr
X-KDE-PluginInfo-Email=shawn.starr@rogers.com
X-KDE-PluginInfo-Name=weather
X-KDE-PluginInfo-Version=1.0
X-KDE-PluginInfo-Website=
X-KDE-PluginInfo-Category=Environment and Weather
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPLv2+
X-KDE-PluginInfo-EnabledByDefault=true
X-Plasma-NotificationArea=true
X-Plasma-Requires-FileDialog=Unused
X-Plasma-Requires-LaunchApp=Required

View file

@ -1,474 +0,0 @@
/***************************************************************************
* Copyright (C) 2007-2009 by Shawn Starr <shawn.starr@rogers.com> *
* Copyright (C) 2008 by Marco Martin <notmart@gmail.com> *
* Copyright (C) 2012 by Luís Gabriel Lima <lampih@gmail.com> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
#include "weatherapplet.h"
#include <QtGui/QGraphicsLinearLayout>
#include <QtDeclarative/QDeclarativeEngine>
#include <QtDeclarative/QDeclarativeContext>
#include <KIcon>
#include <KIconLoader>
#include <KToolInvocation>
#include <kunitconversion.h>
#include <Plasma/ToolTipManager>
#include <Plasma/DeclarativeWidget>
#include <Plasma/Package>
bool isValidIconName(const QString &icon)
{
return !icon.isEmpty() &&
!KIconLoader::global()->loadIcon(icon, KIconLoader::Desktop, 0,
KIconLoader::DefaultState, QStringList(), 0, true).isNull();
}
WeatherApplet::WeatherApplet(QObject *parent, const QVariantList &args)
: WeatherPopupApplet(parent, args)
, m_declarativeWidget(0)
{
setAspectRatioMode(Plasma::IgnoreAspectRatio);
setPopupIcon("weather-none-available");
setDefaultIon("wettercom");
}
void WeatherApplet::init()
{
switch (formFactor()) {
case Plasma::Horizontal:
case Plasma::Vertical:
Plasma::ToolTipManager::self()->registerWidget(this);
break;
default:
Plasma::ToolTipManager::self()->unregisterWidget(this);
break;
}
resetPanelModel();
WeatherPopupApplet::init();
}
WeatherApplet::~WeatherApplet()
{
}
QGraphicsWidget *WeatherApplet::graphicsWidget()
{
if (!m_declarativeWidget) {
m_declarativeWidget = new Plasma::DeclarativeWidget(this);
m_declarativeWidget->engine()->rootContext()->setContextProperty("weatherApplet", this);
Plasma::PackageStructure::Ptr structure = Plasma::PackageStructure::load("Plasma/Generic");
Plasma::Package package(QString(), "org.kde.weather", structure);
m_declarativeWidget->setQmlPath(package.filePath("mainscript"));
}
return m_declarativeWidget;
}
void WeatherApplet::toolTipAboutToShow()
{
if (isPopupShowing()) {
Plasma::ToolTipManager::self()->clearContent(this);
return;
}
QString config = i18nc("Shown when you have not set a weather provider", "Please Configure");
Plasma::ToolTipContent data(config, "", popupIcon().pixmap(IconSize(KIconLoader::Desktop)));
QString location = m_panelModel["location"].toString();
QString conditions = m_panelModel["conditions"].toString();
QString temp = m_panelModel["temp"].toString();
if (!location.isEmpty()) {
data.setMainText(location);
data.setSubText(i18nc("%1 is the weather condition, %2 is the temperature,"
" both come from the weather provider", "%1 %2", conditions, temp));
}
Plasma::ToolTipManager::self()->setContent(this, data);
}
void WeatherApplet::constraintsEvent(Plasma::Constraints constraints)
{
if (constraints & Plasma::FormFactorConstraint) {
switch (formFactor()) {
case Plasma::Horizontal:
case Plasma::Vertical:
Plasma::ToolTipManager::self()->registerWidget(this);
break;
default:
Plasma::ToolTipManager::self()->unregisterWidget(this);
break;
}
}
}
void WeatherApplet::invokeBrowser(const QString& url) const
{
if (url.isEmpty())
KToolInvocation::invokeBrowser(m_creditUrl);
else
KToolInvocation::invokeBrowser(url);
}
QString WeatherApplet::convertTemperature(const QString &format, const QString &value,
int type, bool rounded, bool degreesOnly)
{
const KTemperature temp(value.toDouble(), static_cast<KTemperature::KTempUnit>(type));
const KTemperature totemp(0.0, format);
const QString unit = totemp.unit();
const double number = temp.convertTo(totemp.unitEnum());
if (rounded) {
int tempNumber = qRound(number);
if (degreesOnly) {
return i18nc("temperature, unit", "%1%2", tempNumber, i18nc("Degree, unit symbol", "°"));
} else {
return i18nc("temperature, unit", "%1%2", tempNumber, unit);
}
} else {
float formattedTemp = KUnitConversion::round(number, 1);
if (degreesOnly) {
return i18nc("temperature, unit", "%1%2", formattedTemp, i18nc("Degree, unit symbol", "°"));
} else {
return i18nc("temperature, unit", "%1%2", formattedTemp, unit);
}
}
}
bool WeatherApplet::isValidData(const QVariant &data) const
{
return ((data != "N/A") && (!data.toString().isEmpty()));
}
void WeatherApplet::resetPanelModel()
{
m_panelModel.clear();
m_panelModel["location"] = "";
m_panelModel["forecastTemps"] = "";
m_panelModel["conditions"] = "";
m_panelModel["temp"] = "";
m_panelModel["courtesy"] = "";
m_panelModel["conditionIcon"] = "";
m_panelModel["totalDays"] = "";
m_panelModel["enableLink"] = false;
}
void WeatherApplet::updatePanelModel(const Plasma::DataEngine::Data &data)
{
resetPanelModel();
m_panelModel["location"] = data["Place"].toString();
int unit = data["Temperature Unit"].toInt();
// Get current time period of day
QStringList fiveDayTokens = data["Short Forecast Day 0"].toString().split('|');
if (fiveDayTokens.count() > 1) {
// fiveDayTokens[3] => High Temperature
// fiveDayTokens[4] => Low Temperature
QString high, low;
if (fiveDayTokens[4] != "N/A") {
low = convertTemperature(temperatureUnit(), fiveDayTokens[4], unit, true);
}
if (fiveDayTokens[3] != "N/A") {
high = convertTemperature(temperatureUnit(), fiveDayTokens[3], unit, true);
}
if (!low.isEmpty() && !high.isEmpty()) {
m_panelModel["forecastTemps"] = i18nc("High & Low temperature", "H: %1 L: %2", high, low);
} else if (!low.isEmpty()) {
m_panelModel["forecastTemps"] = i18nc("Low temperature", "Low: %1", low);
} else {
m_panelModel["forecastTemps"] = i18nc("High temperature", "High: %1", high);
}
}
m_panelModel["conditions"] = data["Current Conditions"].toString().trimmed();
if (isValidData(data["Temperature"])) {
m_panelModel["temp"] = convertTemperature(temperatureUnit(), data["Temperature"].toString(), unit);
}
m_panelModel["courtesy"] = data["Credit"].toString();
m_creditUrl = data["Credit Url"].toString();
m_panelModel["enableLink"] = !m_creditUrl.isEmpty();
const QString conditionIcon = data["Condition Icon"].toString();
if (!isValidData(data["Condition Icon"])
|| conditionIcon == "weather-none-available"
|| conditionIcon == "N/U"
|| conditionIcon == "N/A") {
if (fiveDayTokens.count() > 2) {
// if there is no specific icon, show the current weather
m_panelModel["conditionIcon"] = fiveDayTokens[1];
setPopupIcon(KIcon(fiveDayTokens[1]));
} else {
// if we could not find any proper icon then just hide it
m_panelModel["conditionIcon"] = "";
setPopupIcon(KIcon("weather-none-available"));
}
} else {
m_panelModel["conditionIcon"] = conditionIcon;
if (isValidIconName(conditionIcon)) {
setPopupIcon(conditionIcon);
} else {
setPopupIcon("weather-not-available");
}
}
}
void WeatherApplet::updateFiveDaysModel(const Plasma::DataEngine::Data &data)
{
if (data["Total Weather Days"].toInt() <= 0) {
return;
}
m_fiveDaysModel.clear();
QStringList dayItems;
QStringList conditionItems; // Icon
QStringList hiItems;
QStringList lowItems;
for (int i = 0; i < data["Total Weather Days"].toInt(); i++) {
QString current = QString("Short Forecast Day %1").arg(i);
QStringList fiveDayTokens = data[current].toString().split('|');
if (fiveDayTokens.count() != 6) {
// We don't have the right number of tokens, abort trying
break;
}
dayItems << fiveDayTokens[0];
// If we see N/U (Not Used) we skip the item
if (fiveDayTokens[1] != "N/U") {
QString iconAndToolTip;
if (isValidIconName(fiveDayTokens[1])) {
iconAndToolTip = fiveDayTokens[1];
} else {
iconAndToolTip = "weather-not-available";
}
iconAndToolTip += "|";
if (fiveDayTokens[5] != "N/U" && fiveDayTokens[5] != "N/A") {
iconAndToolTip += i18nc("certain weather condition, probability percentage",
"%1 (%2%)", fiveDayTokens[2], fiveDayTokens[5]);
} else {
iconAndToolTip += fiveDayTokens[2];
}
conditionItems << iconAndToolTip;
}
if (fiveDayTokens[3] != "N/U") {
if (fiveDayTokens[3] == "N/A") {
hiItems << i18nc("Short for no data available", "-");
} else {
hiItems << convertTemperature(temperatureUnit(),
fiveDayTokens[3],
data["Temperature Unit"].toInt(),
true);
}
}
if (fiveDayTokens[4] != "N/U") {
if (fiveDayTokens[4] == "N/A") {
lowItems << i18nc("Short for no data available", "-");
} else {
lowItems << convertTemperature(temperatureUnit(),
fiveDayTokens[4],
data["Temperature Unit"].toInt(),
true);
}
}
}
if (dayItems.count() > 0) {
m_fiveDaysModel << dayItems;
}
if (conditionItems.count() > 0) {
m_fiveDaysModel << conditionItems;
}
if (hiItems.count() > 0) {
m_fiveDaysModel << hiItems;
}
if (lowItems.count() > 0) {
m_fiveDaysModel << lowItems;
}
m_panelModel["totalDays"] = i18ncp("Forecast period timeframe", "1 Day",
"%1 Days", data["Total Weather Days"].toInt());
}
void WeatherApplet::updateDetailsModel(const Plasma::DataEngine::Data &data)
{
m_detailsModel.clear();
QVariantMap row;
row["icon"] = "";
row["text"] = "";
int unit = data["Temperature Unit"].toInt();
QString temp;
if (isValidData(data["Windchill"])) {
// Use temperature unit to convert windchill temperature
// we only show degrees symbol not actual temperature unit
temp = convertTemperature(temperatureUnit(), data["Windchill"].toString(), unit, false, true);
row["text"] = i18nc("windchill, unit", "Windchill: %1", temp);
m_detailsModel << row;
}
if (isValidData(data["Humidex"])) {
// Use temperature unit to convert humidex temperature
// we only show degrees symbol not actual temperature unit
temp = convertTemperature(temperatureUnit(), data["Humidex"].toString(), unit, false, true);
row["text"] = i18nc("humidex, unit","Humidex: %1", temp);
m_detailsModel << row;
}
if (isValidData(data["Dewpoint"])) {
temp = convertTemperature(temperatureUnit(), data["Dewpoint"].toString(), unit);
row["text"] = i18nc("ground temperature, unit", "Dewpoint: %1", temp);
m_detailsModel << row;
}
if (isValidData(data["Pressure"])) {
const KPressure pres(data["Pressure"].toDouble(), static_cast<KPressure::KPresUnit>(data["Pressure Unit"].toInt()));
const KPressure topres(0.0, pressureUnit());
const double number = pres.convertTo(topres.unitEnum());
row["text"] = i18nc("pressure, unit","Pressure: %1 %2",
KUnitConversion::round(number, 2), topres.unit());
m_detailsModel << row;
}
if (isValidData(data["Pressure Tendency"])) {
row["text"] = i18nc("pressure tendency, rising/falling/steady",
"Pressure Tendency: %1", data["Pressure Tendency"].toString());
m_detailsModel << row;
}
if (isValidData(data["Visibility"])) {
bool isNumeric;
data["Visibility"].toDouble(&isNumeric);
if (isNumeric) {
const KLength leng(data["Visibility"].toDouble(), static_cast<KLength::KLengUnit>(data["Visibility Unit"].toInt()));
const KLength toleng(0.0, visibilityUnit());
const double number = leng.convertTo(toleng.unitEnum());
row["text"] = i18nc("distance, unit","Visibility: %1 %2",
KUnitConversion::round(number, 1), toleng.unit());
} else {
row["text"] = i18nc("visibility from distance", "Visibility: %1", data["Visibility"].toString());
}
m_detailsModel << row;
}
if (isValidData(data["Humidity"])) {
row["text"] = i18nc("content of water in air", "Humidity: %1%2",
data["Humidity"].toString(), i18nc("Precent, measure unit", "%"));
m_detailsModel << row;
}
if (isValidData(data["Wind Speed"])) {
row["icon"] = data["Wind Direction"].toString();
if (data["Wind Speed"] == "N/A") {
row["text"] = i18nc("Not available","N/A");
} else if (data["Wind Speed"].toDouble() != 0 && data["Wind Speed"] != "Calm") {
const KVelocity velo(data["Wind Speed"].toDouble(), static_cast<KVelocity::KVeloUnit>(data["Wind Speed Unit"].toInt()));
const KVelocity tovelo(0.0, speedUnit());
const double number = velo.convertTo(tovelo.unitEnum());
row["text"] = i18nc("wind direction, speed","%1 %2 %3", data["Wind Direction"].toString(),
KUnitConversion::round(number, 1), tovelo.unit());
} else {
row["text"] = i18nc("Wind condition","Calm");
}
m_detailsModel << row;
row["icon"] = "";
}
if (isValidData(data["Wind Gust"])) {
// Convert the wind format for nonstandard types
const KVelocity velo(data["Wind Gust"].toDouble(), static_cast<KVelocity::KVeloUnit>(data["Wind Gust Unit"].toInt()));
const KVelocity tovelo(0.0, speedUnit());
const double number = velo.convertTo(tovelo.unitEnum());
row["text"] = i18nc("winds exceeding wind speed briefly", "Wind Gust: %1 %2",
KUnitConversion::round(number, 1), tovelo.unit());
m_detailsModel << row;
}
}
void WeatherApplet::updateNoticesModel(const Plasma::DataEngine::Data &data)
{
m_noticesModel.clear();
QVariantList warnings;
for (int i = 0; i < data["Total Warnings Issued"].toInt(); i++) {
QVariantMap warning;
warning["description"] = data[QString("Warning Description %1").arg(i)];
warning["info"] = data[QString("Warning Info %1").arg(i)];
warnings << warning;
}
m_noticesModel << QVariant(warnings);
QVariantList watches;
for (int i = 0; i < data["Total Watches Issued"].toInt(); i++) {
QVariantMap watch;
watch["description"] = data[QString("Watch Description %1").arg(i)];
watch["info"] = data[QString("Watch Info %1").arg(i)];
watches << watch;
}
m_noticesModel << QVariant(watches);
}
void WeatherApplet::dataUpdated(const QString &source, const Plasma::DataEngine::Data &data)
{
if (data.isEmpty()) {
return;
}
updatePanelModel(data);
updateFiveDaysModel(data);
updateDetailsModel(data);
updateNoticesModel(data);
WeatherPopupApplet::dataUpdated(source, data);
emit modelUpdated();
update();
}
void WeatherApplet::configAccepted()
{
resetPanelModel();
m_fiveDaysModel.clear();
m_detailsModel.clear();
emit modelUpdated();
WeatherPopupApplet::configAccepted();
}
#include "moc_weatherapplet.cpp"

View file

@ -1,85 +0,0 @@
/***************************************************************************
* Copyright (C) 2007-2009 by Shawn Starr <shawn.starr@rogers.com> *
* Copyright (C) 2012 by Luís Gabriel Lima <lampih@gmail.com> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
#ifndef WEATHERAPPLET_H
#define WEATHERAPPLET_H
#include <plasmaweather/weatherpopupapplet.h>
namespace Plasma
{
class DeclarativeWidget;
}
class WeatherApplet : public WeatherPopupApplet
{
Q_OBJECT
Q_PROPERTY(QVariantMap panelModel READ panelModel NOTIFY modelUpdated)
Q_PROPERTY(QVariantList fiveDaysModel READ fiveDaysModel NOTIFY modelUpdated)
Q_PROPERTY(QVariantList detailsModel READ detailsModel NOTIFY modelUpdated)
Q_PROPERTY(QVariantList noticesModel READ noticesModel NOTIFY modelUpdated)
public:
WeatherApplet(QObject *parent, const QVariantList &args);
~WeatherApplet();
void init();
QGraphicsWidget *graphicsWidget();
QVariantMap panelModel() const { return m_panelModel; }
QVariantList fiveDaysModel() const { return m_fiveDaysModel; }
QVariantList detailsModel() const { return m_detailsModel; }
QVariantList noticesModel() const { return m_noticesModel; }
signals:
void modelUpdated();
public Q_SLOTS:
void dataUpdated(const QString &source, const Plasma::DataEngine::Data &data);
void invokeBrowser(const QString &url = QString()) const;
protected Q_SLOTS:
void configAccepted();
void toolTipAboutToShow();
protected:
void constraintsEvent(Plasma::Constraints constraints);
private:
bool isValidData(const QVariant &data) const;
void resetPanelModel();
void updatePanelModel(const Plasma::DataEngine::Data &data);
void updateFiveDaysModel(const Plasma::DataEngine::Data &data);
void updateDetailsModel(const Plasma::DataEngine::Data &data);
void updateNoticesModel(const Plasma::DataEngine::Data &data);
QString convertTemperature(const QString &format, const QString &value,
int type, bool rounded = false, bool degreesOnly = false);
Plasma::DeclarativeWidget *m_declarativeWidget;
QString m_creditUrl;
QVariantMap m_panelModel;
QVariantList m_fiveDaysModel;
QVariantList m_detailsModel;
QVariantList m_noticesModel;
};
K_EXPORT_PLASMA_APPLET(weather, WeatherApplet)
#endif

View file

@ -1,47 +0,0 @@
project(plasma-weatherstation)
include_directories(
# for plasmaweather_export.h
${kdeplasma-addons_BINARY_DIR}/libs/plasmaweather
)
set(weatherstation_SRCS
weatherstation.cpp
lcd.cpp
appearanceconfig.ui
)
kde4_add_plugin(plasma_applet_weatherstation ${weatherstation_SRCS})
target_link_libraries(plasma_applet_weatherstation
KDE4::kdeui
KDE4::kio
KDE4::plasma
KDE4::karchive
KDE4Workspace::weather_ion
${QT_QTDECLARATIVE_LIBRARY}
plasmaweather
)
install(
TARGETS plasma_applet_weatherstation
DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}
)
install(
FILES plasma-applet-weatherstation.desktop
DESTINATION ${KDE4_SERVICES_INSTALL_DIR}
)
install(
FILES
lcd2.svgz
lcd_panel.svgz
lcd_digits.svgz
wind_arrows.svgz
weather_icons.svgz
DESTINATION ${KDE4_DATA_INSTALL_DIR}/desktoptheme/default/weatherstation/
)
install(
DIRECTORY package/
DESTINATION ${KDE4_DATA_INSTALL_DIR}/plasma/packages/org.kde.lcdweather
)

View file

@ -1,3 +0,0 @@
#! /usr/bin/env bash
$EXTRACTRC *.ui >> rc.cpp
$XGETTEXT *.cpp -o $podir/plasma_applet_weatherstation.pot

View file

@ -1,65 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AppearanceConfig</class>
<widget class="QWidget" name="AppearanceConfig">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>326</width>
<height>75</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="windowTitle">
<string>Weather Station Configuration</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QCheckBox" name="backgroundCheckBox">
<property name="text">
<string>Show LCD background</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="tooltipCheckBox">
<property name="text">
<string>Show location</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>17</width>
<height>13</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<connections/>
</ui>

View file

@ -1,420 +0,0 @@
/*
* Copyright (C) 2007, 2008 Petri Damsten <damu@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "lcd.h"
#include <QPainter>
#include <QDir>
#include <QGraphicsLinearLayout>
#include <QtGui/qgraphicssceneevent.h>
#include <QtXml/qdom.h>
#include <QCursor>
#include <KDebug>
#include <KDecompressor>
#include <Plasma/Theme>
#include <Plasma/Svg>
class LCD::Private
{
public:
LCD* l;
QString content;
Plasma::Svg svg;
bool dirty;
QPixmap img;
QStringList items;
QMap<QString, QStringList> groups;
QHash<QString, QDomText> texts;
QStringList clickable;
QDomDocument doc;
static const QString A;
static const QString B;
static const QString C;
static const QString D;
static const QString E;
static const QString F;
static const QString G;
static const QString DP;
static QMap<QChar, QStringList> sevenSegmentDigits;
qreal xScale;
qreal yScale;
Private(LCD* lcd) : l(lcd), dirty(false), xScale(1.0), yScale(1.0)
{
// http://en.wikipedia.org/wiki/Seven-segment_display_character_representations
if (sevenSegmentDigits.isEmpty()) {
sevenSegmentDigits[' '] = QStringList();
sevenSegmentDigits['-'] = QStringList() << G;
sevenSegmentDigits['0'] = QStringList() << A << B << C << D << E << F;
sevenSegmentDigits['1'] = QStringList() << B << C;
sevenSegmentDigits['2'] = QStringList() << A << B << D << E << G;
sevenSegmentDigits['3'] = QStringList() << A << B << C << D << G;
sevenSegmentDigits['4'] = QStringList() << B << C << F << G;
sevenSegmentDigits['5'] = QStringList() << A << C << D << F << G;
sevenSegmentDigits['6'] = QStringList() << A << C << D << E << F << G;
sevenSegmentDigits['7'] = QStringList() << A << B << C;
sevenSegmentDigits['8'] = QStringList() << A << B << C << D << E << F << G;
sevenSegmentDigits['9'] = QStringList() << A << B << C << D << F << G;
sevenSegmentDigits['A'] = QStringList() << A << B << C << E << F << G;
sevenSegmentDigits['B'] = QStringList() << A << B << C << D << E << F << G;
sevenSegmentDigits['C'] = QStringList() << A << D << E << F;
sevenSegmentDigits['D'] = QStringList() << A << B << C << D << E << F;
sevenSegmentDigits['E'] = QStringList() << A << D << E << F << G;
sevenSegmentDigits['F'] = QStringList() << A << E << F << G;
sevenSegmentDigits['G'] = QStringList() << A << C << D << E << F;
sevenSegmentDigits['H'] = QStringList() << B << C << E << F << G;
sevenSegmentDigits['I'] = QStringList() << B << C;
sevenSegmentDigits['J'] = QStringList() << B << C << D << E;
sevenSegmentDigits['K'] = QStringList() << E << F << G;
sevenSegmentDigits['L'] = QStringList() << D << E << F;
sevenSegmentDigits['M'] = QStringList() << A << B << D << F;
sevenSegmentDigits['N'] = QStringList() << A << B << C << E << F;
sevenSegmentDigits['O'] = QStringList() << A << B << C << D << E << F;
sevenSegmentDigits['P'] = QStringList() << A << B << E << F << G;
sevenSegmentDigits['Q'] = QStringList() << A << B << D << F << G;
sevenSegmentDigits['R'] = QStringList() << A << E << F;
sevenSegmentDigits['S'] = QStringList() << A << C << D << F << G;
sevenSegmentDigits['T'] = QStringList() << A << E << F;
sevenSegmentDigits['U'] = QStringList() << B << C << D << E << F;
sevenSegmentDigits['V'] = QStringList() << B << C << D << E << F;
sevenSegmentDigits['W'] = QStringList() << B << D << F << G;
sevenSegmentDigits['X'] = QStringList() << B << C << E << F << G;
sevenSegmentDigits['Y'] = QStringList() << B << C << F << G;
sevenSegmentDigits['Z'] = QStringList() << A << B << D << E << G;
sevenSegmentDigits['a'] = QStringList() << A << B << C << D << E << G;
sevenSegmentDigits['b'] = QStringList() << C << D << E << F << G;
sevenSegmentDigits['c'] = QStringList() << D << E << G;
sevenSegmentDigits['d'] = QStringList() << B << C << D << E << G;
sevenSegmentDigits['e'] = QStringList() << A << B << E << F << G;
sevenSegmentDigits['f'] = QStringList() << A << E << F << G;
sevenSegmentDigits['g'] = QStringList() << A << B << C << D << F << G;
sevenSegmentDigits['h'] = QStringList() << C << E << F << G;
sevenSegmentDigits['i'] = QStringList() << C;
sevenSegmentDigits['j'] = QStringList() << C << D;
sevenSegmentDigits['k'] = QStringList() << A << C << E << F << G;
sevenSegmentDigits['l'] = QStringList() << E << F;
sevenSegmentDigits['m'] = QStringList() << A << C << E << G;
sevenSegmentDigits['n'] = QStringList() << C << E << G;
sevenSegmentDigits[QChar(0x00F1)] = QStringList() << A << C << E << G; // ñ
sevenSegmentDigits['o'] = QStringList() << C << D << E << G;
sevenSegmentDigits['p'] = QStringList() << A << B << E << F << G;
sevenSegmentDigits['q'] = QStringList() << A << B << C << F << G;
sevenSegmentDigits['r'] = QStringList() << E << G;
sevenSegmentDigits['s'] = QStringList() << E << G;
sevenSegmentDigits['t'] = QStringList() << D << E << F << G;
sevenSegmentDigits['u'] = QStringList() << C << D << E;
sevenSegmentDigits['v'] = QStringList() << E << G;
sevenSegmentDigits['w'] = QStringList() << E << G;
sevenSegmentDigits['x'] = QStringList() << E << G;
sevenSegmentDigits['y'] = QStringList() << E << G;
sevenSegmentDigits['z'] = QStringList() << E << G;
sevenSegmentDigits[QChar(0x00F6)] = QStringList() << A << C << D << E << G; // ö
}
}
int digits(const QString& name)
{
return groups[name].count();
}
void paint(QPainter* p, const QString& item)
{
QRectF r = svg.elementRect(item);
svg.paint(p, r, item);
}
QRectF scaledRect(const QString& item)
{
QRectF r = svg.elementRect(item);
r.setRect(r.x() * xScale, r.y() * yScale, r.width() * xScale, r.height() * yScale);
return r;
}
void checkIfDirty()
{
const QSizeF lsizef = l->size();
const QSize lsize = lsizef.toSize();
if ((dirty || lsize != img.size()) && lsize != QSize(0, 0)) {
// kDebug() << "Making bitmap" << lsizef;
if (lsize != img.size()) {
img = QPixmap(lsize);
}
img.fill(Qt::transparent);
QPainter p(&img);
xScale = lsizef.width() / svg.size().width();
yScale = lsizef.height() / svg.size().height();
p.setRenderHint(QPainter::TextAntialiasing, true);
p.setRenderHint(QPainter::Antialiasing, true);
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
p.save();
p.scale(
lsizef.width() / svg.size().width(),
lsizef.height() / svg.size().height()
);
foreach (const QString& item, items) {
paint(&p, item);
}
p.restore();
dirty = false;
}
}
void parseXml()
{
// kDebug() << content;
KDecompressor kdecompressor;
if (!kdecompressor.setType(KDecompressor::TypeGZip)) {
kWarning() << "Could not set decompressor type" << kdecompressor.errorString();
return;
}
QFile contentFile(content);
if (!contentFile.open(QFile::ReadOnly)) {
kWarning() << "Could open content file" << content << contentFile.errorString();
return;
}
if (!kdecompressor.process(contentFile.readAll())) {
kWarning() << "Could not decompress content" << kdecompressor.errorString();
return;
}
doc.setContent(kdecompressor.result());
QList<QDomNodeList> lists;
int pos;
lists << doc.elementsByTagName("g");
lists << doc.elementsByTagName("path");
lists << doc.elementsByTagName("rect");
foreach (const QDomNodeList& list, lists) {
for (int i = 0; i < list.count(); ++i) {
QDomElement element = list.item(i).toElement();
QString id = element.attribute("id");
if ((pos = id.lastIndexOf(':')) > -1) {
groups[id.left(pos)] << id.mid(pos + 1);
}
}
}
QDomNodeList list = doc.elementsByTagName("text");
for (int i = 0; i < list.count(); ++i) {
QDomElement element = list.item(i).toElement();
QDomNodeList l = element.elementsByTagName("tspan");
QDomElement e = l.item(0).toElement();
for (QDomNode n = e.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomText t = n.toText();
if (!t.isNull()) {
texts[element.attribute("id")] = t;
}
}
}
// kDebug() << groups;
}
};
QMap<QChar, QStringList> LCD::Private::sevenSegmentDigits;
const QString LCD::Private::A("A");
const QString LCD::Private::B("B");
const QString LCD::Private::C("C");
const QString LCD::Private::D("D");
const QString LCD::Private::E("E");
const QString LCD::Private::F("F");
const QString LCD::Private::G("G");
const QString LCD::Private::DP("DP");
LCD::LCD(QGraphicsItem *parent) :
QGraphicsWidget(parent),
d(new Private(this))
{
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}
LCD::~LCD()
{
delete d;
}
QString LCD::svg() const
{
return d->content;
}
void LCD::setSvg(const QString &svg)
{
d->content = Plasma::Theme::defaultTheme()->imagePath(svg);
d->svg.setImagePath(d->content);
d->parseXml();
d->dirty = true;
update();
}
QStringList LCD::groupItems(const QString &name)
{
return d->groups[name];
}
void LCD::paint(QPainter *p, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option)
Q_UNUSED(widget)
d->checkIfDirty();
p->drawPixmap(0, 0, d->img);
}
void LCD::setDigit(const QString &name, QChar digit, bool dot)
{
QStringList segments;
// kDebug() << name << digit << dot;
if (d->sevenSegmentDigits.keys().contains(digit)) {
segments = d->sevenSegmentDigits[digit];
}
if (dot) {
segments << d->DP;
}
setGroup(name, segments);
}
void LCD::setNumber(const QString &name, const QString& number)
{
int j = 0;
int digits = d->digits(name);
bool dot = false;
// kDebug() << name << number << digits;
for (int i = number.length() - 1; i >= 0; --i) {
if (number[i] == '.') {
dot = true;
} else {
setDigit(name + QString(":%1").arg(j++), number[i], dot);
dot = false;
}
if (j >= digits) {
break;
}
}
for (int i = j; i < digits; ++i) {
setDigit(name + QString(":%1").arg(i), ' ', false);
}
}
void LCD::setGroup(const QString &name, const QStringList& on)
{
QStringList all = d->groups[name];
foreach (const QString& item, all) {
if (on.contains(item)) {
setItemOn(name + ':' + item);
} else {
setItemOff(name + ':' + item);
}
}
}
void LCD::clear()
{
d->items.clear();
}
void LCD::setItemOn(const QString &name)
{
if (!d->items.contains(name)) {
// kDebug() << "++++++++++" << name;
d->items << name;
d->dirty = true;
update();
}
}
void LCD::setItemOff(const QString &name)
{
if (d->items.contains(name)) {
// kDebug() << "----------" << name;
d->items.removeAll(name);
d->dirty = true;
update();
}
}
void LCD::setLabel(const QString &name, const QString &text)
{
if (d->texts[name].data() != text) {
d->texts[name].setData(text);
}
}
QString LCD::label(const QString &name) const
{
return d->texts[name].data();
}
QPixmap LCD::toPixmap()
{
d->checkIfDirty();
return d->img;
}
void LCD::setItemClickable(const QString &name, bool clickable)
{
d->clickable.removeAll(name);
if (clickable) {
setAcceptHoverEvents(true);
d->clickable << name;
}
}
void LCD::hoverMoveEvent(QGraphicsSceneHoverEvent* event)
{
foreach (const QString& name, d->clickable) {
if (d->scaledRect(name).contains(event->pos())) {
setCursor(QCursor(Qt::PointingHandCursor));
return;
}
}
unsetCursor();
}
void LCD::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
foreach (const QString& name, d->clickable) {
if (d->scaledRect(name).contains(event->pos())) {
emit clicked(name);
}
}
}
QSizeF LCD::sizeHint(Qt::SizeHint which, const QSizeF& constraint) const
{
QSizeF s = QGraphicsWidget::sizeHint(which, constraint);
d->checkIfDirty();
if (which == Qt::PreferredSize) {
s = d->svg.size();
} else if (which == Qt::MinimumSize) {
s = d->svg.size() / 2;
} else {
s = QGraphicsWidget::sizeHint(which, constraint);
}
return s;
}
#include "moc_lcd.cpp"

View file

@ -1,156 +0,0 @@
/*
* Copyright (C) 2007, 2008 Petri Damsten <damu@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef LCD_HEADER
#define LCD_HEADER
#include <QGraphicsWidget>
/**
* @class LCD
*
* @short Provides a widget to display lcd like svgs in plasma.
*
* Widget can turn on/off svg elements individually and in groups.
* It has helper functions to handle seven segment numbers in element groups.
* Elements that should be always drawn must be groupped under name 'background'
*
* Element groups are name [maingroup:]groupname:elementname.
* Seven segment numbers are special groups named numbername:digit:segment
* e.g Element for decimal point in first digit in number named speed is speed:0:DP
* Segment names: http://en.wikipedia.org/wiki/Seven-segment_display
*/
class LCD : public QGraphicsWidget
{
Q_OBJECT
Q_PROPERTY(QString svg READ svg WRITE setSvg)
public:
/**
* Constructor
* @param parent the QGraphicsItem this meter is parented to.
*/
explicit LCD(QGraphicsItem *parent = 0);
/**
* Destructor
*/
virtual ~LCD();
/**
* @return path of the svg widget has
*/
QString svg() const;
/**
* Set svg for the widget
* @param svg path of svg
*/
void setSvg(const QString &svg);
/**
* Set seven segment number (multiple digits in a group)
* @param name name of the digit group
* @param number number string e.g 'h 2.3', numbers and
* upper/lower case ascii characters are supported
*/
void setNumber(const QString &name, const QString& number);
/**
* Set seven segment digit
* @param name name of the digit
* @param digit digit char
* @param dot whether to show dot
*/
void setDigit(const QString &name, QChar digit, bool dot = false);
/**
* Set group elements on/off
* @param name name of the element group
* @param on list of group elements that should be on (rest of the elements are off)
*/
void setGroup(const QString &name, const QStringList& on);
/**
* Get group elements
* @param name name of the element group
* @return list of group elements
*/
QStringList groupItems(const QString &name);
/**
* Set svg element off
* @param name name of the element
*/
void setItemOff(const QString &name);
/**
* Set svg element on
* @param name name of the element
*/
void setItemOn(const QString &name);
/**
* Set svg element clickable (clicked is emitted)
* @param name name of the element
*/
void setItemClickable(const QString &name, bool clickable);
/**
* Set text label for the meter
* @param name name of the element.
* @param text text for the label.
*/
void setLabel(const QString &name, const QString &text);
/**
* @param name name of the element
* @return text label for the meter
*/
QString label(const QString &name) const;
/**
* @return lcd as pixmap
*/
QPixmap toPixmap();
/**
* Clear all items
*/
void clear();
/**
* Reimplemented from QGraphicsWidget
*/
void paint(QPainter *p, const QStyleOptionGraphicsItem *option, QWidget *widget);
signals:
void clicked(const QString &name);
protected:
virtual void hoverMoveEvent(QGraphicsSceneHoverEvent* event);
virtual void mousePressEvent(QGraphicsSceneMouseEvent* event);
virtual QSizeF sizeHint(Qt::SizeHint which, const QSizeF& constraint = QSizeF()) const;
private:
class Private;
Private * const d;
};
#endif

View file

@ -1,74 +0,0 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*/
import QtQuick 1.1
import org.kde.plasma.core 0.1 as PlasmaCore
Item {
id: root
property int value: 0
property alias dotVisible: dot.visible
implicitWidth: dummy.naturalSize.width
implicitHeight: dummy.naturalSize.height
QtObject {
id: internal
property real dotWidthRate: dot.naturalSize.width / dummy.naturalSize.width
property real digitWidthRate: digit.naturalSize.width /
(dummy.naturalSize.width - dot.naturalSize.width)
property variant values: ["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"]
}
PlasmaCore.Svg {
id: digitSvg
imagePath: "weatherstation/lcd_digits"
}
// Used just to get the size hints of digit + dot
PlasmaCore.SvgItem { id: dummy; svg: digitSvg; visible: false }
Item {
id: item
height: parent.height
width: parent.width * (1 - internal.dotWidthRate)
PlasmaCore.SvgItem {
id: digit
anchors.right: parent.right
width: parent.width * internal.digitWidthRate
height: parent.height
svg: digitSvg
elementId: internal.values[root.value]
}
}
PlasmaCore.SvgItem {
id: dot
anchors{
right: parent.right
bottom: parent.bottom
}
width: parent.width * internal.dotWidthRate
height: dot.width
visible: false
svg: digitSvg
elementId: "dot"
}
}

View file

@ -1,78 +0,0 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*/
import QtQuick 1.1
import org.kde.plasma.core 0.1 as PlasmaCore
Item {
id: display
property string number
property alias superscript: unitLabel.text
property alias superscriptFont: unitLabel.font
implicitWidth: row.width
implicitHeight: dummy.implicitHeight
QtObject {
id: internal
property bool decimal: display.number.indexOf(".") > 0
property int dotIndex: display.number.length - 3
property real hScaleFactor: display.height / dummy.implicitHeight
function numberToDigits(numberStr) {
digits = [];
for(var i = 0; i < numberStr.length; i++) {
if (numberStr[i] >= '0' && numberStr[i] <= '9')
digits.push(numberStr[i] - '0');
}
return digits;
}
}
// Just to get the implicitHeight.
LCDDigit { id: dummy; visible: false }
Row {
id: row
anchors.centerIn: parent
spacing: Math.max(2 * internal.hScaleFactor, 3)
Repeater {
model: internal.numberToDigits(display.number);
LCDDigit {
height: implicitHeight * internal.hScaleFactor
width: implicitWidth * internal.hScaleFactor
value: modelData
dotVisible: internal.decimal && (index == internal.dotIndex)
}
}
}
Text {
id: unitLabel
anchors {
top: parent.top
left: parent.right
}
color: weatherStation.useBackground ? theme.textColor : "#3d3d3d"
smooth: true
visible: number != ""
}
}

View file

@ -1,67 +0,0 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*/
import QtQuick 1.1
import org.kde.plasma.core 0.1 as PlasmaCore
Item {
id: root
property string direction
property alias speed: speedDisplay.number
property alias unit: unitLabel.text
implicitHeight: windArrows.naturalSize.height
implicitWidth: windArrows.naturalSize.width
QtObject {
id: resizeOpts
property real hScaleFactor: root.height / root.implicitHeight
}
PlasmaCore.Svg {
id: windSvg
imagePath: "weatherstation/wind_arrows"
}
PlasmaCore.SvgItem {
id: windArrows
anchors.fill: parent
svg: windSvg
elementId: "wind:" + root.direction
}
LCDDisplay {
id: speedDisplay
anchors.centerIn: parent
height: 0.65 * implicitHeight * resizeOpts.hScaleFactor
}
Text {
id: unitLabel
anchors{
top: speedDisplay.bottom
topMargin: 3 * resizeOpts.hScaleFactor
horizontalCenter: parent.horizontalCenter
}
font {
family: "Sans"
pixelSize: 9 * resizeOpts.hScaleFactor
}
color: weatherStation.useBackground ? theme.textColor : "#3d3d3d"
}
}

View file

@ -1,256 +0,0 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*/
import QtQuick 1.1
import org.kde.plasma.core 0.1 as PlasmaCore
Item {
id: root
property int minimumWidth: bg.naturalSize.width
property int minimumHeight: bg.naturalSize.height
QtObject {
id: resizeOpts
property real wScaleFactor: Math.max(root.width / root.minimumWidth, 0.1)
property real hScaleFactor: Math.max(root.height / root.minimumHeight, 0.1)
}
Connections {
target: weatherStation
onTemperatureChanged: {
temperatureDisplay.number = (temperature != "-" ? temperature : "");
temperatureDisplay.superscript = unit;
}
onHumidityChanged: humidityDisplay.number = (humidity != "N/A" ? humidity : "");
onProviderLabelChanged: providerLabel.text = label;
onWeatherLabelChanged: weatherLabel.text = label;
onPressureChanged: {
condition.elementId = conditionId;
pressureDisplay.number = pressure;
pressureDisplay.superscript = unit;
pressureDirection.elementId = direction;
}
onWindChanged: {
windWidget.direction = direction;
windWidget.speed = speed;
windWidget.unit = unit;
}
}
PlasmaCore.Theme {
id: theme
}
PlasmaCore.Svg {
id: lcdSvg
imagePath: "weatherstation/lcd2"
}
PlasmaCore.Svg {
id: iconsSvg
imagePath: "weatherstation/weather_icons"
}
PlasmaCore.SvgItem {
anchors.fill: parent
svg: lcdSvg
elementId: "lcd_background"
visible: weatherStation.useBackground
}
PlasmaCore.SvgItem {
id: bg
anchors.fill: parent
svg: lcdSvg
elementId: "background"
}
Text {
id: weatherLabel
anchors {
top: parent.top
left: parent.left
right: parent.right
topMargin: 13 * resizeOpts.hScaleFactor
leftMargin: 5 * resizeOpts.wScaleFactor
rightMargin: 5 * resizeOpts.wScaleFactor
}
horizontalAlignment: Text.AlignLeft
elide: Text.ElideRight
font {
family: "Sans"
pointSize: 6 * resizeOpts.wScaleFactor
}
color: weatherStation.useBackground ? theme.textColor : "#3d3d3d"
smooth: true
text: i18n("CURRENT WEATHER")
}
PlasmaCore.SvgItem {
id: condition
anchors {
top: parent.top
topMargin: 26 * resizeOpts.hScaleFactor
horizontalCenter: parent.horizontalCenter
}
height: naturalSize.height * resizeOpts.hScaleFactor
width: naturalSize.width * resizeOpts.wScaleFactor
visible: elementId != ""
svg: iconsSvg
}
Text {
id: pressureLabel
anchors {
top: parent.top
left: weatherLabel.left
topMargin: 128 * resizeOpts.hScaleFactor
}
font: weatherLabel.font
color: weatherLabel.color
smooth: true
text: i18n("PRESSURE")
}
PlasmaCore.SvgItem {
id: pressureDirection
anchors {
left: parent.left
leftMargin: 84 * resizeOpts.wScaleFactor
verticalCenter: pressureDisplay.verticalCenter
}
height: naturalSize.height * resizeOpts.hScaleFactor
width: naturalSize.width * resizeOpts.wScaleFactor
visible: elementId != ""
svg: lcdSvg
}
LCDDisplay {
id: pressureDisplay
anchors {
right: parent.right
bottom: pressureLabel.bottom
rightMargin: 24 * resizeOpts.wScaleFactor
bottomMargin: 2 * resizeOpts.hScaleFactor
}
height: 20 * resizeOpts.hScaleFactor
superscriptFont: weatherLabel.font
}
Text {
id: temperatureLabel
anchors {
top: parent.top
left: weatherLabel.left
topMargin: 153 * resizeOpts.hScaleFactor
}
font: weatherLabel.font
color: weatherLabel.color
smooth: true
text: i18n("OUTDOOR TEMP")
}
LCDDisplay {
id: temperatureDisplay
anchors {
right: parent.right
top: temperatureLabel.bottom
rightMargin: 97 * resizeOpts.wScaleFactor
topMargin: 3 * resizeOpts.hScaleFactor
}
height: implicitHeight * resizeOpts.hScaleFactor
superscriptFont: weatherLabel.font
}
Text {
id: humidityLabel
anchors {
top: temperatureLabel.top
right: parent.right
rightMargin: 5 * resizeOpts.wScaleFactor
}
font: weatherLabel.font
color: weatherLabel.color
smooth: true
text: i18n("HUMIDITY")
}
LCDDisplay {
id: humidityDisplay
anchors {
top: temperatureDisplay.top
right: parent.right
rightMargin: 12 * resizeOpts.wScaleFactor
}
height: temperatureDisplay.height
superscript: "%"
superscriptFont: weatherLabel.font
}
Text {
id: windLabel
anchors {
top: temperatureLabel.top
left: weatherLabel.left
topMargin: 60 * resizeOpts.hScaleFactor
}
font: weatherLabel.font
color: weatherLabel.color
smooth: true
text: i18n("WIND")
}
Wind {
id: windWidget
anchors {
top: windLabel.top
topMargin: -3 * resizeOpts.hScaleFactor
horizontalCenter: parent.horizontalCenter
}
width: implicitWidth * resizeOpts.wScaleFactor
height: implicitHeight * resizeOpts.hScaleFactor
}
Text {
id: providerLabel
anchors {
left: parent.left
right: parent.right
bottom: parent.bottom
leftMargin: 5 * resizeOpts.wScaleFactor
rightMargin: 5 * resizeOpts.wScaleFactor
}
font {
family: "Sans"
pointSize: 4.5 * resizeOpts.hScaleFactor
}
horizontalAlignment: Text.AlignHCenter
color: weatherLabel.color
smooth: true
MouseArea {
anchors.fill: parent
onClicked: weatherStation.clicked();
}
}
}

View file

@ -1,59 +0,0 @@
[Desktop Entry]
Encoding=UTF-8
Name=LCD Weather Station (QML)
Name[ar]=محطة الطقس المسطحة (QML)
Name[bs]=LCD Meteroloska stanica (QML)
Name[ca]=Estació meteorològica LCD (QML)
Name[ca@valencia]=Estació meteorològica LCD (QML)
Name[cs]=LCD meteostanice (QML)
Name[da]=LCD-vejrstation (QML)
Name[de]=LCD-Wetterstation (QML)
Name[el]=Μετεωρολογικός σταθμός LCD (QML)
Name[en_GB]=LCD Weather Station (QML)
Name[es]=Estación meteorológica LCD (QML)
Name[et]=LCD ilmateade (QML)
Name[fi]=LCD-sääasema (QML)
Name[fr]=Station météo LCD (QML)
Name[ga]=Stáisiún Aimsire LCD (QML)
Name[gl]=Estación meteorolóxica LCD (QML)
Name[hu]=LCD időjárásjelző állomás (QML)
Name[it]=Stazione meteorologica LCD (QML)
Name[kk]=СК-дисплейдегі ауа райы (QML)
Name[ko]=LCD (QML)
Name[lt]=LCD orų stotelė (QML)
Name[mr]=LCD (QML)
Name[nb]=LCD værstasjon (QML)
Name[nds]=LCD-Wederstatschoon (QML)
Name[nl]=LCD weerstation (QML)
Name[pa]=LCD (QML)
Name[pl]=Stacja pogodowa LCD (QML)
Name[pt]=Estação Meteorológica LCD (QML)
Name[pt_BR]=Estação meteorológica LCD (QML)
Name[ro]=Stație meteo ECL (QML)
Name[ru]=ЖКД-гидрометеостанция (порт на QML)
Name[sk]=LCD meteorologická stanica (QML)
Name[sl]=Vremenska postaja LCD (QML)
Name[sr]=ЛЦД метеостаница (КуМЛ)
Name[sr@ijekavian]=ЛЦД метеостаница (КуМЛ)
Name[sr@ijekavianlatin]=LCD meteostanica (QML)
Name[sr@latin]=LCD meteostanica (QML)
Name[sv]=LCD-väderstation (QML)
Name[tr]=LCD Hava Durumu İstasyonu (QML)
Name[uk]=Метеорологічна станція на дисплеї (QML)
Name[x-test]=xxLCD Weather Station (QML)xx
Name[zh_CN]= (QML)
Name[zh_TW]=LCD (QML)
Type=Service
ServiceTypes=Plasma/Applet,Plasma/PopupApplet
Icon=weather-clouds
X-Plasma-MainScript=ui/main.qml
X-Plasma-DefaultSize=250,350
X-KDE-PluginInfo-Author=Luís Gabriel Lima
X-KDE-PluginInfo-Email=lampih@gmail.com
X-KDE-PluginInfo-Name=org.kde.lcdweather
X-KDE-PluginInfo-Version=1.0
X-KDE-PluginInfo-Website=
X-KDE-PluginInfo-Category=Examples
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPLv2+
X-KDE-PluginInfo-EnabledByDefault=true

View file

@ -1,130 +0,0 @@
[Desktop Entry]
Encoding=UTF-8
Name=LCD Weather Station
Name[ar]=محطة الطقس المسطحة
Name[ast]=Estación meteorolóxica LCD
Name[bs]=LCD Meteroloska stanica
Name[ca]=Estació meteorològica LCD
Name[ca@valencia]=Estació meteorològica LCD
Name[cs]=LCD meteostanice
Name[da]=LCD-vejrstation
Name[de]=LCD-Wetterstation
Name[el]=Μετεωρολογικός σταθμός LCD
Name[en_GB]=LCD Weather Station
Name[es]=Estación meteorológica LCD
Name[et]=LCD ilmateade
Name[eu]=LCD eguraldi gunea
Name[fi]=LCD-sääasema
Name[fr]=Station météo LCD
Name[ga]=Stáisiún Aimsire LCD
Name[gl]=Estación meteorolóxica LCD
Name[he]=דיווחי מזג האוויר LCD
Name[hr]=LCD-meteorološka postaja
Name[hu]=LCD időjárásjelző állomás
Name[is]=LCD veðurstöð
Name[it]=Stazione meteorologica a cristalli liquidi
Name[ja]=LCD
Name[kk]=СК-дисплейдегі ауа райы
Name[km]= LCD
Name[ko]=LCD
Name[ku]=LCD Îstasyona Hewayê
Name[lt]=LCD orų stotelė
Name[lv]=LCD laikapstākļu stacija
Name[mr]=LCD
Name[nb]=LCD værstasjon
Name[nds]=LCD-Wederstatschoon
Name[nl]=LCD weerstation
Name[nn]=LCD-vêrstasjon
Name[pa]=LCD
Name[pl]=Stacja pogodowa LCD
Name[pt]=Estação Meteorológica LCD
Name[pt_BR]=Estação meteorológica LCD
Name[ro]=Stație meteo ECL
Name[ru]=ЖКД-метеосводка
Name[sk]=LCD meteorologická stanica
Name[sl]=Vremenska postaja LCD
Name[sr]=ЛЦД метеостаница
Name[sr@ijekavian]=ЛЦД метеостаница
Name[sr@ijekavianlatin]=LCD meteostanica
Name[sr@latin]=LCD meteostanica
Name[sv]=Väderstation
Name[th]= LCD
Name[tr]=LCD Hava Durumu İstasyonu
Name[uk]=Метеорологічна станція на дисплеї
Name[wa]=Sitåcion meteyo LCD
Name[x-test]=xxLCD Weather Stationxx
Name[zh_CN]=
Name[zh_TW]=LCD
Comment=Weather reports with an LCD display style
Comment[ar]=تقارير الطقس بنمط عرض شاشة مسطحة
Comment[ast]=Informes meteorolóxicos con un estilu de pantalla LCD
Comment[bs]=Izvještaj o vremenu preko LCD ekrana
Comment[ca]=Informes meteorològics en una pantalla d'estil LCD
Comment[ca@valencia]=Informes meteorològics en una pantalla d'estil LCD
Comment[cs]=Zprávy o počasí se stylem zobrazení LCD
Comment[da]=Vejrudsigt med stil som en LCD-skærm.
Comment[de]=Wetterberichte im Stil von LCD-Anzeigen
Comment[el]=Αναφορά καιρού με στυλ εμφάνισης LCD
Comment[en_GB]=Weather reports with an LCD display style
Comment[es]=Informes meteorológicos con un estilo de pantalla LCD
Comment[et]=Ilmateade LCD stiilis
Comment[eu]=Eguraldi txostenak LCD bistaraketa tankerarekin
Comment[fi]=Säätiedotukset LCD-tyylisesti
Comment[fr]=Bulletins météo avec un style d'affichage LCD
Comment[ga]=Réamhaisnéis aimsire i stíl taispeána LCD
Comment[gl]=Boletíns meteorolóxicos cun estilo de pantalla LCD
Comment[he]=דיווחי מזג האוויר עם סגנון הצגה LCD
Comment[hr]=Izvješća o vremenu s prikazom u stilu LCD-a
Comment[hu]=Időjárásjelentések egy LCD-kijelző stílusában
Comment[is]=Veðurupplýsingar með LCD-skjá
Comment[it]=Informazioni meteorologiche con uno schermo a cristalli liquidi
Comment[ja]=LCD
Comment[kk]=СК-стильді дисплейдегі ауа райы ақпары
Comment[km]= LCD
Comment[ko]=LCD
Comment[ku]=Raporên hewayê bi teşeya nîşandana LCD re
Comment[lt]=Orų prognozės LCD ekrano stiliuje
Comment[lv]=Rāda laika ziņas LCD stilā
Comment[mr]= LCD ि
Comment[nb]=Værmeldinger med visning i LCD-stil
Comment[nds]=Wederberichten mit en LCD-Dorstellstil
Comment[nl]=Weerberichten met een LCD-achtig display
Comment[nn]=Vêret nett no i LCD-stil
Comment[pa]= LCD ਿ ਿ
Comment[pl]=Informacje pogodowe na wyświetlaczu LCD
Comment[pt]=Boletins meteorológicos com um estilo de visualização LCD
Comment[pt_BR]=Informações meteorológicas com um estilo de visualização LCD
Comment[ro]=Rapoarte meteo cu un stil de Ecran cu Cristale Lichide
Comment[ru]=Сообщение о погоде на LCD-экране
Comment[sk]=Správy o počasí v štýle LCD displeja
Comment[sl]=Vremenska poročila, prikazana v slogu LCD
Comment[sr]=Извештаји о времену преко ЛЦД екрана
Comment[sr@ijekavian]=Извјештаји о времену преко ЛЦД екрана
Comment[sr@ijekavianlatin]=Izvještaji o vremenu preko LCD ekrana
Comment[sr@latin]=Izveštaji o vremenu preko LCD ekrana
Comment[sv]=Väderrapport visad med LCD-stil
Comment[th]= LCD
Comment[tr]=LCD biçiminde hava durumu raporları
Comment[uk]=Прогнози погоди на маленькому дисплеї
Comment[wa]=Rapoirts del meteyo avou on stîle di håynaedje LCD
Comment[x-test]=xxWeather reports with an LCD display stylexx
Comment[zh_CN]=
Comment[zh_TW]= LCD
Type=Service
Icon=weather-clouds
ServiceTypes=Plasma/Applet
X-KDE-Library=plasma_applet_weatherstation
X-KDE-PluginInfo-Author=Petri Damstén
X-KDE-PluginInfo-Email=damu@iki.fi
X-KDE-PluginInfo-Name=weatherstation
X-KDE-PluginInfo-Version=1.0
X-KDE-PluginInfo-Website=
X-KDE-PluginInfo-Category=Environment and Weather
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPLv2+
X-KDE-PluginInfo-EnabledByDefault=true
X-Plasma-Requires-FileDialog=Unused
X-Plasma-Requires-LaunchApp=Optional

View file

@ -1,325 +0,0 @@
/*
* Copyright 2008-2009 Petri Damstén <damu@iki.fi>
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*/
#include "weatherstation.h"
#include <math.h>
#include <QtGui/QGraphicsLinearLayout>
#include <QtDeclarative/QDeclarativeEngine>
#include <QtDeclarative/QDeclarativeContext>
#include <KConfigDialog>
#include <KConfigGroup>
#include <KToolInvocation>
#include <Plasma/Containment>
#include <Plasma/Theme>
#include <Plasma/ToolTipManager>
#include <Plasma/DeclarativeWidget>
#include <Plasma/Package>
#include <plasmaweather/weatherconfig.h>
#include "lcd.h"
WeatherStation::WeatherStation(QObject *parent, const QVariantList &args)
: WeatherPopupApplet(parent, args)
, m_declarativeWidget(0)
, m_lcdPanel(0)
{
resize(250, 350);
setDefaultIon("noaa");
}
WeatherStation::~WeatherStation()
{
}
void WeatherStation::init()
{
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(this);
m_declarativeWidget = new Plasma::DeclarativeWidget(this);
layout->addItem(m_declarativeWidget);
m_declarativeWidget->engine()->rootContext()->setContextProperty("weatherStation", this);
Plasma::PackageStructure::Ptr structure = Plasma::PackageStructure::load("Plasma/Generic");
Plasma::Package package(QString(), "org.kde.lcdweather", structure);
m_declarativeWidget->setQmlPath(package.filePath("mainscript"));
m_lcdPanel = new LCD(this);
m_lcdPanel->setSvg("weatherstation/lcd_panel");
m_lcdPanel->setLabel("temperature-label", i18n("OUTDOOR TEMP"));
m_lcdPanel->hide();
WeatherPopupApplet::init();
}
QGraphicsWidget* WeatherStation::graphicsWidget()
{
return m_declarativeWidget;
}
void WeatherStation::createConfigurationInterface(KConfigDialog *parent)
{
WeatherPopupApplet::createConfigurationInterface(parent);
WeatherConfig* wc = weatherConfig();
wc->setConfigurableUnits(WeatherConfig::Temperature | WeatherConfig::Speed |
WeatherConfig::Pressure);
QWidget *w = new QWidget();
m_appearanceConfig.setupUi(w);
m_appearanceConfig.backgroundCheckBox->setChecked(m_useBackground);
m_appearanceConfig.tooltipCheckBox->setChecked(m_showToolTip);
parent->addPage(w, i18n("Appearance"), icon());
connect(m_appearanceConfig.backgroundCheckBox, SIGNAL(clicked(bool)), parent, SLOT(settingsModified()));
connect(m_appearanceConfig.tooltipCheckBox, SIGNAL(clicked(bool)), parent, SLOT(settingsModified()));
}
bool WeatherStation::useBackground() const
{
return m_useBackground;
}
void WeatherStation::setUseBackground(bool use)
{
if (use == m_useBackground)
return;
m_useBackground = use;
m_lcdPanel->clear();
if (m_useBackground) {
m_lcdPanel->setItemOn("lcd_background");
}
m_lcdPanel->setItemOn("background");
emit useBackgroundChanged();
}
void WeatherStation::setLCDIcon()
{
if (m_lcdPanel->size().toSize() != size().toSize()) {
m_lcdPanel->resize(size());
}
setPopupIcon(QIcon(m_lcdPanel->toPixmap()));
}
void WeatherStation::configAccepted()
{
setUseBackground(m_appearanceConfig.backgroundCheckBox->isChecked());
m_showToolTip = m_appearanceConfig.tooltipCheckBox->isChecked();
KConfigGroup cfg = config();
cfg.writeEntry("background", m_useBackground);
cfg.writeEntry("tooltip", m_showToolTip);
WeatherPopupApplet::configAccepted();
}
void WeatherStation::configChanged()
{
KConfigGroup cfg = config();
setUseBackground(cfg.readEntry("background", true));
m_showToolTip = cfg.readEntry("tooltip", true);
if (!m_showToolTip) {
emit weatherLabelChanged(i18n("CURRENT WEATHER"));
Plasma::ToolTipManager::self()->clearContent(this);
}
setLCDIcon();
WeatherPopupApplet::configChanged();
}
QString WeatherStation::tempValue(const QString& value, int unit)
{
if (value.isEmpty() || value == "N/A") {
return QString();
}
KTemperature temp(value.toDouble(), static_cast<KTemperature::KTempUnit>(unit));
KTemperature totemp(0.0, temperatureUnit());
const double tempvalue = temp.convertTo(totemp.unitEnum());
return QString::number(KUnitConversion::round(tempvalue, 1));
}
QString WeatherStation::presValue(const QString& value, int unit)
{
if (value.isEmpty() || value == "N/A") {
return QString();
}
KPressure pres(value.toDouble(), static_cast<KPressure::KPresUnit>(unit));
KPressure topres(0.0, pressureUnit());
const double presvalue = pres.convertTo(topres.unitEnum());
return QString::number(KUnitConversion::round(presvalue, 1));
}
QString WeatherStation::veloValue(const QString& value, int unit)
{
if (value.isEmpty() || value == "N/A") {
return QString();
}
KVelocity velo(value.toDouble(), static_cast<KVelocity::KVeloUnit>(unit));
KVelocity tovelo(0.0, speedUnit());
const double velovalue = velo.convertTo(tovelo.unitEnum());
return QString::number(KUnitConversion::round(velovalue, 1));
}
void WeatherStation::dataUpdated(const QString& source, const Plasma::DataEngine::Data &data)
{
WeatherPopupApplet::dataUpdated(source, data);
if (!data.contains("Place"))
return;
QString v = data["Temperature"].toString();
QString temp = tempValue(v, data["Temperature Unit"].toInt());
setTemperature(temp);
setPressure(conditionIcon(), presValue(data["Pressure"].toString(),
data["Pressure Unit"].toInt()),
data["Pressure Tendency"].toString());
setHumidity(data["Humidity"].toString());
setWind(veloValue(data["Wind Speed"].toString(), data["Wind Speed Unit"].toInt()),
data["Wind Direction"].toString());
emit providerLabelChanged(data["Credit"].toString());
m_url = data["Credit Url"].toString();
if (m_showToolTip)
setToolTip(data["Place"].toString());
}
QString WeatherStation::fromCondition(const QString& rawCondition)
{
QString::SplitBehavior skip = QString::SkipEmptyParts;
const QString condition = rawCondition.split("weather-", skip).first();
QString id;
if (condition == "clear-night") {
id = "moon";
} else if (condition == "clear") {
id = "sun";
} else if (condition == "few-clouds-night"
|| condition == "clouds-night") {
id = "cloud_nights";
} else if (condition == "few-clouds"
|| condition == "clouds") {
id = "cloud_days";
} else if (condition == "hail") {
id = "hail";
} else if (condition == "many-clouds"
|| condition == "mist") {
id = "clouds_mist";
} else if (condition == "showers-night"
|| condition == "showers-day") {
id = "half_showers";
} else if (condition == "showers") {
id = "showers";
} else if (condition == "showers-scattered-night"
|| condition == "showers-scattered-day"
|| condition == "showers-scattered") {
id = "showers_scattered";
} else if (condition == "snow") {
id = "snow";
} else if (condition == "snow-rain") {
id = "snow_rain";
} else if (condition == "snow-scattered-night"
|| condition == "snow-scattered-day"
|| condition == "snow-scattered") {
id = "snow_scattered";
} else if (condition == "storm") {
id = "snow_storm";
}
return id;
}
void WeatherStation::setPressure(const QString& condition, const QString& pressure,
const QString& tendencyString)
{
QString currentCondition = "weather:" + fromCondition(condition);
qreal t;
if (tendencyString.toLower() == "rising") {
t = 1.0;
} else if (tendencyString.toLower() == "falling") {
t = -1.0;
} else {
t = tendencyString.toDouble();
}
QString direction;
if (t > 0.0) {
direction = "up";
} else if (t < 0.0) {
direction = "down";
}
emit pressureChanged(currentCondition, pressure, pressureUnit(), direction);
}
void WeatherStation::setTemperature(const QString& temperature)
{
m_lcdPanel->setLabel("temperature-unit-label", temperatureUnit());
m_lcdPanel->setNumber("temperature", temperature);
setLCDIcon();
emit temperatureChanged(temperature, temperatureUnit());
}
void WeatherStation::setHumidity(QString humidity)
{
if (humidity != "N/A")
humidity.remove('%');
emit humidityChanged(humidity);
}
void WeatherStation::setToolTip(const QString& place)
{
emit weatherLabelChanged(place.toUpper());
QString t = KGlobal::locale()->formatDateTime(QDateTime::currentDateTime(),
QLocale::NarrowFormat);
Plasma::ToolTipContent ttc(place, i18n("Last updated: %1", t));
Plasma::ToolTipManager::self()->setContent(this, ttc);
}
void WeatherStation::setWind(const QString& speed, const QString& dir)
{
QString direction = dir;
if (dir == "N/A")
direction = "";
emit windChanged(direction, speed, speedUnit());
}
void WeatherStation::clicked()
{
if(!m_url.isEmpty())
KToolInvocation::invokeBrowser(m_url);
}
#include "moc_weatherstation.cpp"

View file

@ -1,100 +0,0 @@
/*
* Copyright 2008-2009 Petri Damstén <damu@iki.fi>
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*/
#ifndef WEATHERSTATION_HEADER
#define WEATHERSTATION_HEADER
#include <kunitconversion.h>
#include <Plasma/PopupApplet>
#include <Plasma/DataEngine>
#include <plasmaweather/weatherpopupapplet.h>
#include "ui_appearanceconfig.h"
class LCD;
namespace Plasma {
class DeclarativeWidget;
}
namespace Conversion {
class Value;
}
class WeatherStation : public WeatherPopupApplet
{
Q_OBJECT
Q_PROPERTY(bool useBackground READ useBackground WRITE setUseBackground NOTIFY useBackgroundChanged)
public:
WeatherStation(QObject *parent, const QVariantList &args);
~WeatherStation();
virtual void init();
QGraphicsWidget* graphicsWidget();
virtual void createConfigurationInterface(KConfigDialog *parent);
bool useBackground() const;
void setUseBackground(bool use);
public slots:
virtual void configAccepted();
virtual void dataUpdated(const QString &name, const Plasma::DataEngine::Data &data);
void clicked();
void configChanged();
signals:
void useBackgroundChanged();
void temperatureChanged(QString temperature, QString unit);
void humidityChanged(QString humidity);
void providerLabelChanged(QString label);
void weatherLabelChanged(QString label);
void conditionChanged();
void pressureChanged(QString conditionId, QString pressure, QString unit, QString direction);
void windChanged(QString direction, QString speed, QString unit);
protected:
void setWind(const QString& speed, const QString& direction);
void setPressure(const QString& condition, const QString& pressure,
const QString& tendency);
void setTemperature(const QString& temperature);
void setHumidity(QString humidity);
void setToolTip(const QString& place);
QString fromCondition(const QString& condition);
QString tempValue(const QString& value, int unit);
QString presValue(const QString& value, int unit);
QString veloValue(const QString& value, int unit);
private:
void setLCDIcon();
Plasma::DeclarativeWidget *m_declarativeWidget;
LCD *m_lcdPanel;
Ui::AppearanceConfig m_appearanceConfig;
bool m_useBackground;
bool m_showToolTip;
QString m_url;
};
K_EXPORT_PLASMA_APPLET(weatherstation, WeatherStation)
#endif

View file

@ -1 +0,0 @@
add_subdirectory(plasmaweather)

View file

@ -1,37 +0,0 @@
set(plasmaweather_LIB_SRCS
weatherpopupapplet.cpp
weathervalidator.cpp
weatherlocation.cpp
weatherconfig.cpp
weatheri18ncatalog.cpp
weatherconfig.ui
)
set(plasmaweather_HEADERS
weatherpopupapplet.h
weathervalidator.h
weatherconfig.h
weatherlocation.h
${CMAKE_CURRENT_BINARY_DIR}/plasmaweather_export.h
)
add_library(plasmaweather SHARED ${plasmaweather_LIB_SRCS})
target_link_libraries(plasmaweather
KDE4::plasma
KDE4::kdeui
KDE4Workspace::weather_ion
)
set_target_properties(plasmaweather PROPERTIES
VERSION ${GENERIC_LIB_VERSION}
SOVERSION ${GENERIC_LIB_SOVERSION}
)
generate_export_header(plasmaweather)
install(
TARGETS plasmaweather
DESTINATION ${KDE4_LIB_INSTALL_DIR}
)
# nothing outside of kdeplasma-addons uses this library, and the API is not stable -> do not install headers!
# install(FILES ${plasmaweather_HEADERS} DESTINATION ${KDE4_INCLUDE_INSTALL_DIR}/plasmaweather)

View file

@ -1,3 +0,0 @@
#! /usr/bin/env bash
$EXTRACTRC *.ui >> rc.cpp
$XGETTEXT *.cpp -o $podir/libplasmaweather.pot

View file

@ -1,341 +0,0 @@
/*
* Copyright (C) 2009 Petri Damstén <damu@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "weatherconfig.h"
#include <KDebug>
#include <KDialog>
#include <KInputDialog>
#include <KPixmapSequence>
#include <KPixmapSequenceWidget>
#include <KUnitConversion>
#include "weatherlocation.h"
#include "weathervalidator.h"
#include "weatheri18ncatalog.h"
#include "ui_weatherconfig.h"
class WeatherConfig::Private
{
public:
Private(WeatherConfig *weatherconfig)
: q(weatherconfig),
location(nullptr),
validator(nullptr),
ion("wettercom"),
dlg(nullptr),
busyWidget(nullptr)
{
}
void setSource(int index)
{
// do not emit the signals when searching, valid source may not even be found
if (!searchLocation.isEmpty()) {
return;
}
QString text = ui.locationCombo->itemData(index).toString();
if (!text.isEmpty()) {
source = text;
emit q->settingsChanged();
emit q->configValueChanged();
}
}
void changePressed()
{
if (!validator) {
kWarning() << "No validator";
return;
}
QString text = ui.locationCombo->currentText();
if (text.isEmpty()) {
return;
}
if (location) {
delete location;
location = nullptr;
}
searchLocation = text;
ui.locationCombo->clear();
if (!busyWidget) {
busyWidget = new KPixmapSequenceWidget(q);
KPixmapSequence seq(QLatin1String("process-working"), 22);
busyWidget->setSequence(seq);
ui.locationSearchLayout->insertWidget(1, busyWidget);
}
validator->validate(text, true);
}
void enableOK()
{
if (dlg) {
dlg->enableButton(KDialog::Ok, !source.isEmpty());
}
}
void addSource(const QString &sources);
void addSources(const QMap<QString, QString> &sources);
void validatorError(const QString &error);
WeatherConfig* q;
QString searchLocation;
WeatherLocation* location;
WeatherValidator* validator;
QString ion;
QString source;
Ui::WeatherConfig ui;
KDialog *dlg;
KPixmapSequenceWidget *busyWidget;
};
WeatherConfig::WeatherConfig(QWidget *parent)
: QWidget(parent)
, d(new Private(this))
{
Weatheri18nCatalog::loadCatalog();
d->dlg = qobject_cast<KDialog*>(parent);
d->ui.setupUi(this);
for (int i = 0; i < KTemperature::UnitCount; i++) {
KTemperature::KTempUnit unit = static_cast<KTemperature::KTempUnit>(i);
d->ui.temperatureComboBox->addItem(KTemperature::unitDescription(unit), unit);
}
for (int i = 0; i < KPressure::UnitCount; i++) {
KPressure::KPresUnit unit = static_cast<KPressure::KPresUnit>(i);
d->ui.pressureComboBox->addItem(KPressure::unitDescription(unit), unit);
}
for (int i = 0; i < KVelocity::UnitCount; i++) {
KVelocity::KVeloUnit unit = static_cast<KVelocity::KVeloUnit>(i);
d->ui.speedComboBox->addItem(KVelocity::unitDescription(unit), unit);
}
for (int i = 0; i < KLength::UnitCount; i++) {
KLength::KLengUnit unit = static_cast<KLength::KLengUnit>(i);
d->ui.visibilityComboBox->addItem(KLength::unitDescription(unit), unit);
}
d->ui.locationMessage->hide();
d->ui.locationMessage->setMessageType(KMessageWidget::Error);
connect(d->ui.locationCombo, SIGNAL(returnPressed()), this, SLOT(changePressed()));
connect(d->ui.changeButton, SIGNAL(clicked()), this, SLOT(changePressed()));
connect(d->ui.updateIntervalSpinBox, SIGNAL(valueChanged(int)),
this, SLOT(setUpdateInterval(int)));
connect(d->ui.updateIntervalSpinBox, SIGNAL(valueChanged(int)),
this, SIGNAL(settingsChanged()));
connect(d->ui.temperatureComboBox, SIGNAL(currentIndexChanged(int)),
this, SIGNAL(settingsChanged()));
connect(d->ui.pressureComboBox, SIGNAL(currentIndexChanged(int)),
this, SIGNAL(settingsChanged()));
connect(d->ui.speedComboBox, SIGNAL(currentIndexChanged(int)),
this, SIGNAL(settingsChanged()));
connect(d->ui.visibilityComboBox, SIGNAL(currentIndexChanged(int)),
this, SIGNAL(settingsChanged()));
connect(d->ui.locationCombo, SIGNAL(currentIndexChanged(int)),
this, SLOT(setSource(int)));
connect(d->ui.updateIntervalSpinBox, SIGNAL(valueChanged(int)) , this , SIGNAL(configValueChanged()));
connect(d->ui.temperatureComboBox, SIGNAL(currentIndexChanged(int)) , this , SIGNAL(configValueChanged()));
connect(d->ui.pressureComboBox, SIGNAL(currentIndexChanged(int)) , this , SIGNAL(configValueChanged()));
connect(d->ui.speedComboBox, SIGNAL(currentIndexChanged(int)) , this , SIGNAL(configValueChanged()));
connect(d->ui.visibilityComboBox, SIGNAL(currentIndexChanged(int)) , this , SIGNAL(configValueChanged()));
}
WeatherConfig::~WeatherConfig()
{
delete d;
}
void WeatherConfig::setDataEngines(Plasma::DataEngine *location, Plasma::DataEngine *weather)
{
delete d->validator;
d->validator = nullptr;
if (weather) {
d->validator = new WeatherValidator(this);
connect(d->validator, SIGNAL(error(QString)), this, SLOT(validatorError(QString)));
connect(d->validator, SIGNAL(finished(QMap<QString,QString>)), this, SLOT(addSources(QMap<QString,QString>)));
d->validator->setDataEngine(weather);
d->validator->setIon(d->ion);
}
if (location && weather) {
d->location = new WeatherLocation(this);
connect(d->location, SIGNAL(valid(QString)), this, SLOT(addSource(QString)));
d->location->setDataEngines(location, weather);
}
}
void WeatherConfig::Private::validatorError(const QString &error)
{
kDebug() << error;
}
void WeatherConfig::Private::addSource(const QString &source)
{
QStringList list = source.split(QLatin1Char('|'), QString::SkipEmptyParts);
if (list.count() > 2) {
// kDebug() << list;
QString result = i18nc("A weather station location and the weather service it comes from",
"%1 (%2)", list[2], list[0]); // the names are too looong ions.value(list[0]));
const int resultIndex = ui.locationCombo->findText(result);
if (resultIndex < 0) {
ui.locationCombo->addItem(result, source);
}
}
}
void WeatherConfig::Private::addSources(const QMap<QString, QString> &sources)
{
QMapIterator<QString, QString> it(sources);
while (it.hasNext()) {
it.next();
addSource(it.value());
}
delete busyWidget;
busyWidget = nullptr;
kDebug() << ui.locationCombo->count();
if (ui.locationCombo->count() == 0) {
ui.locationMessage->setText(i18n("No weather stations found for '%1'", searchLocation));
ui.locationMessage->animatedShow();
} else {
ui.locationCombo->showPopup();
}
searchLocation.clear();
}
void WeatherConfig::setUpdateInterval(int interval)
{
d->ui.updateIntervalSpinBox->setValue(interval);
d->ui.updateIntervalSpinBox->setSuffix(ki18np(" minute", " minutes"));
}
void WeatherConfig::setTemperatureUnit(const QString &unit)
{
KTemperature temp(0.0, unit);
if (temp.unitEnum() != KTemperature::Invalid) {
d->ui.temperatureComboBox->setCurrentIndex(static_cast<int>(temp.unitEnum()));
}
}
void WeatherConfig::setPressureUnit(const QString &unit)
{
KPressure pres(0.0, unit);
if (pres.unitEnum() != KPressure::Invalid) {
d->ui.pressureComboBox->setCurrentIndex(static_cast<int>(pres.unitEnum()));
}
}
void WeatherConfig::setSpeedUnit(const QString &unit)
{
KVelocity velo(0.0, unit);
if (velo.unitEnum() != KVelocity::Invalid) {
d->ui.speedComboBox->setCurrentIndex(static_cast<int>(velo.unitEnum()));
}
}
void WeatherConfig::setVisibilityUnit(const QString &unit)
{
KLength leng(0.0, unit);
if (leng.unitEnum() != KLength::Invalid) {
d->ui.visibilityComboBox->setCurrentIndex(static_cast<int>(leng.unitEnum()));
}
}
void WeatherConfig::setSource(const QString &source)
{
// kDebug() << "source set to" << source;
d->addSource(source);
d->source = source;
}
QString WeatherConfig::source() const
{
return d->source;
}
int WeatherConfig::updateInterval() const
{
return d->ui.updateIntervalSpinBox->value();
}
QString WeatherConfig::temperatureUnit() const
{
KTemperature temp(0.0, static_cast<KTemperature::KTempUnit>(d->ui.temperatureComboBox->currentIndex()));
return temp.unit();
}
QString WeatherConfig::pressureUnit() const
{
KPressure pres(0.0, static_cast<KPressure::KPresUnit>(d->ui.pressureComboBox->currentIndex()));
return pres.unit();
}
QString WeatherConfig::speedUnit() const
{
KVelocity velo(0.0, static_cast<KVelocity::KVeloUnit>(d->ui.speedComboBox->currentIndex()));
return velo.unit();
}
QString WeatherConfig::visibilityUnit() const
{
KLength leng(0.0, static_cast<KLength::KLengUnit>(d->ui.visibilityComboBox->currentIndex()));
return leng.unit();
}
void WeatherConfig::setConfigurableUnits(const ConfigurableUnits units)
{
d->ui.unitsLabel->setVisible(units != None);
d->ui.temperatureLabel->setVisible(units & Temperature);
d->ui.temperatureComboBox->setVisible(units & Temperature);
d->ui.pressureLabel->setVisible(units & Pressure);
d->ui.pressureComboBox->setVisible(units & Pressure);
d->ui.speedLabel->setVisible(units & Speed);
d->ui.speedComboBox->setVisible(units & Speed);
d->ui.visibilityLabel->setVisible(units & Visibility);
d->ui.visibilityComboBox->setVisible(units & Visibility);
}
void WeatherConfig::setHeadersVisible(bool visible)
{
d->ui.locationLabel->setVisible(visible);
d->ui.unitsLabel->setVisible(visible);
}
void WeatherConfig::setIon(const QString &ion)
{
d->ion = ion;
if (d->validator) {
d->validator->setIon(ion);
}
if (d->location) {
d->location->getDefault(ion);
}
}
#include "moc_weatherconfig.cpp"

View file

@ -1,148 +0,0 @@
/*
* Copyright (C) 2009 Petri Damstén <damu@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef WEATHERCONFIG_HEADER
#define WEATHERCONFIG_HEADER
#include <QWidget>
#include "plasmaweather_export.h"
namespace Plasma { class DataEngine; }
/**
* @class WeatherConfig <plasmaweather/weatherconfig.h>
*
* @short Weather config widget class
*/
class PLASMAWEATHER_EXPORT WeatherConfig : public QWidget
{
Q_OBJECT
public:
enum ConfigurableUnit {
None = 0,
Temperature = 1,
Pressure = 2,
Speed = 4,
Visibility = 8
};
Q_DECLARE_FLAGS(ConfigurableUnits, ConfigurableUnit)
WeatherConfig(QWidget *parent = 0);
virtual ~WeatherConfig();
/**
* Set units that are configurable. Default to all.
**/
void setConfigurableUnits(const ConfigurableUnits units);
/**
* Sets dataengine to use
**/
void setDataEngines(Plasma::DataEngine *location, Plasma::DataEngine *weather);
/**
* Sets ion source
**/
void setSource(const QString& source);
/**
* Sets temperature unit
**/
void setTemperatureUnit(const QString& unit);
/**
* Sets pressure unit
**/
void setPressureUnit(const QString& unit);
/**
* Sets speed unit
**/
void setSpeedUnit(const QString& unit);
/**
* Sets visibility unit
**/
void setVisibilityUnit(const QString& unit);
/**
* @return ion source to use
**/
QString source() const;
/**
* @return update interval
**/
int updateInterval() const;
/**
* @return temperature unit
**/
QString temperatureUnit() const;
/**
* @return pressure unit
**/
QString pressureUnit() const;
/**
* @return speed unit
**/
QString speedUnit() const;
/**
* @return visibility unit
**/
QString visibilityUnit() const;
/**
* Sets header labels visible/hidden
**/
void setHeadersVisible(bool visible);
/**
* Sets the ion
**/
void setIon(const QString &ion);
signals:
void settingsChanged();
void configValueChanged();
public Q_SLOTS:
/**
* Sets update interval
**/
void setUpdateInterval(int interval);
private:
class Private;
Private * const d;
Q_PRIVATE_SLOT(d, void changePressed())
Q_PRIVATE_SLOT(d, void setSource(int))
Q_PRIVATE_SLOT(d, void addSource(const QString &source))
Q_PRIVATE_SLOT(d, void addSources(const QMap<QString, QString> &sources))
Q_PRIVATE_SLOT(d, void validatorError(const QString &error))
};
Q_DECLARE_OPERATORS_FOR_FLAGS(WeatherConfig::ConfigurableUnits)
#endif

View file

@ -1,444 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>WeatherConfig</class>
<widget class="QWidget" name="WeatherConfig">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>408</width>
<height>303</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="windowTitle">
<string>Weather Station Configuration</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0" colspan="2">
<widget class="KMessageWidget" name="locationMessage">
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="locationLabel">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>Weather Station</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="cityLabel">
<property name="minimumSize">
<size>
<width>129</width>
<height>0</height>
</size>
</property>
<property name="text">
<string>&amp;Location:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="buddy">
<cstring>locationCombo</cstring>
</property>
</widget>
</item>
<item row="2" column="1">
<layout class="QHBoxLayout" name="locationlayout">
<property name="spacing">
<number>0</number>
</property>
<item>
<widget class="KComboBox" name="locationCombo">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>10</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="editable">
<bool>true</bool>
</property>
<property name="trapReturnKey">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item row="3" column="1">
<layout class="QHBoxLayout" name="locationSearchLayout">
<property name="spacing">
<number>0</number>
</property>
<item>
<spacer name="horizontalSpacer_6">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="KPushButton" name="changeButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>&amp;Search</string>
</property>
<property name="icon">
<iconset theme="edit-find">
<normaloff/>
</iconset>
</property>
</widget>
</item>
</layout>
</item>
<item row="4" column="0">
<widget class="QLabel" name="intervalLabel">
<property name="minimumSize">
<size>
<width>129</width>
<height>0</height>
</size>
</property>
<property name="text">
<string>Update &amp;every:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="buddy">
<cstring>updateIntervalSpinBox</cstring>
</property>
</widget>
</item>
<item row="4" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_4">
<property name="spacing">
<number>0</number>
</property>
<item>
<widget class="KIntSpinBox" name="updateIntervalSpinBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="suffix">
<string> minutes</string>
</property>
<property name="minimum">
<number>30</number>
</property>
<property name="maximum">
<number>3600</number>
</property>
<property name="singleStep">
<number>5</number>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_5">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item row="5" column="0">
<widget class="QLabel" name="unitsLabel">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>Units</string>
</property>
</widget>
</item>
<item row="6" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_5">
<property name="spacing">
<number>0</number>
</property>
<item>
<widget class="KComboBox" name="temperatureComboBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_4">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item row="6" column="0">
<widget class="QLabel" name="temperatureLabel">
<property name="minimumSize">
<size>
<width>129</width>
<height>0</height>
</size>
</property>
<property name="text">
<string>&amp;Temperature:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="buddy">
<cstring>temperatureComboBox</cstring>
</property>
</widget>
</item>
<item row="7" column="0">
<widget class="QLabel" name="pressureLabel">
<property name="minimumSize">
<size>
<width>129</width>
<height>0</height>
</size>
</property>
<property name="text">
<string>&amp;Pressure:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="buddy">
<cstring>pressureComboBox</cstring>
</property>
</widget>
</item>
<item row="7" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_6">
<property name="spacing">
<number>0</number>
</property>
<item>
<widget class="KComboBox" name="pressureComboBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item row="8" column="0">
<widget class="QLabel" name="speedLabel">
<property name="minimumSize">
<size>
<width>129</width>
<height>0</height>
</size>
</property>
<property name="text">
<string>Wind &amp;speed:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="buddy">
<cstring>speedComboBox</cstring>
</property>
</widget>
</item>
<item row="8" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_7">
<property name="spacing">
<number>0</number>
</property>
<item>
<widget class="KComboBox" name="speedComboBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item row="9" column="0">
<widget class="QLabel" name="visibilityLabel">
<property name="minimumSize">
<size>
<width>129</width>
<height>0</height>
</size>
</property>
<property name="text">
<string>&amp;Visibility:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="buddy">
<cstring>visibilityComboBox</cstring>
</property>
</widget>
</item>
<item row="9" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_8">
<property name="spacing">
<number>0</number>
</property>
<item>
<widget class="KComboBox" name="visibilityComboBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item row="10" column="0">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>17</width>
<height>13</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>KMessageWidget</class>
<extends>QFrame</extends>
<header>kmessagewidget.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>KIntSpinBox</class>
<extends>QSpinBox</extends>
<header>knuminput.h</header>
</customwidget>
<customwidget>
<class>KPushButton</class>
<extends>QPushButton</extends>
<header>kpushbutton.h</header>
</customwidget>
<customwidget>
<class>KComboBox</class>
<extends>QComboBox</extends>
<header>kcombobox.h</header>
</customwidget>
</customwidgets>
<connections/>
</ui>

View file

@ -1,36 +0,0 @@
/*
* Copyright (C) 2009 Andrew Coles <andrew_coles@yahoo.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "weatheri18ncatalog.h"
#include <QMutex>
#include <kglobal.h>
#include <klocale.h>
static bool catalogLoaded = false;
static QMutex loadingMutex;
void Weatheri18nCatalog::loadCatalog() {
loadingMutex.lock();
if (!catalogLoaded) {
KGlobal::locale()->insertCatalog(QLatin1String( "libplasmaweather" ));
catalogLoaded = true;
}
loadingMutex.unlock();
}

View file

@ -1,30 +0,0 @@
/*
* Copyright (C) 2009 Andrew Coles <andrew_coles@yahoo.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef WEATHERI18NCATALOG_H
#define WEATHERI18NCATALOG_H
class Weatheri18nCatalog {
public:
static void loadCatalog();
};
#endif

View file

@ -1,134 +0,0 @@
/*
* Copyright (C) 2009 Petri Damstén <damu@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "weatherlocation.h"
#include "weathervalidator.h"
#include "weatheri18ncatalog.h"
#include <kdebug.h>
class WeatherLocation::Private
{
public:
Private(WeatherLocation *location)
: q(location),
locationEngine(nullptr),
weatherEngine(nullptr),
ion("wettercom")
{
}
void validatorFinished(const QMap<QString, QString> &results)
{
WeatherValidator* validator = qobject_cast<WeatherValidator*>(q->sender());
foreach (const QString &source, results.values()) {
if (source.isEmpty()) {
continue;
}
// qDebug() << Q_FUNC_INFO << source;
emit q->valid(source);
}
validators.remove(validator);
if (validators.isEmpty()) {
emit q->finished();
}
}
WeatherLocation *q;
Plasma::DataEngine *locationEngine;
Plasma::DataEngine *weatherEngine;
QString ion;
QMap<WeatherValidator*,QString> validators;
};
WeatherLocation::WeatherLocation(QObject *parent)
: QObject(parent)
, d(new Private(this))
{
Weatheri18nCatalog::loadCatalog();
}
WeatherLocation::~WeatherLocation()
{
Q_ASSERT(d->validators.size() == 0);
delete d;
}
void WeatherLocation::setDataEngines(Plasma::DataEngine* location, Plasma::DataEngine* weather)
{
d->locationEngine = location;
d->weatherEngine = weather;
}
void WeatherLocation::getDefault(const QString &ion)
{
d->ion = ion;
if (d->locationEngine && d->locationEngine->isValid()) {
d->locationEngine->connectSource(QLatin1String("location"), this);
} else {
emit finished();
}
}
void WeatherLocation::dataUpdated(const QString &source, const Plasma::DataEngine::Data &data)
{
if (!d->locationEngine) {
return;
}
Q_ASSERT(d->validators.size() == 0);
d->locationEngine->disconnectSource(source, this);
// sort the data by accuracy, the lower the accuracy number the higher the accuracy is
QMap<int, QVariant> accuratedata;
foreach (const QString &datakey, data.keys()) {
const QVariant datavariant = data[datakey];
const int dataaccuracy = datavariant.toHash()["accuracy"].toInt();
accuratedata.insert(dataaccuracy, datavariant);
}
// qDebug() << Q_FUNC_INFO << accuratedata;
foreach (const int intdatakey, accuratedata.keys()) {
const QVariantHash datahash = accuratedata.value(intdatakey).toHash();
QString city = datahash[QLatin1String("city")].toString();
if (city.contains(QLatin1Char(','))) {
city.truncate(city.indexOf(QLatin1Char(',')) - 1);
}
if (!city.isEmpty()) {
WeatherValidator* validator = new WeatherValidator(this);
validator->setDataEngine(d->weatherEngine);
validator->setIon(d->ion);
connect(
validator, SIGNAL(finished(QMap<QString,QString>)),
this, SLOT(validatorFinished(QMap<QString,QString>))
);
d->validators.insert(validator, city);
kDebug() << "validating" << city;
}
}
if (d->validators.isEmpty()) {
emit finished();
} else {
foreach (WeatherValidator* validator, d->validators.keys()) {
validator->validate(d->validators.value(validator), true);
}
}
}
#include "moc_weatherlocation.cpp"

View file

@ -1,73 +0,0 @@
/*
* Copyright (C) 2009 Petri Damstén <damu@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef WEATHERLOCATION_HEADER
#define WEATHERLOCATION_HEADER
#include <Plasma/DataEngine>
#include "plasmaweather_export.h"
/**
* @class WeatherLocation <plasmaweather/weatherlocation.h>
*
* @short Class to get default source for weather
*/
class PLASMAWEATHER_EXPORT WeatherLocation : public QObject
{
Q_OBJECT
public:
WeatherLocation(QObject *parent = 0);
virtual ~WeatherLocation();
/**
* Get default source
**/
void getDefault(const QString &ion);
/**
* Sets dataengines to use
*
* @param location location dataengine
* @param weather weather dataengine
**/
void setDataEngines(Plasma::DataEngine *location, Plasma::DataEngine *weather);
Q_SIGNALS:
/**
* Emitted when valid source is found
**/
void valid(const QString &source);
/**
* Emitted when validation is done
**/
void finished();
private Q_SLOTS:
void dataUpdated(const QString &source, const Plasma::DataEngine::Data &data);
private:
class Private;
Private * const d;
Q_PRIVATE_SLOT(d, void validatorFinished(const QMap<QString, QString> &results))
};
#endif

View file

@ -1,369 +0,0 @@
/*
* Copyright (C) 2009 Petri Damstén <damu@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "weatherpopupapplet.h"
#include "weatheri18ncatalog.h"
#include "weatherconfig.h"
#include "weatherlocation.h"
#include <QTimer>
#include <KConfigGroup>
#include <KConfigDialog>
#include <KUnitConversion>
#include <Plasma/DataEngineManager>
class WeatherPopupApplet::Private
{
public:
Private(WeatherPopupApplet *weatherapplet)
: q(weatherapplet)
, weatherConfig(nullptr)
, locationEngine(nullptr)
, weatherEngine(nullptr)
, timeEngine(nullptr)
, updateInterval(0)
, location(nullptr)
{
busyTimer = new QTimer(q);
busyTimer->setInterval(2*60*1000);
busyTimer->setSingleShot(true);
QObject::connect(busyTimer, SIGNAL(timeout()), q, SLOT(giveUpBeingBusy()));
}
WeatherPopupApplet *q;
WeatherConfig *weatherConfig;
Plasma::DataEngine *locationEngine;
Plasma::DataEngine *weatherEngine;
Plasma::DataEngine *timeEngine;
QString temperatureUnit;
QString speedUnit;
QString pressureUnit;
QString visibilityUnit;
int updateInterval;
QString source;
WeatherLocation *location;
QString defaultIon;
QString conditionIcon;
QString tend;
double pressure;
double temperature;
double latitude;
double longitude;
QTimer *busyTimer;
void locationReady(const QString &src)
{
// set the location to the first valid one (the most accurate one)
if (source.isEmpty()) {
source = src;
KConfigGroup cfg = q->config();
cfg.writeEntry("source", source);
emit q->configNeedsSaving();
q->connectToEngine();
q->setConfigurationRequired(false);
}
}
void locationFinished()
{
busyTimer->stop();
q->setBusy(false);
if (source.isEmpty()) {
q->showMessage(QIcon(), QString(), Plasma::ButtonNone);
q->setConfigurationRequired(true);
}
delete location;
location = nullptr;
}
void giveUpBeingBusy()
{
q->setBusy(false);
QStringList list = source.split(QLatin1Char( '|' ), QString::SkipEmptyParts);
if (list.count() < 3) {
q->setConfigurationRequired(true);
} else {
q->showMessage(KIcon(QLatin1String( "dialog-error" )),
i18n("Weather information retrieval for %1 timed out.", list.value(2)),
Plasma::ButtonNone);
}
}
qreal tendency(const double pressure, const QString& tendency)
{
qreal t;
if (tendency.toLower() == QLatin1String( "rising" )) {
t = 0.75;
} else if (tendency.toLower() == QLatin1String( "falling" )) {
t = -0.75;
} else {
t = KPressure(tendency.toDouble(), pressureUnit).convertTo(KPressure::Kilopascal);
}
return t;
}
QString conditionFromPressure()
{
if (KPressure(0.0, pressureUnit).unitEnum() == KPressure::Invalid) {
return QLatin1String( "weather-none-available" );
}
qreal temp = KTemperature(temperature, temperatureUnit).convertTo(KTemperature::Celsius);
qreal p = KPressure(pressure, pressureUnit).convertTo(KPressure::Kilopascal);
qreal t = tendency(pressure, tend);
// This is completely unscientific so if anyone have a better formula for this :-)
p += t * 10;
Plasma::DataEngine::Data data = timeEngine->query(
QString(QLatin1String( "Local|Solar|Latitude=%1|Longitude=%2" )).arg(latitude).arg(longitude));
bool day = (data[QLatin1String( "Corrected Elevation" )].toDouble() > 0.0);
QString result;
if (p > 103.0) {
if (day) {
result = QLatin1String( "weather-clear" );
} else {
result = QLatin1String( "weather-clear-night" );
}
} else if (p > 100.0) {
if (day) {
result = QLatin1String( "weather-clouds" );
} else {
result = QLatin1String( "weather-clouds-night" );
}
} else if (p > 99.0) {
if (day) {
if (temp > 1.0) {
result = QLatin1String( "weather-showers-scattered-day" );
} else if (temp < -1.0) {
result = QLatin1String( "weather-snow-scattered-day" );
} else {
result = QLatin1String( "weather-snow-rain" );
}
} else {
if (temp > 1.0) {
result = QLatin1String( "weather-showers-scattered-night" );
} else if (temp < -1.0) {
result = QLatin1String( "weather-snow-scattered-night" );
} else {
result = QLatin1String( "weather-snow-rain" );
}
}
} else {
if (temp > 1.0) {
result = QLatin1String( "weather-showers" );
} else if (temp < -1.0) {
result = QLatin1String( "weather-snow" );
} else {
result = QLatin1String( "weather-snow-rain" );
}
}
//kDebug() << result;
return result;
}
};
WeatherPopupApplet::WeatherPopupApplet(QObject *parent, const QVariantList &args)
: Plasma::PopupApplet(parent, args)
, d(new Private(this))
{
Weatheri18nCatalog::loadCatalog();
setHasConfigurationInterface(true);
}
WeatherPopupApplet::~WeatherPopupApplet()
{
if (d->locationEngine) {
Plasma::DataEngineManager::self()->unloadEngine(QLatin1String("geolocation"));
d->locationEngine = nullptr;
}
if (d->weatherEngine) {
Plasma::DataEngineManager::self()->unloadEngine(QLatin1String("weather"));
d->weatherEngine = nullptr;
}
if (d->timeEngine) {
Plasma::DataEngineManager::self()->unloadEngine(QLatin1String("time"));
d->timeEngine = nullptr;
}
delete d;
}
void WeatherPopupApplet::init()
{
configChanged();
}
void WeatherPopupApplet::connectToEngine()
{
emit newWeatherSource();
const bool missingLocation = d->source.isEmpty();
if (missingLocation) {
if (!d->location) {
d->location = new WeatherLocation(this);
connect(d->location, SIGNAL(valid(QString)), this, SLOT(locationReady(QString)));
connect(d->location, SIGNAL(finished()), this, SLOT(locationFinished()));
}
d->busyTimer->stop();
setBusy(false);
d->location->setDataEngines(d->locationEngine, d->weatherEngine);
d->location->getDefault(d->defaultIon);
} else {
d->busyTimer->start();
setBusy(true);
d->weatherEngine->connectSource(d->source, this, d->updateInterval * 60 * 1000);
}
}
void WeatherPopupApplet::setDefaultIon(const QString &ion)
{
d->defaultIon = ion;
}
void WeatherPopupApplet::createConfigurationInterface(KConfigDialog *parent)
{
d->weatherConfig = new WeatherConfig(parent);
d->weatherConfig->setDataEngines(d->locationEngine, d->weatherEngine);
d->weatherConfig->setSource(d->source);
d->weatherConfig->setIon(d->defaultIon);
d->weatherConfig->setUpdateInterval(d->updateInterval);
d->weatherConfig->setTemperatureUnit(d->temperatureUnit);
d->weatherConfig->setSpeedUnit(d->speedUnit);
d->weatherConfig->setPressureUnit(d->pressureUnit);
d->weatherConfig->setVisibilityUnit(d->visibilityUnit);
parent->addPage(d->weatherConfig, i18n("Weather"), icon());
connect(parent, SIGNAL(applyClicked()), this, SLOT(configAccepted()));
connect(parent, SIGNAL(okClicked()), this, SLOT(configAccepted()));
connect(d->weatherConfig, SIGNAL(configValueChanged()) , parent , SLOT(settingsModified()));
}
void WeatherPopupApplet::configAccepted()
{
d->temperatureUnit = d->weatherConfig->temperatureUnit();
d->speedUnit = d->weatherConfig->speedUnit();
d->pressureUnit = d->weatherConfig->pressureUnit();
d->visibilityUnit = d->weatherConfig->visibilityUnit();
d->updateInterval = d->weatherConfig->updateInterval();
d->source = d->weatherConfig->source();
KConfigGroup cfg = config();
cfg.writeEntry("temperatureUnit", d->temperatureUnit);
cfg.writeEntry("speedUnit", d->speedUnit);
cfg.writeEntry("pressureUnit", d->pressureUnit);
cfg.writeEntry("visibilityUnit", d->visibilityUnit);
cfg.writeEntry("updateInterval", d->updateInterval);
cfg.writeEntry("source", d->source);
emit configNeedsSaving();
}
void WeatherPopupApplet::configChanged()
{
if (!d->source.isEmpty()) {
d->weatherEngine->disconnectSource(d->source, this);
}
KConfigGroup cfg = config();
if (KGlobal::locale()->measureSystem() == QLocale::MetricSystem) {
d->temperatureUnit = cfg.readEntry("temperatureUnit", "C");
d->speedUnit = cfg.readEntry("speedUnit", "m/s");
d->pressureUnit = cfg.readEntry("pressureUnit", "hPa");
d->visibilityUnit = cfg.readEntry("visibilityUnit", "km");
} else {
d->temperatureUnit = cfg.readEntry("temperatureUnit", "F");
d->speedUnit = cfg.readEntry("speedUnit", "mph");
d->pressureUnit = cfg.readEntry("pressureUnit", "inHg");
d->visibilityUnit = cfg.readEntry("visibilityUnit", "mi");
}
d->updateInterval = cfg.readEntry("updateInterval", 30);
d->source = cfg.readEntry("source", "");
setConfigurationRequired(d->source.isEmpty());
d->locationEngine = dataEngine(QLatin1String("geolocation"));
d->weatherEngine = dataEngine(QLatin1String( "weather" ));
d->timeEngine = dataEngine(QLatin1String( "time" ));
connectToEngine();
}
void WeatherPopupApplet::dataUpdated(const QString& source,
const Plasma::DataEngine::Data &data)
{
Q_UNUSED(source)
if (data.isEmpty()) {
return;
}
d->conditionIcon = data[QLatin1String( "Condition Icon" )].toString();
if (data[QLatin1String( "Pressure" )].toString() != QLatin1String( "N/A" )) {
d->pressure = KPressure(data[QLatin1String( "Pressure" )].toDouble(), static_cast<KPressure::KPresUnit>(data[QLatin1String( "Pressure Unit" )].toInt())).number();
} else {
d->pressure = 0.0;
}
d->tend = data[QLatin1String( "Pressure Tendency" )].toString();
d->temperature = KTemperature(data[QLatin1String( "Temperature" )].toDouble(), static_cast<KTemperature::KTempUnit>(data[QLatin1String( "Temperature Unit" )].toInt())).number();
d->latitude = data[QLatin1String( "Latitude" )].toDouble();
d->longitude = data[QLatin1String( "Longitude" )].toDouble();
setAssociatedApplicationUrls(KUrl(data.value(QLatin1String( "Credit Url" )).toString()));
d->busyTimer->stop();
setBusy(false);
showMessage(QIcon(), QString(), Plasma::ButtonNone);
}
QString WeatherPopupApplet::pressureUnit()
{
return d->pressureUnit;
}
QString WeatherPopupApplet::temperatureUnit()
{
return d->temperatureUnit;
}
QString WeatherPopupApplet::speedUnit()
{
return d->speedUnit;
}
QString WeatherPopupApplet::visibilityUnit()
{
return d->visibilityUnit;
}
QString WeatherPopupApplet::conditionIcon()
{
if (d->conditionIcon.isEmpty() || d->conditionIcon == QLatin1String( "weather-none-available" )) {
d->conditionIcon = d->conditionFromPressure();
}
return d->conditionIcon;
}
WeatherConfig* WeatherPopupApplet::weatherConfig()
{
return d->weatherConfig;
}
#include "moc_weatherpopupapplet.cpp"

View file

@ -1,126 +0,0 @@
/*
* Copyright (C) 2009 Petri Damstén <damu@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef WEATHERPOPUPAPPLET_HEADER
#define WEATHERPOPUPAPPLET_HEADER
#include <Plasma/PopupApplet>
#include <Plasma/DataEngine>
#include "plasmaweather_export.h"
class WeatherConfig;
/**
* @class WeatherPopupApplet <plasmaweather/weatherpopupapplet.h>
*
* @short Base class for Weather Applets
*/
class PLASMAWEATHER_EXPORT WeatherPopupApplet : public Plasma::PopupApplet
{
Q_OBJECT
public:
WeatherPopupApplet(QObject *parent, const QVariantList &args);
~WeatherPopupApplet();
/**
* Reimplemented from Plasma::Applet
*/
virtual void init();
/**
* Reimplemented from Plasma::Applet
*/
virtual void createConfigurationInterface(KConfigDialog *parent);
/**
* @return pressure unit
**/
QString pressureUnit();
/**
* @return temperature unit
**/
QString temperatureUnit();
/**
* @return speed unit
**/
QString speedUnit();
/**
* @return visibility unit
**/
QString visibilityUnit();
/**
* @return condition icon with guessed value if it was empty
**/
QString conditionIcon();
/**
* @return weather config dialog widget
**/
WeatherConfig* weatherConfig();
public Q_SLOTS:
/**
* Called when config is accepted
*/
virtual void configAccepted();
/**
* Called when data is updated
*/
virtual void dataUpdated(const QString &name,
const Plasma::DataEngine::Data &data);
/**
* Called when config is chnaged
*/
virtual void configChanged();
Q_SIGNALS:
/**
* Emitted when the applet begins a fetch for a new weather source
*/
void newWeatherSource();
protected:
/**
* Connects applet to dataengine
*/
virtual void connectToEngine();
/**
* Sets the ion used for getting the default location
*
*/
void setDefaultIon(const QString &ion);
private:
class Private;
Private * const d;
Q_PRIVATE_SLOT(d, void locationReady(const QString &source))
Q_PRIVATE_SLOT(d, void locationFinished())
Q_PRIVATE_SLOT(d, void giveUpBeingBusy())
};
#endif

View file

@ -1,138 +0,0 @@
/*
* Copyright (C) 2009 Petri Damstén <damu@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "weathervalidator.h"
#include "weatheri18ncatalog.h"
#include <KInputDialog>
#include <KMessageBox>
class WeatherValidator::Private
{
public:
Private()
: dataengine(nullptr),
ion(QLatin1String("wettercom")),
silent(false)
{
}
Plasma::DataEngine* dataengine;
QString ion;
QString validating;
bool silent;
};
WeatherValidator::WeatherValidator(QObject *parent)
: QObject(parent),
d(new Private())
{
Weatheri18nCatalog::loadCatalog();
}
WeatherValidator::~WeatherValidator()
{
delete d;
}
QString WeatherValidator::ion() const
{
return d->ion;
}
void WeatherValidator::setIon(const QString &ion)
{
d->ion = ion;
}
void WeatherValidator::validate(const QString &location, bool silent)
{
if (d->ion.isEmpty() || !d->dataengine) {
return;
}
d->silent = silent;
QString validation = QString(QLatin1String("%1|validate|%2")).arg(d->ion).arg(location);
if (d->validating != validation) {
d->dataengine->disconnectSource(d->validating, this);
}
d->validating = validation;
d->dataengine->connectSource(validation, this);
}
void WeatherValidator::setDataEngine(Plasma::DataEngine* dataengine)
{
d->dataengine = dataengine;
}
void WeatherValidator::dataUpdated(const QString &source, const Plasma::DataEngine::Data &data)
{
QMap<QString, QString> locations;
d->dataengine->disconnectSource(source, this);
QStringList result = data[QLatin1String("validate")].toString().split(QLatin1Char('|'));
if (result.count() < 2) {
QString message = i18n("Cannot find '%1' using %2.", source, d->ion);
emit error(message);
if (!d->silent) {
KMessageBox::error(0, message);
}
} else if (result[1] == QLatin1String("valid") && result.count() > 2) {
QString weatherSource = result[0] + QLatin1String( "|weather|%1|%2" );
QString singleWeatherSource = result[0] + QLatin1String( "|weather|%1" );
int i = 3;
//kDebug() << d->ion << result.count() << result;
while (i < result.count() - 1) {
if (result[i] == QLatin1String("place")) {
if (i + 1 > result.count()) {
continue;
}
QString name = result[i + 1];
if (i + 2 < result.count() && result[i + 2] == QLatin1String("extra")) {
QString id = result[i + 3];
locations.insert(name, weatherSource.arg(name, id));
i += 4;
} else {
locations.insert(name, singleWeatherSource.arg(name));
i += 2;
}
} else {
++i;
}
}
} else if (result[1] == QLatin1String("timeout")) {
QString message = i18n("Connection to %1 weather server timed out.", d->ion);
emit error(message);
if (!d->silent) {
KMessageBox::error(0, message);
}
} else {
QString message = i18n("Cannot find '%1' using %2.", result.count() > 3 ? result[3] : source, d->ion);
emit error(message);
if (!d->silent) {
KMessageBox::error(0, message);
}
}
emit finished(locations);
}
#include "moc_weathervalidator.cpp"

View file

@ -1,85 +0,0 @@
/*
* Copyright (C) 2009 Petri Damstén <damu@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef WEATHERVALIDATOR_HEADER
#define WEATHERVALIDATOR_HEADER
#include <Plasma/DataEngine>
#include "plasmaweather_export.h"
/**
* @class WeatherValidator <plasmaweather/weathervalidator.h>
*
* @short Weather validator class
*/
class PLASMAWEATHER_EXPORT WeatherValidator : public QObject
{
Q_OBJECT
public:
WeatherValidator(QObject *parent = nullptr);
virtual ~WeatherValidator();
/**
* Validate location; plugin must already have been set
*
* @param location the name of the location to find
* @param silent if true don't show any dialogs
*/
void validate(const QString &location, bool silent = false);
/**
* Sets the ion to use
* @arg plugin the name of the ion
*/
void setIon(const QString &plugin);
/**
* @return the ion currently set to validate with
*/
QString ion() const;
/**
* Sets dataengine to use
*
* @param dataengine use this dataengine
**/
void setDataEngine(Plasma::DataEngine *dataengine);
Q_SIGNALS:
/**
* Emitted when an error in validation occurs
**/
void error(const QString &message);
/**
* Emitted when validation is done
* @arg sources a mapping of user-friendly names to the DataEngine source
**/
void finished(const QMap<QString, QString> &sources);
public Q_SLOTS:
void dataUpdated(const QString &source, const Plasma::DataEngine::Data &data);
private:
class Private;
Private * const d;
};
#endif

View file

@ -1,5 +1,4 @@
add_subdirectory(potd)
add_subdirectory(virus)
add_subdirectory(weather)
add_subdirectory(qmlwallpapers)
add_subdirectory(pattern)

View file

@ -1,18 +0,0 @@
project(plasma-wallpaper-weather)
include_directories(
# for plasmaweather_export.h
${kdeplasma-addons_BINARY_DIR}/libs/plasmaweather
)
set(weather_SRCS
weatherwallpaper.cpp
backgrounddelegate.cpp
backgroundlistmodel.cpp
)
kde4_add_plugin(plasma_wallpaper_weather ${weather_SRCS})
target_link_libraries(plasma_wallpaper_weather KDE4::plasma KDE4::kio KDE4::kfile plasmaweather)
install(TARGETS plasma_wallpaper_weather DESTINATION ${KDE4_PLUGIN_INSTALL_DIR})
install(FILES plasma-wallpaper-weather.desktop DESTINATION ${KDE4_SERVICES_INSTALL_DIR})

View file

@ -1,676 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View file

@ -1,4 +0,0 @@
#! /usr/bin/env bash
$EXTRACTRC *.ui >> rc.cpp
$XGETTEXT *.cpp -o $podir/plasma_wallpaper_weather.pot
rm -f rc.cpp

View file

@ -1,109 +0,0 @@
/*
Copyright (c) 2007 Paolo Capriotti <p.capriotti@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
*/
#include "backgrounddelegate.h"
#include <QPen>
#include <QPainter>
#include <KGlobalSettings>
#include <KLocalizedString>
BackgroundDelegate::BackgroundDelegate(QObject *listener, float ratio, QObject *parent)
: QAbstractItemDelegate(parent),
m_ratio(ratio)
{
Q_UNUSED(listener);
}
void BackgroundDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QString title = index.model()->data(index, Qt::DisplayRole).toString();
QString author = index.model()->data(index, AuthorRole).toString();
QString resolution = index.model()->data(index, ResolutionRole).toString();
QPixmap pix = index.model()->data(index, ScreenshotRole).value<QPixmap>();
// draw selection outline
if (option.state & QStyle::State_Selected) {
QPen oldPen = painter->pen();
painter->setPen(option.palette.color(QPalette::Highlight));
painter->drawRect(option.rect.adjusted(2, 2, -2, -2));
painter->setPen(oldPen);
}
// draw pixmap
int maxheight = SCREENSHOT_SIZE;
int maxwidth = int(maxheight * m_ratio);
if (!pix.isNull()) {
int x = MARGIN + (maxwidth - pix.width()) / 2;
int y = MARGIN + (maxheight - pix.height()) / 2;
QRect imgRect = QRect(option.rect.topLeft(), pix.size()).translated(x, y);
painter->drawPixmap(imgRect, pix);
}
// draw text
painter->save();
int x = option.rect.left() + MARGIN * 2 + maxwidth;
QRect textRect(x,
option.rect.top() + MARGIN,
option.rect.width() - x - MARGIN,
maxheight);
const QRect boundingRect = painter->boundingRect(textRect, Qt::TextWordWrap, title) & option.rect;
painter->drawText(boundingRect, Qt::TextWordWrap, title);
QRect titleRect = painter->boundingRect(boundingRect, Qt::TextWordWrap, title);
QPoint lastText(titleRect.bottomLeft());
// Borrowed from Dolphin for consistency and beauty.
// For the color of the additional info the inactive text color
// is not used as this might lead to unreadable text for some color schemes. Instead
// the text color is slightly mixed with the background color.
const QColor textColor = option.palette.text().color();
const QColor baseColor = option.palette.base().color();
const int p1 = 70;
const int p2 = 100 - p1;
const QColor detailsColor = QColor((textColor.red() * p1 + baseColor.red() * p2) / 100,
(textColor.green() * p1 + baseColor.green() * p2) / 100,
(textColor.blue() * p1 + baseColor.blue() * p2) / 100);
if (!resolution.isEmpty()) {
QRect resolutionRect = QRect(lastText, textRect.size()) & option.rect;
if (!resolutionRect.isEmpty()) {
painter->setPen(detailsColor);
painter->drawText(resolutionRect, Qt::TextWordWrap, resolution);
lastText = painter->boundingRect(resolutionRect, Qt::TextWordWrap, resolution).bottomLeft();
}
}
if (!author.isEmpty()) {
QRect authorRect = QRect(lastText, textRect.size()) & option.rect;
if (!authorRect.isEmpty()) {
painter->setPen(detailsColor);
painter->drawText(authorRect, Qt::TextWordWrap, author);
lastText = painter->boundingRect(authorRect, Qt::TextWordWrap, author).bottomLeft();
}
}
painter->restore();
}
QSize BackgroundDelegate::sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
const QString title = index.model()->data(index, Qt::DisplayRole).toString();
const int maxwidth = int(SCREENSHOT_SIZE * m_ratio);
QFontMetrics fm(option.font);
//kDebug() << QSize(maxwidth + qBound(100, fm.width(title), 500), Background::SCREENSHOT_SIZE + MARGIN * 2);
return QSize(maxwidth + qBound(100, fm.width(title), 500), SCREENSHOT_SIZE + MARGIN * 2);
}

View file

@ -1,40 +0,0 @@
/*
Copyright (c) 2007 Paolo Capriotti <p.capriotti@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
*/
#ifndef BACKGROUNDDELEGATE_H
#define BACKGROUNDDELEGATE_H
#include <QAbstractItemDelegate>
class BackgroundDelegate : public QAbstractItemDelegate
{
public:
enum {
AuthorRole = Qt::UserRole,
ScreenshotRole,
ResolutionRole
};
BackgroundDelegate(QObject *listener,
float ratio, QObject *parent = 0);
virtual void paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const;
virtual QSize sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const;
static const int SCREENSHOT_SIZE = 60;
private:
static const int MARGIN = 5;
float m_ratio;
};
#endif // BACKGROUNDDELEGATEL_H

View file

@ -1,334 +0,0 @@
/*
Copyright (c) 2007 Paolo Capriotti <p.capriotti@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
*/
#include "backgroundlistmodel.h"
#include <QCoreApplication>
#include <QFile>
#include <QDir>
#include <QImageReader>
#include <KDebug>
#include <KGlobal>
#include <KIO/PreviewJob>
#include <KProgressDialog>
#include <KStandardDirs>
#include <Plasma/Package>
#include <Plasma/PackageStructure>
#include "backgrounddelegate.h"
#include "weatherwallpaper.h"
BackgroundListModel::BackgroundListModel(float ratio, Plasma::Wallpaper *listener, QObject *parent)
: QAbstractListModel(parent),
m_listener(listener),
m_structureParent(listener),
m_ratio(ratio),
m_resizeMethod(Plasma::Wallpaper::ScaledResize)
{
connect(&m_dirwatch, SIGNAL(dirty(QString)), this, SLOT(reload()));
}
BackgroundListModel::~BackgroundListModel()
{
qDeleteAll(m_packages);
}
void BackgroundListModel::reload()
{
reload(QStringList());
}
void BackgroundListModel::reload(const QStringList &selected)
{
const QStringList dirs = KGlobal::dirs()->findDirs("wallpaper", QLatin1String(""));
// add wallpaper dirs to dirwatch (recursively)
foreach (const QString &dir, dirs) {
m_dirwatch.addDir(dir, true);
}
QList<Plasma::Package *> tmp;
if (!m_packages.isEmpty()) {
beginRemoveRows(QModelIndex(), 0, m_packages.count() - 1);
qDeleteAll(m_packages);
m_packages.clear();
endRemoveRows();
}
foreach (const QString &file, selected) {
if (!contains(file) && QFile::exists(file)) {
tmp << new Plasma::Package(file, Plasma::Wallpaper::packageStructure(m_structureParent));
}
}
{
KProgressDialog progressDialog;
initProgressDialog(&progressDialog);
foreach (const QString &dir, dirs) {
tmp += findAllBackgrounds(m_structureParent, this, dir, m_ratio, &progressDialog);
}
}
if (!tmp.isEmpty()) {
beginInsertRows(QModelIndex(), 0, tmp.size() - 1);
m_packages = tmp;
endInsertRows();
}
}
void BackgroundListModel::addBackground(const QString& path)
{
if (!contains(path)) {
if (!m_dirwatch.contains(path)) {
m_dirwatch.addFile(path);
}
beginInsertRows(QModelIndex(), 0, 0);
Plasma::PackageStructure::Ptr structure = Plasma::Wallpaper::packageStructure(m_structureParent);
Plasma::Package *pkg = new Plasma::Package(path, structure);
m_packages.prepend(pkg);
endInsertRows();
}
}
int BackgroundListModel::indexOf(const QString &path) const
{
for (int i = 0; i < m_packages.size(); i++) {
if (path.startsWith(m_packages[i]->path())) {
return i;
}
}
return -1;
}
bool BackgroundListModel::contains(const QString &path) const
{
return indexOf(path) != -1;
}
int BackgroundListModel::rowCount(const QModelIndex &) const
{
return m_packages.size();
}
QSize BackgroundListModel::bestSize(Plasma::Package *package) const
{
if (m_sizeCache.contains(package)) {
return m_sizeCache.value(package);
}
QString image = package->filePath("preferred");
if (image.isEmpty()) {
return QSize();
}
QImageReader imagereader(image);
QSize size = imagereader.size();
// backup solution if image handler does not provide size option
if (size.width() == 0 || size.height() == 0) {
kDebug() << "fall back to QImage";
size = QImage(image).size();
}
const_cast<BackgroundListModel *>(this)->m_sizeCache.insert(package, size);
return size;
}
QVariant BackgroundListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
if (index.row() >= m_packages.size()) {
return QVariant();
}
Plasma::Package *b = package(index.row());
if (!b) {
return QVariant();
}
switch (role) {
case Qt::DisplayRole: {
QString title = b->metadata().name();
if (title.isEmpty()) {
return QFileInfo(b->filePath("preferred")).completeBaseName();
}
return title;
}
case BackgroundDelegate::ScreenshotRole: {
if (m_previews.contains(b)) {
return m_previews.value(b);
}
KUrl file(b->filePath("preferred"));
if (file.isValid()) {
const KFileItem fileItem(KFileItem::Unknown, KFileItem::Unknown, file);
KIO::PreviewJob* job = KIO::filePreview(KFileItemList() << fileItem,
QSize(BackgroundDelegate::SCREENSHOT_SIZE,
BackgroundDelegate::SCREENSHOT_SIZE));
connect(job, SIGNAL(gotPreview(KFileItem,QPixmap)),
this, SLOT(showPreview(KFileItem,QPixmap)));
connect(job, SIGNAL(failed(KFileItem)),
this, SLOT(previewFailed(KFileItem)));
const_cast<BackgroundListModel *>(this)->m_previewJobs.insert(file, QPersistentModelIndex(index));
}
QPixmap pix(BackgroundDelegate::SCREENSHOT_SIZE, BackgroundDelegate::SCREENSHOT_SIZE);
pix.fill(Qt::transparent);
const_cast<BackgroundListModel *>(this)->m_previews.insert(b, pix);
return pix;
}
case BackgroundDelegate::AuthorRole:
return b->metadata().author();
case BackgroundDelegate::ResolutionRole:{
QSize size = bestSize(b);
if (size.isValid()) {
return QString::fromLatin1("%1x%2").arg(size.width()).arg(size.height());
}
return QString();
}
default:
return QVariant();
}
return QVariant();
}
void BackgroundListModel::showPreview(const KFileItem &item, const QPixmap &preview)
{
QPersistentModelIndex index = m_previewJobs.value(item.url());
m_previewJobs.remove(item.url());
if (!index.isValid()) {
return;
}
Plasma::Package *b = package(index.row());
if (!b) {
return;
}
m_previews.insert(b, preview);
static_cast<WeatherWallpaper*>(m_listener)->updateScreenshot(index);
}
void BackgroundListModel::previewFailed(const KFileItem &item)
{
m_previewJobs.remove(item.url());
}
Plasma::Package* BackgroundListModel::package(int index) const
{
return m_packages.at(index);
}
void BackgroundListModel::initProgressDialog(KProgressDialog *progress)
{
progress->setAllowCancel(false);
progress->setModal(true);
progress->setLabelText(i18n("Finding images for the weather wallpaper."));
progress->progressBar()->setRange(0, 0);
}
QList<Plasma::Package *> BackgroundListModel::findAllBackgrounds(Plasma::Wallpaper *structureParent,
const BackgroundListModel *container,
const QString &path, float ratio,
KProgressDialog *progress)
{
KProgressDialog *myProgress = 0;
if (!progress) {
myProgress = progress = new KProgressDialog;
initProgressDialog(myProgress);
}
//kDebug() << "looking for" << path;
QList<Plasma::Package *> res;
// get all packages in this directory
//kDebug() << "getting packages";
QStringList packages = Plasma::Package::listInstalledPaths(path);
QSet<QString> validPackages;
foreach (const QString &packagePath, packages) {
QCoreApplication::processEvents();
progress->setLabelText(i18n("Finding images for the weather wallpaper.") + QLatin1String("\n\n") +
i18n("Testing %1 for a Wallpaper package", packagePath));
Plasma::PackageStructure::Ptr structure = Plasma::Wallpaper::packageStructure(structureParent);
Plasma::Package *pkg = new Plasma::Package(path + packagePath, structure);
if (pkg->isValid() && (!container || !container->contains(pkg->path()))) {
progress->setLabelText(i18n("Finding images for the weather wallpaper.") + QLatin1String("\n\n") +
i18n("Adding wallpaper package in %1", packagePath));
res.append(pkg);
//kDebug() << " adding valid package:" << packagePath;
validPackages << packagePath;
} else {
delete pkg;
}
}
// search normal wallpapers
//kDebug() << "listing normal files";
QDir dir(path);
QStringList filters;
filters << QLatin1String("*.png") << QLatin1String("*.jpeg") << QLatin1String("*.jpg") << QLatin1String("*.svg") << QLatin1String("*.svgz");
dir.setNameFilters(filters);
dir.setFilter(QDir::Files | QDir::Hidden | QDir::Readable);
QFileInfoList files = dir.entryInfoList();
foreach (const QFileInfo &wp, files) {
QCoreApplication::processEvents();
if (!container || !container->contains(wp.filePath())) {
//kDebug() << " adding image file" << wp.filePath();
progress->setLabelText(i18n("Finding images for the weather wallpaper.") + QLatin1String("\n\n") +
i18n("Adding image %1", wp.filePath()));
Plasma::PackageStructure::Ptr structure = Plasma::Wallpaper::packageStructure(structureParent);
res.append(new Plasma::Package(wp.filePath(), structure));
}
}
// now recurse the dirs, skipping ones we found packages in
//kDebug() << "recursing dirs";
dir.setFilter(QDir::AllDirs | QDir::Readable);
files = dir.entryInfoList();
foreach (const QFileInfo &wp, files) {
QCoreApplication::processEvents();
QString name = wp.fileName();
if (name != QLatin1String(".") && name != QLatin1String("..") && !validPackages.contains(wp.fileName())) {
//kDebug() << " " << name << wp.filePath();
res += findAllBackgrounds(structureParent, container, wp.filePath(), ratio, progress);
}
}
//kDebug() << "completed.";
delete myProgress;
return res;
}
void BackgroundListModel::setResizeMethod(Plasma::Wallpaper::ResizeMethod resizeMethod)
{
m_resizeMethod = resizeMethod;
}
#include "moc_backgroundlistmodel.cpp"

View file

@ -1,73 +0,0 @@
/*
Copyright (c) 2007 Paolo Capriotti <p.capriotti@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
*/
#ifndef BACKGROUNDLISTMODEL_H
#define BACKGROUNDLISTMODEL_H
#include <QtCore/qabstractitemmodel.h>
#include <QPixmap>
#include <KDirWatch>
#include <KFileItem>
#include <Plasma/Wallpaper>
namespace Plasma
{
class Package;
} // namespace Plasma
class KProgressDialog;
class BackgroundListModel : public QAbstractListModel
{
Q_OBJECT
public:
BackgroundListModel(float ratio, Plasma::Wallpaper *listener, QObject *parent);
virtual ~BackgroundListModel();
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
Plasma::Package *package(int index) const;
void reload();
void reload(const QStringList &selected);
void addBackground(const QString &path);
int indexOf(const QString &path) const;
virtual bool contains(const QString &bg) const;
static QList<Plasma::Package *> findAllBackgrounds(Plasma::Wallpaper *structureParent,
const BackgroundListModel *container,
const QString &path, float ratio,
KProgressDialog *progress = 0);
static void initProgressDialog(KProgressDialog *dialog);
void setResizeMethod(Plasma::Wallpaper::ResizeMethod resizeMethod);
protected Q_SLOTS:
void showPreview(const KFileItem &item, const QPixmap &preview);
void previewFailed(const KFileItem &item);
private:
QSize bestSize(Plasma::Package *package) const;
Plasma::Wallpaper *m_listener;
Plasma::Wallpaper *m_structureParent;
QList<Plasma::Package *> m_packages;
QHash<Plasma::Package *, QSize> m_sizeCache;
QHash<Plasma::Package *, QPixmap> m_previews;
QHash<KUrl, QPersistentModelIndex> m_previewJobs;
float m_ratio;
KDirWatch m_dirwatch;
Plasma::Wallpaper::ResizeMethod m_resizeMethod;
};
#endif // BACKGROUNDLISTMODEL_H

View file

@ -1,108 +0,0 @@
[Desktop Entry]
Type=Service
Name=Weather
Name[ar]=الطقس
Name[ast]=Meteoroloxía
Name[bs]=Vrijeme
Name[ca]=Meteorologia
Name[ca@valencia]=Meteorologia
Name[cs]=Počasí
Name[da]=Vejr
Name[de]=Wetter
Name[el]=Καιρός
Name[en_GB]=Weather
Name[eo]=Vetero
Name[es]=Meteorología
Name[et]=Ilm
Name[fi]=Sää
Name[fr]=Météo
Name[ga]=Aimsir
Name[gl]=Tempo meteorolóxico
Name[hr]=Vrijeme
Name[hu]=Időjárás
Name[is]=Veður
Name[it]=Meteo
Name[ja]=
Name[kk]=Ауа райы
Name[km]=
Name[ko]=
Name[lt]=Orai
Name[lv]=Laikapstākļi
Name[mr]=
Name[nb]=Været
Name[nds]=Weder
Name[nl]=Weer
Name[nn]=Vêr
Name[pa]=
Name[pl]=Pogoda
Name[pt]=Meteorologia
Name[pt_BR]=Meteorologia
Name[ro]=Vreme
Name[ru]=Погода
Name[sk]=Počasie
Name[sl]=Vreme
Name[sq]=Moti
Name[sr]=време
Name[sr@ijekavian]=вријеме
Name[sr@ijekavianlatin]=vrijeme
Name[sr@latin]=vreme
Name[sv]=Väder
Name[th]=
Name[tr]=Hava Durumu
Name[ug]=ھاۋا رايى
Name[uk]=Погода
Name[wa]=Meteyo
Name[x-test]=xxWeatherxx
Name[zh_CN]=
Name[zh_TW]=
Comment=Images that reflect the weather outside
Comment[ar]=صور تعكس حالة القطس في الخارج
Comment[bs]=Slike koje s vana reflektuju vrijeme
Comment[ca]=Imatges que reflecteixen el temps de fora
Comment[ca@valencia]=Imatges que reflecteixen el temps de fora
Comment[cs]=Obrázky odrážející počasí venku
Comment[da]=Billeder der afspejler vejret udenfor
Comment[de]=Bilder, die das aktuelle Wetter abbilden
Comment[el]=Εικόνες που απεικονίζουν τον καιρό
Comment[en_GB]=Images that reflect the weather outside
Comment[es]=Imágenes que reflejan el clima exterior
Comment[et]=Välist ilma peegeldavad pildid
Comment[fi]=Säänmukaiset kuvat
Comment[fr]=Images correspondant à la météo
Comment[gl]=Imaxes que reflicten o tempo que vai fóra.
Comment[hu]=Képek, amelyek reagálnak a külső időjárásra
Comment[it]=Immagini che riflettono le condizioni meteo esterne
Comment[kk]=Даладағы ауа-райын суреттейтін кескін
Comment[ko]=
Comment[nb]=Bilder som viser hvordan været er utenfor
Comment[nds]=Biller, de dat Weder buten wiest
Comment[nl]=Afbeeldingen die het weer buiten laten zien
Comment[pl]=Obrazy, które odzwierciedlają pogodę na zewnątrz
Comment[pt]=Imagens que reflectem o tempo exterior
Comment[pt_BR]=Imagens que refletem o tempo exterior
Comment[ro]=Imagini ce reflectă vremea de afară
Comment[ru]=Изображения, показывающие погоду за окном
Comment[sk]=Obrázky, ktoré odrážajú počasie vonku
Comment[sl]=Slike, ki odsevajo trenutno vreme
Comment[sr]=Слике које одражавају време напољу
Comment[sr@ijekavian]=Слике које одражавају време напољу
Comment[sr@ijekavianlatin]=Slike koje odražavaju vreme napolju
Comment[sr@latin]=Slike koje odražavaju vreme napolju
Comment[sv]=Bilder som återger vädret utomhus
Comment[tr]=Dışarıdaki hava durumunu yansıtan resimler
Comment[uk]=Зображення, що відповідають погоді надворі
Comment[x-test]=xxImages that reflect the weather outsidexx
Comment[zh_CN]=
Comment[zh_TW]=
Icon=weather-clear
ServiceTypes=Plasma/Wallpaper
X-KDE-Library=plasma_wallpaper_weather
X-KDE-PluginInfo-Author=Jonathan Thomas
X-KDE-PluginInfo-Email=echidnaman@kubuntu.org
X-KDE-PluginInfo-Name=weather
X-KDE-PluginInfo-Version=0.3
X-KDE-PluginInfo-Website=
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true

View file

@ -1,285 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>weatherAdvanced</class>
<widget class="QWidget" name="weatherAdvanced">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>283</width>
<height>187</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QGridLayout" name="gridLayout_6">
<item row="0" column="0">
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>&amp;Weather condition:</string>
</property>
<property name="buddy">
<cstring>m_conditionCombo</cstring>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>&amp;Picture:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="buddy">
<cstring>m_wallpaperView</cstring>
</property>
</widget>
</item>
</layout>
</item>
<item row="0" column="1">
<layout class="QGridLayout" name="gridLayout_4">
<item row="0" column="0">
<widget class="KComboBox" name="m_conditionCombo">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>1</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item row="1" column="0">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="KComboBox" name="m_wallpaperView">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>1</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="m_pictureUrlButton">
<property name="toolTip">
<string>Browse</string>
</property>
<property name="text">
<string>...</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item row="1" column="0">
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>98</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="1">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="m_authorLabel">
<property name="text">
<string>Author:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLabel" name="m_authorLine">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="m_emailLabel">
<property name="text">
<string>Email:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLabel" name="m_emailLine">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="m_licenseLabel">
<property name="text">
<string>License:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTop|Qt::AlignTrailing</set>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLabel" name="m_licenseLine">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string/>
</property>
<property name="alignment">
<set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
</property>
</widget>
</item>
</layout>
</item>
<item row="2" column="0">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
<widget class="QLabel" name="label_4">
<property name="text">
<string>P&amp;ositioning:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="buddy">
<cstring>m_resizeMethod</cstring>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_5">
<property name="text">
<string>&amp;Color:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="buddy">
<cstring>m_color</cstring>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item row="2" column="1">
<layout class="QGridLayout" name="gridLayout_5">
<item row="0" column="0">
<widget class="KComboBox" name="m_resizeMethod">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="KColorButton" name="m_color">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="color">
<color>
<red>70</red>
<green>90</green>
<blue>130</blue>
</color>
</property>
<property name="defaultColor">
<color>
<red>70</red>
<green>90</green>
<blue>130</blue>
</color>
</property>
</widget>
</item>
<item row="0" column="1">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>KComboBox</class>
<extends>QComboBox</extends>
<header>kcombobox.h</header>
</customwidget>
<customwidget>
<class>KColorButton</class>
<extends>QPushButton</extends>
<header>kcolorbutton.h</header>
</customwidget>
</customwidgets>
<connections/>
</ui>

View file

@ -1,606 +0,0 @@
/***************************************************************************
* Copyright (C) 2009 by Jonathan Thomas <echidnaman@kubuntu.org> *
* Copyright (C) 2007-2009 by Shawn Starr <shawn.starr@rogers.com> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation; either version 2 of *
* the License or (at your option) version 3 or any later version *
* accepted by the membership of KDE e.V. (or its successor approved *
* by the membership of KDE e.V.), which shall act as a proxy *
* defined in Section 14 of version 3 of the license. *
* *
* This program 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 <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include "weatherwallpaper.h"
// Qt includes
#include <QPainter>
#include <QEasingCurve>
#include <QPropertyAnimation>
// KDE includes
#include <KFileDialog>
#include <KLocalizedString>
#include <KPushButton>
#include <KStandardDirs>
#include <KImageIO>
#include <Plasma/Animator>
#include <Plasma/Theme>
// Libplasmaweather includes
#include "plasmaweather/weatherconfig.h"
#include "plasmaweather/weatherlocation.h"
// Own includes
#include "backgroundlistmodel.h"
#include "backgrounddelegate.h"
K_EXPORT_PLASMA_WALLPAPER(weather, WeatherWallpaper)
WeatherWallpaper::WeatherWallpaper(QObject * parent, const QVariantList & args )
: Plasma::Wallpaper(parent, args)
, m_configWidget(0)
, m_weatherLocation(0)
, m_advancedDialog(0)
, m_fileDialog(0)
, m_fadeValue(0)
, m_animation(0)
, m_model(0)
{
connect(this, SIGNAL(renderHintsChanged()), this, SLOT(calculateGeometry()));
connect(this, SIGNAL(renderCompleted(QImage)), this, SLOT(updateBackground(QImage)));
}
WeatherWallpaper::~WeatherWallpaper()
{
delete m_animation;
}
void WeatherWallpaper::init(const KConfigGroup & config)
{
locationEngine = dataEngine(QLatin1String("geolocation"));
// Connect to weather engine.
weatherEngine = dataEngine(QLatin1String("weather"));
// Set custom weather options
m_source = config.readEntry("source");
m_weatherUpdateTime = config.readEntry("updateWeather", 30);
m_color = config.readEntry("wallpapercolor", QColor(56, 111, 150));
m_usersWallpapers = config.readEntry("userswallpapers", QStringList());
m_resizeMethod = (ResizeMethod)config.readEntry("wallpaperposition", (int)ScaledResize);
m_animation = new QPropertyAnimation(this, "fadeValue");
m_animation->setProperty("easingCurve", QEasingCurve::InQuad);
m_animation->setProperty("duration", 1000);
m_animation->setProperty("startValue", 0.0);
m_animation->setProperty("endValue", 1.0);
const QString defaultWallpaper = Plasma::Theme::defaultTheme()->wallpaperPath();
m_weatherMap[QLatin1String("weather-clear")] = config.readEntry("clearPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-few-clouds")] = config.readEntry("partlyCloudyPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-clouds")] = config.readEntry("cloudyPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-many-clouds")] = config.readEntry("manyCloudsPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-showers")] = config.readEntry("showersPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-showers-scattered")] = config.readEntry("showersScatteredPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-rain")] = config.readEntry("rainPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-mist")] = config.readEntry("mistPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-storm")] = config.readEntry("stormPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-scattered-storms")] = m_weatherMap[QLatin1String("weather-storm")];
m_weatherMap[QLatin1String("weather-hail")] = config.readEntry("hailPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-snow")] = config.readEntry("snowPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-snow-scattered")] = config.readEntry("snowScatteredPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-few-clouds-night")] = config.readEntry("partlyCloudyNightPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-clouds-night")] = config.readEntry("cloudyNightPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-clear-night")] = config.readEntry("clearNightPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-freezing-rain")] = config.readEntry("freezingRainPaper", defaultWallpaper);
m_weatherMap[QLatin1String("weather-snow-rain")] = config.readEntry("snowRainPaper", defaultWallpaper);
calculateGeometry();
connectWeatherSource();
}
void WeatherWallpaper::save(KConfigGroup & config)
{
QString oldSource(m_source);
int oldInterval = m_weatherUpdateTime;
if (m_configWidget) {
m_source = m_configWidget->source();
m_weatherUpdateTime = m_configWidget->updateInterval();
}
if (m_source != oldSource || m_weatherUpdateTime != oldInterval) {
if (!oldSource.isEmpty()) {
weatherEngine->disconnectSource(oldSource, this);
}
if (!m_source.isEmpty()) {
connectWeatherSource();
}
}
config.writeEntry("source", m_source);
config.writeEntry("updateWeather", m_weatherUpdateTime);
config.writeEntry("wallpaperposition", (int)m_resizeMethod);
config.writeEntry("wallpapercolor", m_color);
config.writeEntry("userswallpapers", m_usersWallpapers);
// Save custom wallpaper/weather pairings
config.writeEntry("clearPaper", m_weatherMap[QLatin1String("weather-clear")]);
config.writeEntry("partlyCloudyPaper", m_weatherMap[QLatin1String("weather-few-clouds")]);
config.writeEntry("cloudyPaper", m_weatherMap[QLatin1String("weather-clouds")]);
config.writeEntry("manyCloudsPaper", m_weatherMap[QLatin1String("weather-many-clouds")]);
config.writeEntry("showersPaper", m_weatherMap[QLatin1String("weather-showers")]);
config.writeEntry("showersScatteredPaper", m_weatherMap[QLatin1String("weather-showers-scattered")]);
config.writeEntry("rainPaper", m_weatherMap[QLatin1String("weather-rain")]);
config.writeEntry("mistPaper", m_weatherMap[QLatin1String("weather-mist")]);
config.writeEntry("stormPaper", m_weatherMap[QLatin1String("weather-storm")]);
config.writeEntry("hailPaper", m_weatherMap[QLatin1String("weather-hail")]);
config.writeEntry("snowPaper", m_weatherMap[QLatin1String("weather-snow")]);
config.writeEntry("snowScatteredPaper", m_weatherMap[QLatin1String("weather-snow-scattered")]);
config.writeEntry("partlyCloudyNightPaper", m_weatherMap[QLatin1String("weather-few-clouds-night")]);
config.writeEntry("cloudyNightPaper", m_weatherMap[QLatin1String("weather-clouds-night")]);
config.writeEntry("clearNightPaper", m_weatherMap[QLatin1String("weather-clear-night")]);
config.writeEntry("freezingRainPaper", m_weatherMap[QLatin1String("weather-freezing-rain")]);
config.writeEntry("snowRainPaper", m_weatherMap[QLatin1String("weather-snow-rain")]);
}
void WeatherWallpaper::configWidgetDestroyed()
{
m_configWidget = 0;
}
void WeatherWallpaper::advancedDialogDestroyed()
{
m_advancedDialog = 0;
m_model = 0;
}
QWidget * WeatherWallpaper::createConfigurationInterface(QWidget * parent)
{
QWidget *top = new QWidget(parent);
QVBoxLayout *layout = new QVBoxLayout(top);
layout->setMargin(0);
m_configWidget = new WeatherConfig(top);
connect(m_configWidget, SIGNAL(destroyed(QObject*)), this, SLOT(configWidgetDestroyed()));
m_configWidget->setDataEngines(locationEngine, weatherEngine);
m_configWidget->setSource(m_source);
m_configWidget->setIon("wettercom");
m_configWidget->setUpdateInterval(m_weatherUpdateTime);
m_configWidget->setConfigurableUnits(WeatherConfig::None);
m_configWidget->setHeadersVisible(false);
layout->addWidget(m_configWidget);
QHBoxLayout *buttonLayout = new QHBoxLayout;
KPushButton *buttonAdvanced = new KPushButton(m_configWidget);
buttonAdvanced->setText( i18n("&Advanced..."));
m_configWidget->layout()->addWidget(buttonAdvanced);
buttonLayout->addStretch();
buttonLayout->addWidget(buttonAdvanced);
layout->addLayout(buttonLayout);
connect(buttonAdvanced, SIGNAL(clicked()), this, SLOT(showAdvancedDialog()));
connect(this, SIGNAL(settingsChanged(bool)), parent, SLOT(settingsChanged(bool)));
connect(m_configWidget, SIGNAL(settingsChanged()), this, SIGNAL(settingsChanged()));
return top;
}
void WeatherWallpaper::calculateGeometry()
{
m_size = boundingRect().size().toSize();
}
void WeatherWallpaper::paint(QPainter * painter, const QRectF & exposedRect)
{
// Check if geometry changed
if (m_size != boundingRect().size().toSize()) {
calculateGeometry();
if (!m_size.isEmpty() && !m_img.isEmpty()) { // We have previous image
renderWallpaper();
return;
}
}
if (m_pixmap.isNull()) {
painter->fillRect(exposedRect, QBrush(m_color));
return;
}
if (painter->worldMatrix() == QMatrix()) {
// draw the background untransformed when possible;(saves lots of per-pixel-math)
painter->resetTransform();
}
// blit the background (saves all the per-pixel-products that blending does)
painter->setCompositionMode(QPainter::CompositionMode_Source);
// for pixmaps we draw only the exposed part (untransformed since the
// bitmapBackground already has the size of the viewport)
painter->drawPixmap(exposedRect, m_pixmap, exposedRect.translated(-boundingRect().topLeft()));
if (!m_oldFadedPixmap.isNull()) {
// Put old faded image on top.
painter->setCompositionMode(QPainter::CompositionMode_SourceAtop);
painter->drawPixmap(exposedRect, m_oldFadedPixmap,
exposedRect.translated(-boundingRect().topLeft()));
}
}
void WeatherWallpaper::loadImage()
{
m_wallpaper = m_weatherMap.value(m_condition);
if (m_wallpaper.isEmpty()) {
QHashIterator<QString, QString> it(m_weatherMap);
while (it.hasNext()) {
it.next();
if (m_condition.startsWith(it.key())) {
m_wallpaper = it.value();
break;
}
}
}
if (m_wallpaper.isEmpty()) {
m_wallpaper = Plasma::Theme::defaultTheme()->wallpaperPath();
}
Plasma::Package b(m_wallpaper, packageStructure(this));
QString img = b.filePath("preferred");
if (img.isEmpty()) {
img = m_wallpaper;
}
if (!m_size.isEmpty()) {
renderWallpaper(img);
}
}
void WeatherWallpaper::showAdvancedDialog()
{
if (m_advancedDialog == 0) {
m_advancedDialog = new KDialog;
m_advancedUi.setupUi(m_advancedDialog->mainWidget());
m_advancedDialog->mainWidget()->layout()->setMargin(0);
m_advancedDialog->setCaption(i18n("Advanced Wallpaper Settings"));
m_advancedDialog->setButtons(KDialog::Ok | KDialog::Cancel);
qreal ratio = m_size.isEmpty() ? 1.0 : m_size.width() / qreal(m_size.height());
m_model = new BackgroundListModel(ratio, this, m_advancedDialog);
m_model->setResizeMethod(m_resizeMethod);
m_model->reload(m_usersWallpapers);
m_advancedUi.m_wallpaperView->setModel(m_model);
m_advancedUi.m_wallpaperView->setItemDelegate(new BackgroundDelegate(m_advancedUi.m_wallpaperView->view(),
ratio, m_advancedDialog));
m_advancedUi.m_wallpaperView->view()->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
connect(m_advancedUi.m_conditionCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(conditionChanged(int)));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-clear")), i18nc("weather condition", "Clear"), QLatin1String("weather-clear"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-few-clouds")), i18n("Partly Cloudy"), QLatin1String("weather-few-clouds"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-clouds")), i18n("Cloudy"), QLatin1String("weather-clouds"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-many-clouds")), i18n("Very Cloudy"), QLatin1String("weather-many-clouds"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-showers")), i18n("Showering"), QLatin1String("weather-showers"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-showers-scattered")), i18n("Scattered Showers"), QLatin1String("weather-showers-scattered"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-showers")), i18n("Rainy"), QLatin1String("weather-rain"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-mist")), i18n("Misty"), QLatin1String("weather-mist"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-storm")), i18n("Storming"), QLatin1String("weather-storm"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-hail")), i18n("Hailing"), QLatin1String("weather-hail"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-snow")), i18n("Snowing"), QLatin1String("weather-snow"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-snow-scattered")), i18n("Scattered Snow"), QLatin1String("weather-snow-scattered"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-few-clouds-night")), i18n("Partly Cloudy Night"), QLatin1String("weather-few-clouds-night"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-clouds-night")), i18n("Cloudy Night"), QLatin1String("weather-clouds-night"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-clear-night")), i18n("Clear Night"), QLatin1String("weather-clear-night"));
m_advancedUi.m_conditionCombo->addItem(KIcon(QLatin1String("weather-snow-rain")), i18n("Mixed Precipitation"), QLatin1String("weather-snow-rain"));
// Set to the current weather condition
m_advancedUi.m_conditionCombo->setCurrentIndex(m_advancedUi.m_conditionCombo->findData(m_condition));
connect(m_advancedUi.m_wallpaperView, SIGNAL(currentIndexChanged(int)), this, SLOT(pictureChanged(int)));
m_advancedUi.m_pictureUrlButton->setIcon(KIcon(QLatin1String("document-open")));
connect(m_advancedUi.m_pictureUrlButton, SIGNAL(clicked()), this, SLOT(showFileDialog()));
m_advancedUi.m_emailLine->setTextInteractionFlags(Qt::TextSelectableByMouse);
m_advancedUi.m_resizeMethod->addItem(i18n("Scaled & Cropped"), ScaledAndCroppedResize);
m_advancedUi.m_resizeMethod->addItem(i18n("Scaled"), ScaledResize);
m_advancedUi.m_resizeMethod->addItem(i18n("Scaled, keep proportions"), MaxpectResize);
m_advancedUi.m_resizeMethod->addItem(i18n("Centered"), CenteredResize);
m_advancedUi.m_resizeMethod->addItem(i18n("Tiled"), TiledResize);
m_advancedUi.m_resizeMethod->addItem(i18n("Center Tiled"), CenterTiledResize);
for (int i = 0; i < m_advancedUi.m_resizeMethod->count(); ++i) {
if (m_resizeMethod == m_advancedUi.m_resizeMethod->itemData(i).value<int>()) {
m_advancedUi.m_resizeMethod->setCurrentIndex(i);
break;
}
}
connect(m_advancedUi.m_resizeMethod, SIGNAL(currentIndexChanged(int)),
this, SLOT(positioningChanged(int)));
m_advancedUi.m_color->setColor(m_color);
connect(m_advancedUi.m_color, SIGNAL(changed(QColor)), this, SLOT(colorChanged(QColor)));
}
KDialog::centerOnScreen(m_advancedDialog);
connect(m_advancedDialog, SIGNAL(destroyed(QObject*)), this, SLOT(advancedDialogDestroyed()));
m_advancedDialog->show();
}
void WeatherWallpaper::colorChanged(const QColor& color)
{
m_color = color;
emit settingsChanged(true);
loadImage();
}
void WeatherWallpaper::pictureChanged(int index)
{
if (index == -1 || !m_model) {
return;
}
Plasma::Package *b = m_model->package(index);
if (!b) {
return;
}
QString conditionIndexValue = m_advancedUi.m_conditionCombo->itemData(m_advancedUi.m_conditionCombo->currentIndex()).toString();
fillMetaInfo(b);
if (b->structure()->contentsPrefix().isEmpty()) {
// it's not a full package, but a single paper
m_weatherMap[conditionIndexValue] = b->filePath("preferred");
} else {
m_weatherMap[conditionIndexValue] = b->path();
}
emit settingsChanged(true);
loadImage();
}
void WeatherWallpaper::conditionChanged(int index)
{
if (index == -1) {
return;
}
QString conditionIndexValue = m_advancedUi.m_conditionCombo->itemData(index).toString();
QString paper = m_weatherMap[conditionIndexValue];
int modelIndex = m_model->indexOf(paper);
if (modelIndex != -1) {
m_advancedUi.m_wallpaperView->setCurrentIndex(modelIndex);
Plasma::Package *b = m_model->package(modelIndex);
if (b) {
fillMetaInfo(b);
}
}
emit settingsChanged(true);
}
void WeatherWallpaper::positioningChanged(int index)
{
m_resizeMethod = (ResizeMethod)m_advancedUi.m_resizeMethod->itemData(index).value<int>();
loadImage();
setResizeMethodHint(m_resizeMethod);
if (m_model) {
m_model->setResizeMethod(m_resizeMethod);
}
emit settingsChanged(true);
}
void WeatherWallpaper::fillMetaInfo(Plasma::Package *b)
{
// Prepare more user-friendly forms of some pieces of data.
// - license by config is more a of a key value,
// try to get the proper name if one of known licenses.
// not needed for now...
//QString license = b->license();
/*
KAboutLicense knownLicense = KAboutLicense::byKeyword(license);
if (knownLicense.key() != KAboutData::License_Unknown) {
license = knownLicense.name(KAboutData::ShortName);
}
*/
// - last ditch attempt to localize author's name, if not such by config
// (translators can "hook" names from outside if resolute enough).
QString author = b->metadata().author();
if (author.isEmpty()) {
setMetadata(m_advancedUi.m_authorLine, QString());
m_advancedUi.m_authorLabel->setAlignment(Qt::AlignLeft);
} else {
QString authorIntl = i18nc("Wallpaper info, author name", "%1", author);
m_advancedUi.m_authorLabel->setAlignment(Qt::AlignRight);
setMetadata(m_advancedUi.m_authorLine, authorIntl);
}
setMetadata(m_advancedUi.m_licenseLine, QString());
setMetadata(m_advancedUi.m_emailLine, QString());
m_advancedUi.m_emailLabel->hide();
m_advancedUi.m_licenseLabel->hide();
}
bool WeatherWallpaper::setMetadata(QLabel *label, const QString &text)
{
if (text.isEmpty()) {
label->hide();
return false;
}
else {
label->show();
label->setText(text);
return true;
}
}
void WeatherWallpaper::showFileDialog()
{
if (!m_fileDialog) {
m_fileDialog = new KFileDialog(KUrl(), KImageIO::pattern(KImageIO::Reading), m_advancedDialog);
m_fileDialog->setOperationMode(KFileDialog::Opening);
m_fileDialog->setInlinePreviewShown(true);
m_fileDialog->setCaption(i18n("Select Wallpaper Image File"));
m_fileDialog->setModal(false);
}
m_fileDialog->show();
m_fileDialog->raise();
m_fileDialog->activateWindow();
connect(m_fileDialog, SIGNAL(okClicked()), this, SLOT(wallpaperBrowseCompleted()));
connect(m_fileDialog, SIGNAL(destroyed(QObject*)), this, SLOT(fileDialogFinished()));
}
void WeatherWallpaper::fileDialogFinished()
{
m_fileDialog = 0;
}
void WeatherWallpaper::wallpaperBrowseCompleted()
{
Q_ASSERT(m_model);
const QFileInfo info(m_fileDialog->selectedFile());
//the full file path, so it isn't broken when dealing with symlinks
const QString wallpaper = info.canonicalFilePath();
if (wallpaper.isEmpty()) {
return;
}
if (m_model->contains(wallpaper)) {
m_advancedUi.m_wallpaperView->setCurrentIndex(m_model->indexOf(wallpaper));
return;
}
// add background to the model
m_model->addBackground(wallpaper);
// select it
int index = m_model->indexOf(wallpaper);
if (index != -1) {
m_advancedUi.m_wallpaperView->setCurrentIndex(index);
}
// save it
m_usersWallpapers << wallpaper;
}
void WeatherWallpaper::renderWallpaper(const QString& image)
{
if (!image.isEmpty()) {
m_img = image;
}
if (m_img.isEmpty()) {
return;
}
render(m_img, m_size, m_resizeMethod, m_color);
}
void WeatherWallpaper::connectWeatherSource()
{
if (m_source.isEmpty()) {
// A location probably hasn't been configured, so call loadImage to load
// the default wallpaper in case we can't guess later
loadImage();
// We can see if we can be nice and figure out where the user is
m_weatherLocation = new WeatherLocation(this);
connect(m_weatherLocation, SIGNAL(valid(QString)),
this, SLOT(locationReady(QString)));
m_weatherLocation->setDataEngines(locationEngine, weatherEngine);
m_weatherLocation->getDefault("wettercom");
} else {
weatherEngine->connectSource(m_source, this, m_weatherUpdateTime * 60 * 1000);
}
}
void WeatherWallpaper::locationReady(const QString &source)
{
m_source = source;
if (!m_source.isEmpty()) {
if (m_configWidget) {
m_configWidget->setSource(m_source);
}
connectWeatherSource();
}
}
void WeatherWallpaper::updateBackground(const QImage &img)
{
m_oldPixmap = m_pixmap;
m_oldFadedPixmap = m_oldPixmap;
m_pixmap = QPixmap::fromImage(img);
if (!m_oldPixmap.isNull()) {
m_animation->start();
} else {
emit update(boundingRect());
}
}
void WeatherWallpaper::updateScreenshot(QPersistentModelIndex index)
{
if (m_advancedDialog) {
m_advancedUi.m_wallpaperView->view()->update(index);
}
}
qreal WeatherWallpaper::fadeValue()
{
return m_fadeValue;
}
void WeatherWallpaper::setFadeValue(qreal value)
{
m_fadeValue = value;
//If we are done, delete the pixmaps and don't draw.
if (qFuzzyCompare(m_fadeValue, qreal(1.0))) {
m_oldFadedPixmap = QPixmap();
m_oldPixmap = QPixmap();
emit update(boundingRect());
return;
}
//Create the faded image.
m_oldFadedPixmap.fill(Qt::transparent);
QPainter p;
p.begin(&m_oldFadedPixmap);
p.drawPixmap(0, 0, m_oldPixmap);
p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
p.fillRect(m_oldFadedPixmap.rect(), QColor(0, 0, 0, 254 * (1-m_fadeValue)));//255*((150 - m_fadeValue)/150)));
p.end();
emit update(boundingRect());
}
void WeatherWallpaper::dataUpdated(const QString &source, const Plasma::DataEngine::Data &data)
{
Q_UNUSED(source);
if (data.isEmpty()) {
return;
}
m_condition = data[QLatin1String("Condition Icon")].toString();
loadImage();
}
#include "moc_weatherwallpaper.cpp"

View file

@ -1,121 +0,0 @@
/***************************************************************************
* Copyright (C) 2009 by Jonathan Thomas <echidnaman@kubuntu.org> *
* Copyright (C) 2007-2009 by Shawn Starr <shawn.starr@rogers.com> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation; either version 2 of *
* the License or (at your option) version 3 or any later version *
* accepted by the membership of KDE e.V. (or its successor approved *
* by the membership of KDE e.V.), which shall act as a proxy *
* defined in Section 14 of version 3 of the license. *
* *
* This program 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 <http://www.gnu.org/licenses/>. *
***************************************************************************/
#ifndef WEATHERWALLPAPER_H
#define WEATHERWALLPAPER_H
#include <Plasma/DataEngine>
#include <Plasma/Package>
#include <Plasma/Wallpaper>
#include <KDialog>
#include "ui_weatherAdvanced.h"
#include <QPropertyAnimation>
#include <QStandardItemModel>
class KFileDialog;
class BackgroundListModel;
class WeatherConfig;
class WeatherLocation;
class WeatherWallpaper : public Plasma::Wallpaper
{
Q_OBJECT
Q_PROPERTY(qreal fadeValue READ fadeValue WRITE setFadeValue)
public:
WeatherWallpaper(QObject * parent, const QVariantList & args);
~WeatherWallpaper();
QWidget * createConfigurationInterface(QWidget * parent);
void paint(QPainter * painter, const QRectF & exposedRect);
void updateScreenshot(QPersistentModelIndex index);
qreal fadeValue();
signals:
void settingsChanged(bool changed = true);
public slots:
void showAdvancedDialog();
void dataUpdated(const QString &source, const Plasma::DataEngine::Data &data);
void connectWeatherSource(void);
void save(KConfigGroup & config);
protected slots:
void colorChanged(const QColor& color);
void pictureChanged(int index);
void conditionChanged(int index);
void positioningChanged(int index);
void fileDialogFinished();
void wallpaperBrowseCompleted();
void updateBackground(const QImage &img);
void showFileDialog();
void setFadeValue(qreal value);
void configWidgetDestroyed();
void advancedDialogDestroyed();
void locationReady(const QString &source);
void calculateGeometry();
protected:
void init(const KConfigGroup & config);
void fillMetaInfo(Plasma::Package *b);
bool setMetadata(QLabel *label, const QString &text);
void renderWallpaper(const QString& image = QString());
private slots:
void loadImage();
private:
WeatherConfig* m_configWidget;
WeatherLocation* m_weatherLocation;
KDialog *m_advancedDialog;
Ui::weatherAdvanced m_advancedUi;
QStringList m_usersWallpapers;
QString m_source; // Current source
QString m_condition; // Current condition
int m_weatherUpdateTime;
QHash<QString,QString> m_weatherMap;
Plasma::DataEngine *locationEngine;
Plasma::DataEngine *weatherEngine;
Plasma::DataEngine::Data m_ionPlugins;
Plasma::Wallpaper::ResizeMethod m_resizeMethod;
QColor m_color;
QString m_wallpaper;
QPixmap m_pixmap;
QPixmap m_oldPixmap;
QPixmap m_oldFadedPixmap;
KFileDialog *m_fileDialog;
qreal m_fadeValue;
QPropertyAnimation *m_animation;
BackgroundListModel *m_model;
QSize m_size;
QString m_img;
};
#endif //PLASMA_PLUGIN_WALLPAPER_WEATHER_H