1
0
mirror of https://github.com/AvengeMedia/DankMaterialShell.git synced 2026-01-28 07:22:50 -05:00

weather: initial support for overriding location

This commit is contained in:
bbedward
2025-07-15 17:13:24 -04:00
parent 13ef607758
commit ac2c327bbb
5 changed files with 722 additions and 120 deletions

View File

@@ -19,6 +19,8 @@ Singleton {
property bool useFahrenheit: false property bool useFahrenheit: false
property bool nightModeEnabled: false property bool nightModeEnabled: false
property string profileImage: "" property string profileImage: ""
property bool weatherLocationOverrideEnabled: false
property string weatherLocationOverride: ""
// Widget visibility preferences for TopBar // Widget visibility preferences for TopBar
property bool showFocusedWindow: true property bool showFocusedWindow: true
@@ -82,6 +84,8 @@ Singleton {
useFahrenheit = settings.useFahrenheit !== undefined ? settings.useFahrenheit : false useFahrenheit = settings.useFahrenheit !== undefined ? settings.useFahrenheit : false
nightModeEnabled = settings.nightModeEnabled !== undefined ? settings.nightModeEnabled : false nightModeEnabled = settings.nightModeEnabled !== undefined ? settings.nightModeEnabled : false
profileImage = settings.profileImage !== undefined ? settings.profileImage : "" profileImage = settings.profileImage !== undefined ? settings.profileImage : ""
weatherLocationOverrideEnabled = settings.weatherLocationOverrideEnabled !== undefined ? settings.weatherLocationOverrideEnabled : false
weatherLocationOverride = settings.weatherLocationOverride !== undefined ? settings.weatherLocationOverride : ""
showFocusedWindow = settings.showFocusedWindow !== undefined ? settings.showFocusedWindow : true showFocusedWindow = settings.showFocusedWindow !== undefined ? settings.showFocusedWindow : true
showWeather = settings.showWeather !== undefined ? settings.showWeather : true showWeather = settings.showWeather !== undefined ? settings.showWeather : true
showMusic = settings.showMusic !== undefined ? settings.showMusic : true showMusic = settings.showMusic !== undefined ? settings.showMusic : true
@@ -115,6 +119,8 @@ Singleton {
useFahrenheit, useFahrenheit,
nightModeEnabled, nightModeEnabled,
profileImage, profileImage,
weatherLocationOverrideEnabled,
weatherLocationOverride,
showFocusedWindow, showFocusedWindow,
showWeather, showWeather,
showMusic, showMusic,
@@ -296,4 +302,17 @@ Singleton {
spotlightLauncherViewMode = mode spotlightLauncherViewMode = mode
saveSettings() saveSettings()
} }
// Weather location override setters
function setWeatherLocationOverrideEnabled(enabled) {
console.log("Prefs setWeatherLocationOverrideEnabled called - weatherLocationOverrideEnabled:", enabled)
weatherLocationOverrideEnabled = enabled
saveSettings()
}
function setWeatherLocationOverride(location) {
console.log("Prefs setWeatherLocationOverride called - weatherLocationOverride:", location)
weatherLocationOverride = location
saveSettings()
}
} }

View File

