Update plasma

This commit is contained in:
BuyMyMojo 2025-04-22 01:30:36 +10:00
parent cf88cf4a7b
commit d83c5a0a54
Signed by untrusted user who does not match committer: aria
GPG key ID: 19AB7AA462B8AB3B
160 changed files with 7837 additions and 0 deletions

View file

@ -0,0 +1,81 @@
import QtQuick
import org.kde.ksvg 1.0 as KSvg
import Qt5Compat.GraphicalEffects
Item {
property int marginLeft: maskSvg2.marg
property color leftColor: "red"
Grid {
id: maskSvg2
width: parent.width
height: parent.height
//visible: false
columns: 2
property var marg: topleft2.implicitWidth
KSvg.SvgItem {
id: topleft2
imagePath: "dialogs/background"
elementId: "topleft"
}
KSvg.SvgItem {
id: top2
imagePath: "dialogs/background"
elementId: "top"
width: parent.width - topleft2.implicitWidth *1
}
KSvg.SvgItem {
id: left2
imagePath: "dialogs/background"
elementId: "left"
height: parent.height - topleft2.implicitHeight*2
}
KSvg.SvgItem {
imagePath: "dialogs/background"
elementId: "center"
height: parent.height - topleft2.implicitHeight*2
width: top2.width
}
KSvg.SvgItem {
id: bottomleft2
imagePath: "dialogs/background"
elementId: "bottomleft"
}
KSvg.SvgItem {
id: bottom2
imagePath: "dialogs/background"
elementId: "bottom"
width: parent.width - bottomleft2.implicitWidth
}
}
Rectangle {
color: leftColor //Kirigami.Theme.highlightColor
width: maskSvg2.width
height: maskSvg2.height
layer.enabled: true
layer.effect: OpacityMask {
maskSource: maskSvg2
}
}
Rectangle {
color: leftColor //Kirigami.Theme.highlightColor
width: maskSvg2.width
height: maskSvg2.height
layer.enabled: true
layer.effect: OpacityMask {
maskSource: maskSvg2
}
}
KSvg.SvgItem {
anchors.right: maskSvg2.right
imagePath: "widgets/line"
elementId: "vertical-line"
height: parent.height
}
}

View file

@ -0,0 +1,159 @@
import QtQuick
import QtQuick.Layouts 1.1
import QtQuick.Controls
import org.kde.plasma.plasmoid
import org.kde.kirigami as Kirigami
import org.kde.plasma.core as PlasmaCore
import org.kde.plasma.components 3.0 as PlasmaComponents3
//import org.kde.plasma.plasma5support as Plasma5Support
Item {
id: iconAndTem
Layout.minimumWidth: widthReal
Layout.minimumHeight: heightReal
property QtObject dashWindow: null
readonly property bool isVertical: Plasmoid.formFactor === PlasmaCore.Types.Vertical
property string undefanchors: activeweathershottext ? undefined : parent.verticalCenter
property bool textweather: Plasmoid.configuration.displayWeatherInPanel
property bool activeweathershottext: heightH > 34
property int fonssizes: Plasmoid.configuration.sizeFontConfig
property int heightH: wrapper.height
property var widthWidget: activeweathershottext ? temOfCo.implicitWidth : temOfCo.implicitWidth + wrapper_weathertext.width
property var widthReal: isVertical ? wrapper.width : initial.implicitWidth
property var hVerti: wrapper_vertical.implicitHeight
property var heightReal: isVertical ? hVerti : wrapper.height
MouseArea {
id: compactMouseArea
anchors.fill: parent
hoverEnabled: true
onClicked: {
dashWindow.visible = !dashWindow.visible;
}
}
RowLayout {
id: initial
width: icon.width + columntemandweathertext.width + icon.width * 0.3
height: parent.height
spacing: icon.width / 5
visible: !isVertical
Kirigami.Icon {
id: icon
width: root.height < 17 ? 16 : root.height < 24 ? 22 : 24
height: width
source: wrapper.currentIcon
anchors.top: parent.top
anchors.bottom: parent.bottom
roundToIconSize: false
}
Column {
id: columntemandweathertext
width: widthWidget
height: temOfCo.implicitHeight
anchors.verticalCenter: parent.verticalCenter
Row {
id: temOfCo
width: textGrados.implicitWidth + subtextGrados.implicitWidth
height: textGrados.implicitHeight
anchors.verticalCenter: undefanchors
Label {
id: textGrados
height: parent.height
width: parent.width - subtextGrados.implicitWidth
text: wrapper.currentTemp
font.bold: boldfonts
font.pixelSize: fonssizes
color: PlasmaCore.Theme.textColor
horizontalAlignment: Text.AlignLeft
verticalAlignment: Text.AlignVCenter
}
Label {
id: subtextGrados
height: parent.height
width: parent.width - textGrados.implicitWidth
text: (wrapper.unitsTemperature === "0") ? " °C " : " °F "
horizontalAlignment: Text.AlignLeft
font.bold: boldfonts
font.pixelSize: fonssizes
color: PlasmaCore.Theme.textColor
verticalAlignment: Text.AlignVCenter
}
}
Item {
id: wrapper_weathertext
height: shortweathertext.implicitHeight
width: shortweathertext.implicitWidth
visible: activeweathershottext & textweather
Label {
id: shortweathertext
text: wrapper.weather
font.pixelSize: fonssizes
font.bold: true
verticalAlignment: Text.AlignVCenter
}
}
}
}
ColumnLayout {
id: wrapper_vertical
width: root.width
height: icon_vertical.height + textGrados_vertical.implicitHeight
spacing: 2
visible: isVertical
Kirigami.Icon {
id: icon_vertical
width: wrapper.width < 17 ? 16 : wrapper.width < 24 ? 22 : 24
height: wrapper.width < 17 ? 16 : wrapper.width < 24 ? 22 : 24
source: wrapper.currentIcon
anchors.left: parent.left
anchors.right: parent.right
roundToIconSize: false
}
Row {
id: temOfCo_vertical
width: textGrados_vertical.implicitWidth + subtextGrados_vertical.implicitWidth
height: textGrados_vertical.implicitHeight
Layout.alignment: Qt.AlignHCenter
Label {
id: textGrados_vertical
height: parent.height
text: wrapper.currentTemp
font.bold: boldfonts
font.pixelSize: fonssizes
color: PlasmaCore.Theme.textColor
horizontalAlignment: Text.AlignHCenter
}
Label {
id: subtextGrados_vertical
height: parent.height
text: (wrapper.unitsTemperature === "0") ? " °C" : " °F"
font.bold: boldfonts
font.pixelSize: fonssizes
color: PlasmaCore.Theme.textColor
horizontalAlignment: Text.AlignHCenter
}
}
}
Component.onCompleted: {
dashWindow = Qt.createQmlObject("Representation {}", wrapper);
plasmoid.activated.connect(function() {
dashWindow.plasmoidWidV = widthReal
dashWindow.plasmoidWidH = heightReal
dashWindow.visible = !dashWindow.visible;
});
}
}

View file

@ -0,0 +1,150 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
import org.kde.plasma.core 2.0 as PlasmaCore
Item {
id: root
signal configurationChanged
//QtObject {
// id: toCurrency
//property var value
//}
QtObject {
id: fontsizeValue
property var value
}
QtObject {
id: unidWeatherValue
property var value
}
property alias cfg_coordinatesIP: coordinatesIP.checked
property alias cfg_displayWeatherInPanel: displayWeather.checked
property alias cfg_manualLatitude: latitude.text
property alias cfg_manualLongitude: longitude.text
property alias cfg_temperatureUnit: unidWeatherValue.value
property alias cfg_sizeFontConfig: fontsizeValue.value
property alias cfg_fontBoldWeather: boldWeather.checked
ColumnLayout {
id:mainColumn
spacing: Kirigami.Units.largeSpacing
Layout.fillWidth: true
GridLayout{
id: firslayout
columns: 2
Label {
id: refrestitle
Layout.minimumWidth: root.width/2
text: i18n("Use geographical coordinates from the IP") + ":"
horizontalAlignment: Label.AlignRight
}
CheckBox {
id: coordinatesIP
}
}
GridLayout{
columns: 2
Label {
Layout.minimumWidth: root.width/2
text: i18n("Latitude") + ":"
visible: !coordinatesIP.checked
horizontalAlignment: Label.AlignRight
}
TextField {
id: latitude
visible: !coordinatesIP.checked
width: 110
}
Label {
Layout.minimumWidth: root.width/2
text: i18n("Longitude") + ":"
visible: !coordinatesIP.checked
horizontalAlignment: Label.AlignRight
}
TextField {
id: longitude
visible: !coordinatesIP.checked
width: 110
}
Label {
Layout.minimumWidth: root.width/2
text: i18n("Display weather conditions on the panel") + ":"
horizontalAlignment: Label.AlignRight
}
CheckBox {
id: displayWeather
}
Label {
Layout.minimumWidth: root.width/2
text: i18n("Bold Weather Conditions") + ":"
horizontalAlignment: Label.AlignRight
}
CheckBox {
id: boldWeather
}
Label {
Layout.minimumWidth: root.width/2
text: i18n("Temperature unit") + ":"
horizontalAlignment: Label.AlignRight
}
ComboBox {
textRole: "text"
valueRole: "value"
id: positionComboBox
model: [
{text: i18n("Celsius (°C)"), value: 0},
{text: i18n("Fahrenheit (°F)"), value: 1},
]
onActivated: unidWeatherValue.value = currentValue
Component.onCompleted: currentIndex = indexOfValue(unidWeatherValue.value)
}
Label {
Layout.minimumWidth: root.width/2
text: i18n("Font Size") + ":"
horizontalAlignment: Label.AlignRight
}
ComboBox {
textRole: "text"
valueRole: "value"
width: 32
id: valueForSizeFont
model: [
{text: i18n("8"), value: 8},
{text: i18n("9"), value: 9},
{text: i18n("10"), value: 10},
{text: i18n("11"), value: 11},
{text: i18n("12"), value: 12},
{text: i18n("13"), value: 13},
{text: i18n("14"), value: 14},
{text: i18n("15"), value: 15},
{text: i18n("16"), value: 16},
{text: i18n("17"), value: 17},
{text: i18n("18"), value: 18},
]
onActivated: fontsizeValue.value = currentValue
Component.onCompleted: currentIndex = indexOfValue(fontsizeValue.value)
}
}
}
}

