Branchwell

Voxley / app · voxley.si / Sources / Voxley / VoxleyOnboarding.swift

1import AppKit
2import SwiftUI
3
4@MainActor
5final class SetupWindow: NSObject, NSWindowDelegate {
6 private var window: NSWindow?
7 private weak var controller: DictationController?
8
9 var isVisible: Bool { window?.isVisible ?? false }
10
11 func show(_ controller: DictationController) {
12 if let window {
13 bringForward(window)
14 return
15 }
16 self.controller = controller
17 controller.refreshPermissions()
18 let window = NSWindow(
19 contentRect: NSRect(x: 0, y: 0, width: 680, height: 450),
20 styleMask: [.titled, .closable, .miniaturizable],
21 backing: .buffered, defer: false
22 )
23 window.title = "Voxley Onboarding"
24 window.isReleasedWhenClosed = false
25 window.delegate = self
26 window.contentView = NSHostingView(rootView: VoxleyOnboarding(controller: controller,
27 initialStep: UserDefaults.standard.bool(forKey: "didCompleteVoxleySetup") ? .shortcut : .welcome,
28 windowForRecording: { [weak window] in window },
29 select: { [weak window, weak controller] step in
30 controller?.shortcutProbeWindow = step == .shortcut ? window : nil
31 controller?.practiceWindow = step == .practice ? window : nil
32 },
33 finish: { [weak window] in
34 UserDefaults.standard.set(true, forKey: "didCompleteVoxleySetup")
35 window?.close()
36 }
37 ))
38 self.window = window
39 window.center()
40 bringForward(window)
41 }
42
43 private func bringForward(_ window: NSWindow) {
44 // Onboarding is a normal app window. Dictation returns to menu bar mode when it closes.
45 NSApp.setActivationPolicy(.regular)
46 if window.isMiniaturized { window.deminiaturize(nil) }
47 window.makeKeyAndOrderFront(nil)
48 NSApp.activate()
49 }
50
51 func windowWillClose(_ notification: Notification) {
52 controller?.endSetupTest()
53 window = nil
54 NSApp.setActivationPolicy(.accessory)
55 }
56}
57
58private struct VoxleyOnboarding: View {
59 enum Step: Int, CaseIterable {
60 case welcome, access, shortcut, practice
61
62 var title: String {
63 switch self {
64 case .welcome: "Welcome to Voxley"
65 case .access: "Permissions"
66 case .shortcut: "Keyboard shortcut"
67 case .practice: "Practice dictation"
68 }
69 }
70
71 var icon: String {
72 switch self {
73 case .welcome: "waveform.circle"
74 case .access: "checkmark.shield"
75 case .shortcut: "keyboard"
76 case .practice: "waveform"
77 }
78 }
79 }
80
81 let controller: DictationController
82 let windowForRecording: () -> NSWindow?
83 let select: (Step) -> Void
84 let finish: () -> Void
85 @State private var step: Step
86 @State private var startingPresses = 0
87 @State private var practiceText = ""
88 @FocusState private var practiceFocused: Bool
89
90 init(controller: DictationController, initialStep: Step,
91 windowForRecording: @escaping () -> NSWindow?,
92 select: @escaping (Step) -> Void, finish: @escaping () -> Void) {
93 self.controller = controller
94 self.windowForRecording = windowForRecording
95 self.select = select
96 self.finish = finish
97 _step = State(initialValue: initialStep)
98 }
99
100 var body: some View {
101 HStack(spacing: 0) {
102 sidebar
103 Divider()
104 VStack(alignment: .leading, spacing: 17) {
105 Text(step.title)
106 .font(.system(size: 26, weight: .semibold))
107 .accessibilityAddTraits(.isHeader)
108
109 switch step {
110 case .welcome:
111 Text("Speak instead of typing. Voxley transcribes on your Mac and can paste at your cursor.")
112 .foregroundStyle(.secondary)
113 Text("Check permissions, set your keyboard shortcut, and try a practice dictation.")
114 .foregroundStyle(.secondary)
115 case .access: permissions
116 case .shortcut: shortcut
117 case .practice: practice
118 }
119
120 Spacer(minLength: 0)
121 if let message = controller.message {
122 Text(message).font(.callout).foregroundStyle(.secondary)
123 .lineLimit(3)
124 }
125 Divider()
126 HStack {
127 if let previous = Step(rawValue: step.rawValue - 1) {
128 Button("Back") { step = previous }
129 }
130 Spacer()
131 if let next = Step(rawValue: step.rawValue + 1) {
132 Button(step == .welcome ? "Get Started" : "Continue") { step = next }
133 .buttonStyle(.borderedProminent).foregroundStyle(.black)
134 } else {
135 Button("Done", action: finish)
136 .buttonStyle(.borderedProminent).foregroundStyle(.black)
137 }
138 }
139 }
140 .padding(26)
141 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
142 }
143 .frame(minWidth: 680, minHeight: 450)
144 .background(.black)
145 .tint(.voxleyAccent)
146 .onChange(of: step, initial: true) {
147 startingPresses = controller.shortcutPresses
148 select(step)
149 }
150 }
151
152 private var sidebar: some View {
153 VStack(alignment: .leading, spacing: 13) {
154 Label("Voxley", systemImage: "waveform.circle.fill")
155 .font(.title2.weight(.semibold))
156 .padding(.bottom, 15)
157 ForEach(Step.allCases, id: \.rawValue) { item in
158 Button {
159 step = item
160 } label: {
161 Label(item == .welcome ? "Welcome" : item.title, systemImage: item.icon)
162 .font(.callout.weight(step == item ? .semibold : .regular))
163 .frame(maxWidth: .infinity, alignment: .leading)
164 .padding(8)
165 .background(step == item ? Color.voxleyAccent.opacity(0.14) : .clear,
166 in: RoundedRectangle(cornerRadius: 7))
167 .contentShape(Rectangle())
168 }
169 .buttonStyle(.plain)
170 .accessibilityAddTraits(step == item ? .isSelected : [])
171 }
172 Spacer()
173 Text("Setup & diagnostics").font(.caption).foregroundStyle(.secondary)
174 }
175 .padding(17)
176 .frame(width: 192)
177 .frame(maxHeight: .infinity, alignment: .topLeading)
178 .background(.quaternary.opacity(0.35))
179 }
180
181 private var permissions: some View {
182 VStack(alignment: .leading, spacing: 16) {
183 Text("Microphone access is required. Automatic paste is optional: without it, Voxley copies your dictation so you can paste it yourself.")
184 .foregroundStyle(.secondary)
185 statusRow("Microphone", detail: controller.microphoneReady ? "Allowed" : "Permission required",
186 ready: controller.microphoneReady) {
187 if !controller.microphoneReady { Button("Allow Microphone", action: controller.allowMicrophone) }
188 }
189 statusRow("Automatic paste (optional)", detail: controller.accessibilityReady ? "Allowed" : "Not enabled",
190 ready: controller.accessibilityReady) {
191 if !controller.accessibilityReady { Button("Open System Settings", action: controller.allowAccessibility) }
192 }
193 statusRow("Apple Speech", detail: controller.speechStatus,
194 ready: controller.speechStatus == "Ready on this Mac") { EmptyView() }
195 Button("Check Permissions Again", action: controller.refreshPermissions)
196 }
197 }
198
199 private var shortcut: some View {
200 VStack(alignment: .leading, spacing: 16) {
201 Text("Record your own key combination, then press it here. The indicator shows when Voxley receives the global key press and release.")
202 .foregroundStyle(.secondary)
203 ShortcutRecorder(controller: controller, windowForRecording: windowForRecording)
204 let detected = controller.shortcutPresses > startingPresses
205 statusRow("Shortcut test",
206 detail: controller.shortcutPressed ? "Pressed" : detected ? "Press and release detected" : "Waiting for your shortcut",
207 ready: detected) {
208 Text(controller.preferences.shortcutKey.label)
209 .font(.system(.callout, design: .monospaced).weight(.semibold))
210 .padding(.horizontal, 9).padding(.vertical, 5)
211 .background(.quaternary, in: RoundedRectangle(cornerRadius: 5))
212 }
213 if !controller.shortcutReady {
214 Label("This shortcut couldn’t be registered. Try a different key combination.",
215 systemImage: "exclamationmark.triangle")
216 .foregroundStyle(.secondary)
217 Button("Retry Shortcut", action: controller.retryShortcut)
218 }
219 Text("Hold to talk and release to paste. For hands-free dictation, tap once to start and again to stop.")
220 .font(.callout).foregroundStyle(.secondary)
221 if controller.preferences.refineEnabled {
222 Text("Want to shape an idea before it lands? Press \(controller.preferences.refineShortcutKey.label) instead to open the Refine window, where you can edit and chat with Apple Intelligence before copying.")
223 .font(.callout).foregroundStyle(.secondary)
224 }
225 }
226 .onChange(of: controller.preferences.shortcutKey) {
227 startingPresses = controller.shortcutPresses
228 }
229 }
230
231 private var practice: some View {
232 VStack(alignment: .leading, spacing: 12) {
233 Text("Click the field, hold \(controller.preferences.shortcutKey.label), say “Voxley is ready,” then release.")
234 .foregroundStyle(.secondary)
235 TextEditor(text: $practiceText)
236 .font(.body)
237 .focused($practiceFocused)
238 .scrollContentBackground(.hidden)
239 .padding(8)
240 .frame(height: 72)
241 .background(.quaternary.opacity(0.42), in: RoundedRectangle(cornerRadius: 8))
242 .overlay {
243 RoundedRectangle(cornerRadius: 8).strokeBorder(.quaternary).allowsHitTesting(false)
244 }
245 .accessibilityLabel("Practice text field")
246 statusRow("This test", detail: controller.testingPracticePaste ? "Testing paste…" :
247 controller.phase != .idle ? controller.phase.title :
248 controller.lastPracticePasteStatus ?? "Waiting for dictation",
249 ready: controller.lastPracticePasteStatus == "Paste confirmed") {
250 Button("Test Paste") {
251 practiceFocused = true
252 Task {
253 try? await Task.sleep(for: .milliseconds(100))
254 if step == .practice { await controller.testPracticePaste() }
255 }
256 }
257 .disabled(controller.phase != .idle || controller.testingPracticePaste)
258 Button("Clear") { practiceText = "" }
259 .disabled(practiceText.isEmpty || controller.phase != .idle || controller.testingPracticePaste)
260 }
261 if let lastPaste = controller.lastPasteStatus {
262 Text("Last paste in another app: \(lastPaste)").font(.callout).foregroundStyle(.secondary)
263 }
264 Text(controller.accessibilityReady
265 ? "To check another app, dictate into an unsent draft there, then return here to see its paste status."
266 : "Automatic paste is off. Press ⌘V to paste your dictation from the clipboard.")
267 .font(.callout).foregroundStyle(.secondary)
268 }
269 }
270
271 private func statusRow<T: View>(_ title: String, detail: String, ready: Bool,
272 @ViewBuilder trailing: () -> T) -> some View {
273 HStack(spacing: 10) {
274 Image(systemName: ready ? "checkmark.circle.fill" : "circle")
275 .foregroundStyle(ready ? Color.green : Color.secondary)
276 .accessibilityHidden(true)
277 VStack(alignment: .leading, spacing: 3) {
278 Text(title).font(.callout.weight(.semibold))
279 Text(detail).font(.caption).foregroundStyle(.secondary)
280 }
281 Spacer(minLength: 4)
282 trailing()
283 }
284 }
285}