-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
508 lines (433 loc) · 12.9 KB
/
main.js
File metadata and controls
508 lines (433 loc) · 12.9 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
const {
app,
BrowserWindow,
ipcMain,
session,
systemPreferences,
globalShortcut,
Tray,
Menu,
clipboard,
nativeImage,
screen,
} = require("electron");
const path = require("path");
const { exec } = require("child_process");
const WebSocket = require("ws");
const fs = require("fs");
const SAMPLE_RATE = 16000;
const LOG = "/tmp/speak-log.txt";
let tray = null;
let win = null; // single window: settings + audio capture
let dgSocket = null;
let currentHotkey = null;
let isDictating = false;
let isInjecting = false;
let injectedLength = 0; // track chars injected for correction
let accumulatedTranscript = ""; // full transcript for final correction
// ── Logging ──
function log(...args) {
const line = `[${new Date().toISOString().slice(11, 19)}] ${args.join(" ")}\n`;
fs.appendFileSync(LOG, line);
}
fs.writeFileSync(LOG, "=== Speak v2 started ===\n");
// ── Settings ──
function settingsPath() {
return path.join(app.getPath("userData"), "settings.json");
}
const DEFAULTS = {
apiKey: "",
hotkey: "CommandOrControl+Shift+K",
language: "en",
keyterms: [],
micDeviceId: "",
pillX: null,
pillY: null,
};
function loadSettings() {
try {
return { ...DEFAULTS, ...JSON.parse(fs.readFileSync(settingsPath(), "utf8")) };
} catch {
return { ...DEFAULTS };
}
}
function saveSettings(settings) {
fs.writeFileSync(settingsPath(), JSON.stringify(settings, null, 2));
}
// ── Global hotkey ──
function registerHotkey(accelerator) {
if (currentHotkey) globalShortcut.unregister(currentHotkey);
currentHotkey = accelerator;
const ok = globalShortcut.register(accelerator, toggleDictation);
log(ok ? `Hotkey registered: ${accelerator}` : `Hotkey FAILED: ${accelerator}`);
return ok;
}
// ── Dictation ──
function toggleDictation() {
if (isDictating) stopDictation();
else startDictation();
}
function startDictation() {
const s = loadSettings();
if (!s.apiKey) {
log("No API key — can't start");
showSettings();
return;
}
isDictating = true;
injectedLength = 0;
accumulatedTranscript = "";
audioChunkCount = 0;
injectQueue.length = 0;
tray?.setTitle(" ● Rec");
log("Dictation START");
// Mic stream is acquired persistently on page load (while window was visible).
// We just need to show the pill and tell renderer to start sending audio.
if (win) {
isParked = false;
const display = screen.getPrimaryDisplay();
const pillWidth = 240;
const pillHeight = 52;
// Use saved position or default to top center
const x = (s.pillX != null) ? s.pillX : Math.round(display.bounds.width / 2 - pillWidth / 2);
const y = (s.pillY != null) ? s.pillY : display.bounds.y + 8;
win.setMovable(true);
win.setBounds({ x, y, width: pillWidth, height: pillHeight });
win.setAlwaysOnTop(true, "floating");
win.webContents.send("mode:dictating", true);
win.webContents.send("dictation:start", s.micDeviceId);
} else {
log("No window — can't start dictation");
isDictating = false;
return;
}
connectDeepgram(s);
}
function stopDictation() {
isDictating = false;
tray?.setTitle("");
log("Dictation STOP");
// Save pill position before parking
if (win) {
const bounds = win.getBounds();
const s = loadSettings();
s.pillX = bounds.x;
s.pillY = bounds.y;
saveSettings(s);
}
win?.webContents.send("dictation:stop");
win?.webContents.send("mode:dictating", false);
closeDeepgram();
// Park the pill offscreen
setTimeout(() => {
if (!isDictating) {
win?.setMovable(false);
parkWindow();
}
}, 500);
// Final correction: select all injected text and replace with clean version
const finalText = accumulatedTranscript.trim();
if (finalText && injectedLength > 0) {
setTimeout(() => {
doFinalCorrection(finalText, injectedLength);
}, 300);
}
}
// ── Final correction: select injected text and replace ──
function doFinalCorrection(finalText, charCount) {
// Select the text we injected by pressing Shift+Left arrow charCount times
// Then paste the corrected version
log(`Final correction: ${charCount} chars → "${finalText}"`);
const selectScript = `
tell application "System Events"
repeat ${charCount} times
key code 123 using shift down
end repeat
end tell
`;
exec(`osascript -e '${selectScript.replace(/'/g, "'\"'\"'")}'`, { timeout: 5000 }, (err) => {
if (err) {
log("Selection failed:", err.message);
return;
}
// Now paste the corrected text over the selection
const saved = clipboard.readText();
clipboard.writeText(finalText);
exec(
`osascript -e 'tell application "System Events" to keystroke "v" using command down'`,
{ timeout: 3000 },
(err2) => {
if (err2) log("Correction paste failed:", err2.message);
else log("Final correction done");
setTimeout(() => clipboard.writeText(saved), 200);
}
);
});
}
// ── Deepgram ──
function connectDeepgram(settings) {
closeDeepgram();
const params = new URLSearchParams({
model: "nova-3",
language: settings.language,
smart_format: "true",
encoding: "linear16",
channels: "1",
sample_rate: String(SAMPLE_RATE),
interim_results: "true",
utterance_end_ms: "1000",
vad_events: "true",
endpointing: "300",
});
for (const term of (settings.keyterms || [])) {
const t = term.trim();
if (t) params.append("keyterm", t);
}
const url = `wss://api.deepgram.com/v1/listen?${params}`;
dgSocket = new WebSocket(url, {
headers: { Authorization: `Token ${settings.apiKey}` },
});
dgSocket.on("open", () => {
log("Deepgram OPEN");
});
dgSocket.on("message", (data) => {
try {
const msg = JSON.parse(data.toString());
const t = msg?.channel?.alternatives?.[0]?.transcript;
if (msg.type === "Results" && t) {
if (msg.is_final) {
log("FINAL:", t);
accumulatedTranscript += t + " ";
const chunk = t + " ";
injectedLength += chunk.length;
injectText(chunk);
}
}
} catch (err) {
log("DG parse error:", err.message);
}
});
dgSocket.on("error", (err) => {
log("Deepgram ERROR:", err.message);
});
dgSocket.on("close", (code) => {
log("Deepgram CLOSED:", code);
});
}
function closeDeepgram() {
if (!dgSocket) return;
try { dgSocket.send(JSON.stringify({ type: "CloseStream" })); } catch {}
dgSocket.close();
dgSocket = null;
}
// ── Real-time text injection ──
const injectQueue = [];
function injectText(text) {
injectQueue.push(text);
if (!isInjecting) processInjectQueue();
}
function processInjectQueue() {
if (injectQueue.length === 0) {
isInjecting = false;
return;
}
isInjecting = true;
const text = injectQueue.shift();
const saved = clipboard.readText();
clipboard.writeText(text);
exec(
`osascript -e 'tell application "System Events" to keystroke "v" using command down'`,
{ timeout: 3000 },
(err) => {
if (err) log("Paste failed:", err.message);
setTimeout(() => {
clipboard.writeText(saved);
setTimeout(() => processInjectQueue(), 50);
}, 100);
}
);
}
// ── Audio from window ──
ipcMain.on("mic:ready", () => {
log("Renderer: mic stream acquired and ready");
});
ipcMain.on("hotkey:suspend", () => {
if (currentHotkey) {
globalShortcut.unregister(currentHotkey);
log("Hotkey suspended for capture");
}
});
ipcMain.on("hotkey:resume", () => {
if (currentHotkey) {
registerHotkey(currentHotkey);
}
});
ipcMain.on("renderer:log", (event, msg) => {
log("[renderer]", msg);
});
let audioChunkCount = 0;
ipcMain.on("dg:audio", (event, buffer) => {
audioChunkCount++;
if (audioChunkCount <= 3 || audioChunkCount % 500 === 0) {
const buf = Buffer.from(buffer);
let sumSq = 0;
for (let i = 0; i < buf.length - 1; i += 2) {
const s = buf.readInt16LE(i);
sumSq += s * s;
}
const rms = Math.sqrt(sumSq / (buf.length / 2));
log(`Audio #${audioChunkCount}, ${buf.length}B, RMS: ${rms.toFixed(1)}`);
}
if (dgSocket?.readyState === WebSocket.OPEN) {
dgSocket.send(Buffer.from(buffer));
}
});
// ── Tray icon ──
function createTrayIcon() {
const img = nativeImage.createFromBuffer(
Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAWklEQVR4nO3UMQ4AIAgDQP7/ad2JKBqgRtvEkXKDKsKcp6kDXV6KsJaXIQgggAACygG62AsIAxFwHWCGWM2FATLnzCJvYdqz3AWkBf4TjjCw/AmA3wE4gHkrHXHYwT+S0kEcAAAAAElFTkSuQmCC",
"base64"
),
{ width: 32, height: 32, scaleFactor: 2.0 }
);
img.setTemplateImage(true);
return img;
}
// ── Main window (settings + audio capture) ──
function createWindow() {
const trayBounds = tray.getBounds();
const winWidth = 340;
const winHeight = 480;
const x = Math.round(trayBounds.x + trayBounds.width / 2 - winWidth / 2);
const y = trayBounds.y + trayBounds.height + 4;
win = new BrowserWindow({
x,
y,
width: winWidth,
height: winHeight,
resizable: false,
movable: false,
minimizable: false,
maximizable: false,
fullscreenable: false,
title: "",
frame: false,
transparent: true,
hasShadow: false,
backgroundColor: "#00000000",
skipTaskbar: true,
alwaysOnTop: true,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
backgroundThrottling: false,
preload: path.join(__dirname, "preload.js"),
},
});
win.loadFile("settings.html");
win.on("blur", () => {
if (!isDictating) parkWindow();
});
win.on("closed", () => {
win = null;
});
// Park window after mic is acquired (renderer signals mic:ready)
win.once("ready-to-show", () => {
setTimeout(() => {
if (!isDictating) parkWindow();
}, 2000);
});
}
// "Park" the window: keep it visible but move it offscreen so macOS
// doesn't mute the audio track. A hidden window kills getUserMedia.
let isParked = false;
function parkWindow() {
if (!win) return;
isParked = true;
const display = screen.getPrimaryDisplay();
// Move offscreen to the right, keep 1x1 size
win.setBounds({ x: display.bounds.width + 100, y: 0, width: 1, height: 1 });
log("Window parked offscreen");
}
function showSettings() {
if (isDictating) return;
if (!win) {
createWindow();
win.show();
return;
}
if (!isParked) {
// Settings are showing — park it
parkWindow();
} else {
// Settings are parked — show them
isParked = false;
const trayBounds = tray.getBounds();
const winWidth = 340;
const winHeight = 480;
const x = Math.round(trayBounds.x + trayBounds.width / 2 - winWidth / 2);
const y = trayBounds.y + trayBounds.height + 4;
win.setMovable(false);
win.setBounds({ x, y, width: winWidth, height: winHeight });
win.webContents.send("mode:dictating", false);
win.show();
win.focus();
}
}
// ── IPC: Settings ──
ipcMain.handle("settings:get", () => loadSettings());
ipcMain.handle("settings:save", (event, newSettings) => {
const merged = { ...loadSettings(), ...newSettings };
saveSettings(merged);
if (newSettings.hotkey) registerHotkey(merged.hotkey);
log("Settings saved — language:", merged.language, "hotkey:", merged.hotkey, "mic:", merged.micDeviceId?.slice(0, 8));
return true;
});
ipcMain.handle("accessibility:check", () => {
return systemPreferences.isTrustedAccessibilityClient(false);
});
ipcMain.handle("accessibility:request", () => {
return systemPreferences.isTrustedAccessibilityClient(true);
});
ipcMain.on("app:restart", () => {
app.relaunch();
app.exit(0);
});
// ── App init ──
app.whenReady().then(async () => {
app.dock?.hide();
if (process.platform === "darwin") {
const status = systemPreferences.getMediaAccessStatus("microphone");
log("Mic status:", status);
if (status !== "granted") {
const granted = await systemPreferences.askForMediaAccess("microphone");
log("Mic access granted:", granted);
}
}
session.defaultSession.setPermissionRequestHandler((wc, perm, cb) => cb(true));
session.defaultSession.setPermissionCheckHandler(() => true);
// Tray
tray = new Tray(createTrayIcon());
tray.setToolTip("Speak");
tray.on("click", () => showSettings());
tray.on("right-click", () => {
const menu = Menu.buildFromTemplate([
{ label: "Settings", click: showSettings },
{ type: "separator" },
{ label: "Restart", click: () => { app.relaunch(); app.exit(0); } },
{ label: "Quit", click: () => { app.isQuitting = true; app.quit(); } },
]);
tray.popUpContextMenu(menu);
});
// Create window (settings + capture) — show it to get mic access
createWindow();
win.show();
// Register hotkey
const s = loadSettings();
registerHotkey(s.hotkey);
log("App ready — menu bar mode");
});
app.on("before-quit", () => { app.isQuitting = true; });
app.on("window-all-closed", () => { /* stay alive in tray */ });
app.on("will-quit", () => globalShortcut.unregisterAll());