View file

@ -0,0 +1,113 @@
import QtQuick
import org.kde.kirigami as Kirigami
import QtQuick.Controls as Controls
Item {
property int leftPanelMargin: 0
property int topPanelMargin: 0
property int exedentHight: 0
property int widthOfLeftPanel: 130
property int spacingElements: 5
property string currentWatherTemp: "?"
LeftPanel {
id: leftPanel
anchors.left: parent.left
anchors.leftMargin: - leftPanelMargin
anchors.top: parent.top
anchors.topMargin: - topPanelMargin
leftPanelColor: Kirigami.Theme.highlightColor
width: widthOfLeftPanel
height: parent.height + exedentHight
}
Item {
width: leftPanel.width
anchors.top: parent.top
Kirigami.Heading {
id: city
width: parent.width - leftPanel.marginLeftReal
text: wrapper.location //"Ciudad"
color: Kirigami.Theme.highlightedTextColor
level: 3
font.weight: Font.DemiBold
elide: Text.ElideRight
}
Row {
id: current
width: parent.width - leftPanel.marginLeftReal
anchors.top: city.bottom
anchors.topMargin: spacingElements
height: text.implicitHeight
spacing: 5
Kirigami.Icon {
id: logo
source: wrapper.currentIcon
width: Kirigami.Units.iconSizes.medium
height: width
color: Kirigami.Theme.highlightedTextColor
anchors.verticalCenter: parent.verticalCenter
}
Controls.Label {
id: text
width: parent.width - logo.width
text: wrapper.currentTemp
color: Kirigami.Theme.highlightedTextColor
font.weight: Font.DemiBold
font.pixelSize: logo.height
anchors.verticalCenter: parent.verticalCenter
}
}
Column {
anchors.top: current.bottom
width: current.width
height: textDo.implicitHeight * 2
anchors.topMargin: spacingElements
opacity: 0.7
Kirigami.Heading {
id: textDo
width: parent.width - leftPanel.marginLeftReal
text: wrapper.weather //"Summy"
color: Kirigami.Theme.highlightedTextColor
level: 5
//font.weight: Font.DemiBold
elide: Text.ElideRight
}
Kirigami.Heading {
width: parent.width - leftPanel.marginLeftReal
text: wrapper.currentMaxMin
color: Kirigami.Theme.highlightedTextColor
level: 5
//font.weight: Font.DemiBold
elide: Text.ElideRight
}
}
}
Item {
width: link.implicitWidth
height: link.implicitHeight
anchors.bottom: parent.bottom
//anchors.bottomMargin: height
Kirigami.Heading {
id: link
width: parent.width
text: "open-meteo.com"
color: Kirigami.Theme.highlightedTextColor
level: 5
font.underline: true
opacity: 0.4
elide: Text.ElideRight
}
MouseArea {
anchors.fill: parent
onClicked: {
Qt.openUrlExternally("https://open-meteo.com")
}
}
}
}

View file

@ -0,0 +1,93 @@
import QtQuick
import org.kde.kirigami as Kirigami
Item {
property int widthTxt: 0
Row {
id: hourlyForecast
width: parent.width
height: parent.height /2
Repeater {
model: forecastHours
delegate: Item {
width: parent.width/5
height: parent.height
Column {
width: text.implicitWidth
spacing: Kirigami.Units.iconSizes.small/3
anchors.horizontalCenter: parent.horizontalCenter
Kirigami.Heading {
id: text
width: parent.width
text: model.hours % 24
color: Kirigami.Theme.textColor
level: 5
}
Kirigami.Icon {
width: Kirigami.Units.iconSizes.smallMedium
height: width
anchors.horizontalCenter: parent.horizontalCenter
source: model.icon
}
Kirigami.Heading {
width: parent.width
text: model.temp
color: Kirigami.Theme.textColor
horizontalAlignment: Text.AlignHCenter
level: 5
}
}
}
}
}
Column {
width: parent.width
height: parent.height/2
anchors.top: hourlyForecast.bottom
Repeater {
model: forecastFullModel
delegate: Row {
height: parent.height/3
width: parent.width
spacing: 8
Kirigami.Heading {
id: day
width: parent.width - logo.width - widthTxt - 16
height: parent.height
text: model.date
color: Kirigami.Theme.textColor
verticalAlignment: Text.AlignVCenter
level: 5
}
Kirigami.Icon {
id: logo
width: Kirigami.Units.iconSizes.smallMedium
height: width
source: model.icon
anchors.verticalCenter: parent.verticalCenter
}
Kirigami.Heading {
id: forecastText
width: widthTxt
height: parent.height
text: model.maxTemp + "°/" + model.minTemp + "°"
color: Kirigami.Theme.textColor
verticalAlignment: Text.AlignVCenter
level: 5
}
Component.onCompleted: {
if (forecastText.implicitWidth > widthTxt) {
widthTxt = forecastText.implicitWidth
}
}
}
}
}
}

View file

@ -0,0 +1,12 @@
import QtQuick
Item {
property color leftPanelColor: "red"
property int marginLeftReal: card.marginLeft
Card {
id: card
leftColor: leftPanelColor
width: parent.width
height: parent.height
}
}

View file