@@ -12,13 +12,14 @@ Specifically created for [Niri](https://github.com/YaLTeR/niri).
```bash ```bash
# Arch # Arch
paru -S quickshell-git nerd-fonts ttf-material-symbols-variable-git matugen cliphist cava wl-clipboard ddcutil paru -S quickshell-git nerd-fonts ttf-material-symbols-variable-git matugen cliphist cava wl-clipboard ddcutil qt6-5compat
# Some dependencies are optional # Some dependencies are optional
# - cava for audio visualizer, without it music will just randomly visualize # - cava for audio visualizer, without it music will just randomly visualize
# - cliphist for clipboard history # - cliphist for clipboard history
# - matugen for dynamic themes based on wallpaper # - matugen for dynamic themes based on wallpaper
# - ddcutil for brightness changing # - ddcutil for brightness changing
# - qt6-5compat - havent been able to figure out circular cropping pictures without it.
``` ```
2. Configure SwayBG (Optional) 2. Configure SwayBG (Optional)

View File

@@ -1,6 +1,7 @@
import QtQuick import QtQuick
import Quickshell import Quickshell
import Quickshell.Io import Quickshell.Io
import "../Common"
pragma Singleton pragma Singleton
pragma ComponentBehavior: Bound pragma ComponentBehavior: Bound
@@ -22,6 +23,13 @@ Singleton {
pressure: 0 pressure: 0
}) })
property int updateInterval: 600000 // 10 minutes
property int retryAttempts: 0
property int maxRetryAttempts: 3
property int retryDelay: 30000 // 30 seconds
property int lastFetchTime: 0
property int minFetchInterval: 30000 // 30 seconds minimum between fetches
// Weather icon mapping (based on wttr.in weather codes) // Weather icon mapping (based on wttr.in weather codes)
property var weatherIcons: ({ property var weatherIcons: ({
"113": "clear_day", "113": "clear_day",
@@ -78,9 +86,68 @@ Singleton {
return weatherIcons[code] || "cloud" return weatherIcons[code] || "cloud"
} }
function getWeatherUrl() {
if (Prefs.weatherLocationOverrideEnabled && Prefs.weatherLocationOverride) {
const url = `wttr.in/${encodeURIComponent(Prefs.weatherLocationOverride)}?format=j1`
console.log("Using override location:", Prefs.weatherLocationOverride, "URL:", url)
return url
}
console.log("Using auto-detected location")
return "wttr.in/?format=j1"
}
function fetchWeather() {
if (weatherFetcher.running) {
console.log("Weather fetch already in progress, skipping")
return
}
// Check if we've fetched recently to prevent spam
const now = Date.now()
if (now - root.lastFetchTime < root.minFetchInterval) {
console.log("Weather fetch throttled, too soon since last fetch")
return
}
console.log("Fetching weather from:", getWeatherUrl())
root.lastFetchTime = now
root.weather.loading = true
weatherFetcher.command = ["bash", "-c", `curl -s --connect-timeout 10 --max-time 30 '${getWeatherUrl()}'`]
weatherFetcher.running = true
}
function forceRefresh() {
console.log("Force refreshing weather")
root.lastFetchTime = 0 // Reset throttle
fetchWeather()
}
function handleWeatherSuccess() {
root.retryAttempts = 0
// Don't restart the timer - let it continue its normal interval
if (updateTimer.interval !== root.updateInterval) {
updateTimer.interval = root.updateInterval
}
}
function handleWeatherFailure() {
root.retryAttempts++
if (root.retryAttempts < root.maxRetryAttempts) {
console.log(`Weather fetch failed, retrying in ${root.retryDelay/1000}s (attempt ${root.retryAttempts}/${root.maxRetryAttempts})`)
retryTimer.start()
} else {
console.warn("Weather fetch failed after maximum retry attempts")
root.weather.available = false
root.weather.loading = false
root.retryAttempts = 0
// Set longer interval for next automatic retry
updateTimer.interval = root.updateInterval * 2
}
}
Process { Process {
id: weatherFetcher id: weatherFetcher
command: ["bash", "-c", "curl -s 'wttr.in/?format=j1'"] command: ["bash", "-c", `curl -s --connect-timeout 10 --max-time 30 '${root.getWeatherUrl()}'`]
running: false running: false
stdout: StdioCollector { stdout: StdioCollector {
@@ -88,7 +155,7 @@ Singleton {
const raw = text.trim() const raw = text.trim()
if (!raw || raw[0] !== "{") { if (!raw || raw[0] !== "{") {
console.warn("No valid weather data received") console.warn("No valid weather data received")
root.weather.available = false root.handleWeatherFailure()
return return
} }
@@ -120,11 +187,12 @@ Singleton {
console.log("Weather updated:", root.weather.city, console.log("Weather updated:", root.weather.city,
`${root.weather.temp}°C`) `${root.weather.temp}°C`)
root.handleWeatherSuccess()
} catch (e) { } catch (e) {
console.warn("Failed to parse weather data:", e.message) console.warn("Failed to parse weather data:", e.message)
root.weather.available = false root.handleWeatherFailure()
root.weather.loading = false
} }
} }
} }
@@ -132,19 +200,44 @@ Singleton {
onExited: (exitCode) => { onExited: (exitCode) => {
if (exitCode !== 0) { if (exitCode !== 0) {
console.warn("Weather fetch failed with exit code:", exitCode) console.warn("Weather fetch failed with exit code:", exitCode)
root.weather.available = false root.handleWeatherFailure()
root.weather.loading = false
} }
} }
} }
Timer { Timer {
interval: 600000 // 10 minutes id: updateTimer
interval: root.updateInterval
running: true running: true
repeat: true repeat: true
triggeredOnStart: true triggeredOnStart: true
onTriggered: { onTriggered: {
weatherFetcher.running = true root.fetchWeather()
} }
} }
Timer {
id: retryTimer
interval: root.retryDelay
running: false
repeat: false
onTriggered: {
root.fetchWeather()
}
}
Component.onCompleted: {
// Watch for preference changes to refetch weather
Prefs.weatherLocationOverrideChanged.connect(() => {
if (Prefs.weatherLocationOverrideEnabled && Prefs.weatherLocationOverride.length > 0) {
console.log("Weather location override changed, force refreshing weather")
Qt.callLater(root.forceRefresh)
}
})
Prefs.weatherLocationOverrideEnabledChanged.connect(() => {
console.log("Weather location override enabled/disabled, force refreshing weather")
Qt.callLater(root.forceRefresh)
})
}
} }

