WiFi: improved UI and service

This commit is contained in:
LemmyCook 2025-09-05 08:36:36 -04:00
parent 35283a6923
commit b9c1a8a54f
2 changed files with 827 additions and 562 deletions

View file

@ -10,18 +10,17 @@ import qs.Widgets
NPanel { NPanel {
id: root id: root
panelWidth: 380 * scaling panelWidth: 440 * scaling
panelHeight: 500 * scaling panelHeight: 500 * scaling
// Enable keyboard focus for WiFi panel (needed for password input)
panelKeyboardFocus: true panelKeyboardFocus: true
property string passwordPromptSsid: "" property string passwordPromptSsid: ""
property string passwordInput: "" property string passwordInput: ""
property bool showPasswordPrompt: false property bool showPasswordPrompt: false
property string expandedNetwork: "" // Track which network shows options
onOpened: { onOpened: {
if (Settings.data.network.wifiEnabled && wifiPanel.visible) { if (Settings.data.network.wifiEnabled) {
NetworkService.refreshNetworks() NetworkService.refreshNetworks()
} }
} }
@ -37,6 +36,7 @@ NPanel {
// Header // Header
RowLayout { RowLayout {
Layout.fillWidth: true Layout.fillWidth: true
spacing: Style.marginM * scaling
NIcon { NIcon {
text: "wifi" text: "wifi"
@ -53,23 +53,28 @@ NPanel {
Layout.leftMargin: Style.marginS * scaling Layout.leftMargin: Style.marginS * scaling
} }
// Connection status indicator
Rectangle {
visible: NetworkService.hasActiveConnection
width: 8 * scaling
height: 8 * scaling
radius: 4 * scaling
color: Color.mPrimary
}
NIconButton { NIconButton {
icon: "refresh" icon: "refresh"
tooltipText: "Refresh networks" tooltipText: "Refresh networks"
sizeRatio: 0.8 sizeRatio: 0.8
enabled: Settings.data.network.wifiEnabled && !NetworkService.isLoading enabled: Settings.data.network.wifiEnabled && !NetworkService.isLoading
onClicked: { onClicked: NetworkService.refreshNetworks()
NetworkService.refreshNetworks()
}
} }
NIconButton { NIconButton {
icon: "close" icon: "close"
tooltipText: "Close" tooltipText: "Close"
sizeRatio: 0.8 sizeRatio: 0.8
onClicked: { onClicked: root.close()
root.close()
}
} }
} }
@ -77,6 +82,47 @@ NPanel {
Layout.fillWidth: true Layout.fillWidth: true
} }
// Error banner
Rectangle {
visible: NetworkService.connectStatus === "error" && NetworkService.connectError.length > 0
Layout.fillWidth: true
Layout.preferredHeight: errorText.implicitHeight + (Style.marginM * scaling * 2)
color: Qt.rgba(Color.mError.r, Color.mError.g, Color.mError.b, 0.1)
radius: Style.radiusS * scaling
border.width: Math.max(1, Style.borderS * scaling)
border.color: Color.mError
RowLayout {
anchors.fill: parent
anchors.margins: Style.marginM * scaling
spacing: Style.marginS * scaling
NIcon {
text: "error"
font.pointSize: Style.fontSizeL * scaling
color: Color.mError
}
NText {
id: errorText
text: NetworkService.connectError
color: Color.mError
font.pointSize: Style.fontSizeS * scaling
wrapMode: Text.Wrap
Layout.fillWidth: true
}
NIconButton {
icon: "close"
sizeRatio: 0.6
onClicked: {
NetworkService.connectStatus = ""
NetworkService.connectError = ""
}
}
}
}
ScrollView { ScrollView {
Layout.fillWidth: true Layout.fillWidth: true
Layout.fillHeight: true Layout.fillHeight: true
@ -87,27 +133,18 @@ NPanel {
ColumnLayout { ColumnLayout {
width: parent.width width: parent.width
spacing: Style.marginS * scaling spacing: Style.marginM * scaling
// Show errors at the very top // Loading state
NText {
visible: NetworkService.connectStatus === "error" && NetworkService.connectError.length > 0
text: NetworkService.connectError
color: Color.mError
font.pointSize: Style.fontSizeXS * scaling
wrapMode: Text.Wrap
Layout.fillWidth: true
}
// Scanning... - Now properly centered
ColumnLayout { ColumnLayout {
Layout.fillWidth: true Layout.fillWidth: true
Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
visible: Settings.data.network.wifiEnabled && NetworkService.isLoading visible: Settings.data.network.wifiEnabled && NetworkService.isLoading && Object.keys(
NetworkService.networks).length === 0
spacing: Style.marginM * scaling spacing: Style.marginM * scaling
NBusyIndicator { NBusyIndicator {
running: NetworkService.isLoading running: true
color: Color.mPrimary color: Color.mPrimary
size: Style.baseWidgetSize * scaling size: Style.baseWidgetSize * scaling
Layout.alignment: Qt.AlignHCenter Layout.alignment: Qt.AlignHCenter
@ -121,7 +158,7 @@ NPanel {
} }
} }
// WiFi disabled message // WiFi disabled state
ColumnLayout { ColumnLayout {
Layout.fillWidth: true Layout.fillWidth: true
Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
@ -142,147 +179,211 @@ NPanel {
Layout.alignment: Qt.AlignHCenter Layout.alignment: Qt.AlignHCenter
} }
NText { NButton {
text: "Enable WiFi to see available networks" text: "Enable WiFi"
font.pointSize: Style.fontSizeNormal * scaling icon: "wifi"
color: Color.mOnSurfaceVariant
Layout.alignment: Qt.AlignHCenter Layout.alignment: Qt.AlignHCenter
onClicked: {
Settings.data.network.wifiEnabled = true
Settings.save()
NetworkService.setWifiEnabled(true)
}
} }
} }
// Network list // Network list
Repeater { Repeater {
model: Settings.data.network.wifiEnabled && !NetworkService.isLoading ? Object.values( model: {
NetworkService.networks) : [] if (!Settings.data.network.wifiEnabled || NetworkService.isLoading)
return []
Rectangle { // Sort networks: connected first, then by signal strength
const nets = Object.values(NetworkService.networks)
return nets.sort((a, b) => {
if (a.connected && !b.connected)
return -1
if (!a.connected && b.connected)
return 1
return b.signal - a.signal
})
}
Item {
Layout.fillWidth: true Layout.fillWidth: true
Layout.preferredHeight: networkLayout.implicitHeight + (Style.marginM * scaling * 2) implicitHeight: networkRect.implicitHeight
radius: Style.radiusM * scaling
color: Color.mSurface
border.width: Math.max(1, Style.borderS * scaling)
border.color: modelData.connected ? Color.mOnSurface : Color.mOutline
ColumnLayout { Rectangle {
id: networkLayout id: networkRect
anchors.fill: parent width: parent.width
anchors.margins: Style.marginM * scaling implicitHeight: networkContent.implicitHeight + (Style.marginM * scaling * 2)
spacing: 0 radius: Style.radiusM * scaling
color: modelData.connected ? Qt.rgba(Color.mPrimary.r, Color.mPrimary.g, Color.mPrimary.b,
0.05) : Color.mSurface
border.width: Math.max(1, Style.borderS * scaling)
border.color: modelData.connected ? Color.mPrimary : Color.mOutline
clip: true
RowLayout { ColumnLayout {
Layout.fillWidth: true id: networkContent
spacing: Style.marginS * scaling width: parent.width - (Style.marginM * scaling * 2)
x: Style.marginM * scaling
y: Style.marginM * scaling
spacing: Style.marginM * scaling
NIcon { // Main network row
text: NetworkService.signalIcon(modelData.signal) RowLayout {
font.pointSize: Style.fontSizeXXL * scaling
color: Color.mOnSurface
}
ColumnLayout {
Layout.fillWidth: true Layout.fillWidth: true
Layout.alignment: Qt.AlignVCenter spacing: Style.marginS * scaling
spacing: 0
// SSID // Signal icon
NText { NIcon {
Layout.fillWidth: true text: NetworkService.signalIcon(modelData.signal)
text: modelData.ssid || "Unknown Network" font.pointSize: Style.fontSizeXXL * scaling
font.pointSize: Style.fontSizeNormal * scaling color: modelData.connected ? Color.mPrimary : Color.mOnSurface
elide: Text.ElideRight
color: Color.mOnSurface
} }
// Security Protocol // Network info
NText { ColumnLayout {
text: modelData.security && modelData.security !== "--" ? modelData.security : "Open"
font.pointSize: Style.fontSizeXXS * scaling
elide: Text.ElideRight
Layout.fillWidth: true Layout.fillWidth: true
color: Color.mOnSurfaceVariant Layout.alignment: Qt.AlignVCenter
spacing: 0
NText {
text: modelData.ssid || "Unknown Network"
font.pointSize: Style.fontSizeNormal * scaling
font.weight: modelData.connected ? Style.fontWeightBold : Style.fontWeightMedium
elide: Text.ElideRight
color: Color.mOnSurface
Layout.fillWidth: true
}
NText {
text: {
const security = modelData.security
&& modelData.security !== "--" ? modelData.security : "Open"
const signal = `${modelData.signal}%`
return `${signal} ${security}`
}
font.pointSize: Style.fontSizeXXS * scaling
color: Color.mOnSurfaceVariant
}
} }
}
Item {
Layout.preferredWidth: Style.baseWidgetSize * 0.7 * scaling
Layout.preferredHeight: Style.baseWidgetSize * 0.7 * scaling
visible: NetworkService.connectStatusSsid === modelData.ssid
&& (NetworkService.connectStatus !== ""
|| NetworkService.connectingSsid === modelData.ssid)
// Loading indicator
NBusyIndicator { NBusyIndicator {
visible: NetworkService.connectingSsid === modelData.ssid visible: NetworkService.connectingSsid === modelData.ssid
running: NetworkService.connectingSsid === modelData.ssid running: NetworkService.connectingSsid === modelData.ssid
color: Color.mOnSurface color: Color.mPrimary
anchors.centerIn: parent size: Style.baseWidgetSize * 0.6 * scaling
size: Style.baseWidgetSize * 0.7 * scaling
} }
}
// Call to action // Right-aligned items container
NButton { RowLayout {
id: button Layout.alignment: Qt.AlignRight | Qt.AlignVCenter
outlined: !button.hovered spacing: Style.marginS * scaling
fontSize: Style.fontSizeXS * scaling
fontWeight: Style.fontWeightMedium // Status badges
backgroundColor: { Rectangle {
if (modelData.connected) { visible: modelData.connected
return Color.mError color: Color.mPrimary
} radius: width * 0.5
return Color.mPrimary width: connectedLabel.implicitWidth + (Style.marginS * scaling * 2)
} height: connectedLabel.implicitHeight + (Style.marginXS * scaling * 2)
text: {
if (modelData.connected) { NText {
return "Disconnect" id: connectedLabel
} anchors.centerIn: parent
if (modelData.existing) { text: "Connected"
return "Connect" font.pointSize: Style.fontSizeXXS * scaling
} color: Color.mOnPrimary
return ""
}
icon: (modelData.connected ? "cancel" : "wifi")
onClicked: {
if (modelData.connected) {
NetworkService.disconnectNetwork(modelData.ssid)
showPasswordPrompt = false
} else if (NetworkService.isSecured(modelData.security) && !modelData.existing) {
showPasswordPrompt = !showPasswordPrompt
if (showPasswordPrompt) {
passwordPromptSsid = modelData.ssid
passwordInput = "" // Clear previous input
Qt.callLater(function () {
passwordInputField.forceActiveFocus()
})
} }
} else {
NetworkService.connectNetwork(modelData.ssid, modelData.security)
} }
}
}
}
// Password prompt section
Rectangle {
visible: modelData.ssid === passwordPromptSsid && showPasswordPrompt
Layout.fillWidth: true
Layout.preferredHeight: modelData.ssid === passwordPromptSsid && showPasswordPrompt ? 60 * scaling : 0
Layout.margins: Style.marginS * scaling
color: Color.mSurfaceVariant
radius: Style.radiusS * scaling
RowLayout {
anchors.fill: parent
anchors.margins: Style.marginS * scaling
spacing: Style.marginS * scaling
Item {
Layout.fillWidth: true
Layout.preferredHeight: Math.round(Style.barHeight * scaling)
Rectangle { Rectangle {
anchors.fill: parent visible: modelData.cached && !modelData.connected
color: Color.mSurfaceVariant
radius: width * 0.5
width: savedLabel.implicitWidth + (Style.marginS * scaling * 2)
height: savedLabel.implicitHeight + (Style.marginXS * scaling * 2)
border.color: Color.mOutline
border.width: Math.max(1, Style.borderS * scaling)
NText {
id: savedLabel
anchors.centerIn: parent
text: "Saved"
font.pointSize: Style.fontSizeXXS * scaling
color: Color.mOnSurfaceVariant
}
}
NIconButton {
visible: modelData.existing || modelData.cached
icon: "more_vert"
tooltipText: "Options"
sizeRatio: 0.7
onClicked: {
expandedNetwork = expandedNetwork === modelData.ssid ? "" : modelData.ssid
showPasswordPrompt = false
}
}
// Action buttons
RowLayout {
spacing: Style.marginXS * scaling
visible: NetworkService.connectingSsid !== modelData.ssid
NButton {
visible: !modelData.connected && (expandedNetwork !== modelData.ssid || !showPasswordPrompt)
outlined: !hovered
fontSize: Style.fontSizeXS * scaling
text: modelData.existing ? "Connect" : (NetworkService.isSecured(
modelData.security) ? "Password" : "Connect")
icon: "wifi"
onClicked: {
if (modelData.existing || !NetworkService.isSecured(modelData.security)) {
NetworkService.connectNetwork(modelData.ssid, modelData.security)
} else {
expandedNetwork = modelData.ssid
passwordPromptSsid = modelData.ssid
showPasswordPrompt = true
passwordInput = ""
Qt.callLater(() => passwordInputField.forceActiveFocus())
}
}
}
NButton {
visible: modelData.connected
outlined: !hovered
fontSize: Style.fontSizeXS * scaling
backgroundColor: Color.mError
text: "Disconnect"
icon: "cancel"
onClicked: NetworkService.disconnectNetwork(modelData.ssid)
}
}
}
}
// Password input section
Rectangle {
visible: modelData.ssid === passwordPromptSsid && showPasswordPrompt
Layout.fillWidth: true
implicitHeight: visible ? 50 * scaling : 0
color: Color.mSurfaceVariant
radius: Style.radiusS * scaling
RowLayout {
anchors.fill: parent
anchors.margins: Style.marginS * scaling
spacing: Style.marginS * scaling
Rectangle {
Layout.fillWidth: true
Layout.fillHeight: true
radius: Style.radiusXS * scaling radius: Style.radiusXS * scaling
color: Color.transparent color: Color.mSurface
border.color: passwordInputField.activeFocus ? Color.mPrimary : Color.mOutline border.color: passwordInputField.activeFocus ? Color.mPrimary : Color.mOutline
border.width: Math.max(1, Style.borderS * scaling) border.width: Math.max(1, Style.borderS * scaling)
@ -295,36 +396,79 @@ NPanel {
color: Color.mOnSurface color: Color.mOnSurface
verticalAlignment: TextInput.AlignVCenter verticalAlignment: TextInput.AlignVCenter
clip: true clip: true
focus: true focus: modelData.ssid === passwordPromptSsid && showPasswordPrompt
selectByMouse: true selectByMouse: true
activeFocusOnTab: true
inputMethodHints: Qt.ImhNone
echoMode: TextInput.Password echoMode: TextInput.Password
onTextChanged: passwordInput = text onTextChanged: passwordInput = text
onAccepted: { onAccepted: {
if (passwordInput !== "") { if (passwordInput) {
NetworkService.submitPassword(passwordPromptSsid, passwordInput) NetworkService.submitPassword(passwordPromptSsid, passwordInput)
showPasswordPrompt = false showPasswordPrompt = false
expandedNetwork = ""
} }
} }
Text {
visible: parent.text.length === 0
anchors.verticalCenter: parent.verticalCenter
text: "Enter password..."
color: Color.mOnSurfaceVariant
font.pointSize: Style.fontSizeS * scaling
}
} }
} }
}
// Connect button NButton {
NButton { text: "Connect"
id: connectButton icon: "check"
outlined: !connectButton.hovered fontSize: Style.fontSizeXS * scaling
fontSize: Style.fontSizeXS * scaling enabled: passwordInput.length > 0
fontWeight: Style.fontWeightMedium onClicked: {
backgroundColor: Color.mPrimary if (passwordInput) {
text: "Connect" NetworkService.submitPassword(passwordPromptSsid, passwordInput)
icon: "check" showPasswordPrompt = false
enabled: passwordInput !== "" expandedNetwork = ""
onClicked: { }
if (passwordInput !== "") { }
NetworkService.submitPassword(passwordPromptSsid, passwordInput) }
NIconButton {
icon: "close"
tooltipText: "Cancel"
sizeRatio: 0.7
onClicked: {
showPasswordPrompt = false showPasswordPrompt = false
expandedNetwork = ""
passwordInput = ""
}
}
}
}
// Options menu (forget network)
Rectangle {
visible: expandedNetwork === modelData.ssid && !showPasswordPrompt && (modelData.existing
|| modelData.cached)
Layout.fillWidth: true
implicitHeight: visible ? 40 * scaling : 0
color: Color.mSurfaceVariant
radius: Style.radiusS * scaling
RowLayout {
anchors.fill: parent
anchors.margins: Style.marginS * scaling
spacing: Style.marginM * scaling
NButton {
Layout.fillWidth: true
text: "Forget Network"
icon: "delete"
fontSize: Style.fontSizeXS * scaling
backgroundColor: Color.mError
outlined: !hovered
onClicked: {
NetworkService.forgetNetwork(modelData.ssid)
expandedNetwork = ""
} }
} }
} }
@ -333,6 +477,36 @@ NPanel {
} }
} }
} }
// No networks found
ColumnLayout {
Layout.fillWidth: true
Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
visible: Settings.data.network.wifiEnabled && !NetworkService.isLoading && Object.keys(
NetworkService.networks).length === 0
spacing: Style.marginM * scaling
NIcon {
text: "wifi_find"
font.pointSize: Style.fontSizeXXXL * scaling
color: Color.mOnSurfaceVariant
Layout.alignment: Qt.AlignHCenter
}
NText {
text: "No networks found"
font.pointSize: Style.fontSizeL * scaling
color: Color.mOnSurfaceVariant
Layout.alignment: Qt.AlignHCenter
}
NButton {
text: "Refresh"
icon: "refresh"
Layout.alignment: Qt.AlignHCenter
onClicked: NetworkService.refreshNetworks()
}
}
} }
} }
} }

View file

@ -8,33 +8,87 @@ import qs.Commons
Singleton { Singleton {
id: root id: root
// Core properties
property var networks: ({}) property var networks: ({})
property string connectingSsid: "" property string connectingSsid: ""
property string connectStatus: "" property string connectStatus: ""
property string connectStatusSsid: "" property string connectStatusSsid: ""
property string connectError: "" property string connectError: ""
property string detectedInterface: ""
property string lastConnectedNetwork: ""
property bool isLoading: false property bool isLoading: false
property bool ethernet: false property bool ethernet: false
property int retryCount: 0
property int maxRetries: 3
// File path for persistent storage
property string cacheFile: Settings.cacheDir + "network.json"
// Stable properties for UI
readonly property alias cache: adapter
readonly property string lastConnectedNetwork: adapter.lastConnected
// File-based persistent storage
FileView {
id: cacheFileView
path: root.cacheFile
onAdapterUpdated: saveTimer.start()
onLoaded: {
Logger.log("Network", "Loaded network cache from disk")
// Try to auto-connect on startup if WiFi is enabled
if (Settings.data.network.wifiEnabled && adapter.lastConnected) {
autoConnectTimer.start()
}
}
onLoadFailed: function (error) {
Logger.log("Network", "No existing cache found, creating new one")
// Initialize with empty data
adapter.knownNetworks = ({})
adapter.lastConnected = ""
}
JsonAdapter {
id: adapter
property var knownNetworks: ({})
property string lastConnected: ""
property int lastRefresh: 0
}
}
// Save timer to batch writes
Timer {
id: saveTimer
running: false
interval: 1000
onTriggered: cacheFileView.writeAdapter()
}
Component.onCompleted: { Component.onCompleted: {
Logger.log("Network", "Service started") Logger.log("Network", "Service started")
// Only refresh networks if WiFi is enabled
if (Settings.data.network.wifiEnabled) { if (Settings.data.network.wifiEnabled) {
refreshNetworks() refreshNetworks()
} }
} }
// Signal strength icon mapping
function signalIcon(signal) { function signalIcon(signal) {
if (signal >= 80) const levels = [{
return "network_wifi" "threshold": 80,
if (signal >= 60) "icon": "network_wifi"
return "network_wifi_3_bar" }, {
if (signal >= 40) "threshold": 60,
return "network_wifi_2_bar" "icon": "network_wifi_3_bar"
if (signal >= 20) }, {
return "network_wifi_1_bar" "threshold": 40,
"icon": "network_wifi_2_bar"
}, {
"threshold": 20,
"icon": "network_wifi_1_bar"
}]
for (const level of levels) {
if (signal >= level.threshold)
return level.icon
}
return "signal_wifi_0_bar" return "signal_wifi_0_bar"
} }
@ -42,455 +96,492 @@ Singleton {
return security && security.trim() !== "" && security.trim() !== "--" return security && security.trim() !== "" && security.trim() !== "--"
} }
// Enhanced refresh with retry logic
function refreshNetworks() { function refreshNetworks() {
if (isLoading)
return
isLoading = true isLoading = true
checkEthernet.running = true retryCount = 0
existingNetwork.running = true adapter.lastRefresh = Date.now()
performRefresh()
} }
function performRefresh() {
checkEthernet.running = true
existingNetworkProcess.running = true
}
// Retry mechanism for failed operations
function retryRefresh() {
if (retryCount < maxRetries) {
retryCount++
Logger.log("Network", `Retrying refresh (${retryCount}/${maxRetries})`)
retryTimer.start()
} else {
isLoading = false
connectError = "Failed to refresh networks after multiple attempts"
}
}
Timer {
id: retryTimer
interval: 1000 * retryCount // Progressive backoff
repeat: false
onTriggered: performRefresh()
}
Timer {
id: autoConnectTimer
interval: 3000
repeat: false
onTriggered: {
if (adapter.lastConnected && networks[adapter.lastConnected]?.existing) {
Logger.log("Network", `Auto-connecting to ${adapter.lastConnected}`)
connectToExisting(adapter.lastConnected)
}
}
}
// Forget network function
function forgetNetwork(ssid) {
Logger.log("Network", `Forgetting network: ${ssid}`)
// Remove from cache
let known = adapter.knownNetworks
delete known[ssid]
adapter.knownNetworks = known
// Clear last connected if it's this network
if (adapter.lastConnected === ssid) {
adapter.lastConnected = ""
}
// Save changes
saveTimer.restart()
// Remove NetworkManager profile
forgetProcess.ssid = ssid
forgetProcess.running = true
}
Process {
id: forgetProcess
property string ssid: ""
running: false
command: ["nmcli", "connection", "delete", "id", ssid]
stdout: StdioCollector {
onStreamFinished: {
Logger.log("Network", `Successfully forgot network: ${forgetProcess.ssid}`)
refreshNetworks()
}
}
stderr: StdioCollector {
onStreamFinished: {
if (text.includes("no such connection profile")) {
Logger.log("Network", `Network profile not found: ${forgetProcess.ssid}`)
} else {
Logger.warn("Network", `Error forgetting network: ${text}`)
}
refreshNetworks()
}
}
}
// WiFi enable/disable functions
function setWifiEnabled(enabled) { function setWifiEnabled(enabled) {
if (enabled) { if (enabled) {
// Enable WiFi radio
isLoading = true isLoading = true
enableWifiProcess.running = true wifiRadioProcess.action = "on"
wifiRadioProcess.running = true
} else { } else {
// Disconnect from current network and store it for reconnection // Save current connection for later
for (const ssid in networks) { for (const ssid in networks) {
if (networks[ssid].connected) { if (networks[ssid].connected) {
lastConnectedNetwork = ssid adapter.lastConnected = ssid
// Disconnect from the current network before disabling WiFi saveTimer.restart()
disconnectNetwork(ssid) disconnectNetwork(ssid)
break break
} }
} }
// Disable WiFi radio wifiRadioProcess.action = "off"
disableWifiProcess.running = true wifiRadioProcess.running = true
} }
} }
function connectNetwork(ssid, security) { // Unified WiFi radio control
pendingConnect = { Process {
"ssid": ssid, id: wifiRadioProcess
"security": security, property string action: "on"
"password": "" running: false
command: ["nmcli", "radio", "wifi", action]
onRunningChanged: {
if (!running) {
if (action === "on") {
wifiEnableTimer.start()
} else {
root.networks = ({})
root.isLoading = false
}
}
} }
doConnect()
stderr: StdioCollector {
onStreamFinished: {
if (text.trim()) {
Logger.warn("Network", `Error ${action === "on" ? "enabling" : "disabling"} WiFi: ${text}`)
}
}
}
}
Timer {
id: wifiEnableTimer
interval: 2000
repeat: false
onTriggered: {
refreshNetworks()
if (adapter.lastConnected) {
reconnectTimer.start()
}
}
}
Timer {
id: reconnectTimer
interval: 3000
repeat: false
onTriggered: {
if (adapter.lastConnected && networks[adapter.lastConnected]?.existing) {
connectToExisting(adapter.lastConnected)
}
}
}
// Connection management
function connectNetwork(ssid, security) {
connectingSsid = ssid
connectStatus = ""
connectStatusSsid = ssid
connectError = ""
// Check if profile exists
if (networks[ssid]?.existing) {
connectToExisting(ssid)
return
}
// Check cache for known network
const known = adapter.knownNetworks[ssid]
if (known?.profileName) {
connectToExisting(known.profileName)
return
}
// New connection - need password for secured networks
if (isSecured(security)) {
// Password will be provided through submitPassword
return
}
// Open network - connect directly
createAndConnect(ssid, "", security)
} }
function submitPassword(ssid, password) { function submitPassword(ssid, password) {
pendingConnect = { const security = networks[ssid]?.security || ""
"ssid": ssid, createAndConnect(ssid, password, security)
"security": networks[ssid].security, }
"password": password
} function connectToExisting(ssid) {
doConnect() connectingSsid = ssid
upConnectionProcess.profileName = ssid
upConnectionProcess.running = true
}
function createAndConnect(ssid, password, security) {
connectingSsid = ssid
connectProcess.ssid = ssid
connectProcess.password = password
connectProcess.isSecured = isSecured(security)
connectProcess.running = true
} }
function disconnectNetwork(ssid) { function disconnectNetwork(ssid) {
disconnectProfileProcess.connectionName = ssid disconnectProcess.ssid = ssid
disconnectProfileProcess.running = true disconnectProcess.running = true
} }
property var pendingConnect: null // Connection process
Process {
function doConnect() {
const params = pendingConnect
if (!params)
return
connectingSsid = params.ssid
connectStatus = ""
connectStatusSsid = params.ssid
const targetNetwork = networks[params.ssid]
if (targetNetwork && targetNetwork.existing) {
upConnectionProcess.profileName = params.ssid
upConnectionProcess.running = true
pendingConnect = null
return
}
if (params.security && params.security !== "--") {
getInterfaceProcess.running = true
return
}
connectProcess.security = params.security
connectProcess.ssid = params.ssid
connectProcess.password = params.password
connectProcess.running = true
pendingConnect = null
}
property int refreshInterval: 25000
// Only refresh when we have an active connection and WiFi is enabled
property bool hasActiveConnection: {
for (const net in networks) {
if (networks[net].connected) {
return true
}
}
return false
}
property Timer refreshTimer: Timer {
interval: root.refreshInterval
// Only run timer when we're connected to a network and WiFi is enabled
running: root.hasActiveConnection && Settings.data.network.wifiEnabled
repeat: true
onTriggered: root.refreshNetworks()
}
// Force a refresh when menu is opened
function onMenuOpened() {
if (Settings.data.network.wifiEnabled) {
refreshNetworks()
}
}
function onMenuClosed() {// No need to do anything special on close
}
// Process to enable WiFi radio
property Process enableWifiProcess: Process {
id: enableWifiProcess
running: false
command: ["nmcli", "radio", "wifi", "on"]
onRunningChanged: {
if (!running) {
// Wait a moment for the radio to be enabled, then refresh networks
enableWifiDelayTimer.start()
}
}
stderr: StdioCollector {
onStreamFinished: {
if (text.trim() !== "") {
Logger.warn("Network", "Error enabling WiFi:", text)
}
}
}
}
// Timer to delay network refresh after enabling WiFi
property Timer enableWifiDelayTimer: Timer {
id: enableWifiDelayTimer
interval: 2000 // Wait 2 seconds for radio to be ready
repeat: false
onTriggered: {
// Force refresh networks multiple times to ensure UI updates
root.refreshNetworks()
// Try to auto-reconnect to the last connected network if it exists
if (lastConnectedNetwork) {
autoReconnectTimer.start()
}
// Set up additional refresh to ensure UI is populated
postEnableRefreshTimer.start()
}
}
// Additional timer to ensure networks are populated after enabling
property Timer postEnableRefreshTimer: Timer {
id: postEnableRefreshTimer
interval: 1000
repeat: false
onTriggered: {
root.refreshNetworks()
}
}
// Timer to attempt auto-reconnection to the last connected network
property Timer autoReconnectTimer: Timer {
id: autoReconnectTimer
interval: 3000 // Wait 3 seconds after scan for networks to be available
repeat: false
onTriggered: {
if (lastConnectedNetwork && networks[lastConnectedNetwork]) {
const network = networks[lastConnectedNetwork]
if (network.existing && !network.connected) {
upConnectionProcess.profileName = lastConnectedNetwork
upConnectionProcess.running = true
}
}
}
}
// Process to disable WiFi radio
property Process disableWifiProcess: Process {
id: disableWifiProcess
running: false
command: ["nmcli", "radio", "wifi", "off"]
onRunningChanged: {
if (!running) {
// Clear networks when WiFi is disabled
root.networks = ({})
root.connectingSsid = ""
root.connectStatus = ""
root.connectStatusSsid = ""
root.connectError = ""
root.isLoading = false
}
}
stderr: StdioCollector {
onStreamFinished: {
if (text.trim() !== "") {
Logger.warn("Network", "Error disabling WiFi:", text)
}
}
}
}
property Process disconnectProfileProcess: Process {
id: disconnectProfileProcess
property string connectionName: ""
running: false
command: ["nmcli", "connection", "down", connectionName]
onRunningChanged: {
if (!running) {
// Clear connection status when disconnecting
root.connectingSsid = ""
root.connectStatus = ""
root.connectStatusSsid = ""
root.connectError = ""
}
}
}
property Process existingNetwork: Process {
id: existingNetwork
running: false
command: ["nmcli", "-t", "-f", "NAME,TYPE", "connection", "show"]
stdout: StdioCollector {
onStreamFinished: {
const lines = text.split("\n")
const networksMap = {}
for (var i = 0; i < lines.length; ++i) {
const line = lines[i].trim()
if (!line)
continue
const parts = line.split(":")
if (parts.length < 2) {
Logger.warn("Network", "Malformed nmcli output line:", line)
continue
}
const ssid = parts[0]
const type = parts[1]
if (ssid) {
networksMap[ssid] = {
"ssid": ssid,
"type": type
}
}
}
scanProcess.existingNetwork = networksMap
scanProcess.running = true
}
}
}
property Process scanProcess: Process {
id: scanProcess
running: false
command: ["nmcli", "-t", "-f", "SSID,SECURITY,SIGNAL,IN-USE", "device", "wifi", "list"]
property var existingNetwork
stdout: StdioCollector {
onStreamFinished: {
const lines = text.split("\n")
const networksMap = {}
for (var i = 0; i < lines.length; ++i) {
const line = lines[i].trim()
if (!line)
continue
const parts = line.split(":")
if (parts.length < 4) {
Logger.warn("Network", "Malformed nmcli output line:", line)
continue
}
const ssid = parts[0]
const security = parts[1]
const signal = parseInt(parts[2])
const inUse = parts[3] === "*"
if (ssid) {
if (!networksMap[ssid]) {
networksMap[ssid] = {
"ssid": ssid,
"security": security,
"signal": signal,
"connected": inUse,
"existing": ssid in scanProcess.existingNetwork
}
} else {
const existingNet = networksMap[ssid]
if (inUse) {
existingNet.connected = true
}
if (signal > existingNet.signal) {
existingNet.signal = signal
existingNet.security = security
}
}
}
}
root.networks = networksMap
root.isLoading = false
scanProcess.existingNetwork = {}
}
}
}
property Process connectProcess: Process {
id: connectProcess id: connectProcess
property string ssid: "" property string ssid: ""
property string password: "" property string password: ""
property string security: "" property bool isSecured: false
running: false running: false
command: { command: {
if (password) { const cmd = ["nmcli", "device", "wifi", "connect", ssid]
return ["nmcli", "device", "wifi", "connect", `'${ssid}'`, "password", password] if (isSecured && password) {
} else { cmd.push("password", password)
return ["nmcli", "device", "wifi", "connect", `'${ssid}'`]
}
}
stdout: StdioCollector {
onStreamFinished: {
root.connectingSsid = ""
root.connectStatus = "success"
root.connectStatusSsid = connectProcess.ssid
root.connectError = ""
root.lastConnectedNetwork = connectProcess.ssid
root.refreshNetworks()
}
}
stderr: StdioCollector {
onStreamFinished: {
root.connectingSsid = ""
root.connectStatus = "error"
root.connectStatusSsid = connectProcess.ssid
root.connectError = text
}
}
}
property Process getInterfaceProcess: Process {
id: getInterfaceProcess
running: false
command: ["nmcli", "-t", "-f", "DEVICE,TYPE,STATE", "device"]
stdout: StdioCollector {
onStreamFinished: {
var lines = text.split("\n")
for (var i = 0; i < lines.length; ++i) {
var parts = lines[i].split(":")
if (parts[1] === "wifi" && parts[2] !== "unavailable") {
root.detectedInterface = parts[0]
break
}
}
if (root.detectedInterface) {
var params = root.pendingConnect
addConnectionProcess.ifname = root.detectedInterface
addConnectionProcess.ssid = params.ssid
addConnectionProcess.password = params.password
addConnectionProcess.profileName = params.ssid
addConnectionProcess.security = params.security
addConnectionProcess.running = true
} else {
root.connectStatus = "error"
root.connectStatusSsid = root.pendingConnect.ssid
root.connectError = "No Wi-Fi interface found."
root.connectingSsid = ""
root.pendingConnect = null
}
}
}
}
property Process checkEthernet: Process {
id: checkEthernet
running: false
command: ["nmcli", "-t", "-f", "DEVICE,TYPE,STATE", "device"]
stdout: StdioCollector {
onStreamFinished: {
var lines = text.split("\n")
for (var i = 0; i < lines.length; ++i) {
var parts = lines[i].split(":")
if (parts[1] === "ethernet" && parts[2] === "connected") {
root.ethernet = true
break
}
}
}
}
}
property Process addConnectionProcess: Process {
id: addConnectionProcess
property string ifname: ""
property string ssid: ""
property string password: ""
property string profileName: ""
property string security: ""
running: false
command: {
var cmd = ["nmcli", "connection", "add", "type", "wifi", "ifname", ifname, "con-name", profileName, "ssid", ssid]
if (security && security !== "--") {
cmd.push("wifi-sec.key-mgmt")
cmd.push("wpa-psk")
cmd.push("wifi-sec.psk")
cmd.push(password)
} }
return cmd return cmd
} }
stdout: StdioCollector { stdout: StdioCollector {
onStreamFinished: { onStreamFinished: {
upConnectionProcess.profileName = addConnectionProcess.profileName handleConnectionSuccess(connectProcess.ssid)
upConnectionProcess.running = true
} }
} }
stderr: StdioCollector { stderr: StdioCollector {
onStreamFinished: { onStreamFinished: {
upConnectionProcess.profileName = addConnectionProcess.profileName handleConnectionError(connectProcess.ssid, text)
upConnectionProcess.running = true
} }
} }
} }
property Process upConnectionProcess: Process { Process {
id: upConnectionProcess id: upConnectionProcess
property string profileName: "" property string profileName: ""
running: false running: false
command: ["nmcli", "connection", "up", "id", profileName] command: ["nmcli", "connection", "up", "id", profileName]
stdout: StdioCollector { stdout: StdioCollector {
onStreamFinished: { onStreamFinished: {
root.connectingSsid = "" handleConnectionSuccess(upConnectionProcess.profileName)
root.connectStatus = "success"
root.connectStatusSsid = root.pendingConnect ? root.pendingConnect.ssid : upConnectionProcess.profileName
root.connectError = ""
root.lastConnectedNetwork = upConnectionProcess.profileName
root.pendingConnect = null
root.refreshNetworks()
} }
} }
stderr: StdioCollector { stderr: StdioCollector {
onStreamFinished: { onStreamFinished: {
root.connectingSsid = "" handleConnectionError(upConnectionProcess.profileName, text)
root.connectStatus = "error"
root.connectStatusSsid = root.pendingConnect ? root.pendingConnect.ssid : upConnectionProcess.profileName
root.connectError = text
root.pendingConnect = null
} }
} }
} }
}
Process {
id: disconnectProcess
property string ssid: ""
running: false
command: ["nmcli", "connection", "down", "id", ssid]
onRunningChanged: {
if (!running) {
connectingSsid = ""
connectStatus = ""
connectStatusSsid = ""
connectError = ""
refreshNetworks()
}
}
stderr: StdioCollector {
onStreamFinished: {
if (text.trim()) {
Logger.warn("Network", `Disconnect warning: ${text}`)
}
}
}
}
// Connection result handlers
function handleConnectionSuccess(ssid) {
connectingSsid = ""
connectStatus = "success"
connectStatusSsid = ssid
connectError = ""
// Update cache
let known = adapter.knownNetworks
known[ssid] = {
"profileName": ssid,
"lastConnected": Date.now(),
"autoConnect": true
}
adapter.knownNetworks = known
adapter.lastConnected = ssid
saveTimer.restart()
Logger.log("Network", `Successfully connected to ${ssid}`)
refreshNetworks()
}
function handleConnectionError(ssid, error) {
connectingSsid = ""
connectStatus = "error"
connectStatusSsid = ssid
connectError = parseError(error)
Logger.warn("Network", `Failed to connect to ${ssid}: ${error}`)
}
function parseError(error) {
// Simplify common error messages
if (error.includes("Secrets were required") || error.includes("no secrets provided")) {
return "Incorrect password"
}
if (error.includes("No network with SSID")) {
return "Network not found"
}
if (error.includes("Connection activation failed")) {
return "Connection failed. Please try again."
}
if (error.includes("Timeout")) {
return "Connection timeout. Network may be out of range."
}
// Return first line only
return error.split("\n")[0].trim()
}
// Network scanning processes
Process {
id: existingNetworkProcess
running: false
command: ["nmcli", "-t", "-f", "NAME,TYPE", "connection", "show"]
stdout: StdioCollector {
onStreamFinished: {
const profiles = {}
const lines = text.split("\n").filter(l => l.trim())
for (const line of lines) {
const [ = line.split(":")
if (name && type === "802-11-wireless") {
profiles[name] = {
"ssid": name,
"type": type
}
}
}
scanProcess.existingProfiles = profiles
scanProcess.running = true
}
}
stderr: StdioCollector {
onStreamFinished: {
if (text.trim()) {
Logger.warn("Network", "Error listing connections:", text)
retryRefresh()
}
}
}
}
Process {
id: scanProcess
property var existingProfiles: ({})
running: false
command: ["nmcli", "-t", "-f", "SSID,SECURITY,SIGNAL,IN-USE", "device", "wifi", "list"]
stdout: StdioCollector {
onStreamFinished: {
const networksMap = {}
const lines = text.split("\n").filter(l => l.trim())
for (const line of lines) {
const parts = line.split(":")
if (parts.length < 4)
continue
const [ = parts
if (!ssid)
continue
const signal = parseInt(signalStr) || 0
const connected = inUse === "*"
// Update last connected if we find the connected network
if (connected && adapter.lastConnected !== ssid) {
adapter.lastConnected = ssid
saveTimer.restart()
}
// Merge with existing or create new
if (!networksMap[ssid] || signal > networksMap[ssid].signal) {
networksMap[ssid] = {
"ssid": ssid,
"security": security || "--",
"signal": signal,
"connected": connected,
"existing": ssid in scanProcess.existingProfiles,
"cached": ssid in adapter.knownNetworks
}
}
}
root.networks = networksMap
root.isLoading = false
scanProcess.existingProfiles = {}
Logger.log("Network", `Found ${Object.keys(networksMap).length} networks`)
}
}
stderr: StdioCollector {
onStreamFinished: {
if (text.trim()) {
Logger.warn("Network", "Error scanning networks:", text)
retryRefresh()
}
}
}
}
Process {
id: checkEthernet
running: false
command: ["nmcli", "-t", "-f", "DEVICE,TYPE,STATE", "device"]
stdout: StdioCollector {
onStreamFinished: {
root.ethernet = text.split("\n").some(line => {
const parts = line.split(":")
return parts[1] === "ethernet"
&& parts[2] === "connected"
})
}
}
}
// Auto-refresh timer
Timer {
interval: 30000 // 30 seconds
running: Settings.data.network.wifiEnabled && !isLoading
repeat: true
onTriggered: {
// Only refresh if we should
const now = Date.now()
const timeSinceLastRefresh = now - adapter.lastRefresh
// Refresh if: connected, or it's been more than 30 seconds
if (hasActiveConnection || timeSinceLastRefresh > 30000) {
refreshNetworks()
}
}
}
property bool hasActiveConnection: {
return Object.values(networks).some(net => net.connected)
}
// Menu state management
function onMenuOpened() {
if (Settings.data.network.wifiEnabled) {
refreshNetworks()
}
}
function onMenuClosed() {
// Clean up temporary states
connectStatus = ""
connectError = ""
}
}