@ -0,0 +1,133 @@
/*
* SPDX-FileCopyrightText: zayronxio
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import QtQuick 2.4
import QtQuick.Layouts 1.1
import org.kde.plasma.plasmoid 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import Qt5Compat.GraphicalEffects
import org.kde.kirigami as Kirigami
import org.kde.ksvg 1.0 as KSvg
//import QtQuick.Controls 2.15
//import QtQuick.Effects
Item {
id: main
property int plasmoidWidV: 0
property int plasmoidWidH: 0
onVisibleChanged: {
root.visible = !root.visible
}
KSvg.FrameSvgItem {
id : backgroundSvg
visible: false
imagePath: "dialogs/background"
}
Plasmoid.status: root.visible ? PlasmaCore.Types.RequiresAttentionStatus : PlasmaCore.Types.PassiveStatus
PlasmaCore.Dialog {
id: root
objectName: "popupWindow"
flags: Qt.WindowStaysOnTopHint
location: PlasmaCore.Types.Floating
hideOnWindowDeactivate: true
onHeightChanged: {
var pos = popupPosition(width, height);
x = pos.x;
y = pos.y;
}
onWidthChanged: {
var pos = popupPosition(width, height);
x = pos.x;
y = pos.y;
}
function toggle() {
main.visible = !main.visible;
}
onVisibleChanged: {
if (visible) {
var pos = popupPosition(width, height);
x = pos.x;
y = pos.y;
//animation1.start()
}
}
function popupPosition(width, height) {
var screenAvail = wrapper.availableScreenRect;
var screen = wrapper.screenGeometry;
var panelH = wrapper.height
var panelW = wrapper.width
var horizMidPoint = screen.x + (screen.width / 2);
var vertMidPoint = screen.y + (screen.height / 2);
var appletTopLeft = parent.mapToGlobal(0, 0);
function calculatePosition(x, y) {
return Qt.point(x, y);
}
switch (plasmoid.location) {
case PlasmaCore.Types.BottomEdge:
var x = appletTopLeft.x < (screen.width - width/2 + backgroundSvg.margins.left + Kirigami.Units.gridUnit) ? appletTopLeft.x < ((width/2) + backgroundSvg.margins.left) ? Kirigami.Units.gridUnit - backgroundSvg.margins.left : appletTopLeft.x - width/2 : screen.width - (width - backgroundSvg.margins.left*2) - Kirigami.Units.gridUnit ;
var y = appletTopLeft.y - height - Kirigami.Units.gridUnit
return calculatePosition(x, y);
case PlasmaCore.Types.TopEdge:
x = appletTopLeft.x < (width/2 + backgroundSvg.margins.left + Kirigami.Units.gridUnit) ? backgroundSvg.margins.left : appletTopLeft.x > (screen.width - (width/2) - backgroundSvg.margins.left - Kirigami.Units.gridUnit) ? screen.width - width - backgroundSvg.margins.left : appletTopLeft.x - width/2 - backgroundSvg.margins.left
y = appletTopLeft.y + panelH + Kirigami.Units.gridUnit
return calculatePosition(x, y);
case PlasmaCore.Types.LeftEdge:
x = appletTopLeft.x + panelW + Kirigami.Units.gridUnit / 2;
y = appletTopLeft.y < screen.height - height ? appletTopLeft.y : appletTopLeft.y - height + iconUser.height / 2;
return calculatePosition(x, y);
case PlasmaCore.Types.RightEdge:
x = appletTopLeft.x - width - Kirigami.Units.gridUnit / 2;
y = appletTopLeft.y < screen.height - height ? appletTopLeft.y : screen.height - height - Kirigami.Units.gridUnit / 5;
return calculatePosition(x, y);
default:
return;
}
}
FocusScope {
id: rootItem
Layout.minimumWidth: Kirigami.Units.gridUnit * 20
Layout.maximumWidth: minimumWidth
Layout.minimumHeight: Kirigami.Units.gridUnit * 9 // 170
Layout.maximumHeight: minimumHeight
focus: true
FullContainer {
id: fullContainer
leftPanelMargin: backgroundSvg.margins.left
topPanelMargin: backgroundSvg.margins.top
exedentHight: backgroundSvg.margins.top + backgroundSvg.margins.bottom
widthOfLeftPanel: 130
width: widthOfLeftPanel
height: parent.height
}
ItemForecasts {
width: parent.width - fullContainer.width
height: parent.height
anchors.left: fullContainer.right
}
}
}
}

View file

@ -0,0 +1,418 @@
import QtQuick 2.15
import QtQuick.Controls 2.15
import "../js/traductor.js" as Traduc
import "../js/GetInfoApi.js" as GetInfoApi
import "../js/geoCoordinates.js" as GeoCoordinates
import "../js/GetCity.js" as GetCity
import "../js/GetModelWeather.js" as GetModelWeather
Item {
signal dataChanged // Definir el signal aquí
signal simpleDataReady // Definir el signal aquí
function obtener(texto, indice) {
var palabras = texto.split(/\s+/); // Divide el texto en palabras utilizando el espacio como separador
return palabras[indice - 1]; // El índice - 1 porque los índices comienzan desde 0 en JavaScript
}
function fahrenheit(temp) {
if (temperatureUnit == 0) {
return temp;
} else {
return Math.round((temp * 9 / 5) + 32);
}
}
property bool isUpdate: false
property string lastUpdate: "0"
property int hoursC: 0
property string newValuesWeather: "0"
property string newValuesForeWeather: "0"
property bool active: plasmoid.configuration.weatheCardActive
property bool isInExecution: false
property string useCoordinatesIp: plasmoid.configuration.coordinatesIP
property string latitudeC: plasmoid.configuration.manualLatitude
property string longitudeC: plasmoid.configuration.manualLongitude
property string temperatureUnit: plasmoid.configuration.temperatureUnit
property string latitude: (useCoordinatesIp === "true") ? latitudeIP : (latitudeC === "0") ? latitudeIP : latitudeC
property string longitud: (useCoordinatesIp === "true") ? longitudIP : (longitudeC === "0") ? longitudIP : longitudeC
property var observerCoordenates: latitude + longitud
property int currentTime: Number(Qt.formatDateTime(new Date(), "h"))
property string datosweather: "0"
property string forecastWeather: "0"
property string observer: datosweather + forecastWeather
property int retrysCity: 0
property string oneIcon: asingicon(obtener(forecastWeather, 1))
property string twoIcon: asingicon(obtener(forecastWeather, 2))
property string threeIcon: asingicon(obtener(forecastWeather, 3))
property string fourIcon: asingicon(obtener(forecastWeather, 4))
property string fiveIcon: asingicon(obtener(forecastWeather, 5))
property string sixIcon: asingicon(obtener(forecastWeather, 6))
property string sevenIcon: asingicon(obtener(forecastWeather, 7))
property int oneMax: fahrenheit(obtener(forecastWeather, 8))
property int twoMax: fahrenheit(obtener(forecastWeather, 9))
property int threeMax: fahrenheit(obtener(forecastWeather, 10))
property int fourMax: fahrenheit(obtener(forecastWeather, 11))
property int fiveMax: fahrenheit(obtener(forecastWeather, 12))
property int sixMax: fahrenheit(obtener(forecastWeather, 13))
property int sevenMax: fahrenheit(obtener(forecastWeather, 14))
property int oneMin: fahrenheit(obtener(forecastWeather, 15))
property int twoMin: fahrenheit(obtener(forecastWeather, 16))
property int threeMin: fahrenheit(obtener(forecastWeather, 17))
property int fourMin: fahrenheit(obtener(forecastWeather, 18))
property int fiveMin: fahrenheit(obtener(forecastWeather, 19))
property int sixMin: fahrenheit(obtener(forecastWeather, 20))
property int sevenMin: fahrenheit(obtener(forecastWeather, 21))
property string day: (Qt.formatDateTime(new Date(), "yyyy-MM-dd"))
property string therday: Qt.formatDateTime(new Date(new Date().getTime() + (numberOfDays * 24 * 60 * 60 * 1000)), "yyyy-MM-dd")
property string finDay: Qt.formatDateTime(new Date(new Date().getTime() + (1 * 24 * 60 * 60 * 1000)), "yyyy-MM-dd")
property int numberOfDays: 6
property string currentTemperature: datosweather !== "0" ? fahrenheit(obtener(datosweather, 1)) : "?"
property string codeleng: ((Qt.locale().name)[0] + (Qt.locale().name)[1])
property string codeweather: obtener(datosweather, 4)
property string codeweatherTomorrow: obtener(forecastWeather, 2)
property string codeweatherDayAftertomorrow: obtener(forecastWeather, 3)
property string codeweatherTwoDaysAfterTomorrow: obtener(forecastWeather, 4)
property string minweatherCurrent: fahrenheit(obtener(datosweather, 2))
property string maxweatherCurrent: fahrenheit(obtener(datosweather, 3))
property var tempHours: [fahrenheit(obtener(datosweather, 9)), fahrenheit(obtener(datosweather, 10)), fahrenheit(obtener(datosweather, 11)), fahrenheit(obtener(datosweather, 12)), fahrenheit(obtener(datosweather, 13))]
property var iconHours: [asingicon(obtener(datosweather, 14)), asingicon(obtener(datosweather, 15)), asingicon(obtener(datosweather, 16)), asingicon(obtener(datosweather, 17)), asingicon(obtener(datosweather, 18)) ]
property string minweatherTomorrow: twoMin
property string maxweatherTomorrow: twoMax
property string minweatherDayAftertomorrow: threeMin
property string maxweatherDayAftertomorrow: threeMax
property string minweatherTwoDaysAfterTomorrow: fourMax
property string maxweatherTwoDaysAfterTomorrow: fourMax
property string iconWeatherCurrent: asingicon(codeweather)
property string uvindex: uvIndexLevelAssignment(obtener(datosweather, 7))
property string windSpeed: obtener(datosweather, 6)
property string weatherLongtext: i18n(textWeather(codeweather))
property string weatherShottext: i18n(shortTextWeather(codeweather))
property string probabilidadDeLLuvia: obtener(datosweather, 5)
property string textProbability: Traduc.rainProbabilityText(codeleng)
property string completeCoordinates: ""
property string oldCompleteCoordinates: "1"
property string latitudeIP: completeCoordinates.substring(0, (completeCoordinates.indexOf(' ')) - 1)
property string longitudIP: completeCoordinates.substring(completeCoordinates.indexOf(' ') + 1)
property string uvtext: Traduc.uvRadiationText(codeleng)
property string windSpeedText: Traduc.windSpeedText(codeleng)
property int isDay: obtener(datosweather, 8)
property string city: "unk"
property string prefixIcon: isDay === 1 ? "" : "-night"
Component.onCompleted: {
updateWeather(1);
}
function uvIndexLevelAssignment(nivel) {
if (nivel < 3) {
return nivel + " " + Traduc.lavelUV(codeleng, 0);
} else {
if (nivel < 6) {
return nivel + " " + Traduc.lavelUV(codeleng, 1);
} else {
if (nivel < 8) {
return nivel + " " + Traduc.lavelUV(codeleng, 2);
} else {
if (nivel < 11) {
return nivel + " " + Traduc.lavelUV(codeleng, 3);
} else {
return nivel + " " + Traduc.lavelUV(codeleng, 4);
}
}
}
}
}
function getCoordinatesWithIp() {
GeoCoordinates.obtenerCoordenadas(function(result) {
completeCoordinates = result;
retryCoordinate.start()
});
}
onObserverCoordenatesChanged: {
console.log("Coordenadas cambiaron, actualizando clima");
if (latitude && longitud && latitude !== "0" && longitud !== "0") {
updateWeather(2);
getCityFuncion();
} else {
console.warn("Coordenadas inválidas, reintentando...");
retryCoordinate.start();
}
}
function getCityFuncion() {
if (!latitude || !longitud || latitude === "0" || longitud === "0") {
console.error("Coordenadas inválidas para la solicitud de ciudad");
return;
}
GetCity.getNameCity(latitude, longitud, codeleng, function(result) {
city = result;
retrycity.start()
});
}
function getWeatherApi() {
GetInfoApi.obtenerDatosClimaticos(latitude, longitud, day, finDay, currentTime, function(result) {
if (isUpdate) {
newValuesWeather = result;
} else {
datosweather = result;
}
getForecastWeather()
retry.start()
});
}
function getForecastWeather() {
GetModelWeather.GetForecastWeather(latitude, longitud, day, therday, function(result) {
if (isUpdate) {
newValuesForeWeather = result
} else {
forecastWeather = result
};
});
}
function asingicon(x, b) {
let wmocodes = {
0: "clear",
1: "few-clouds",
2: "few-clouds",
3: "clouds",
51: "showers-scattered",
53: "showers-scattered",
55: "showers-scattered",
56: "showers-scattered",
57: "showers-scattered",
61: "showers",
63: "showers",
65: "showers",
66: "showers-scattered",
67: "showers",
71: "snow-scattered",
73: "snow",
75: "snow",
77: "hail",
80: "showers",
81: "showers",
82: "showers",
85: "snow-scattered",
86: "snow",
95: "storm",
96: "storm",
99: "storm",
};
var iconName = "weather-" + (wmocodes[x] || "unknown");
var iconNamePresicion = iconName + prefixIcon
return b === "preciso" ? iconNamePresicion : iconName;
}
function textWeather(x) {
let text = {
0: "Clear",
1: "Mainly clear",
2: "Partly cloudy",
3: "Overcast",
51: "Drizzle light intensity",
53: "Drizzle moderate intensity",
55: "Drizzle dense intensity",
56: "Freezing Drizzle light intensity",
57: "Freezing Drizzle dense intensity",
61: "Rain slight intensity",
63: "Rain moderate intensity",
65: "Rain heavy intensity",
66: "Freezing Rain light intensity",
67: "Freezing Rain heavy intensity",
71: "Snowfall slight intensity",
73: "Snowfall moderate intensity",
75: "Snowfall heavy intensity",
77: "Snow grains",
80: "Rain showers slight",
81: "Rain showers moderate",
82: "Rain showers violent",
85: "Snow showers slight",
86: "Snow showers heavy",
95: "Thunderstorm",
96: "Thunderstorm with slight hail"
};
return text[x]
}
function shortTextWeather(x) {
let text = {
0: "Clear",
1: "Clear",
2: "Cloudy",
3: "Cloudy",
51: "Drizzle",
53: "Drizzle",
55: "Drizzle",
56: "Drizzle",
57: "Drizzle",
61: "Rain",
63: "Rain",
65: "Rain",
66: "Rain",
67: "Rain",
71: "Snow",
73: "Snow",
75: "Snow",
77: "Hail",
80: "Showers",
81: "Showers",
82: "Showers",
85: "Showers",
86: "Showers",
95: "Storm",
96: "Storm",
99: "Storm"
};
return text[x]
}
function updateWeather(x) {
if (x === 1) {
if (useCoordinatesIp === "true") {
getCoordinatesWithIp();
} else {
if (latitudeC === "0" || longitudC === "0") {
getCoordinatesWithIp();
} else {
getWeatherApi()
}
}
}
///
if (x === 2) {
getWeatherApi();
}
}
onObserverChanged: {
if (forecastWeather.length > 3) {
lastUpdate = new Date()
dataChanged();
}
}
onNewValuesForeWeatherChanged: {
if (newValuesForeWeather.length > 3) {
datosweather = newValuesWeather;
forecastWeather = newValuesForeWeather;
newValuesWeather = "0";
newValuesForeWeather= "0";
}
}
Timer {
id: retryCoordinate
interval: 5000
running: false
repeat: false
onTriggered: {
if (completeCoordinates === "") {
getCoordinatesWithIp();
} else {
if (isUpdate) {
veri.start()
}
}
}
}
Timer {
id: retrycity
interval: 6000
running: false
repeat: false
onTriggered: {
if (city === "unk" && retrysCity < 5) {
retrysCity = retrysCity + 1
getCityFuncion();
}
}
}
Timer {
id: retry
interval: 5000
running: false
repeat: false
onTriggered: {
if (datosweather === "0") {
getWeatherApi();
}
}
}
Timer {
id: weatherupdate
interval: 900000
running: true
repeat: true
onTriggered: {
isUpdate = true
oldCompleteCoordinates = completeCoordinates
getCoordinatesWithIp()
//updateWeather(1);
//veri.start()
}
}
Timer {
id: observateHours
interval: 1000
running: true
repeat: true
onTriggered: {
hoursC = Qt.formatDateTime(new Date(), "h")
}
}
Timer {
id: veri
interval: 4000
running: false
repeat: false
onTriggered: {
//newValuesWeather = "0"
if (oldCompleteCoordinates === completeCoordinates) {
updateWeather(2)
}
}
}
onUseCoordinatesIpChanged: {
if (active) {
updateWeather(1);
isInExecution = true
}
}
}

View file

@ -0,0 +1,39 @@
function getNameCity(latitude, longitud, leng, callback) {
let url = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitud}&accept-language=${leng}`;
console.log("Generated URL: ", url); // Para verificar la URL generada
let req = new XMLHttpRequest();
req.open("GET", url, true);
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (req.status === 200) {
try {
let datos = JSON.parse(req.responseText);
let address = datos.address;
let city = address.city;
let county = address.county;
let state = address.state;
let full = city ? city : state ? state : county;
console.log(full);
callback(full);
} catch (e) {
console.error("Error al analizar la respuesta JSON: ", e);
}
} else {
console.error(`city failed`);
}
}
};
req.onerror = function () {
console.error("La solicitud falló");
};
req.ontimeout = function () {
console.error("La solicitud excedió el tiempo de espera");
};
req.send();
}

View file

@ -0,0 +1,61 @@
function obtenerDatosClimaticos(latitud, longitud, fechaInicio, fechaFin, hours, callback) {
let url = `https://api.open-meteo.com/v1/forecast?latitude=${latitud}&longitude=${longitud}&hourly=temperature_2m,weather_code&current=temperature_2m,is_day,weather_code,wind_speed_10m&hourly=uv_index&daily=temperature_2m_max,temperature_2m_min,precipitation_probability_max&timezone=auto&start_date=${fechaInicio}&end_date=${(fechaFin)}`;
const now = new Date();
const hoursC = now.getHours(); // Horas (0-23)
const minutes = now.getMinutes(); // Minutos (0-59)
const currentTime = minutes > 44 ? hoursC + 2 : hoursC + 1;
let req = new XMLHttpRequest();
req.open("GET", url, true);
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (req.status === 200) {
let datos = JSON.parse(req.responseText);
let currents = datos.current;
let isday = currents.is_day;
let temperaturaActual = currents.temperature_2m;
let windSpeed = currents.wind_speed_10m;
let codeCurrentWeather = currents.weather_code;
let datosDiarios = datos.daily;
let propabilityPrecipitationCurrent = datosDiarios.precipitation_probability_max[0];
let hourly = datos.hourly
let propabilityUVindex = hourly.uv_index[hours];
let tempForecastHorylOne = hourly.temperature_2m[currentTime];
let tempForecastHorylTwo = hourly.temperature_2m[currentTime + 1];
let tempForecastHorylThree = hourly.temperature_2m[currentTime + 2];
let tempForecastHorylFour = hourly.temperature_2m[currentTime + 3];
let tempForecastHorylFive = hourly.temperature_2m[currentTime + 4];
let hoursWether = tempForecastHorylOne + " " + tempForecastHorylTwo + " " + tempForecastHorylThree + " " + tempForecastHorylFour + " " + tempForecastHorylFive
let codeForecastHorylOne = hourly.weather_code[currentTime];
let codeForecastHorylTwo = hourly.weather_code[currentTime + 1];
let codeForecastHorylThree = hourly.weather_code[currentTime + 2];
let codeForecastHorylFour = hourly.weather_code[currentTime + 3];
let codeForecastHorylFive = hourly.weather_code[currentTime + 4];
let weather_codeWether = codeForecastHorylOne + " " + codeForecastHorylTwo + " " + codeForecastHorylThree + " " + codeForecastHorylFour + " " + codeForecastHorylFive
let tempMin = datosDiarios.temperature_2m_min[0];
let tempMax = datosDiarios.temperature_2m_max[0];
let full = temperaturaActual + " " + tempMin + " " + tempMax + " " + codeCurrentWeather + " " + propabilityPrecipitationCurrent + " " + windSpeed + " " + propabilityUVindex + " " + isday + " " + hoursWether + " " + weather_codeWether
console.log(`${full}`);
callback(full);
console.log(`https://api.open-meteo.com/v1/forecast?latitude=${latitud}&longitude=${longitud}&hourly=temperature_2m,weather_code&current=temperature_2m,is_day,weather_code,wind_speed_10m&hourly=uv_index&daily=temperature_2m_max,temperature_2m_min,precipitation_probability_max&timezone=auto&start_date=${fechaInicio}&end_date=${fechaInicio}`)
} else {
console.error(`Error en la solicitud: weathergeneral ${req.status}`);
//callback(`failed ${req.status}`)
}
}
};
req.send();
}

View file

@ -0,0 +1,27 @@
function GetForecastWeather(latitud, longitud, fechaInicio, fechaFin, callback) {
let url = `https://api.open-meteo.com/v1/forecast?latitude=${latitud}&longitude=${longitud}&daily=weather_code,temperature_2m_max,temperature_2m_min&timezone=auto&start_date=${fechaInicio}&end_date=${fechaFin}`;
let req = new XMLHttpRequest();
req.open("GET", url, true);
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (req.status === 200) {
let datos = JSON.parse(req.responseText);
let daily = datos.daily;
let codes = daily.weather_code.join(' ');
let max = daily.temperature_2m_max.join(' ');
let min = daily.temperature_2m_min.join(' ');
let full = codes + " " + max + " " + min
console.log(`${full}`);
callback(full);
} else {
console.error(`Error en la solicitud: ${req.status}`);
}
}
};
req.send();
}

View file

@ -0,0 +1,145 @@
function getBtDevice() {
var connectedDevices = [];
for (var i = 0; i < btManager.devices.length; ++i) {
var device = btManager.devices[i];
if (device.connected) {
connectedDevices.push(device);
}
}
if (btManager.bluetoothBlocked) {
return i18n("Disabled");
} else if (!btManager.bluetoothOperational) {
if (!btManager.adapters.length) {
return i18n("Unavailable");
} else {
return i18n("Offline");
}
} else if (connectedDevices.length >= 1) {
return i18n(connectedDevices[0].name)
} else {
return i18n("Not Connected");
}
}
function toggleBluetooth()
{
var enable = !btManager.bluetoothOperational;
btManager.bluetoothBlocked = !enable;
for (var i = 0; i < btManager.adapters.length; ++i) {
var adapter = btManager.adapters[i];
adapter.powered = enable;
}
}
function checkInhibition() {
var inhibited = false;
if (!NotificationManager.Server.valid) {
return false;
}
console.log("pass")
var inhibitedUntil = notificationSettings.notificationsInhibitedUntil;
if (!isNaN(inhibitedUntil.getTime())) {
inhibited |= (Date.now() < inhibitedUntil.getTime());
}
if (notificationSettings.notificationsInhibitedByApplication) {
inhibited |= true;
}
if (notificationSettings.inhibitNotificationsWhenScreensMirrored) {
inhibited |= notificationSettings.screensMirrored;
}
return inhibited;
}
function toggleDnd() {
if (Funcs.checkInhibition()) {
notificationSettings.notificationsInhibitedUntil = undefined;
notificationSettings.revokeApplicationInhibitions();
// overrules current mirrored screen setup, updates again when screen configuration
notificationSettings.screensMirrored = false;
notificationSettings.save();
return;
}
var d = new Date();
d.setYear(d.getFullYear()+1)
notificationSettings.notificationsInhibitedUntil = d
notificationSettings.save()
}
function revokeInhibitions() {
notificationSettings.notificationsInhibitedUntil = undefined;
notificationSettings.revokeApplicationInhibitions();
// overrules current mirrored screen setup, updates again when screen configuration changes
notificationSettings.screensMirrored = false;
notificationSettings.save();
}
function toggleRedshiftInhibition() {
if (!monitor.available) {
return;
}
switch (inhibitor.state) {
case Redshift.Inhibitor.Inhibiting:
case Redshift.Inhibitor.Inhibited:
inhibitor.uninhibit();
break;
case Redshift.Inhibitor.Uninhibiting:
case Redshift.Inhibitor.Uninhibited:
inhibitor.inhibit();
break;
}
}
function volumePercent(volume) {
return volume / PulseAudio.NormalVolume * 100
}
function boundVolume(volume) {
return Math.max(PulseAudio.MinimalVolume, Math.min(volume, PulseAudio.NormalVolume));
}
function changeVolumeByPercent(volumeObject, deltaPercent) {
const oldVolume = volumeObject.volume;
const oldPercent = volumePercent(oldVolume);
const targetPercent = oldPercent + deltaPercent;
const newVolume = boundVolume(Math.round(PulseAudio.NormalVolume * (targetPercent/100)));
const newPercent = volumePercent(newVolume);
volumeObject.muted = newPercent == 0;
volumeObject.volume = newVolume;
return newPercent;
}
function volIconName(volume, muted, prefix) {
console.log(volume, muted, prefix)
if (!prefix) {
prefix = "audio-volume";
}
var icon = null;
var percent = volume / PulseAudio.NormalVolume
if (percent <= 0.0 || muted) {
icon = prefix + "-muted";
} else if (percent <= 0.25) {
icon = prefix + "-low";
} else if (percent <= 0.75) {
icon = prefix + "-medium";
} else {
icon = prefix + "-high";
}
return icon;
}
function sumarDia(a) {
var fechaActual = new Date();
fechaActual.setDate(fechaActual.getDate() + a);
var fechaFormateada = Qt.formatDateTime(fechaActual, "dddd");
console.log("Fecha con un día añadido:", fechaFormateada);
return fechaFormateada
}

View file

@ -0,0 +1,34 @@
function obtenerCoordenadas(callback) {
let url = "http://ip-api.com/json/?fields=lat,lon";
let req = new XMLHttpRequest();
req.open("GET", url, true);
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (req.status === 200) {
try {
let datos = JSON.parse(req.responseText);
let latitud = datos.lat;
let longitud = datos.lon;
let full = `${latitud}, ${longitud}`;
console.log(`Coordenadas obtenidas: ${full}`);
callback(full); // Devolver coordenadas completas
} catch (error) {
console.error("Error procesando la respuesta JSON:", error);
callback(null); // Devolver null en caso de error de parsing
}
} else {
console.error(`Error en la solicitud: ${req.status}`);
callback(null); // Devolver null en caso de error de solicitud
}
}
};
req.onerror = function () {
console.error("Error de red al intentar obtener coordenadas.");
callback(null); // Devolver null en caso de error de red
};
req.send();
}

View file

@ -0,0 +1,866 @@
function weatherShortText(languageCode, code) {
let descriptions = {
en: {
0: "Clear",
1: "Clear",
2: "Cloudy",
3: "Cloudy",
51: "Drizzle",
53: "Drizzle",
55: "Drizzle",
56: "Drizzle",
57: "Drizzle",
61: "Rain",
63: "Rain",
65: "Rain",
66: "Rain",
67: "Rain",
71: "Snow",
73: "Snow",
75: "Snow",
77: "Hail",
80: "Showers",
81: "Showers",
82: "Showers",
85: "Showers",
86: "Showers",
95: "Storm",
96: "Storm",
99: "Storm"
},
es: {
0: "Despejado",
1: "Despejado",
2: "Nublado",
3: "Nublado",
51: "Llovizna",
53: "Llovizna",
55: "Llovizna",
56: "Llovizna",
57: "Llovizna",
61: "Lluvia",
63: "Lluvia",
65: "Lluvia",
66: "Lluvia",
67: "Lluvia",
71: "Nieve",
73: "Nieve",
75: "Nieve",
77: "Granizo",
80: "Aguaceros",
81: "Aguaceros",
82: "Aguaceros",
85: "Aguaceros",
86: "Aguaceros",
95: "Tormenta",
96: "Tormenta",
99: "Tormenta"
},
hi: {
0: "साफ",
1: "साफ",
2: "बादल",
3: "बादल",
51: "बूँदा बाँदी",
53: "बूँदा बाँदी",
55: "बूँदा बाँदी",
56: "बूँदा बाँदी",
57: "बूँदा बाँदी",
61: "वर्षा",
63: "वर्षा",
65: "वर्षा",
66: "वर्षा",
67: "वर्षा",
71: "बर्फ",
73: "बर्फ",
75: "बर्फ",
77: "ओला",
80: "झरी",
81: "झरी",
82: "झरी",
85: "झरी",
86: "झरी",
95: "तूफान",
96: "तूफान",
99: "तूफान"
},
fr: {
0: "Clair",
1: "Clair",
2: "Nuageux",
3: "Nuageux",
51: "Bruine",
53: "Bruine",
55: "Bruine",
56: "Bruine",
57: "Bruine",
61: "Pluie",
63: "Pluie",
65: "Pluie",
66: "Pluie",
67: "Pluie",
71: "Neige",
73: "Neige",
75: "Neige",
77: "Grêle",
80: "Averses",
81: "Averses",
82: "Averses",
85: "Averses",
86: "Averses",
95: "Tempête",
96: "Tempête",
99: "Tempête"
},
ru: {
0: "Ясно",
1: "Ясно",
2: "Облачно",
3: "Облачно",
51: "Морось",
53: "Морось",
55: "Морось",
56: "Морось",
57: "Морось",
61: "Дождь",
63: "Дождь",
65: "Дождь",
66: "Дождь",
67: "Дождь",
71: "Снег",
73: "Снег",
75: "Снег",
77: "Град",
80: "Ливни",
81: "Ливни",
82: "Ливни",
85: "Ливни",
86: "Ливни",
95: "Буря",
96: "Буря",
99: "Буря"
},
zh: {
0: "晴朗",
1: "晴朗",
2: "多云",
3: "多云",
51: "小雨",
53: "小雨",
55: "小雨",
56: "小雨",
57: "小雨",
61: "雨",
63: "雨",
65: "雨",
66: "雨",
67: "雨",
71: "雪",
73: "雪",
75: "雪",
77: "冰雹",
80: "阵雨",
81: "阵雨",
82: "阵雨",
85: "阵雨",
86: "阵雨",
95: "暴风",
96: "暴风",
99: "暴风"
},
pt: {
0: "Claro",
1: "Claro",
2: "Nublado",
3: "Nublado",
51: "Garoa",
53: "Garoa",
55: "Garoa",
56: "Garoa",
57: "Garoa",
61: "Chuva",
63: "Chuva",
65: "Chuva",
66: "Chuva",
67: "Chuva",
71: "Neve",
73: "Neve",
75: "Neve",
77: "Granizo",
80: "Chuvas",
81: "Chuvas",
82: "Chuvas",
85: "Chuvas",
86: "Chuvas",
95: "Tempestade",
96: "Tempestade",
99: "Tempestade"
},
ar: {
0: "صافي",
1: "صافي",
2: "غائم",
3: "غائم",
51: "رذاذ",
53: "رذاذ",
55: "رذاذ",
56: "رذاذ",
57: "رذاذ",
61: "مطر",
63: "مطر",
65: "مطر",
66: "مطر",
67: "مطر",
71: "ثلج",
73: "ثلج",
75: "ثلج",
77: "بَرَد",
80: "زخات",
81: "زخات",
82: "زخات",
85: "زخات",
86: "زخات",
95: "عاصفة",
96: "عاصفة",
99: "عاصفة"
},
bn: {
0: "পরিষ্কার",
1: "পরিষ্কার",
2: "মেঘলা",
3: "মেঘলা",
51: "ঝিরঝিরি",
53: "ঝিরঝিরি",
55: "ঝিরঝিরি",
56: "ঝিরঝিরি",
57: "ঝিরঝিরি",
61: "বৃষ্টি",
63: "বৃষ্টি",
65: "বৃষ্টি",
66: "বৃষ্টি",
67: "বৃষ্টি",
71: "তুষার",
73: "তুষার",
75: "তুষার",
77: "শিলা",
80: "ঝরণা",
81: "ঝরণা",
82: "ঝরণা",
85: "ঝরণা",
86: "ঝরণা",
95: "ঝড়",
96: "ঝড়",
99: "ঝড়"
},
de: {
0: "Klar",
1: "Klar",
2: "Bewölkt",
3: "Bewölkt",
51: "Niesel",
53: "Niesel",
55: "Niesel",
56: "Niesel",
57: "Niesel",
61: "Regen",
63: "Regen",
65: "Regen",
66: "Regen",
67: "Regen",
71: "Schnee",
73: "Schnee",
75: "Schnee",
77: "Hagel",
80: "Schauer",
81: "Schauer",
82: "Schauer",
85: "Schauer",
86: "Schauer",
95: "Sturm",
96: "Sturm",
99: "Sturm"
},
ja: {
0: "晴れ",
1: "晴れ",
2: "曇り",
3: "曇り",
51: "霧雨",
53: "霧雨",
55: "霧雨",
56: "霧雨",
57: "霧雨",
61: "雨",
63: "雨",
65: "雨",
66: "雨",
67: "雨",
71: "雪",
73: "雪",
75: "雪",
77: "ひょう",
80: "にわか雨",
81: "にわか雨",
82: "にわか雨",
85: "にわか雨",
86: "にわか雨",
95: "嵐",
96: "嵐",
99: "嵐"
},
ko: {
0: "맑음",
1: "맑음",
2: "흐림",
3: "흐림",
51: "이슬비",
53: "이슬비",
55: "이슬비",
56: "이슬비",
57: "이슬비",
61: "비",
63: "비",
65: "비",
66: "비",
67: "비",
71: "눈",
73: "눈",
75: "눈",
77: "우박",
80: "소나기",
81: "소나기",
82: "소나기",
85: "소나기",
86: "소나기",
95: "폭풍",
96: "폭풍",
99: "폭풍"
},
it: {
0: "Sereno",
1: "Sereno",
2: "Nuvoloso",
3: "Nuvoloso",
51: "Pioggerella",
53: "Pioggerella",
55: "Pioggerella",
56: "Pioggerella",
57: "Pioggerella",
61: "Pioggia",
63: "Pioggia",
65: "Pioggia",
66: "Pioggia",
67: "Pioggia",
71: "Neve",
73: "Neve",
75: "Neve",
77: "Grandine",
80: "Rovesci",
81: "Rovesci",
82: "Rovesci",
85: "Rovesci",
86: "Rovesci",
95: "Tempesta",
96: "Tempesta",
99: "Tempesta"
}
};
if (descriptions[languageCode]) {
return descriptions[languageCode][code] || "Unknown";
} else {
return "Language not supported";
}
}
function weatherLongText(languageCode, code) {
let descriptions = {
en: {
0: "Clear",
1: "Mainly clear",
2: "Partly cloudy",
3: "Overcast",
51: "Drizzle light intensity",
53: "Drizzle moderate intensity",
55: "Drizzle dense intensity",
56: "Freezing Drizzle light intensity",
57: "Freezing Drizzle dense intensity",
61: "Rain slight intensity",
63: "Rain moderate intensity",
65: "Rain heavy intensity",
66: "Freezing Rain light intensity",
67: "Freezing Rain heavy intensity",
71: "Snowfall slight intensity",
73: "Snowfall moderate intensity",
75: "Snowfall heavy intensity",
77: "Snow grains",
80: "Rain showers slight",
81: "Rain showers moderate",
82: "Rain showers violent",
85: "Snow showers slight",
86: "Snow showers heavy",
95: "Thunderstorm",
96: "Thunderstorm with slight hail",
99: "Thunderstorm with heavy hail"
},
es: {
0: "Despejado",
1: "Mayormente despejado",
2: "Parcialmente nublado",
3: "Nublado",
51: "Llovizna de baja intensidad",
53: "Llovizna de intensidad moderada",
55: "Llovizna de intensidad densa",
56: "Llovizna helada de baja intensidad",
57: "Llovizna helada de intensidad densa",
61: "Lluvia de ligera intensidad",
63: "Lluvia de intensidad moderada",
65: "Lluvia de intensidad fuerte",
66: "Lluvia helada de baja intensidad",
67: "Lluvia helada de alta intensidad",
71: "Nieve de ligera intensidad",
73: "Nieve de intensidad moderada",
75: "Nieve de intensidad fuerte",
77: "Granizo",
80: "Aguaceros de lluvia de ligera intensidad",
81: "Aguaceros de lluvia de intensidad moderada",
82: "Aguaceros de lluvia de intensidad violenta",
85: "Aguaceros de nieve de ligera intensidad",
86: "Aguaceros de nieve de intensidad fuerte",
95: "Tormenta",
96: "Tormenta con granizo ligero",
99: "Tormenta con granizo fuerte"
},
fr: {
0: "Clair",
1: "Partiellement clair",
2: "Partiellement nuageux",
3: "Couvert",
51: "Bruine légère",
53: "Bruine modérée",
55: "Bruine dense",
56: "Bruine verglaçante légère",
57: "Bruine verglaçante dense",
61: "Pluie légère",
63: "Pluie modérée",
65: "Pluie forte",
66: "Pluie verglaçante légère",
67: "Pluie verglaçante forte",
71: "Légère chute de neige",
73: "Chute de neige modérée",
75: "Chute de neige forte",
77: "Grains de neige",
80: "Averses de pluie légères",
81: "Averses de pluie modérées",
82: "Averses de pluie violentes",
85: "Averses de neige légères",
86: "Averses de neige fortes",
95: "Orage",
96: "Orage avec grêle légère",
99: "Orage avec grêle forte"
},
de: {
0: "Klar",
1: "Überwiegend klar",
2: "Teilweise bewölkt",
3: "Bedeckt",
51: "Leichter Nieselregen",
53: "Mäßiger Nieselregen",
55: "Dichter Nieselregen",
56: "Leichter Gefrierender Nieselregen",
57: "Dichter Gefrierender Nieselregen",
61: "Leichter Regen",
63: "Mäßiger Regen",
65: "Starker Regen",
66: "Leichter Gefrierender Regen",
67: "Starker Gefrierender Regen",
71: "Leichter Schneefall",
73: "Mäßiger Schneefall",
75: "Starker Schneefall",
77: "Schneekörner",
80: "Leichte Regenschauer",
81: "Mäßige Regenschauer",
82: "Starker Regenschauer",
85: "Leichte Schneeschauer",
86: "Starke Schneeschauer",
95: "Gewitter",
96: "Gewitter mit leichtem Hagel",
99: "Gewitter mit starkem Hagel"
},
it: {
0: "Sereno",
1: "Prevalentemente sereno",
2: "Parzialmente nuvoloso",
3: "Nuvoloso",
51: "Pioviggine debole",
53: "Pioviggine moderata",
55: "Pioviggine intensa",
56: "Pioviggine ghiacciata debole",
57: "Pioviggine ghiacciata intensa",
61: "Pioggia debole",
63: "Pioggia moderata",
65: "Pioggia intensa",
66: "Pioggia ghiacciata debole",
67: "Pioggia ghiacciata intensa",
71: "Nevicata debole",
73: "Nevicata moderata",
75: "Nevicata intensa",
77: "Granuli di neve",
80: "Pioggia debole con rovesci",
81: "Pioggia moderata con rovesci",
82: "Pioggia intensa con rovesci",
85: "Nevicata debole con rovesci",
86: "Nevicata intensa con rovesci",
95: "Temporale",
96: "Temporale con grandine leggera",
99: "Temporale con grandine forte"
},
pt: {
0: "Céu limpo",
1: "Céu pouco nublado",
2: "Parcialmente nublado",
3: "Céu nublado",
51: "Chuviscos de fraca intensidade",
53: "Chuviscos de intensidade moderada",
55: "Chuviscos de intensidade forte",
56: "Chuviscos congelantes de fraca intensidade",
57: "Chuviscos congelantes de intensidade forte",
61: "Chuva de fraca intensidade",
63: "Chuva de intensidade moderada",
65: "Chuva de intensidade forte",
66: "Chuva congelante de fraca intensidade",
67: "Chuva congelante de intensidade forte",
71: "Queda de neve de fraca intensidade",
73: "Queda de neve de intensidade moderada",
75: "Queda de neve de intensidade forte",
77: "Granulado de neve",
80: "Aguaceiros de chuva fracos",
81: "Aguaceiros de chuva moderados",
82: "Aguaceiros de chuva fortes",
85: "Aguaceiros de neve fracos",
86: "Aguaceiros de neve fortes",
95: "Trovoada",
96: "Trovoada com granizo fraco",
99: "Trovoada com granizo forte"
},
ja: {
0: "晴れ",
1: "大部分晴れ",
2: "一部曇り",
3: "曇り",
51: "わずかな霧雨",
53: "穏やかな霧雨",
55: "濃い霧雨",
56: "軽い凍雨",
57: "濃い凍雨",
61: "弱い雨",
63: "穏やかな雨",
65: "激しい雨",
66: "軽い着氷性の雨",
67: "激しい着氷性の雨",
71: "弱い雪",
73: "穏やかな雪",
75: "激しい雪",
77: "雪の粒",
80: "弱いにわか雨",
81: "穏やかなにわか雨",
82: "激しいにわか雨",
85: "弱いにわか雪",
86: "激しいにわか雪",
95: "雷雨",
96: "軽い雹を伴う雷雨",
99: "激しい雹を伴う雷雨"
},
ru: {
0: "Ясно",
1: "В основном ясно",
2: "Частично облачно",
3: "Пасмурно",
51: "Морось слабая интенсивность",
53: "Морось умеренная интенсивность",
55: "Морось плотная интенсивность",
56: "Ледяной дождь слабой интенсивности",
57: "Ледяной дождь сильной интенсивности",
61: "Дождь слабой интенсивности",
63: "Дождь умеренной интенсивности",
65: "Дождь сильной интенсивности",
66: "Ледяной дождь слабой интенсивности",
67: "Ледяной дождь сильной интенсивности",
71: "Снег слабой интенсивности",
73: "Снег умеренной интенсивности",
75: "Снег сильной интенсивности",
77: "Снежные зерна",
80: "Дождь с прояснениями слабый",
81: "Дождь с прояснениями умеренный",
82: "Дождь с прояснениями сильный",
85: "Снег с прояснениями слабый",
86: "Снег с прояснениями сильный",
95: "Гроза",
96: "Гроза с небольшим градом",
99: "Гроза с сильным градом"
},
zh: {
0: "晴",
1: "晴间多云",
2: "局部多云",
3: "阴天",
51: "小雨",
53: "中雨",
55: "大雨",
56: "小冻雨",
57: "大冻雨",
61: "小雨夹雪",
63: "中雨夹雪",
65: "大雨夹雪",
66: "小冰雨",
67: "大冰雨",
71: "小雪",
73: "中雪",
75: "大雪",
77: "雪粒",
80: "小雨 showers",
81: "中雨 showers",
82: "大雨 showers",
85: "小雪 showers",
86: "大雪 showers",
95: "雷暴",
96: "雷暴并伴有小冰雹",
99: "雷暴并伴有大冰雹"
},
ko: {
0: "맑음",
1: "구름 조금",
2: "부분적으로 흐림",
3: "흐림",
51: "약한 이슬비",
53: "중간 강도의 이슬비",
55: "짙은 이슬비",
56: "약한 동결 이슬비",
57: "강한 동결 이슬비",
61: "약한 비",
63: "중간 강도의 비",
65: "강한 비",
66: "약한 동결 비",
67: "강한 동결 비",
71: "약한 눈",
73: "중간 강도의 눈",
75: "강한 눈",
77: "눈송이",
80: "약한 비 샤워",
81: "중간 강도의 비 샤워",
82: "강한 비 샤워",
85: "약한 눈 샤워",
86: "강한 눈 샤워",
95: "천둥 번개",
96: "약한 우박을 동반한 천둥 번개",
99: "강한 우박을 동반한 천둥 번개"
},
// Agrega más idiomas aquí según sea necesario
};
if (descriptions[languageCode]) {
return descriptions[languageCode][code] || "Unknown";
} else {
return "Language not supported";
}
}
function rainProbabilityText(languageCode) {
const translations = {
es: "Probabilidad de lluvia", // Spanish
"en": "Probability of rain", // English
"hi": "बारिश की संभावना", // Hindi
"fr": "Probabilité de pluie", // French
"de": "Regenwahrscheinlichkeit", // German
"it": "Probabilità di pioggia", // Italian
"pt": "Probabilidade de chuva", // Portuguese
"ru": "Вероятность дождя", // Russian
"zh-cn": "降雨概率", // Simplified Chinese (Mainland China)
"zh-tw": "降雨機率", // Traditional Chinese (Taiwan)
"ja": "降雨確率", // Japanese
"ko": "비 올 확률", // Korean
"nl": "Regenkans", // Dutch
"ny": "Mwayi wamagulu" // Chichewa
};
// Return the translation for the language code or default to English if not found
return translations[languageCode] || translations["en"];
}
function lavelUV(languageCode, lavel) {
const translations = {
es: {
0: "Bajo",
1: "Moderado",
2: "Alto",
3: "Muy Alto",
4: "Extremo"
},
en: {
0: "Low",
1: "Moderate",
2: "High",
3: "Very High",
4: "Extreme"
},
hi: {
0: "कम",
1: "मध्यम",
2: "उच्च",
3: "बहुत उच्च",
4: "अत्यधिक"
},
fr: {
0: "Faible",
1: "Modéré",
2: "Élevé",
3: "Très Élevé",
4: "Extrême"
},
de: {
0: "Niedrig",
1: "Mäßig",
2: "Hoch",
3: "Sehr Hoch",
4: "Extrem"
},
it: {
0: "Basso",
1: "Moderato",
2: "Alto",
3: "Molto Alto",
4: "Estremo"
},
pt: {
0: "Baixo",
1: "Moderado",
2: "Alto",
3: "Muito Alto",
4: "Extremo"
},
ru: {
0: "Низкий",
1: "Умеренный",
2: "Высокий",
3: "Очень Высокий",
4: "Экстремальный"
},
"zh-cn": {
0: "低",
1: "中等",
2: "高",
3: "很高",
4: "极高"
},
"zh-tw": {
0: "低",
1: "中等",
2: "高",
3: "很高",
4: "極高"
},
ja: {
0: "低い",
1: "中程度",
2: "高い",
3: "非常に高い",
4: "極端"
},
ko: {
0: "낮음",
1: "보통",
2: "높음",
3: "매우 높음",
4: "극심함"
},
nl: {
0: "Laag",
1: "Matig",
2: "Hoog",
3: "Zeer Hoog",
4: "Extreem"
},
ny: {
0: "Zochepa",
1: "Apakatikati",
2: "Wapamwamba",
3: "Wapamwamba Kwambiri",
4: "Mowopsa"
}
};
// Return the translation for the language code or default to English if not found
if (translations[languageCode]) {
return translations[languageCode][lavel] || "Unknown";
} else {
return "Language not supported";
}
}
function windSpeedText(languageCode) {
const translations = {
"es": "Velocidad del viento",
"en": "Wind Speed",
"hi": "हवा की गति",
"fr": "Vitesse du vent",
"de": "Windgeschwindigkeit",
"it": "Velocità del vento",
"pt": "Velocidade do vento",
"ru": "Скорость ветра",
"zh-cn": "风速",
"zh-tw": "風速",
"ja": "風速",
"ko": "풍속",
"nl": "Windsnelheid",
"ny": "Zachitentha"
};
const shortTranslations = {
"es": "Viento",
"en": "Wind",
"hi": "हवा",
"fr": "Vent",
"de": "Wind",
"it": "Vento",
"pt": "Vento",
"ru": "Ветер",
"zh-cn": "风",
"zh-tw": "風",
"ja": "風",
"ko": "바람",
"nl": "Wind",
"ny": "Mphepo"
};
// Get the full translation or default to English if not found
const fullTranslation = translations[languageCode] || translations["en"];
// Return the short translation if the full one is longer than 15 characters
if (fullTranslation.length > 15) {
return shortTranslations[languageCode] || shortTranslations["en"];
}
return fullTranslation;
}
function uvRadiationText(languageCode) {
const translations = {
"es": "UV",
"en": "UV",
"hi": "यूवी विकिरण",
"fr": "UV",
"de": "UV",
"it": "UV",
"pt": "UV",
"ru": "УФ-излучение",
"zh-cn": "紫外线辐射",
"zh-tw": "紫外線輻射",
"ja": "UV",
"ko": "자외선 방사",
"nl": "UV",
"ny": "UV"
};
// Return the translation for the language code or default to "UV" if not found
return translations[languageCode] || "UV";
}

View file

@ -0,0 +1,41 @@
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function getTranslateInJs(language, word) {
const translatesUi = {
cs: ["síť", "bluetooth", "offline", "nastavení", "nastavení systému", "vypnuto", "nerušit", "hlasitost", "předpověď počasí"],
da: ["netværk", "bluetooth", "offline", "indstillinger", "systemindstillinger", "fra", "forstyr ikke", "lydstyrke", "vejrudsigten"],
de: ["Netzwerk", "Bluetooth", "offline", "Einstellungen", "Systemeinstellungen", "aus", "nicht stören", "Lautstärke", "Wettervorhersage"],
en: ["network", "bluetooth", "offline", "settings", "system settings", "off", "don't disturb", "volume", "weather forecast"],
es: ["red", "bluetooth", "sin conexión", "configuración", "configuración del sistema", "apagado", "no molestar", "volumen", "pronóstico del tiempo"],
et: ["võrk", "bluetooth", "ühenduseta", "seaded", "süsteemi seaded", "väljas", "mitte segada", "helitugevus", "ilmaprognoos"],
fi: ["verkko", "bluetooth", "offline", "asetukset", "järjestelmäasetukset", "pois", "älä häiritse", "äänenvoimakkuus", "sääennuste"],
fr: ["réseau", "bluetooth", "hors ligne", "paramètres", "paramètres du système", "éteindre", "ne pas déranger", "volume", "prévisions météorologiques"],
hr: ["mreža", "bluetooth", "offline", "postavke", "postavke sustava", "isključeno", "ne ometaj", "glasnoća", "vremenska prognoza"],
hu: ["hálózat", "bluetooth", "offline", "beállítások", "rendszerbeállítások", "kikapcsolva", "ne zavarjanak", "hangerő", "időjárás előrejelzés"],
is: ["net", "bluetooth", "ótengdur", "stillingar", "kerfisstillingar", "af", "trufla ekki", "hljóðstyrkur", "veðurspá"],
it: ["rete", "bluetooth", "offline", "impostazioni", "impostazioni di sistema", "spento", "non disturbare", "volume", "previsioni del tempo"],
lt: ["tinklas", "bluetooth", "neprisijungęs", "nustatymai", "sistemos nustatymai", "išjungta", "netrukdyti", "garsas", "orų prognozė"],
lv: ["tīkls", "bluetooth", "bezsaistē", "iestatījumi", "sistēmas iestatījumi", "izslēgts", "netraucēt", "skaļums", "laika prognoze"],
nl: ["netwerk", "bluetooth", "offline", "instellingen", "systeeminstellingen", "uit", "niet storen", "volume", "weersvoorspelling"],
no: ["nettverk", "bluetooth", "offline", "innstillinger", "systeminnstillinger", "av", "ikke forstyrr", "volum", "værmelding"],
pl: ["sieć", "bluetooth", "offline", "ustawienia", "ustawienia systemowe", "wyłączony", "nie przeszkadzać", "głośność", "prognoza pogody"],
pt: ["rede", "bluetooth", "offline", "configurações", "configurações do sistema", "desligado", "não incomodar", "volume", "previsão do tempo"],
ro: ["rețea", "bluetooth", "offline", "setări", "setări de sistem", "oprit", "nu deranjați", "volum", "prognoza meteo"],
sk: ["sieť", "bluetooth", "offline", "nastavenia", "nastavenia systému", "vypnuté", "nerušiť", "hlasitosť", "predpoveď počasia"],
sl: ["omrežje", "bluetooth", "offline", "nastavitve", "sistemske nastavitve", "izklopljeno", "ne moti", "glasnost", "vremenska napoved"],
sq: ["rrjet", "bluetooth", "offline", "cilësimet", "cilësimet e sistemit", "fikur", "mos shqetësoni", "vëllimi", "parashikimi i motit"],
sv: ["nätverk", "bluetooth", "offline", "inställningar", "systeminställningar", "av", "stör ej", "volym", "väderprognos"]
};
const index = translatesUi['en'].indexOf(word.toLowerCase());
if (index !== -1) {
const translatedWord = translatesUi[language] ? translatesUi[language][index] : translatesUi["en"][index];
return capitalizeFirstLetter(translatedWord);
} else {
return capitalizeFirstLetter(word);
}
}

View file

@ -0,0 +1,209 @@
import QtQuick
import QtQuick.Layouts 1.1
import org.kde.plasma.plasmoid
import org.kde.plasma.core 2.0 as PlasmaCore
import "components" as Components
import org.kde.kirigami as Kirigami
import org.kde.ksvg as KSvg
PlasmoidItem {
id: wrapper
anchors.fill: parent
Components.WeatherData {
id: weatherData
}
signal reset
//property bool dashWindowIsFocus: true
property string currentTemp: weatherData.currentTemperature
property string unitsTemperature: plasmoid.configuration.temperatureUnit
//property string textUnitsTemper: ? "C" : "F"
property string location: weatherData.city
property string weather: weatherData.weatherShottext
property string currentIcon: weatherData.iconWeatherCurrent
property string currentMaxMin: weatherData.maxweatherCurrent + "°/" + weatherData.minweatherCurrent + "°"
property var temps: weatherData.tempHours
property var icons: weatherData.iconHours
property alias forecastHours: hoursWeatherModel
property alias forecastFullModel: forecastModel
property bool isUpdate: false
property date currentDateTime: new Date()
readonly property int currentDayOfWeek: currentDateTime.getDay()
ListModel {
id: hoursWeatherModel
}
ListModel {
id: forecastModel
}
function getTranslatedDayInitial(dayIndex) {
var tempDate = new Date(currentDateTime);
tempDate.setDate(tempDate.getDate() + dayIndex);
return tempDate.toLocaleString(Qt.locale(), "dddd");
}
function hoursForModel(v) {
const now = new Date();
const hoursC = now.getHours(); // Horas (0-23)
const minutes = now.getMinutes(); // Minutos (0-59)
const currentTime = minutes > 44 ? hoursC + 2 : hoursC + 1;
var hoursForecast = [currentTime, currentTime + 1, currentTime + 2, currentTime + 3, currentTime + 4]
return hoursForecast[v]
}
function hoursForecast() {
hoursWeatherModel.clear()
for (var i = 0; i < 5; i++) {
hoursWeatherModel.append({
icon: icons[i],
temp: temps[i],
hours: hoursForModel(i)
});
}
}
function hoursForecastUpdate() {
for (var o = 0; o < hoursWeatherModel.count; o++) {
hoursWeatherModel.set(o, { "icon": icons[o] });
hoursWeatherModel.set(o, { "temp": String(parseFloat(temps[o])) });
hoursWeatherModel.set(o, { "hours": hoursForModel(o) });
}
}
function updateUnitsTempe() {
let Maxs = {
0: weatherData.oneMax,
1: weatherData.twoMax,
2: weatherData.threeMax,
3: weatherData.fourMax,
4: weatherData.fiveMax,
}
let Mins = {
0: weatherData.oneMin,
1: weatherData.twoMin,
2: weatherData.threeMin,
3: weatherData.fourMin,
4: weatherData.fiveMin,
}
for (var z = 0; z < forecastModel.count; z++) {
forecastModel.set(z, { "maxTemp": Maxs[z], "minTemp": Mins[z] })
}
for (var e = 0; e < hoursWeatherModel.count; e++) {
var roles = hoursWeatherModel.get(e);
console.log("Roles for index " + e + ":", JSON.stringify(roles));
// Convierte temps[e] a cadena antes de asignarlo
var gy = String(parseFloat(temps[e]));
hoursWeatherModel.set(e, { "temp": gy });
}
}
Timer {
id: checkUpdateTimer
interval: 5000 // 20 segundos
repeat: true
running: true
onTriggered: {
if (weatherData.lastUpdate !== "") {
let now = new Date()
let lastUpdateDate = new Date(weatherData.lastUpdate) // Crear objeto Date desde la cadena almacenada
let diffMinutes = (now - lastUpdateDate) / 60000 // Convertir la diferencia a minutos
if (diffMinutes > 17) {
forms()
}
}
}
}
function updateForecastModel() {
let icons = {
0: weatherData.oneIcon,
1: weatherData.twoIcon,
2: weatherData.threeIcon,
3: weatherData.fourIcon,
4: weatherData.fiveIcon,
}
let Maxs = {
0: weatherData.oneMax,
1: weatherData.twoMax,
2: weatherData.threeMax,
3: weatherData.fourMax,
4: weatherData.fiveMax,
}
let Mins = {
0: weatherData.oneMin,
1: weatherData.twoMin,
2: weatherData.threeMin,
3: weatherData.fourMin,
4: weatherData.fiveMin,
}
forecastModel.clear();
for (var i = 1; i < 4; i++) {
var icon = icons[i]
var maxTemp = Maxs[i]
var minTemp = Mins[i]
var date = getTranslatedDayInitial(i)
forecastModel.append({
date: date,
icon: icon,
maxTemp: maxTemp,
minTemp: minTemp
});
}
}
function forms() {
if (isUpdate) {
currentDateTime = new Date()
hoursForecastUpdate()
updateForecastModel()
} else {
currentDateTime = new Date()
hoursForecast()
updateForecastModel()
isUpdate = true
}
}
onUnitsTemperatureChanged: {
//hoursForecast()
updateUnitsTempe()
}
Component.onCompleted: {
weatherData.dataChanged.connect(() => {
Qt.callLater(forms); // Asegura que la función se ejecute al final del ciclo de eventos
});
}
preferredRepresentation: compactRepresentation
compactRepresentation: compactRepresentation
fullRepresentation: compactRepresentation
Component {
id: compactRepresentation
CompactRepresentation {}
}
}