-
Notifications
You must be signed in to change notification settings - Fork 406
Expand file tree
/
Copy pathWifiCustomizationStep.qml
More file actions
558 lines (481 loc) · 22.8 KB
/
WifiCustomizationStep.qml
File metadata and controls
558 lines (481 loc) · 22.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
/*
* SPDX-License-Identifier: Apache-2.0
* Copyright (C) 2020 Raspberry Pi Ltd
*/
import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import "../qmlcomponents"
import "components"
import RpiImager
WizardStepBase {
id: root
required property ImageWriter imageWriter
required property var wizardContainer
// "open" | "secure"
property string wifiMode: "secure"
property string originalSavedSSID: ""
property bool hadSavedCrypt: false
property bool showPw: wifiMode === "secure"
function ssidUnchanged(ssid, prev) { return (ssid || "") === (prev || "") }
title: qsTr("Customisation: Choose Wi‑Fi")
subtitle: qsTr("If you will use a network cable only, you can skip Wi‑Fi setup below.")
showSkipButton: true
nextButtonAccessibleDescription: qsTr("Save Wi-Fi settings and continue to next customisation step")
backButtonAccessibleDescription: qsTr("Return to previous step")
skipButtonAccessibleDescription: qsTr("Skip all customisation and proceed directly to writing the image")
// Initial focus will automatically go to title, then subtitle (if present), then first control (handled by WizardStepBase)
// Track whether we've already auto-detected SSID/PSK to avoid re-prompting
property bool ssidAutoDetected: false
function useWiredEthernetOnly() {
fieldWifiSSID.text = ""
fieldWifiPassword.text = ""
fieldWifiPasswordConfirm.text = ""
chkWifiHidden.checked = false
wifiMode = "secure"
updatePasswordFieldUI()
root.nextClicked()
}
Component.onCompleted: {
root.registerFocusGroup("wifi_modes", function() {
return [btnUseEthernet, tabSecure, tabOpen]
}, 0)
// Labels are automatically skipped when screen reader is not active (via activeFocusOnTab)
root.registerFocusGroup("wifi_fields", function(){
var items = [labelSSID, fieldWifiSSID]
if (showPw) {
items.push(lblPassword)
items.push(fieldWifiPassword)
items.push(lblPasswordConfirm)
items.push(fieldWifiPasswordConfirm)
}
return items
}, 1)
root.registerFocusGroup("wifi_options", function(){ return [chkWifiHidden] }, 2)
fieldWifiSSID.placeholderText = qsTr("Network name")
// Prefill from conserved customization settings
var settings = wizardContainer.customizationSettings
// Then set text values after, so they properly override the placeholder
if (settings.wifiSSID) {
fieldWifiSSID.text = settings.wifiSSID
}
// If not saved, try to auto-detect the current SSID from the system
if (!fieldWifiSSID.text || fieldWifiSSID.text.length === 0) {
var detectedSsid = imageWriter.getSSID()
console.log("WifiCustomizationStep: detected SSID:", detectedSsid)
if (detectedSsid && detectedSsid.length > 0) {
fieldWifiSSID.text = detectedSsid
ssidAutoDetected = true
}
}
if (settings.wifiHidden !== undefined) {
chkWifiHidden.checked = (settings.wifiHidden === true || settings.wifiHidden === "true")
}
originalSavedSSID = settings.wifiSSID || ""
// Remember if a crypted PSK is already saved (affects placeholder/keep semantics)
hadSavedCrypt = !!settings.wifiPasswordCrypt
// if no saved crypt, try to prefill a PSK from system
// IMPORTANT: Only attempt PSK retrieval if we have an SSID (either saved or detected)
// Pass the SSID to getPSKForSSID() to avoid race condition where SSID detection
// might fail during the keychain permission dialog on macOS
if (!hadSavedCrypt && fieldWifiSSID.text && fieldWifiSSID.text.length > 0) {
// Auto-populate WiFi password from system keychain when available
// Only when no crypted password is already saved
var psk = imageWriter.getPSKForSSID(fieldWifiSSID.text)
if (psk && psk.length > 0) {
fieldWifiPassword.text = psk
fieldWifiPasswordConfirm.text = psk
}
}
// wifiMode: prefer saved value; otherwise infer from whether a password is present
wifiMode = (settings.wifiMode === "secure" || settings.wifiMode === "open")
? settings.wifiMode
: "secure"
updatePasswordFieldUI()
// UpdatePasswordFieldUI already takes care of this
//root.rebuildFocusOrder()
}
// Handle location permission granted after timeout (macOS race condition fix)
// This is called when the user clicks "Allow" in the macOS location permission dialog
// after the initial 5-second timeout has expired
Connections {
target: imageWriter
function onLocationPermissionGranted() {
console.log("WifiCustomizationStep: Location permission granted, retrying SSID detection")
// Only retry if SSID field is still empty (user hasn't manually entered one)
if (!fieldWifiSSID.text || fieldWifiSSID.text.length === 0) {
var detectedSsid = imageWriter.getSSID()
console.log("WifiCustomizationStep: re-detected SSID:", detectedSsid)
if (detectedSsid && detectedSsid.length > 0) {
fieldWifiSSID.text = detectedSsid
ssidAutoDetected = true
// Also try to auto-populate the password if we don't have one saved
if (!hadSavedCrypt && (!fieldWifiPassword.text || fieldWifiPassword.text.length === 0)) {
var psk = imageWriter.getPSKForSSID(detectedSsid)
if (psk && psk.length > 0) {
fieldWifiPassword.text = psk
fieldWifiPasswordConfirm.text = psk
}
}
}
}
}
}
function updatePasswordFieldUI() {
var ssid = (fieldWifiSSID.text || "").trim()
var prevSSID = originalSavedSSID
if (wifiMode === "open") {
fieldWifiPassword.text = ""
fieldWifiPassword.enabled = false
fieldWifiPassword.placeholderText = qsTr("No password (open network)")
fieldWifiPasswordConfirm.text = ""
return
}
// secure
fieldWifiPassword.enabled = true
var canKeep = hadSavedCrypt && ssidUnchanged(ssid, prevSSID)
fieldWifiPassword.placeholderText = canKeep
? qsTr("Saved (hidden) — leave blank to keep")
: qsTr("Network password")
}
function passwordErrorMessage() {
if (!showPw) return " ";
// Gather state
var ssidNow = (fieldWifiSSID.text || "").trim();
var canKeep = hadSavedCrypt && ssidUnchanged(ssidNow, originalSavedSSID);
var pwd = fieldWifiPassword.text || "";
var conf = fieldWifiPasswordConfirm.text || "";
// Open mode: no errors
if (wifiMode === "open") return " ";
// If we can keep the saved crypt and user left blank => OK
if (canKeep && pwd.length === 0) return " ";
// New/changed password is required from here
// Empty -> prompt explicitly
if (pwd.length === 0) return qsTr("Enter a password");
// Detailed validity (mirrors isValidWifiPassword)
// 64 hex is allowed => if it's 64 chars but not hex, say invalid chars
var isHex = isHex64(pwd);
if (!isHex) {
if (pwd.length < 8) return qsTr("Password is too short (min 8 characters)");
if (pwd.length > 63) return qsTr("Password is too long (max 63 characters)");
if (!isAsciiPrintable(pwd)) return qsTr("Password contains unsupported characters");
}
// Always enforce match when either field has content (like user customization step)
if ((conf.length > 0 || pwd.length > 0) && pwd !== conf)
return qsTr("Passwords don't match");
// No errors -> keep row height stable
return " ";
}
// Content
content: [
ScrollView {
id: wifiScroll
anchors.fill: parent
clip: true
ScrollBar.vertical.policy: ScrollBar.AsNeeded
// Smoothly bring a child item into view (vertical)
function scrollToItem(item, margin) {
if (!item || !wifiScroll.contentItem) return;
var flick = wifiScroll.contentItem; // QQuickFlickable
var content = flick.contentItem; // the inner Item holding children
if (!content) return;
var pos = item.mapToItem(content, 0, 0); // item position in content coords
var top = pos.y;
var bottom = top + item.height;
var m = (margin === undefined ? 12 : margin);
var viewTop = flick.contentY;
var viewBottom = viewTop + flick.height;
if (top < viewTop + m) {
flick.contentY = Math.max(0, top - m);
} else if (bottom > viewBottom - m) {
var target = bottom - flick.height + m;
flick.contentY = Math.min(target, flick.contentHeight - flick.height);
}
}
ColumnLayout {
anchors.left: parent.left
anchors.right: parent.right
anchors.verticalCenter: parent.verticalCenter
anchors.margins: Style.sectionPadding
spacing: Style.stepContentSpacing
width: wifiScroll.availableWidth
WizardSectionContainer {
RowLayout {
Layout.fillWidth: true
spacing: Style.spacingSmall
ImButton {
id: btnUseEthernet
text: qsTr("Use wired Ethernet only")
accessibleDescription: qsTr("Clear Wi-Fi settings and continue to the next step. Other customisation settings are kept.")
onClicked: root.useWiredEthernetOnly()
}
Item { Layout.fillWidth: true }
}
RowLayout {
Layout.fillWidth: true
spacing: Style.spacingSmall
ImToggleTab {
id: tabSecure
text: qsTr("Secure network")
accessibleDescription: qsTr("Configure Wi-Fi for a password-protected network with WPA2/WPA3 encryption")
active: wifiMode === "secure"
onClicked: { wifiMode = "secure"; updatePasswordFieldUI() }
onActiveFocusChanged: {
if (activeFocus) wifiScroll.scrollToItem(this);
}
}
ImToggleTab {
id: tabOpen
text: qsTr("Open network")
accessibleDescription: qsTr("Configure Wi-Fi for an unencrypted network without password protection")
active: wifiMode === "open"
onClicked: { wifiMode = "open"; updatePasswordFieldUI() }
onActiveFocusChanged: {
if (activeFocus) wifiScroll.scrollToItem(this);
}
}
Item { Layout.fillWidth: true }
}
// No explicit enable checkbox; intent is inferred from inputs
GridLayout {
Layout.fillWidth: true
columns: 2
columnSpacing: Style.formColumnSpacing
rowSpacing: Style.formRowSpacing
WizardFormLabel {
id: labelSSID
text: qsTr("SSID:")
accessibleDescription: qsTr("Enter the network name (SSID) of your Wi-Fi network. This is the name that appears when you search for available networks.")
}
ImTextField {
id: fieldWifiSSID
Layout.fillWidth: true
font.pointSize: Style.fontSizeInput
onTextChanged: updatePasswordFieldUI()
onActiveFocusChanged: {
if (activeFocus)
wifiScroll.scrollToItem(this);
}
}
WizardFormLabel {
id: lblPassword
text: CommonStrings.password
visible: showPw
accessibleDescription: {
var canKeep = hadSavedCrypt && ssidUnchanged((fieldWifiSSID.text || "").trim(), originalSavedSSID)
return canKeep
? qsTr("Enter a new Wi-Fi password, or leave blank to keep the previously saved password. Must be 8-63 characters or a 64-character hexadecimal key.")
: qsTr("Enter your Wi-Fi network password. Must be 8-63 characters or a 64-character hexadecimal key. You will need to re-enter it in the next field to confirm.")
}
}
ImPasswordField {
id: fieldWifiPassword
Layout.fillWidth: true
font.pointSize: Style.fontSizeInput
visible: showPw
textField.onActiveFocusChanged: {
if (textField.activeFocus)
wifiScroll.scrollToItem(fieldWifiPassword);
}
textField.onTextChanged: {
updatePasswordFieldUI()
wifiScroll.scrollToItem(fieldWifiPassword)
}
}
/* Confirm password row */
WizardFormLabel {
id: lblPasswordConfirm
text: qsTr("Confirm password:")
visible: showPw
accessibleDescription: {
var canKeep = hadSavedCrypt && ssidUnchanged((fieldWifiSSID.text || "").trim(), originalSavedSSID)
return canKeep
? qsTr("Re-enter the new Wi-Fi password to confirm, or leave blank to keep the previously saved password.")
: qsTr("Re-enter the Wi-Fi password to confirm it matches.")
}
}
ImPasswordField {
id: fieldWifiPasswordConfirm
Layout.fillWidth: true
font.pointSize: Style.fontSizeInput
placeholderText: {
var canKeep = hadSavedCrypt && ssidUnchanged((fieldWifiSSID.text || "").trim(), originalSavedSSID)
return canKeep ? qsTr("Re-enter to change password") : qsTr("Re-enter password")
}
visible: showPw
textField.onActiveFocusChanged: {
if (textField.activeFocus)
wifiScroll.scrollToItem(fieldWifiPasswordConfirm);
}
textField.onTextChanged: {
// keep scroll behavior pleasant while typing
wifiScroll.scrollToItem(fieldWifiPasswordConfirm);
}
}
// Empty label to maintain grid alignment
Item { width: 1; height: 1; visible: showPw }
Text {
id: pwdHint
Layout.fillWidth: true
Layout.columnSpan: 1
visible: showPw
wrapMode: Text.WordWrap
text: passwordErrorMessage()
color: (text === " ") ? "transparent" : Style.formLabelErrorColor
font.pointSize: Style.fontSizeDescription
// lock a minimum height so even " " keeps the same line height
// TextMetrics is lighter than FontMetrics in Controls:
TextMetrics { id: pwdHintMetrics; font: pwdHint.font; text: "X" }
Layout.preferredHeight: pwdHintMetrics.height
}
ImCheckBox {
id: chkWifiHidden
text: qsTr("Hidden SSID")
Accessible.description: qsTr("Check this if your Wi-Fi network does not broadcast its name and requires manual SSID entry to connect.")
onActiveFocusChanged: {
if (activeFocus)
wifiScroll.scrollToItem(this);
}
}
}
}
}
}
]
// WPA2/3 PSK validation helpers
function isAsciiPrintable(text) {
for (var i = 0; i < text.length; i++) {
var code = text.charCodeAt(i)
if (code < 32 || code > 126) {
return false
}
}
return true
}
function isHex64(text) {
if (text.length !== 64) {
return false
}
for (var i = 0; i < text.length; i++) {
var code = text.charCodeAt(i)
var isDigit = code >= 48 && code <= 57 // 0-9
var isLower = code >= 97 && code <= 102 // a-f
var isUpper = code >= 65 && code <= 70 // A-F
if (!(isDigit || isLower || isUpper)) {
return false
}
}
return true
}
function isValidWifiPassword(text) {
if (!text || text.length === 0) {
// Allow open networks
return true
}
if (isHex64(text)) {
return true
}
// 8–63 ASCII printable characters
return text.length >= 8 && text.length <= 63 && isAsciiPrintable(text)
}
// Validation: allow proceed when
// - SSID entered and either new PSK provided or a saved crypt exists; or
// - all WiFi fields are empty (skip)
nextButtonEnabled: (function(){
var haveSSID = fieldWifiSSID.text && fieldWifiSSID.text.trim().length > 0
if (!haveSSID) return true // allow skipping by leaving fields empty
if (wifiMode === "open") return true
// secure / closed mode
var ssidNow = fieldWifiSSID.text.trim()
var canKeep = hadSavedCrypt && ssidUnchanged(ssidNow, originalSavedSSID)
var pwd = fieldWifiPassword.text || ""
// If we *can* keep and user left blank, OK
if (canKeep && pwd.length === 0) {
return true
}
// Need a new password -> must be valid and must match confirm (like user customization step)
if (pwd.length === 0) return false
if (!root.isValidWifiPassword(pwd)) return false
// Always check that passwords match
if (pwd !== (fieldWifiPasswordConfirm.text || "")) return false
return true
})()
// Save settings when moving to next step
onNextClicked: {
var ssid = fieldWifiSSID.text ? fieldWifiSSID.text.trim() : ""
var pwd = fieldWifiPassword.text
var prevSSID = wizardContainer.customizationSettings.wifiSSID || ""
var hidden = chkWifiHidden.checked
var hadCryptBefore = !!wizardContainer.customizationSettings.wifiPasswordCrypt
var sameSSID = ssidUnchanged(ssid, prevSSID)
// Update conserved customization settings (runtime state)
wizardContainer.customizationSettings.wifiMode = wifiMode
// Handle SSID and password
if (ssid.length > 0) {
wizardContainer.customizationSettings.wifiSSID = ssid
if (wifiMode === "open") {
// always clear in open mode
delete wizardContainer.customizationSettings.wifiPasswordCrypt
} else {
// secure / closed mode
if (pwd.length > 0) {
// extra safety; normally unreachable because nextButtonEnabled prevents this
if (pwd !== fieldWifiPasswordConfirm.text) return;
// overwrite with new password
var isPassphrase = (pwd.length >= 8 && pwd.length < 64)
wizardContainer.customizationSettings.wifiPasswordCrypt = isPassphrase ? imageWriter.pbkdf2(pwd, ssid) : pwd
} else if (hadCryptBefore && sameSSID) {
// keep the existing crypt
// (do nothing)
} else {
// no password provided and can't keep -> ensure cleared
delete wizardContainer.customizationSettings.wifiPasswordCrypt
}
}
wizardContainer.customizationSettings.wifiHidden = hidden
wizardContainer.wifiConfigured = true
} else {
// No SSID -> clear SSID and password settings
delete wizardContainer.customizationSettings.wifiSSID
delete wizardContainer.customizationSettings.wifiPasswordCrypt
delete wizardContainer.customizationSettings.wifiHidden
wizardContainer.wifiConfigured = false
}
// Also persist for future sessions
var saved = imageWriter.getSavedCustomisationSettings()
saved.wifiMode = wifiMode
if (ssid.length > 0) {
saved.wifiSSID = ssid
if (wifiMode === "open") {
delete saved.wifiPasswordCrypt
} else {
if (pwd.length > 0) {
var isPassphrase2 = (pwd.length >= 8 && pwd.length < 64)
saved.wifiPasswordCrypt = isPassphrase2 ? imageWriter.pbkdf2(pwd, ssid) : pwd
} else if (hadCryptBefore && sameSSID) {
// keep existing
} else {
delete saved.wifiPasswordCrypt
}
}
saved.wifiHidden = hidden
} else {
delete saved.wifiSSID
delete saved.wifiPasswordCrypt
delete saved.wifiHidden
}
imageWriter.setSavedCustomisationSettings(saved)
// Do not log sensitive data
}
// Handle skip button
onSkipClicked: {
// Clear all customization flags
wizardContainer.hostnameConfigured = false
wizardContainer.localeConfigured = false
wizardContainer.userConfigured = false
wizardContainer.wifiConfigured = false
wizardContainer.sshEnabled = false
// Jump to writing step
wizardContainer.jumpToStep(wizardContainer.stepWriting)
}
}