View File

@@ -1,6 +1,6 @@
import QtQuick import QtQuick
import QtQuick.Controls import QtQuick.Controls
import QtQuick.Effects import Qt5Compat.GraphicalEffects
import Quickshell import Quickshell
import Quickshell.Widgets import Quickshell.Widgets
import Quickshell.Wayland import Quickshell.Wayland
@@ -104,9 +104,7 @@ PanelWindow {
easing.type: Theme.emphasizedEasing easing.type: Theme.emphasizedEasing
} }
} }
// Height animation handled by states below for better performance
Column { Column {
anchors.fill: parent anchors.fill: parent
anchors.margins: Theme.spacingL anchors.margins: Theme.spacingL
@@ -117,7 +115,6 @@ PanelWindow {
width: parent.width width: parent.width
spacing: Theme.spacingL spacing: Theme.spacingL
// User Info Section - Jony Ive inspired
Rectangle { Rectangle {
width: parent.width width: parent.width
height: 90 height: 90
@@ -133,76 +130,64 @@ PanelWindow {
anchors.rightMargin: Theme.spacingL anchors.rightMargin: Theme.spacingL
spacing: Theme.spacingL spacing: Theme.spacingL
// Profile Picture Container // Profile Picture Container with circular outline
Item { Rectangle {
width: 64 width: 64
height: 64 height: 64
radius: width / 2
color: "transparent"
border.color: Qt.rgba(0, 0, 0, 0.15)
border.width: 1
property bool hasImage: Prefs.profileImage !== "" && profileImage.status !== Image.Error // Hidden image for OpacityMask source
Image {
// Background circle for fallback icon id: profileImage
Rectangle {
anchors.fill: parent anchors.fill: parent
radius: 32 anchors.margins: 5 // Inset by border width
color: Theme.primary fillMode: Image.PreserveAspectCrop
visible: !parent.hasImage smooth: true
} asynchronous: true
mipmap: true
// Circular clipping container for profile image cache: true
ClippingRectangle { sourceSize.width: 128
anchors.fill: parent sourceSize.height: 128
anchors.margins: 1 visible: false // Hidden, only used as mask source
radius: width / 2 source: {
antialiasing: true if (Prefs.profileImage === "") return ""
color: "transparent" // Add file:// prefix if it's a local path (starts with /)
visible: parent.hasImage if (Prefs.profileImage.startsWith("/")) {
return "file://" + Prefs.profileImage
Image {
id: profileImage
anchors.fill: parent
source: {
if (Prefs.profileImage === "") return ""
// Add file:// prefix if it's a local path (starts with /)
if (Prefs.profileImage.startsWith("/")) {
return "file://" + Prefs.profileImage
}
// Return as-is if it already has a protocol or is a web URL
return Prefs.profileImage
} }
fillMode: Image.PreserveAspectCrop // Return as-is if it already has a protocol or is a web URL
smooth: false // Disable smooth scaling during animations for performance return Prefs.profileImage
asynchronous: true
mipmap: false // Disable mipmap for better performance
cache: true // Enable caching to prevent reloads
// Optimize source size to prevent unnecessary scaling
sourceSize.width: 64
sourceSize.height: 64
} }
} }
// Subtle circular outline for images // OpacityMask inset by 1px to leave border visible
Rectangle { OpacityMask {
anchors.fill: parent anchors.fill: profileImage
radius: 32 visible: Prefs.profileImage !== "" && profileImage.status !== Image.Error
color: "transparent" source: profileImage
border.color: Qt.rgba(0, 0, 0, 0.15) // Subtle dark outline
border.width: 1 maskSource: Rectangle {
visible: parent.hasImage width: profileImage.width
height: profileImage.height
radius: width / 2
color: "white"
visible: false
}
} }
// Highlight ring to make it pop // Fallback background for no image
Rectangle { Rectangle {
anchors.fill: parent anchors.fill: parent
anchors.margins: -1 anchors.margins: 2
radius: 33 radius: width / 2
color: "transparent" color: Theme.primary
border.color: Qt.rgba(255, 255, 255, 0.1) // Subtle light ring visible: Prefs.profileImage === ""
border.width: 1
visible: parent.hasImage
} }
// Fallback icon for no profile picture (generic person) // Fallback icon for no profile picture
Text { Text {
anchors.centerIn: parent anchors.centerIn: parent
text: "person" text: "person"

View File

@@ -166,82 +166,73 @@ PanelWindow {
spacing: Theme.spacingM spacing: Theme.spacingM
// Circular profile image preview // Circular profile image preview
Item { Rectangle {
id: avatarBox id: avatarContainer
width: 54 width: 54
height: 54 height: 54
radius: width / 2
color: Theme.primary
clip: true
property bool hasImage: profileImageInput.text !== "" && avatarImage.status !== Image.Error property bool hasImage: profileImageInput.text !== "" && avatarImage.status !== Image.Error
/* 1 px inner padding; change both "1" values to "2" for 2 px */ Image {
ClippingRectangle { id: avatarImage
id: avatarClip
anchors.fill: parent anchors.fill: parent
anchors.margins: 1 // ← inner gap between photo & ring anchors.margins: 1
radius: width / 2 // = perfect circle fillMode: Image.PreserveAspectCrop
antialiasing: true // smooth edge source: profileImageInput.text.startsWith("/")
color: "transparent" ? "file://" + profileImageInput.text
visible: avatarBox.hasImage // show only when we have a real photo : profileImageInput.text
smooth: true
Image { asynchronous: true
id: avatarImage mipmap: true
anchors.fill: parent cache: true
fillMode: Image.PreserveAspectCrop sourceSize.width: 128
source: profileImageInput.text.startsWith("/") sourceSize.height: 128
? "file://" + profileImageInput.text visible: avatarContainer.hasImage
: profileImageInput.text
smooth: true property string lastLoggedSource: ""
asynchronous: true
mipmap: true onStatusChanged: {
cache: true if (source !== lastLoggedSource && (status === Image.Ready || status === Image.Error)) {
lastLoggedSource = source
property string lastLoggedSource: "" if (status === Image.Ready) {
console.log("Profile image loaded successfully, size:", sourceSize.width + "x" + sourceSize.height)
onStatusChanged: { } else if (status === Image.Error) {
if (source !== lastLoggedSource && (status === Image.Ready || status === Image.Error)) { console.log("Profile image failed to load:", source)
lastLoggedSource = source
if (status === Image.Ready) {
console.log("Profile image loaded successfully, size:", sourceSize.width + "x" + sourceSize.height)
} else if (status === Image.Error) {
console.log("Profile image failed to load:", source)
}
} }
} }
} }
} }
/* Fallback / error icon */ // Fallback icon
Rectangle {
anchors.fill: parent
radius: width / 2
color: Theme.primary
visible: !avatarBox.hasImage
}
Text { Text {
anchors.centerIn: parent anchors.centerIn: parent
text: profileImageInput.text === "" ? "person" : "warning" text: profileImageInput.text === "" ? "person" : "warning"
font.family: Theme.iconFont font.family: Theme.iconFont
font.pixelSize: Theme.iconSize + 8 font.pixelSize: Theme.iconSize + 8
color: Theme.primaryText color: Theme.primaryText
visible: !avatarBox.hasImage visible: !avatarContainer.hasImage
} }
/* Decorative rings (drawn only when a real image is shown) */ // Decorative rings
Rectangle { // dark outline Rectangle {
anchors.fill: parent anchors.fill: parent
radius: width / 2 radius: width / 2
border.color: Qt.rgba(0, 0, 0, 0.15) border.color: Qt.rgba(0, 0, 0, 0.15)
border.width: 1 border.width: 1
color: "transparent" color: "transparent"
visible: avatarBox.hasImage visible: avatarContainer.hasImage
} }
Rectangle { // light highlight Rectangle {
anchors.fill: parent anchors.fill: parent
anchors.margins: -1 // hugs just outside the dark outline anchors.margins: -1
radius: width / 2 + 1 radius: width / 2 + 1
border.color: Qt.rgba(255, 255, 255, 0.1) border.color: Qt.rgba(255, 255, 255, 0.1)
border.width: 1 border.width: 1
color: "transparent" color: "transparent"
visible: avatarBox.hasImage visible: avatarContainer.hasImage
} }
} }
@@ -336,6 +327,379 @@ PanelWindow {
checked: Prefs.useFahrenheit checked: Prefs.useFahrenheit
onToggled: (checked) => Prefs.setTemperatureUnit(checked) onToggled: (checked) => Prefs.setTemperatureUnit(checked)
} }
// Weather Location Override
Column {
width: parent.width
spacing: Theme.spacingM
SettingsToggle {
text: "Override Location"
description: "Use a specific location instead of auto-detection"
checked: Prefs.weatherLocationOverrideEnabled
onToggled: (checked) => Prefs.setWeatherLocationOverrideEnabled(checked)
}
// Location input - only visible when override is enabled
Column {
width: parent.width
spacing: Theme.spacingS
visible: Prefs.weatherLocationOverrideEnabled
opacity: visible ? 1.0 : 0.0
Behavior on opacity {
NumberAnimation {
duration: Theme.mediumDuration
easing.type: Theme.emphasizedEasing
}
}
Text {
text: "Location"
font.pixelSize: Theme.fontSizeMedium
color: Theme.surfaceText
font.weight: Font.Medium
}
// Weather Location Search Component
Item {
width: parent.width
height: searchInputField.height + (searchDropdown.visible ? searchDropdown.height : 0)
Timer {
id: locationSearchTimer
interval: 500
running: false
repeat: false
onTriggered: {
if (weatherLocationInput.text.length > 2 && !locationSearcher.running) {
// Clear previous results before starting new search
locationSearchResults.searchResults = 0
locationSearchResults.searchResultNames = new Array()
locationSearchResults.searchResultQueries = new Array()
locationSearchResults.isLoading = true
locationSearchResults.currentQuery = weatherLocationInput.text
const searchLocation = weatherLocationInput.text
console.log("=== Starting location search for:", searchLocation)
// Use OpenStreetMap Nominatim API for location search
const encodedLocation = encodeURIComponent(searchLocation)
const curlCommand = `curl -s --connect-timeout 5 --max-time 10 'https://nominatim.openstreetmap.org/search?q=${encodedLocation}&format=json&limit=5&addressdetails=1'`
console.log("Running command:", curlCommand)
locationSearcher.command = ["bash", "-c", curlCommand]
locationSearcher.running = true
} else if (locationSearcher.running) {
console.log("Location search already running, skipping")
}
}
}
Timer {
id: dropdownHideTimer
interval: 1000 // Even longer delay
running: false
repeat: false
onTriggered: {
console.log("Hide timer triggered, hiding dropdown")
searchDropdown.visible = false
}
}
// Search input field
Rectangle {
id: searchInputField
width: parent.width
height: 48
radius: Theme.cornerRadius
color: Theme.surfaceVariant
border.color: weatherLocationInput.activeFocus ? Theme.primary : Qt.rgba(Theme.outline.r, Theme.outline.g, Theme.outline.b, 0.3)
border.width: weatherLocationInput.activeFocus ? 2 : 1
Row {
anchors.fill: parent
anchors.margins: Theme.spacingM
spacing: Theme.spacingS
Text {
width: 20
height: parent.height
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
font.family: Theme.iconFont
font.pixelSize: Theme.iconSize - 4
color: Theme.surfaceVariantText
text: "search"
}
TextInput {
id: weatherLocationInput
width: parent.width - 40 - Theme.spacingS * 2
height: parent.height
verticalAlignment: TextInput.AlignVCenter
color: Theme.surfaceText
font.pixelSize: Theme.fontSizeMedium
text: Prefs.weatherLocationOverride
selectByMouse: true
onTextChanged: {
console.log("Text changed to:", text, "length:", text.length)
if (text.length > 2) {
// Don't clear results immediately when starting a new search
// Only set loading state and restart timer
locationSearchResults.isLoading = true
locationSearchTimer.restart()
searchDropdown.visible = true
console.log("Starting new search, dropdown visible:", searchDropdown.visible)
} else {
locationSearchTimer.stop()
searchDropdown.visible = false
locationSearchResults.searchResults = 0
locationSearchResults.searchResultNames = new Array()
locationSearchResults.searchResultQueries = new Array()
locationSearchResults.isLoading = false
console.log("Text too short, hiding dropdown")
}
}
onEditingFinished: {
if (!searchDropdown.visible) {
Prefs.setWeatherLocationOverride(text)
}
}
onActiveFocusChanged: {
console.log("Input focus changed:", activeFocus, "dropdown hovered:", searchDropdown.hovered, "aboutToClick:", searchDropdown.aboutToClick, "results count:", locationSearchResults.searchResults)
// Start timer on focus loss, but only if dropdown is visible
if (!activeFocus && !searchDropdown.hovered && !searchDropdown.aboutToClick && searchDropdown.visible) {
console.log("Starting hide timer due to focus loss")
dropdownHideTimer.start()
} else if (activeFocus) {
console.log("Canceling hide timer due to focus gain")
dropdownHideTimer.stop()
}
}
// Placeholder text
Text {
anchors.verticalCenter: parent.verticalCenter
text: "Search for a location..."
color: Qt.rgba(Theme.surfaceVariantText.r, Theme.surfaceVariantText.g, Theme.surfaceVariantText.b, 0.6)
font.pixelSize: Theme.fontSizeMedium
visible: weatherLocationInput.text.length === 0 && !weatherLocationInput.activeFocus
}
MouseArea {
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.IBeamCursor
acceptedButtons: Qt.NoButton
}
}
// Status icon
Text {
width: 20
height: parent.height
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
font.family: Theme.iconFont
font.pixelSize: Theme.iconSize - 4
color: {
if (locationSearchResults.isLoading) return Theme.surfaceVariantText
if (locationSearchResults.searchResults > 0) return Theme.success || Theme.primary
if (weatherLocationInput.text.length > 2) return Theme.error
return "transparent"
}
text: {
if (locationSearchResults.isLoading) return "hourglass_empty"
if (locationSearchResults.searchResults > 0) return "check_circle"
if (weatherLocationInput.text.length > 2) return "error"
return ""
}
opacity: weatherLocationInput.text.length > 2 ? 1.0 : 0.0
Behavior on opacity {
NumberAnimation {
duration: Theme.shortDuration
easing.type: Theme.standardEasing
}
}
}
}
}
// Search results dropdown
Rectangle {
id: searchDropdown
width: parent.width
height: Math.min(searchResultsColumn.height + Theme.spacingS * 2, 200)
y: searchInputField.height
radius: Theme.cornerRadius
color: Theme.popupBackground()
border.color: Qt.rgba(Theme.outline.r, Theme.outline.g, Theme.outline.b, 0.3)
border.width: 1
visible: false
property bool hovered: false
property bool aboutToClick: false
onVisibleChanged: {
console.log("Dropdown visibility changed:", visible)
if (!visible) {
console.log("Dropdown hidden, current results count:", locationSearchResults.searchResults)
}
}
MouseArea {
anchors.fill: parent
hoverEnabled: true
onEntered: {
console.log("Dropdown hovered, canceling hide timer")
parent.hovered = true
dropdownHideTimer.stop()
}
onExited: {
console.log("Dropdown hover exited")
parent.hovered = false
if (!weatherLocationInput.activeFocus) {
console.log("Starting hide timer due to hover exit")
dropdownHideTimer.start()
}
}
acceptedButtons: Qt.NoButton
}
ScrollView {
anchors.fill: parent
anchors.margins: Theme.spacingS
clip: true
Column {
id: searchResultsColumn
width: parent.width
spacing: 2
Repeater {
model: locationSearchResults.searchResults
onModelChanged: {
console.log("Repeater model changed, new count:", model)
console.log("Names array length:", locationSearchResults.searchResultNames.length)
console.log("Queries array length:", locationSearchResults.searchResultQueries.length)
}
Rectangle {
width: parent.width
height: 36
radius: Theme.cornerRadius
color: resultMouseArea.containsMouse ? Qt.rgba(Theme.primary.r, Theme.primary.g, Theme.primary.b, 0.1) : "transparent"
Row {
anchors.fill: parent
anchors.margins: Theme.spacingM
spacing: Theme.spacingS
Text {
font.family: Theme.iconFont
font.pixelSize: Theme.iconSize - 6
color: Theme.surfaceVariantText
text: "place"
anchors.verticalCenter: parent.verticalCenter
}
Text {
text: locationSearchResults.searchResultNames[index] || "Unknown"
font.pixelSize: Theme.fontSizeMedium
color: Theme.surfaceText
anchors.verticalCenter: parent.verticalCenter
elide: Text.ElideRight
width: parent.width - 30
}
}
MouseArea {
id: resultMouseArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onPressed: {
searchDropdown.aboutToClick = true
}
onClicked: {
const selectedName = locationSearchResults.searchResultNames[index]
const selectedQuery = locationSearchResults.searchResultQueries[index]
// Clear search state first
dropdownHideTimer.stop()
searchDropdown.aboutToClick = false
locationSearchResults.searchResults = 0
locationSearchResults.searchResultNames = new Array()
locationSearchResults.searchResultQueries = new Array()
locationSearchResults.isLoading = false
weatherLocationInput.text = selectedName
searchDropdown.visible = false
Prefs.setWeatherLocationOverride(selectedQuery)
console.log("Selected location:", selectedName, "Query:", selectedQuery)
}
onCanceled: {
searchDropdown.aboutToClick = false
}
}
}
}
// No results message
Text {
width: parent.width
height: 36
text: locationSearchResults.isLoading ? "Searching..." : "No locations found"
font.pixelSize: Theme.fontSizeMedium
color: Theme.surfaceVariantText
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
visible: locationSearchResults.searchResults === 0 && weatherLocationInput.text.length > 2 && !locationSearchResults.isLoading
}
}
}
}
}
Text {
text: {
if (locationSearchResults.searchResults > 0) {
return `${locationSearchResults.searchResults} location${locationSearchResults.searchResults > 1 ? 's' : ''} found. Click to select.`
} else if (locationSearchResults.isLoading) {
return "Searching for locations..."
} else if (weatherLocationInput.text.length > 2) {
return "No locations found. Try a different search term."
} else {
return "Examples: \"New York\", \"Tokyo\", \"44511\""
}
}
font.pixelSize: Theme.fontSizeSmall
color: {
if (locationSearchResults.searchResults > 0) {
return Theme.success || Theme.primary
} else if (locationSearchResults.isLoading) {
return Theme.surfaceVariantText
} else if (weatherLocationInput.text.length > 2) {
return Theme.error
} else {
return Theme.surfaceVariantText
}
}
wrapMode: Text.WordWrap
width: parent.width
}
}
}
} }
} }
@@ -559,6 +923,146 @@ PanelWindow {
} }
} }
// Weather location search results
QtObject {
id: locationSearchResults
property var searchResults: []
property var searchResultNames: []
property var searchResultQueries: []
property bool isLoading: false
property string currentQuery: ""
}
// Weather location validation
QtObject {
id: locationValidationStatus
property string validationState: "none" // "none", "validating", "valid", "invalid"
property string lastValidatedLocation: ""
property string validatedLocationName: ""
}
Process {
id: locationSearcher
command: ["bash", "-c", "echo"]
running: false
stdout: StdioCollector {
onStreamFinished: {
const raw = text.trim()
locationSearchResults.isLoading = false
console.log("=== Location search response received")
console.log("Response length:", raw.length)
console.log("Response preview:", raw.substring(0, 300))
if (!raw) {
console.log("Empty response from location search")
locationSearchResults.searchResults = 0
locationSearchResults.searchResultNames = new Array()
locationSearchResults.searchResultQueries = new Array()
return
}
if (raw[0] !== "[") {
console.log("Non-JSON array response from location search:", raw)
locationSearchResults.searchResults = 0
locationSearchResults.searchResultNames = new Array()
locationSearchResults.searchResultQueries = new Array()
return
}
try {
const data = JSON.parse(raw)
console.log("Parsed JSON array length:", data.length)
if (data.length === 0) {
console.log("No locations found in search results")
locationSearchResults.searchResults = 0
// Force new empty arrays to trigger QML reactivity
locationSearchResults.searchResultNames = new Array()
locationSearchResults.searchResultQueries = new Array()
console.log("Cleared arrays - Names length:", locationSearchResults.searchResultNames.length, "Queries length:", locationSearchResults.searchResultQueries.length)
return
}
const results = []
for (let i = 0; i < Math.min(data.length, 5); i++) {
const location = data[i]
console.log(`Location ${i}:`, {
display_name: location.display_name,
lat: location.lat,
lon: location.lon,
type: location.type,
class: location.class
})
if (location.display_name && location.lat && location.lon) {
// Create a clean location name from display_name
const parts = location.display_name.split(', ')
let cleanName = parts[0] // Start with the first part
// Add state/region if available and different from first part
if (parts.length > 1) {
const state = parts[parts.length - 2] // Usually the state is second to last
if (state && state !== cleanName) {
cleanName += `, ${state}`
}
}
// Use coordinates as the query for wttr.in (most reliable)
const query = `${location.lat},${location.lon}`
const result = {
"name": cleanName,
"query": query
}
results.push(result)
console.log(`Added result ${i}: name="${cleanName}" query="${query}"`)
} else {
console.log(`Skipped location ${i}: missing required fields`)
}
}
console.log("=== Final results array:", results)
// Create separate arrays for names and queries
const names = []
const queries = []
for (let i = 0; i < results.length; i++) {
names.push(results[i].name)
queries.push(results[i].query)
}
// Set all arrays atomically
locationSearchResults.searchResultNames = names
locationSearchResults.searchResultQueries = queries
locationSearchResults.searchResults = results.length // Just use count for now
console.log("Location search completed:", results.length, "results set")
console.log("Names:", names)
console.log("Queries:", queries)
} catch (e) {
console.log("Location search JSON parse error:", e.message)
console.log("Raw response:", raw.substring(0, 500))
locationSearchResults.searchResults = 0
locationSearchResults.searchResultNames = new Array()
locationSearchResults.searchResultQueries = new Array()
}
}
}
onExited: (exitCode) => {
locationSearchResults.isLoading = false
if (exitCode !== 0) {
console.log("Location search process failed with exit code:", exitCode)
locationSearchResults.searchResults = []
}
}
}
// Keyboard focus and shortcuts // Keyboard focus and shortcuts
FocusScope { FocusScope {
anchors.fill: parent anchors.fill: parent