Repository navigation
Expand file tree
/
Copy pathsettings.js
More file actions
384 lines (320 loc) · 10.6 KB
/
Copy pathsettings.js
File metadata and controls
384 lines (320 loc) · 10.6 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
const apiKeyInput = document.getElementById("apiKey");
const hotkeyInput = document.getElementById("hotkey");
const hotkeyBtn = document.getElementById("hotkeyBtn");
const languageSelect = document.getElementById("language");
const micSelect = document.getElementById("mic");
const keytermsArea = document.getElementById("keyterms");
const saveBtn = document.getElementById("saveBtn");
const restartBtn = document.getElementById("restartBtn");
const accessDot = document.getElementById("accessDot");
const accessLabel = document.getElementById("accessLabel");
const accessBtn = document.getElementById("accessBtn");
const pill = document.getElementById("pill");
const settingsPanel = document.getElementById("settingsPanel");
const waveformEl = document.getElementById("waveform");
const pillTimeEl = document.getElementById("pillTime");
const SAMPLE_RATE = 16000;
const NUM_BARS = 12;
// Persistent audio state — acquired on page load, never released
let persistentStream = null;
let audioContext = null;
let sourceNode = null;
let analyserNode = null;
// Dictation-only state — connected/disconnected on start/stop
let processorNode = null;
let sending = false;
let waveformBars = [];
let waveformRAF = null;
let dictationTimer = null;
let dictationStartTime = 0;
// ── Create waveform bars ──
for (let i = 0; i < NUM_BARS; i++) {
const bar = document.createElement("div");
bar.className = "bar";
waveformEl.appendChild(bar);
waveformBars.push(bar);
}
// ── Persistent mic stream — acquired once on page load ──
async function initMic(deviceId) {
try {
const audioConstraints = {
channelCount: 1,
echoCancellation: false,
noiseSuppression: false,
autoGainControl: false,
};
if (deviceId && deviceId !== "" && deviceId !== "default") {
audioConstraints.deviceId = { exact: deviceId };
}
persistentStream = await navigator.mediaDevices.getUserMedia({ audio: audioConstraints });
const track = persistentStream.getAudioTracks()[0];
window.speak.log("Mic acquired:", track.label);
audioContext = new AudioContext({ sampleRate: SAMPLE_RATE });
sourceNode = audioContext.createMediaStreamSource(persistentStream);
// Analyser for waveform (always connected, but only drawn during dictation)
analyserNode = audioContext.createAnalyser();
analyserNode.fftSize = 256;
analyserNode.smoothingTimeConstant = 0.7;
sourceNode.connect(analyserNode);
window.speak.log("Mic pipeline ready, AudioContext state:", audioContext.state);
window.speak.micReady();
} catch (err) {
console.error("initMic error:", err);
}
}
// ── Start/stop sending audio to main process ──
function startSending() {
if (!audioContext || !sourceNode) {
console.error("No audio pipeline — can't send");
return;
}
if (sending) return;
sending = true;
// Resume AudioContext if suspended (Chrome policy)
if (audioContext.state === "suspended") {
audioContext.resume();
}
const bufferSize = 4096;
processorNode = audioContext.createScriptProcessor(bufferSize, 1, 1);
processorNode.onaudioprocess = (e) => {
if (!sending) return;
const float32 = e.inputBuffer.getChannelData(0);
const int16 = new Int16Array(float32.length);
for (let i = 0; i < float32.length; i++) {
const s = Math.max(-1, Math.min(1, float32[i]));
int16[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
}
window.speak.sendAudio(int16.buffer);
};
sourceNode.connect(processorNode);
processorNode.connect(audioContext.destination);
startWaveform();
window.speak.log("Audio sending started, processor connected");
}
function stopSending() {
sending = false;
stopWaveform();
if (processorNode) {
processorNode.disconnect();
processorNode = null;
}
console.log("Audio sending stopped");
}
// ── Mode switching (pill vs settings) ──
window.speak.onModeChange((active) => {
if (active) {
pill.classList.add("active");
settingsPanel.classList.add("hidden");
startTimer();
} else {
pill.classList.remove("active");
settingsPanel.classList.remove("hidden");
stopTimer();
stopWaveform();
}
});
// ── Timer ──
function startTimer() {
dictationStartTime = Date.now();
pillTimeEl.textContent = "0:00";
dictationTimer = setInterval(() => {
const elapsed = Math.floor((Date.now() - dictationStartTime) / 1000);
const mins = Math.floor(elapsed / 60);
const secs = elapsed % 60;
pillTimeEl.textContent = `${mins}:${secs.toString().padStart(2, "0")}`;
}, 1000);
}
function stopTimer() {
if (dictationTimer) {
clearInterval(dictationTimer);
dictationTimer = null;
}
}
// ── Waveform visualizer ──
function startWaveform() {
if (!analyserNode) return;
const dataArray = new Uint8Array(analyserNode.frequencyBinCount);
function draw() {
waveformRAF = requestAnimationFrame(draw);
analyserNode.getByteFrequencyData(dataArray);
const step = Math.floor(dataArray.length / NUM_BARS);
for (let i = 0; i < NUM_BARS; i++) {
const idx = i * step;
const val = dataArray[idx] || 0;
const h = 4 + (val / 255) * 16;
waveformBars[i].style.height = `${h}px`;
}
}
draw();
}
function stopWaveform() {
if (waveformRAF) {
cancelAnimationFrame(waveformRAF);
waveformRAF = null;
}
for (const bar of waveformBars) {
bar.style.height = "4px";
}
}
// ── Dictation events from main process ──
window.speak.onDictationStart(async (micId) => {
window.speak.log("Dictation start received, micId:", micId || "default");
// If mic not yet acquired, init with the requested device
if (!persistentStream) {
await initMic(micId);
}
startSending();
});
window.speak.onDictationStop(() => {
console.log("Dictation stop received");
stopSending();
});
// ── Load devices & settings ──
async function loadDevices() {
try {
const all = await navigator.mediaDevices.enumerateDevices();
const mics = all.filter((d) => d.kind === "audioinput");
micSelect.innerHTML = "";
const defaultOpt = document.createElement("option");
defaultOpt.value = "";
defaultOpt.textContent = "Default";
micSelect.appendChild(defaultOpt);
let fifineId = null;
for (const d of mics) {
const opt = document.createElement("option");
opt.value = d.deviceId;
opt.textContent = d.label || "Unknown mic";
micSelect.appendChild(opt);
if (d.label.toLowerCase().includes("fifine")) fifineId = d.deviceId;
}
return fifineId;
} catch (err) {
console.error("Device load error:", err);
return null;
}
}
async function init() {
// Load settings first to know which mic to use
const s = await window.speak.getSettings();
apiKeyInput.value = s.apiKey || "";
hotkeyInput.value = s.hotkey || "CommandOrControl+Shift+K";
languageSelect.value = s.language || "en";
keytermsArea.value = (s.keyterms || []).join("\n");
const fifineId = await loadDevices();
// Determine which mic device to use
let micId = s.micDeviceId;
if (!micId && fifineId) {
micId = fifineId;
}
if (micId) {
micSelect.value = micId;
} else if (fifineId) {
micSelect.value = fifineId;
}
// Acquire mic with the correct device while window is visible on startup
await initMic(micId);
checkAccess();
}
init();
// ── Accessibility ──
async function checkAccess() {
const ok = await window.speak.checkAccessibility();
accessDot.className = "status-dot " + (ok ? "ok" : "bad");
accessLabel.textContent = ok ? "Accessibility granted" : "Accessibility required";
accessBtn.style.display = ok ? "none" : "";
}
setInterval(checkAccess, 3000);
accessBtn.addEventListener("click", () => {
window.speak.requestAccessibility();
});
// ── Hotkey capture ──
let capturing = false;
hotkeyBtn.addEventListener("click", () => {
if (capturing) return;
capturing = true;
hotkeyInput.value = "Press shortcut...";
hotkeyInput.classList.add("listening");
hotkeyBtn.textContent = "...";
hotkeyInput.focus();
// Suspend global shortcut so it doesn't fire during capture
window.speak.suspendHotkey();
});
hotkeyInput.addEventListener("keydown", (e) => {
if (!capturing) return;
e.preventDefault();
const parts = [];
if (e.metaKey) parts.push("Command");
if (e.ctrlKey) parts.push("Control");
if (e.altKey) parts.push("Alt");
if (e.shiftKey) parts.push("Shift");
// Ignore modifier-only presses
if (["Meta", "Control", "Alt", "Shift"].includes(e.key)) return;
// Must have at least one modifier
if (parts.length === 0) return;
// Map browser key names to Electron accelerator names
const keyMap = {
" ": "Space", "ArrowUp": "Up", "ArrowDown": "Down",
"ArrowLeft": "Left", "ArrowRight": "Right",
"Escape": "Escape", "Enter": "Return", "Backspace": "Backspace",
"Delete": "Delete", "Tab": "Tab",
};
let keyName = keyMap[e.key] || (e.key.length === 1 ? e.key.toUpperCase() : e.key);
parts.push(keyName);
const combo = parts.join("+");
hotkeyInput.value = combo;
hotkeyInput.classList.remove("listening");
capturing = false;
hotkeyBtn.textContent = "Set";
window.speak.log("Hotkey captured:", combo);
// Auto-save new hotkey immediately
doSave();
});
hotkeyInput.addEventListener("keyup", (e) => {
if (e.key === "Escape" && capturing) {
capturing = false;
hotkeyInput.classList.remove("listening");
hotkeyBtn.textContent = "Set";
// Restore previous hotkey and re-register it
window.speak.getSettings().then((s) => {
hotkeyInput.value = s.hotkey || "CommandOrControl+Shift+K";
});
window.speak.resumeHotkey();
}
});
// ── Save ──
function gatherSettings() {
return {
apiKey: apiKeyInput.value.trim(),
hotkey: hotkeyInput.value,
language: languageSelect.value,
micDeviceId: micSelect.value,
keyterms: keytermsArea.value
.split("\n")
.map((l) => l.trim())
.filter(Boolean),
};
}
async function doSave() {
const settings = gatherSettings();
await window.speak.saveSettings(settings);
window.speak.log("Settings saved:", JSON.stringify(settings));
}
// Auto-save on any field change
languageSelect.addEventListener("change", doSave);
micSelect.addEventListener("change", doSave);
apiKeyInput.addEventListener("change", doSave);
keytermsArea.addEventListener("change", doSave);
// Save button still works for explicit save + visual feedback
saveBtn.addEventListener("click", async () => {
await doSave();
saveBtn.textContent = "Saved!";
saveBtn.style.background = "#16a34a";
setTimeout(() => {
saveBtn.textContent = "Save";
saveBtn.style.background = "";
}, 1200);
});
// Restart button
restartBtn.addEventListener("click", () => {
window.speak.restart();
});