Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

refactor: major overhaul

Gabriel Stein0fa5d1b70707
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d84f4c8d4..c2f078fe6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,21 +7,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- **Draggable Interface**: Click and drag the dictation panel to any position on screen
+- **Dynamic Hotkey Display**: Tooltip shows your actual hotkey setting instead of generic text
+- **Flexible Hotkey System**: Fixed hardcoded hotkey limitation - now fully respects user settings
+
### Changed
-- **[BREAKING]** Project rebranded from "OpenWispr" to "OpenWispr"
-- Cleaned up excessive developer logging for better user experience
-- Improved console output clarity by removing verbose operational messages
+- **[BREAKING]** Removed click-to-record functionality to prevent conflicts with dragging
+- **UI Behavior**: Recording is now exclusively controlled via hotkey (no accidental triggering)
+- **Tooltip Text**: Shows "Press {your-hotkey} to speak" with actual configured hotkey
+- **Cursor Styles**: Changed to grab/grabbing cursors to indicate draggable interface
### Fixed
-- Reduced console noise while preserving essential error handling
-- Maintained all critical debugging information for troubleshooting
+- **Hotkey Bug**: Fixed issue where hotkey setting was stored but not actually used by global shortcut
+- **Documentation**: Updated all docs to reflect current UI behavior and hotkey system
+- **User Experience**: Eliminated confusion between drag and click actions
### Technical Details
-- Removed routine operational confirmations from App.jsx
-- Cleaned up verbose success messages in ControlPanel.tsx
-- Streamlined environment loading and system setup logging in main.js
-- Preserved all error messages, database operations, and accessibility features
-- Maintained appropriate logging for open-source project debugging
+- Added IPC handlers for dynamic hotkey updates (`update-hotkey`)
+- Implemented window-level dragging using screen cursor tracking
+- Added real-time hotkey loading from localStorage in main dictation component
+- Updated WindowManager to support runtime hotkey changes
+- Added proper drag state management with smooth 60fps window positioning
+- **Code Organization**: Extracted functionality into dedicated managers and React hooks:
+ - HotkeyManager, DragManager, AudioManager, MenuManager, DevServerManager
+ - useAudioRecording, useWindowDrag, useHotkey React hooks
+ - WindowConfig utility for centralized window configuration
+ - Reduced WindowManager from 465 to 190 lines through composition pattern
## [0.1.0] - 2024-XX-XX
diff --git a/LOCAL_WHISPER_SETUP.md b/LOCAL_WHISPER_SETUP.md
index 4b9334d33..add222473 100644
--- a/LOCAL_WHISPER_SETUP.md
+++ b/LOCAL_WHISPER_SETUP.md
@@ -102,9 +102,9 @@ For **local Whisper processing**, users still need:
1. Enable "Use Local Whisper" in Control Panel
2. Select "base" model (recommended for testing)
3. Save settings
-4. Press the backtick key (`) to start dictation
+4. Press your hotkey (default: backtick `) to start dictation
5. Speak clearly for 2-3 seconds
-6. Press backtick again to stop
+6. Press your hotkey again to stop
7. The transcription should appear and paste automatically
### Test 3: Model Download (First Time)
@@ -119,6 +119,7 @@ The app is configured with intelligent fallback:
1. **Primary**: Use local Whisper if enabled and working
2. **Fallback**: Automatically switch to OpenAI API if local fails
3. **Error Handling**: Clear messages about what's happening
+4. **Hotkey Control**: All recording is controlled via customizable hotkey (no clicking required)
## πŸ“Š Model Performance Guide
@@ -178,9 +179,11 @@ Current timeout is 30 seconds. To change:
Your app now supports both local and cloud transcription! You can:
1. **Switch modes anytime** via Control Panel
-2. **Test different models** to find your preference
+2. **Test different models** to find your preference
3. **Enjoy complete privacy** with local processing
4. **Keep API access** as a backup option
+5. **Customize your hotkey** to any key you prefer
+6. **Drag the panel** to position it anywhere on your screen
The integration is complete and ready for production use. All files have been modified and the Python bridge is fully functional.
diff --git a/README.md b/README.md
index 49e6ec001..3628591e8 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@ An open source desktop dictation application that converts speech to text using
## Features
-- 🎀 **Global Hotkey**: Select your own hotkey to start/stop dictation from anywhere
+- 🎀 **Global Hotkey**: Customizable hotkey to start/stop dictation from anywhere (default: backtick `)
- πŸ€– **Dual AI Processing**: Choose between local Whisper models (private) or OpenAI API (fast)
- πŸ”’ **Privacy-First**: Local processing keeps your voice data completely private
- 🎨 **Modern UI**: Built with React 19, TypeScript, and Tailwind CSS v4
@@ -14,6 +14,7 @@ An open source desktop dictation application that converts speech to text using
- πŸ”§ **Model Management**: Download and manage local Whisper models (tiny, base, small, medium, large)
- 🌐 **Cross-Platform**: Works on macOS, Windows, and Linux
- ⚑ **Automatic Pasting**: Transcribed text automatically pastes at your cursor location
+- πŸ–±οΈ **Draggable Interface**: Move the dictation panel anywhere on your screen
## Quick Start
@@ -63,17 +64,18 @@ An open source desktop dictation application that converts speech to text using
## Usage
### Basic Dictation
-1. **Start the app** - A small transparent overlay appears on your screen
-2. **Press ` (backtick)** - Start dictating (overlay shows recording animation)
-3. **Press ` again** - Stop dictation and begin transcription (overlay shows processing animation)
+1. **Start the app** - A small draggable panel appears on your screen
+2. **Press your hotkey** (default: backtick `) - Start dictating (panel shows recording animation)
+3. **Press your hotkey again** - Stop dictation and begin transcription (panel shows processing animation)
4. **Text appears** - Transcribed text is automatically pasted at your cursor location
+5. **Drag the panel** - Click and drag to move the dictation panel anywhere on your screen
### Control Panel
-- **Access**: Right-click the tray icon (macOS) or click the overlay
+- **Access**: Right-click the tray icon (macOS) or through the system menu
- **Configure**: Choose between local and cloud processing
- **History**: View, copy, and delete past transcriptions
- **Models**: Download and manage local Whisper models
-- **Settings**: Configure API keys, hotkeys, and permissions
+- **Settings**: Configure API keys, customize hotkeys, and manage permissions
### Processing Options
- **Local Processing**:
@@ -217,7 +219,8 @@ For local processing, OpenWispr will automatically:
### Customization
-- **Hotkey**: Change in the Control Panel (default: backtick `)`
+- **Hotkey**: Change in the Control Panel (default: backtick `) - fully customizable
+- **Panel Position**: Drag the dictation panel to any location on your screen`
- **Processing Method**: Choose local or cloud in Control Panel
- **Whisper Model**: Select quality vs speed in Control Panel
- **UI Theme**: Edit CSS variables in `src/index.css`
@@ -247,8 +250,9 @@ For local processing, OpenWispr will automatically:
- Ensure Python 3.7+ is installed
- Use Control Panel to install Whisper automatically
- Check available disk space for models
-5. **Global hotkey conflicts**: Change the hotkey in the Control Panel
+5. **Global hotkey conflicts**: Change the hotkey in the Control Panel - any key can be used
6. **Text not pasting**: Check accessibility permissions and try manual paste with Cmd+V
+7. **Panel position**: If the panel appears off-screen, restart the app to reset position
### Getting Help
diff --git a/package.json b/package.json
index 2a80f84b6..637e63f08 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-wispr",
- "version": "0.0.5-alpha",
+ "version": "0.0.6-alpha",
"description": "A desktop dictation application using OpenAI Whisper for speech-to-text transcription",
"main": "main.js",
"private": true,
diff --git a/preload.js b/preload.js
index 96a631073..074f96d23 100644
--- a/preload.js
+++ b/preload.js
@@ -57,6 +57,9 @@ contextBridge.exposeInMainWorld("electronAPI", {
// Cleanup function
cleanupApp: () => ipcRenderer.invoke("cleanup-app"),
+ updateHotkey: (hotkey) => ipcRenderer.invoke("update-hotkey", hotkey),
+ startWindowDrag: () => ipcRenderer.invoke("start-window-drag"),
+ stopWindowDrag: () => ipcRenderer.invoke("stop-window-drag"),
// Update functions
checkForUpdates: () => ipcRenderer.invoke("check-for-updates"),
@@ -74,4 +77,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
onUpdateDownloadProgress: (callback) =>
ipcRenderer.on("update-download-progress", callback),
onUpdateError: (callback) => ipcRenderer.on("update-error", callback),
+
+ // Audio event listeners
+ onNoAudioDetected: (callback) =>
+ ipcRenderer.on("no-audio-detected", callback),
});
diff --git a/setup.js b/setup.js
index 54303b978..a09e9c0aa 100644
--- a/setup.js
+++ b/setup.js
@@ -34,8 +34,8 @@ Next steps:
3. Run the app: npm start
Features:
-- Global shortcut: Fn key (Mac) or Cmd+\` (alternative)
-- Space bar to start/stop recording
+- Global hotkey: Customizable (default: backtick \`) - set your own in Control Panel
+- Draggable dictation panel: Click and drag to position anywhere on screen
- ESC to close the app
- Automatic text pasting at cursor location
- FFmpeg bundled (no separate installation needed)
diff --git a/src/App.jsx b/src/App.jsx
index f19237236..79dd075eb 100644
--- a/src/App.jsx
+++ b/src/App.jsx
@@ -2,6 +2,8 @@ import React, { useState, useEffect, useRef } from "react";
import "./index.css";
import { useToast } from "./components/ui/Toast";
import { LoadingDots } from "./components/ui/LoadingDots";
+import { useHotkey } from "./hooks/useHotkey";
+import { useWindowDrag } from "./hooks/useWindowDrag";
// Sound Wave Icon Component (for idle/hover states)
const SoundWaveIcon = ({ size = 16 }) => {
@@ -78,6 +80,10 @@ export default function App() {
const mediaRecorderRef = useRef(null);
const audioChunksRef = useRef([]);
const { toast } = useToast();
+ const { hotkey } = useHotkey();
+ const { isDragging, handleMouseDown, handleMouseUp, handleClick } = useWindowDrag();
+ const [dragStartPos, setDragStartPos] = useState(null);
+ const [hasDragged, setHasDragged] = useState(false);
const startRecording = async () => {
try {
@@ -369,12 +375,12 @@ export default function App() {
case "idle":
return {
className: `${baseClasses} bg-black/50 cursor-pointer`,
- tooltip: "Click to speak",
+ tooltip: `Press [${hotkey}] to speak`,
};
case "hover":
return {
className: `${baseClasses} bg-black/50 cursor-pointer`,
- tooltip: "Click to speak",
+ tooltip: `Press [${hotkey}] to speak`,
};
case "recording":
return {
@@ -403,7 +409,33 @@ export default function App() {
<div className="fixed bottom-6 right-6 z-50">
<Tooltip content={micProps.tooltip}>
<button
- onClick={toggleListening}
+ onMouseDown={(e) => {
+ const rect = e.currentTarget.getBoundingClientRect();
+ setDragStartPos({ x: e.clientX, y: e.clientY });
+ setHasDragged(false);
+ handleMouseDown(e);
+ }}
+ onMouseMove={(e) => {
+ if (dragStartPos && !hasDragged) {
+ const distance = Math.sqrt(
+ Math.pow(e.clientX - dragStartPos.x, 2) +
+ Math.pow(e.clientY - dragStartPos.y, 2)
+ );
+ if (distance > 5) { // 5px threshold for drag
+ setHasDragged(true);
+ }
+ }
+ }}
+ onMouseUp={(e) => {
+ handleMouseUp(e);
+ setDragStartPos(null);
+ }}
+ onClick={(e) => {
+ if (!hasDragged) {
+ toggleListening();
+ }
+ e.preventDefault();
+ }}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
onFocus={() => setIsHovered(true)}
@@ -415,6 +447,8 @@ export default function App() {
cursor:
micState === "processing"
? "not-allowed !important"
+ : isDragging
+ ? "grabbing !important"
: "pointer !important",
transition:
"transform 0.25s cubic-bezier(0.4, 0, 0.2, 1), background-color 0.25s ease-out",
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index 1466c6840..790fe313c 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -6,12 +6,14 @@ import SettingsPage from "./SettingsPage";
import TitleBar from "./TitleBar";
import TranscriptionItem from "./ui/TranscriptionItem";
import { ConfirmDialog, AlertDialog } from "./ui/dialog";
+import { useHotkey } from "../hooks/useHotkey";
import type { TranscriptionItem as TranscriptionItemType } from "../types/electron";
export default function ControlPanel() {
const [history, setHistory] = useState<TranscriptionItemType[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [showSettings, setShowSettings] = useState(false);
+ const { hotkey } = useHotkey();
const [updateStatus, setUpdateStatus] = useState({
updateAvailable: false,
updateDownloaded: false,
@@ -249,8 +251,8 @@ export default function ControlPanel() {
No transcriptions yet
</h3>
<p className="text-neutral-600 mb-4 max-w-sm mx-auto">
- Press your hotkey (backtick by default) to start recording
- and create your first transcription.
+ Press your hotkey to start recording and create your first
+ transcription.
</p>
<div className="bg-neutral-50 border border-neutral-200 rounded-lg p-4 max-w-md mx-auto">
<h4 className="font-medium text-neutral-800 mb-2">
@@ -261,7 +263,7 @@ export default function ControlPanel() {
<li>
2. Press{" "}
<kbd className="bg-white px-2 py-1 rounded text-xs font-mono border border-neutral-300">
- `
+ {hotkey}
</kbd>{" "}
to start recording
</li>
@@ -269,7 +271,7 @@ export default function ControlPanel() {
<li>
4. Press{" "}
<kbd className="bg-white px-2 py-1 rounded text-xs font-mono border border-neutral-300">
- `
+ {hotkey}
</kbd>{" "}
again to stop
</li>
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 3bcf802b7..c6f98007f 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -154,13 +154,23 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
// Whisper functions now handled by hooks
- const saveKey = () => {
- localStorage.setItem("dictationKey", key);
- setAlertDialog({
- open: true,
- title: "Key Saved",
- description: `Dictation key inscribed: ${key}`,
- });
+ const saveKey = async () => {
+ try {
+ localStorage.setItem("dictationKey", key);
+ await window.electronAPI.updateHotkey(key);
+ setAlertDialog({
+ open: true,
+ title: "Key Saved",
+ description: `Dictation key inscribed: ${key}`,
+ });
+ } catch (error) {
+ console.error("Failed to update hotkey:", error);
+ setAlertDialog({
+ open: true,
+ title: "Error",
+ description: `Failed to update hotkey: ${error.message}`,
+ });
+ }
};
const saveApiKey = async () => {
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
new file mode 100644
index 000000000..7ef12ea6c
--- /dev/null
+++ b/src/helpers/audioManager.js
@@ -0,0 +1,245 @@
+class AudioManager {
+ constructor() {
+ this.mediaRecorder = null;
+ this.audioChunks = [];
+ this.isRecording = false;
+ this.isProcessing = false;
+ this.onStateChange = null;
+ this.onError = null;
+ this.onTranscriptionComplete = null;
+ }
+
+ // Set callback functions
+ setCallbacks({ onStateChange, onError, onTranscriptionComplete }) {
+ this.onStateChange = onStateChange;
+ this.onError = onError;
+ this.onTranscriptionComplete = onTranscriptionComplete;
+ }
+
+ async startRecording() {
+ try {
+ if (this.isRecording) {
+ console.warn("Recording already in progress");
+ return false;
+ }
+
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+
+ this.mediaRecorder = new MediaRecorder(stream);
+ this.audioChunks = [];
+
+ this.mediaRecorder.ondataavailable = (event) => {
+ this.audioChunks.push(event.data);
+ };
+
+ this.mediaRecorder.onstop = async () => {
+ this.isRecording = false;
+ this.isProcessing = true;
+ this.onStateChange?.({ isRecording: false, isProcessing: true });
+
+ const audioBlob = new Blob(this.audioChunks, { type: "audio/wav" });
+ await this.processAudio(audioBlob);
+
+ // Clean up stream
+ stream.getTracks().forEach((track) => track.stop());
+ };
+
+ this.mediaRecorder.start();
+ this.isRecording = true;
+ this.onStateChange?.({ isRecording: true, isProcessing: false });
+
+ return true;
+ } catch (error) {
+ console.error("Recording error:", error);
+ this.onError?.({
+ title: "Recording Error",
+ description: `Failed to access microphone: ${error.message}`,
+ });
+ return false;
+ }
+ }
+
+ stopRecording() {
+ if (this.mediaRecorder && this.isRecording) {
+ this.mediaRecorder.stop();
+ // State change will be handled in onstop callback
+ return true;
+ }
+ return false;
+ }
+
+ async processAudio(audioBlob) {
+ try {
+ // Get user preferences
+ const useLocalWhisper =
+ localStorage.getItem("useLocalWhisper") === "true";
+ const whisperModel = localStorage.getItem("whisperModel") || "base";
+
+ let result;
+ if (useLocalWhisper) {
+ result = await this.processWithLocalWhisper(audioBlob, whisperModel);
+ } else {
+ result = await this.processWithOpenAIAPI(audioBlob);
+ }
+
+ this.onTranscriptionComplete?.(result);
+ } catch (error) {
+ console.error("Transcription error:", error);
+ this.onError?.({
+ title: "Transcription Error",
+ description: `Transcription failed: ${error.message}`,
+ });
+ } finally {
+ this.isProcessing = false;
+ this.onStateChange?.({ isRecording: false, isProcessing: false });
+ }
+ }
+
+ async processWithLocalWhisper(audioBlob, model = "base") {
+ try {
+ const arrayBuffer = await audioBlob.arrayBuffer();
+ const options = { model };
+ const result = await window.electronAPI.transcribeLocalWhisper(
+ arrayBuffer,
+ options
+ );
+
+ if (result.success && result.text) {
+ const text = result.text.trim();
+ if (text) {
+ return { success: true, text, source: "local" };
+ } else {
+ throw new Error("No text transcribed");
+ }
+ } else if (
+ result.success === false &&
+ result.message === "No audio detected"
+ ) {
+ throw new Error("No audio detected");
+ } else {
+ throw new Error(result.error || "Local Whisper transcription failed");
+ }
+ } catch (error) {
+ console.error("Local Whisper error:", error);
+
+ // Check if it's a "No audio detected" error and don't retry
+ if (error.message === "No audio detected") {
+ throw error;
+ }
+
+ // Try fallback to OpenAI API if enabled
+ const allowFallback =
+ localStorage.getItem("allowOpenAIFallback") === "true";
+ if (allowFallback) {
+ console.log("Falling back to OpenAI API...");
+ try {
+ return await this.processWithOpenAIAPI(audioBlob);
+ } catch (fallbackError) {
+ // If OpenAI fallback also fails, throw the original error
+ throw new Error(
+ `Local Whisper failed: ${error.message}. OpenAI fallback also failed: ${fallbackError.message}`
+ );
+ }
+ } else {
+ throw new Error(`Local Whisper failed: ${error.message}`);
+ }
+ }
+ }
+
+ async processWithOpenAIAPI(audioBlob) {
+ try {
+ // Get API key
+ let apiKey = await window.electronAPI.getOpenAIKey();
+ if (
+ !apiKey ||
+ apiKey.trim() === "" ||
+ apiKey === "your_openai_api_key_here"
+ ) {
+ apiKey = localStorage.getItem("openaiApiKey");
+ }
+
+ if (
+ !apiKey ||
+ apiKey.trim() === "" ||
+ apiKey === "your_openai_api_key_here"
+ ) {
+ throw new Error(
+ "OpenAI API key not found. Please set your API key in the .env file or Control Panel."
+ );
+ }
+
+ const formData = new FormData();
+ formData.append("file", audioBlob, "audio.wav");
+ formData.append("model", "whisper-1");
+
+ const response = await fetch(
+ "https://api.openai.com/v1/audio/transcriptions",
+ {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ },
+ body: formData,
+ }
+ );
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`API Error: ${response.status} ${errorText}`);
+ }
+
+ const result = await response.json();
+ const text = result.text.trim();
+
+ if (text) {
+ return { success: true, text, source: "openai" };
+ } else {
+ throw new Error("No text transcribed");
+ }
+ } catch (error) {
+ console.error("OpenAI API error:", error);
+ throw error;
+ }
+ }
+
+ async safePaste(text) {
+ try {
+ await window.electronAPI.pasteText(text);
+ return true;
+ } catch (error) {
+ this.onError?.({
+ title: "Paste Error",
+ description: `Failed to paste text. Please check accessibility permissions. ${error.message}`,
+ });
+ return false;
+ }
+ }
+
+ async saveTranscription(text) {
+ try {
+ await window.electronAPI.saveTranscription(text);
+ return true;
+ } catch (error) {
+ console.error("Failed to save transcription:", error);
+ return false;
+ }
+ }
+
+ getState() {
+ return {
+ isRecording: this.isRecording,
+ isProcessing: this.isProcessing,
+ };
+ }
+
+ cleanup() {
+ if (this.mediaRecorder && this.isRecording) {
+ this.stopRecording();
+ }
+ this.onStateChange = null;
+ this.onError = null;
+ this.onTranscriptionComplete = null;
+ }
+}
+
+export default AudioManager;
diff --git a/src/helpers/clipboard.js b/src/helpers/clipboard.js
index a96ea4be2..72e4b9a9f 100644
--- a/src/helpers/clipboard.js
+++ b/src/helpers/clipboard.js
@@ -361,7 +361,7 @@ Would you like to open System Settings now?`;
tryNextCommand();
}
- readClipboard() {
+ async readClipboard() {
try {
const text = clipboard.readText();
console.log("πŸ“‹ Clipboard read:", text ? "Text found" : "Empty");
@@ -371,6 +371,20 @@ Would you like to open System Settings now?`;
throw error;
}
}
+
+ async writeClipboard(text) {
+ try {
+ clipboard.writeText(text);
+ console.log(
+ "πŸ“‹ Text written to clipboard:",
+ text.substring(0, 50) + "..."
+ );
+ return { success: true };
+ } catch (error) {
+ console.error("❌ Error writing to clipboard:", error);
+ throw error;
+ }
+ }
}
module.exports = ClipboardManager;
diff --git a/src/helpers/devServerManager.js b/src/helpers/devServerManager.js
new file mode 100644
index 000000000..26905313a
--- /dev/null
+++ b/src/helpers/devServerManager.js
@@ -0,0 +1,70 @@
+class DevServerManager {
+ static async waitForDevServer(
+ url = "http://localhost:5174/",
+ maxAttempts = 30,
+ delay = 1000
+ ) {
+ for (let i = 0; i < maxAttempts; i++) {
+ try {
+ const http = require("http");
+ const urlObj = new URL(url);
+
+ const result = await new Promise((resolve) => {
+ const req = http.get(
+ {
+ hostname: urlObj.hostname,
+ port: urlObj.port || 80,
+ path: urlObj.pathname,
+ timeout: 2000,
+ },
+ (res) => {
+ resolve(res.statusCode >= 200 && res.statusCode < 400);
+ }
+ );
+
+ req.on("error", () => resolve(false));
+ req.on("timeout", () => {
+ req.destroy();
+ resolve(false);
+ });
+ });
+
+ if (result) {
+ console.log(`Dev server ready after ${i + 1} attempts`);
+ return true;
+ }
+ } catch (error) {
+ console.log(
+ `Waiting for dev server... attempt ${i + 1}/${maxAttempts}`
+ );
+ }
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ }
+ console.error("Dev server failed to start within timeout");
+ return false;
+ }
+
+ static getAppUrl(isControlPanel = false) {
+ if (process.env.NODE_ENV === "development") {
+ return isControlPanel
+ ? "http://localhost:5174/?panel=true"
+ : "http://localhost:5174/";
+ } else {
+ const path = require("path");
+ const htmlPath = path.join(
+ __dirname,
+ "..",
+ "..",
+ "src",
+ "dist",
+ "index.html"
+ );
+ const url = isControlPanel
+ ? `file://${htmlPath}?panel=true`
+ : `file://${htmlPath}`;
+ return url;
+ }
+ }
+}
+
+module.exports = DevServerManager;
\ No newline at end of file
diff --git a/src/helpers/dragManager.js b/src/helpers/dragManager.js
new file mode 100644
index 000000000..72d4e523d
--- /dev/null
+++ b/src/helpers/dragManager.js
@@ -0,0 +1,124 @@
+const { screen } = require("electron");
+
+class DragManager {
+ constructor() {
+ this.isDragging = false;
+ this.dragOffset = { x: 0, y: 0 };
+ this.mouseTrackingInterval = null;
+ this.targetWindow = null;
+ }
+
+ setTargetWindow(window) {
+ this.targetWindow = window;
+ }
+
+ async startWindowDrag() {
+ if (!this.targetWindow || this.targetWindow.isDestroyed()) {
+ return { success: false, message: "Window not available" };
+ }
+
+ try {
+ this.isDragging = true;
+
+ // Get current cursor position
+ const cursorPos = screen.getCursorScreenPoint();
+ const windowPos = this.targetWindow.getPosition();
+
+ // Calculate offset from cursor to window position
+ this.dragOffset = {
+ x: cursorPos.x - windowPos[0],
+ y: cursorPos.y - windowPos[1],
+ };
+
+ // Start tracking mouse movements
+ this.setupMouseTracking();
+
+ console.log("πŸ–±οΈ Window drag started");
+ return { success: true };
+ } catch (error) {
+ console.error("Failed to start window drag:", error);
+ this.isDragging = false;
+ return { success: false, message: error.message };
+ }
+ }
+
+ async stopWindowDrag() {
+ try {
+ this.isDragging = false;
+ this.stopMouseTracking();
+ console.log("πŸ–±οΈ Window drag stopped");
+ return { success: true };
+ } catch (error) {
+ console.error("Failed to stop window drag:", error);
+ return { success: false, message: error.message };
+ }
+ }
+
+ setupMouseTracking() {
+ if (this.mouseTrackingInterval) {
+ clearInterval(this.mouseTrackingInterval);
+ }
+
+ this.mouseTrackingInterval = setInterval(() => {
+ if (
+ this.isDragging &&
+ this.targetWindow &&
+ !this.targetWindow.isDestroyed()
+ ) {
+ this.updateWindowPosition();
+ }
+ }, 16); // ~60fps
+ }
+
+ updateWindowPosition() {
+ try {
+ const cursorPos = screen.getCursorScreenPoint();
+ const newX = cursorPos.x - this.dragOffset.x;
+ const newY = cursorPos.y - this.dragOffset.y;
+
+ // Get screen bounds to keep window visible
+ const display = screen.getDisplayNearestPoint(cursorPos);
+ const bounds = display.workArea;
+
+ // Get window size for boundary calculations
+ const windowBounds = this.targetWindow.getBounds();
+
+ // Constrain to screen bounds
+ const constrainedX = Math.max(
+ bounds.x,
+ Math.min(newX, bounds.x + bounds.width - windowBounds.width)
+ );
+ const constrainedY = Math.max(
+ bounds.y,
+ Math.min(newY, bounds.y + bounds.height - windowBounds.height)
+ );
+
+ this.targetWindow.setPosition(constrainedX, constrainedY);
+ } catch (error) {
+ console.error("Error updating window position:", error);
+ this.stopWindowDrag();
+ }
+ }
+
+ stopMouseTracking() {
+ if (this.mouseTrackingInterval) {
+ clearInterval(this.mouseTrackingInterval);
+ this.mouseTrackingInterval = null;
+ }
+ }
+
+ isDragActive() {
+ return this.isDragging;
+ }
+
+ getDragOffset() {
+ return { ...this.dragOffset };
+ }
+
+ cleanup() {
+ this.stopWindowDrag();
+ this.targetWindow = null;
+ }
+}
+
+module.exports = DragManager;
diff --git a/src/helpers/hotkeyManager.js b/src/helpers/hotkeyManager.js
new file mode 100644
index 000000000..a9d106f3f
--- /dev/null
+++ b/src/helpers/hotkeyManager.js
@@ -0,0 +1,108 @@
+const { globalShortcut } = require("electron");
+
+class HotkeyManager {
+ constructor() {
+ this.currentHotkey = "`";
+ this.isInitialized = false;
+ }
+
+ setupShortcuts(hotkey = "`", callback) {
+ if (!callback) {
+ throw new Error("Callback function is required for hotkey setup");
+ }
+
+ // Unregister all existing shortcuts
+ globalShortcut.unregisterAll();
+
+ try {
+ // Register the new hotkey
+ const success = globalShortcut.register(hotkey, callback);
+
+ if (success) {
+ this.currentHotkey = hotkey;
+ console.log(`πŸ”‘ Hotkey registered: ${hotkey}`);
+ return { success: true, hotkey };
+ } else {
+ console.error(`❌ Failed to register hotkey: ${hotkey}`);
+ return {
+ success: false,
+ error: `Failed to register hotkey: ${hotkey}`,
+ };
+ }
+ } catch (error) {
+ console.error("Error setting up shortcuts:", error);
+ return { success: false, error: error.message };
+ }
+ }
+
+ async initializeHotkey(mainWindow, callback) {
+ if (!mainWindow || !callback) {
+ throw new Error("mainWindow and callback are required");
+ }
+
+ // Set up default hotkey first
+ this.setupShortcuts("`", callback);
+
+ // Listen for window to be ready, then get saved hotkey
+ mainWindow.webContents.once("did-finish-load", () => {
+ setTimeout(() => {
+ this.loadSavedHotkey(mainWindow, callback);
+ }, 1000);
+ });
+
+ this.isInitialized = true;
+ }
+
+ async loadSavedHotkey(mainWindow, callback) {
+ try {
+ const savedHotkey = await mainWindow.webContents.executeJavaScript(`
+ localStorage.getItem("dictationKey") || "\`"
+ `);
+
+ if (savedHotkey && savedHotkey !== "`") {
+ const result = this.setupShortcuts(savedHotkey, callback);
+ if (result.success) {
+ console.log("πŸ”‘ Hotkey initialized from localStorage:", savedHotkey);
+ }
+ }
+ } catch (err) {
+ console.error("Failed to get saved hotkey:", err);
+ }
+ }
+
+ async updateHotkey(hotkey, callback) {
+ if (!callback) {
+ throw new Error("Callback function is required for hotkey update");
+ }
+
+ try {
+ const result = this.setupShortcuts(hotkey, callback);
+ if (result.success) {
+ return { success: true, message: `Hotkey updated to: ${hotkey}` };
+ } else {
+ return { success: false, message: result.error };
+ }
+ } catch (error) {
+ console.error("Failed to update hotkey:", error);
+ return {
+ success: false,
+ message: `Failed to update hotkey: ${error.message}`,
+ };
+ }
+ }
+
+ getCurrentHotkey() {
+ return this.currentHotkey;
+ }
+
+ unregisterAll() {
+ globalShortcut.unregisterAll();
+ console.log("πŸ”‘ All hotkeys unregistered");
+ }
+
+ isHotkeyRegistered(hotkey) {
+ return globalShortcut.isRegistered(hotkey);
+ }
+}
+
+module.exports = HotkeyManager;
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index e7e71cc27..f9d4b1fa7 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -231,6 +231,18 @@ class IPCHandlers {
throw error;
}
});
+
+ ipcMain.handle("update-hotkey", async (event, hotkey) => {
+ return await this.windowManager.updateHotkey(hotkey);
+ });
+
+ ipcMain.handle("start-window-drag", async (event) => {
+ return await this.windowManager.startWindowDrag();
+ });
+
+ ipcMain.handle("stop-window-drag", async (event) => {
+ return await this.windowManager.stopWindowDrag();
+ });
}
}
diff --git a/src/helpers/menuManager.js b/src/helpers/menuManager.js
new file mode 100644
index 000000000..fee3d3729
--- /dev/null
+++ b/src/helpers/menuManager.js
@@ -0,0 +1,67 @@
+const { Menu } = require("electron");
+
+class MenuManager {
+ static setupMainMenu() {
+ if (process.platform === "darwin") {
+ const template = [
+ {
+ label: "OpenWispr",
+ submenu: [
+ { role: "about" },
+ { type: "separator" },
+ { role: "quit", label: "Quit OpenWispr" },
+ ],
+ },
+ ];
+ const menu = Menu.buildFromTemplate(template);
+ Menu.setApplicationMenu(menu);
+ }
+ }
+
+ static setupControlPanelMenu(controlPanelWindow) {
+ const template = [
+ {
+ label: "File",
+ submenu: [{ role: "close", label: "Close Window" }],
+ },
+ {
+ label: "Edit",
+ submenu: [
+ { role: "undo", label: "Undo" },
+ { role: "redo", label: "Redo" },
+ { type: "separator" },
+ { role: "cut", label: "Cut" },
+ { role: "copy", label: "Copy" },
+ { role: "paste", label: "Paste" },
+ { role: "pasteAndMatchStyle", label: "Paste and Match Style" },
+ { type: "separator" },
+ { role: "selectall", label: "Select All" },
+ ],
+ },
+ {
+ label: "View",
+ submenu: [
+ { role: "reload", label: "Reload" },
+ { role: "forceReload", label: "Force Reload" },
+ { role: "toggleDevTools", label: "Toggle Developer Tools" },
+ { type: "separator" },
+ { role: "resetZoom", label: "Actual Size" },
+ { role: "zoomIn", label: "Zoom In" },
+ { role: "zoomOut", label: "Zoom Out" },
+ { type: "separator" },
+ { role: "togglefullscreen", label: "Toggle Full Screen" },
+ ],
+ },
+ ];
+
+ const menu = Menu.buildFromTemplate(template);
+ controlPanelWindow.setMenu(menu);
+
+ // Also set as application menu on macOS for clipboard access
+ if (process.platform === "darwin") {
+ Menu.setApplicationMenu(menu);
+ }
+ }
+}
+
+module.exports = MenuManager;
diff --git a/src/helpers/whisper.js b/src/helpers/whisper.js
index 55adf8854..e0107c117 100644
--- a/src/helpers/whisper.js
+++ b/src/helpers/whisper.js
@@ -92,21 +92,25 @@ class WhisperManager {
// Get FFmpeg path with proper production/development handling
let ffmpegPath;
- if (process.env.NODE_ENV === "development") {
+ try {
ffmpegPath = require("ffmpeg-static");
- } else {
- // Production: try unpacked location first, then fallback
- try {
- const originalPath = require("ffmpeg-static");
- ffmpegPath = originalPath.replace("app.asar", "app.asar.unpacked");
- if (!fs.existsSync(ffmpegPath)) {
- ffmpegPath = originalPath;
+ // In production, try unpacked version if original doesn't exist
+ if (
+ process.env.NODE_ENV !== "development" &&
+ !fs.existsSync(ffmpegPath)
+ ) {
+ const unpackedPath = ffmpegPath.replace(
+ "app.asar",
+ "app.asar.unpacked"
+ );
+ if (fs.existsSync(unpackedPath)) {
+ ffmpegPath = unpackedPath;
}
- } catch (e) {
- console.error("Could not resolve FFmpeg path:", e.message);
- ffmpegPath = null;
}
+ } catch (e) {
+ console.error("Could not resolve FFmpeg path:", e.message);
+ ffmpegPath = "ffmpeg"; // Try system ffmpeg as fallback
}
// Enhanced environment setup
diff --git a/src/helpers/windowConfig.js b/src/helpers/windowConfig.js
new file mode 100644
index 000000000..a6abaab43
--- /dev/null
+++ b/src/helpers/windowConfig.js
@@ -0,0 +1,81 @@
+const path = require("path");
+
+// Main dictation window configuration
+const MAIN_WINDOW_CONFIG = {
+ width: 100,
+ height: 100,
+ webPreferences: {
+ preload: path.join(__dirname, "..", "..", "preload.js"),
+ nodeIntegration: false,
+ contextIsolation: true,
+ enableRemoteModule: false,
+ sandbox: true,
+ },
+ frame: false,
+ alwaysOnTop: true,
+ resizable: false,
+ transparent: true,
+ show: true,
+ skipTaskbar: false,
+ focusable: true,
+};
+
+// Control panel window configuration
+const CONTROL_PANEL_CONFIG = {
+ width: 800,
+ height: 700,
+ webPreferences: {
+ preload: path.join(__dirname, "..", "..", "preload.js"),
+ nodeIntegration: false,
+ contextIsolation: true,
+ enableRemoteModule: false,
+ sandbox: false,
+ webSecurity: false,
+ spellcheck: false,
+ experimentalFeatures: false,
+ allowRunningInsecureContent: false,
+ enableWebSQL: false,
+ enableBlinkFeatures: "",
+ defaultEncoding: "UTF-8",
+ disableHtmlFullscreenWindowResize: false,
+ enableClipboardAccess: true,
+ clipboard: true,
+ },
+ title: "OpenWispr Control Panel",
+ resizable: true,
+ show: false,
+ titleBarStyle: "hiddenInset",
+ frame: false,
+ transparent: false,
+ backgroundColor: "#ffffff",
+ minimizable: true,
+ maximizable: true,
+ closable: true,
+ fullscreenable: true,
+};
+
+// Window positioning utilities
+class WindowPositionUtil {
+ static getMainWindowPosition(display) {
+ const { width, height } = MAIN_WINDOW_CONFIG;
+ const x = Math.max(
+ 0,
+ display.bounds.x + display.workArea.width - width - 20
+ );
+ const y = Math.max(0, display.bounds.y + display.workArea.height);
+ return { x, y, width, height };
+ }
+
+ static setupAlwaysOnTop(window) {
+ window.setAlwaysOnTop(true, "screen-saver");
+ window.setVisibleOnAllWorkspaces(true, {
+ visibleOnFullScreen: true,
+ });
+ }
+}
+
+module.exports = {
+ MAIN_WINDOW_CONFIG,
+ CONTROL_PANEL_CONFIG,
+ WindowPositionUtil,
+};
diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.js
index 18bdb6acd..9f63069e0 100644
--- a/src/helpers/windowManager.js
+++ b/src/helpers/windowManager.js
@@ -1,60 +1,43 @@
+const { screen, BrowserWindow } = require("electron");
+const HotkeyManager = require("./hotkeyManager");
+const DragManager = require("./dragManager");
+const MenuManager = require("./menuManager");
+const DevServerManager = require("./devServerManager");
const {
- screen,
- BrowserWindow,
- globalShortcut,
- Menu,
- Tray,
-} = require("electron");
-const path = require("path");
+ MAIN_WINDOW_CONFIG,
+ CONTROL_PANEL_CONFIG,
+ WindowPositionUtil,
+} = require("./windowConfig");
class WindowManager {
constructor() {
this.mainWindow = null;
this.controlPanelWindow = null;
this.tray = null;
+ this.hotkeyManager = new HotkeyManager();
+ this.dragManager = new DragManager();
}
async createMainWindow() {
console.log("πŸ”„ Creating main window...");
const display = screen.getPrimaryDisplay();
- const width = 100;
- const height = 100;
- // Position window in bottom-right corner, but ensure it's visible
- const x = Math.max(
- 0,
- display.bounds.x + display.workArea.width - width - 20
- );
- const y = Math.max(0, display.bounds.y + display.workArea.height);
+ const position = WindowPositionUtil.getMainWindowPosition(display);
- console.log("πŸ“ Window dimensions:", { width, height, x, y });
+ console.log("πŸ“ Window dimensions:", position);
this.mainWindow = new BrowserWindow({
- width,
- height,
- x,
- y,
- webPreferences: {
- preload: path.join(__dirname, "..", "..", "preload.js"),
- nodeIntegration: false,
- contextIsolation: true,
- enableRemoteModule: false,
- sandbox: true,
- },
- frame: false,
- alwaysOnTop: true,
- resizable: false,
- transparent: true,
- show: true,
- skipTaskbar: false,
- focusable: true,
+ ...MAIN_WINDOW_CONFIG,
+ ...position,
});
console.log("πŸ“± Loading main window content...");
await this.loadMainWindow();
console.log("⌨️ Setting up shortcuts...");
- this.setupShortcuts();
+ await this.initializeHotkey();
+ console.log("πŸ–±οΈ Setting up drag manager...");
+ this.dragManager.setTargetWindow(this.mainWindow);
console.log("🍎 Setting up menu...");
- this.setupMenu();
+ MenuManager.setupMainMenu();
console.log("βœ… Main window created successfully");
this.mainWindow.webContents.on(
@@ -72,7 +55,7 @@ class WindowManager {
) {
console.log("Retrying connection to dev server in 2 seconds...");
setTimeout(async () => {
- const isReady = await this.waitForDevServer();
+ const isReady = await DevServerManager.waitForDevServer();
if (isReady) {
console.log("Dev server ready, reloading...");
this.mainWindow.reload();
@@ -104,22 +87,16 @@ class WindowManager {
});
// Ensure window is always on top, even above fullscreen apps
- this.mainWindow.setAlwaysOnTop(true, "screen-saver");
- this.mainWindow.setVisibleOnAllWorkspaces(true, {
- visibleOnFullScreen: true,
- });
+ WindowPositionUtil.setupAlwaysOnTop(this.mainWindow);
this.mainWindow.on("show", () => {
- this.mainWindow.setAlwaysOnTop(true, "screen-saver");
- this.mainWindow.setVisibleOnAllWorkspaces(true, {
- visibleOnFullScreen: true,
- });
+ WindowPositionUtil.setupAlwaysOnTop(this.mainWindow);
});
}
async loadMainWindow() {
- const appUrl = this.getAppUrl(false);
+ const appUrl = DevServerManager.getAppUrl(false);
if (process.env.NODE_ENV === "development") {
- const isReady = await this.waitForDevServer();
+ const isReady = await DevServerManager.waitForDevServer();
if (!isReady) {
console.error("Dev server not ready, loading anyway...");
}
@@ -127,76 +104,34 @@ class WindowManager {
this.mainWindow.loadURL(appUrl);
}
- setupShortcuts() {
- globalShortcut.unregisterAll();
- globalShortcut.register("`", () => {
+ async initializeHotkey() {
+ const callback = () => {
if (!this.mainWindow.isVisible()) {
this.mainWindow.show();
}
this.mainWindow.webContents.send("toggle-dictation");
- });
- }
+ };
- setupMenu() {
- if (process.platform === "darwin") {
- const template = [
- {
- label: "OpenWispr",
- submenu: [
- { role: "about" },
- { type: "separator" },
- { role: "quit", label: "Quit OpenWispr" },
- ],
- },
- ];
- const menu = Menu.buildFromTemplate(template);
- Menu.setApplicationMenu(menu);
- }
+ await this.hotkeyManager.initializeHotkey(this.mainWindow, callback);
}
- setupControlPanelMenu() {
- const template = [
- {
- label: "File",
- submenu: [{ role: "close", label: "Close Window" }],
- },
- {
- label: "Edit",
- submenu: [
- { role: "undo", label: "Undo" },
- { role: "redo", label: "Redo" },
- { type: "separator" },
- { role: "cut", label: "Cut" },
- { role: "copy", label: "Copy" },
- { role: "paste", label: "Paste" },
- { role: "pasteAndMatchStyle", label: "Paste and Match Style" },
- { type: "separator" },
- { role: "selectall", label: "Select All" },
- ],
- },
- {
- label: "View",
- submenu: [
- { role: "reload", label: "Reload" },
- { role: "forceReload", label: "Force Reload" },
- { role: "toggleDevTools", label: "Toggle Developer Tools" },
- { type: "separator" },
- { role: "resetZoom", label: "Actual Size" },
- { role: "zoomIn", label: "Zoom In" },
- { role: "zoomOut", label: "Zoom Out" },
- { type: "separator" },
- { role: "togglefullscreen", label: "Toggle Full Screen" },
- ],
- },
- ];
+ async updateHotkey(hotkey) {
+ const callback = () => {
+ if (!this.mainWindow.isVisible()) {
+ this.mainWindow.show();
+ }
+ this.mainWindow.webContents.send("toggle-dictation");
+ };
+
+ return await this.hotkeyManager.updateHotkey(hotkey, callback);
+ }
- const menu = Menu.buildFromTemplate(template);
- this.controlPanelWindow.setMenu(menu);
+ async startWindowDrag() {
+ return await this.dragManager.startWindowDrag();
+ }
- // Also set the menu as the application menu to ensure clipboard access
- if (process.platform === "darwin") {
- Menu.setApplicationMenu(menu);
- }
+ async stopWindowDrag() {
+ return await this.dragManager.stopWindowDrag();
}
async createControlPanelWindow() {
@@ -210,52 +145,13 @@ class WindowManager {
return;
}
- this.controlPanelWindow = new BrowserWindow({
- width: 800,
- height: 700,
- webPreferences: {
- preload: path.join(__dirname, "..", "..", "preload.js"),
- nodeIntegration: false,
- contextIsolation: true,
- enableRemoteModule: false,
- sandbox: false,
- webSecurity: false,
- // Enable text input and clipboard access
- spellcheck: false,
- experimentalFeatures: false,
- // Ensure text input works
- allowRunningInsecureContent: false,
- // Enable proper text selection and input
- enableWebSQL: false,
- // Allow paste operations
- enableBlinkFeatures: "",
- // Additional settings for text input
- defaultEncoding: "UTF-8",
- // Ensure text input is not blocked
- disableHtmlFullscreenWindowResize: false,
- // Enable clipboard access
- enableClipboardAccess: true,
- // Allow clipboard read/write
- clipboard: true,
- },
- title: "OpenWispr Control Panel",
- resizable: true,
- show: false, // Don't show until content is loaded
- titleBarStyle: "hiddenInset",
- frame: false,
- transparent: false,
- backgroundColor: "#ffffff",
- minimizable: true,
- maximizable: true,
- closable: true,
- fullscreenable: true,
- });
+ this.controlPanelWindow = new BrowserWindow(CONTROL_PANEL_CONFIG);
console.log("πŸ“± Loading control panel content...");
await this.loadControlPanel();
// Set up menu for control panel to ensure text input works
- this.setupControlPanelMenu();
+ MenuManager.setupControlPanelMenu(this.controlPanelWindow);
// Show and focus the window after content is loaded
this.controlPanelWindow.show();
@@ -270,9 +166,9 @@ class WindowManager {
}
async loadControlPanel() {
- const appUrl = this.getAppUrl(true);
+ const appUrl = DevServerManager.getAppUrl(true);
if (process.env.NODE_ENV === "development") {
- const isReady = await this.waitForDevServer();
+ const isReady = await DevServerManager.waitForDevServer();
if (!isReady) {
console.error(
"Dev server not ready for control panel, loading anyway..."
@@ -290,72 +186,6 @@ class WindowManager {
this.mainWindow.focus();
}
}
-
- async waitForDevServer(
- url = "http://localhost:5174/",
- maxAttempts = 30,
- delay = 1000
- ) {
- for (let i = 0; i < maxAttempts; i++) {
- try {
- const http = require("http");
- const urlObj = new URL(url);
-
- const result = await new Promise((resolve) => {
- const req = http.get(
- {
- hostname: urlObj.hostname,
- port: urlObj.port || 80,
- path: urlObj.pathname,
- timeout: 2000,
- },
- (res) => {
- resolve(res.statusCode >= 200 && res.statusCode < 400);
- }
- );
-
- req.on("error", () => resolve(false));
- req.on("timeout", () => {
- req.destroy();
- resolve(false);
- });
- });
-
- if (result) {
- console.log(`Dev server ready after ${i + 1} attempts`);
- return true;
- }
- } catch (error) {
- console.log(
- `Waiting for dev server... attempt ${i + 1}/${maxAttempts}`
- );
- }
- await new Promise((resolve) => setTimeout(resolve, delay));
- }
- console.error("Dev server failed to start within timeout");
- return false;
- }
-
- getAppUrl(isControlPanel = false) {
- if (process.env.NODE_ENV === "development") {
- return isControlPanel
- ? "http://localhost:5174/?panel=true"
- : "http://localhost:5174/";
- } else {
- const htmlPath = path.join(
- __dirname,
- "..",
- "..",
- "src",
- "dist",
- "index.html"
- );
- const url = isControlPanel
- ? `file://${htmlPath}?panel=true`
- : `file://${htmlPath}`;
- return url;
- }
- }
}
module.exports = WindowManager;
diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.js
new file mode 100644
index 000000000..708b2404d
--- /dev/null
+++ b/src/hooks/useAudioRecording.js
@@ -0,0 +1,122 @@
+import { useState, useEffect, useRef } from "react";
+import AudioManager from "../helpers/audioManager";
+
+export const useAudioRecording = (toast) => {
+ const [isRecording, setIsRecording] = useState(false);
+ const [isProcessing, setIsProcessing] = useState(false);
+ const [transcript, setTranscript] = useState("");
+ const audioManagerRef = useRef(null);
+
+ useEffect(() => {
+ // Initialize AudioManager
+ audioManagerRef.current = new AudioManager();
+
+ // Set up callbacks
+ audioManagerRef.current.setCallbacks({
+ onStateChange: ({ isRecording, isProcessing }) => {
+ setIsRecording(isRecording);
+ setIsProcessing(isProcessing);
+ },
+ onError: (error) => {
+ toast({
+ title: error.title,
+ description: error.description,
+ variant: "destructive",
+ });
+ },
+ onTranscriptionComplete: async (result) => {
+ if (result.success) {
+ setTranscript(result.text);
+
+ // Paste immediately
+ await audioManagerRef.current.safePaste(result.text);
+
+ // Save to database in parallel
+ audioManagerRef.current.saveTranscription(result.text);
+
+ // Show success notification if local fallback was used
+ if (
+ result.source === "openai" &&
+ localStorage.getItem("useLocalWhisper") === "true"
+ ) {
+ toast({
+ title: "Fallback Mode",
+ description: "Local Whisper failed. Used OpenAI API instead.",
+ variant: "default",
+ });
+ }
+ }
+ },
+ });
+
+ // Set up hotkey listener
+ let recording = false;
+ const handleToggle = () => {
+ const currentState = audioManagerRef.current.getState();
+
+ if (
+ !recording &&
+ !currentState.isRecording &&
+ !currentState.isProcessing
+ ) {
+ audioManagerRef.current.startRecording();
+ recording = true;
+ } else if (currentState.isRecording) {
+ audioManagerRef.current.stopRecording();
+ recording = false;
+ }
+ };
+
+ window.electronAPI.onToggleDictation(handleToggle);
+
+ // Set up no-audio-detected listener
+ const handleNoAudioDetected = () => {
+ toast({
+ title: "No Audio Detected",
+ description:
+ "The recording contained no detectable audio. Please try again.",
+ variant: "default",
+ });
+ };
+
+ window.electronAPI.onNoAudioDetected?.(handleNoAudioDetected);
+
+ // Cleanup
+ return () => {
+ if (audioManagerRef.current) {
+ audioManagerRef.current.cleanup();
+ }
+ };
+ }, [toast]);
+
+ const startRecording = async () => {
+ if (audioManagerRef.current) {
+ return await audioManagerRef.current.startRecording();
+ }
+ return false;
+ };
+
+ const stopRecording = () => {
+ if (audioManagerRef.current) {
+ return audioManagerRef.current.stopRecording();
+ }
+ return false;
+ };
+
+ const toggleListening = () => {
+ if (!isRecording && !isProcessing) {
+ startRecording();
+ } else if (isRecording) {
+ stopRecording();
+ }
+ };
+
+ return {
+ isRecording,
+ isProcessing,
+ transcript,
+ startRecording,
+ stopRecording,
+ toggleListening,
+ };
+};
diff --git a/src/hooks/useHotkey.js b/src/hooks/useHotkey.js
new file mode 100644
index 000000000..e2dd48b3b
--- /dev/null
+++ b/src/hooks/useHotkey.js
@@ -0,0 +1,18 @@
+import { useState, useEffect } from "react";
+
+export const useHotkey = () => {
+ const [hotkey, setHotkey] = useState("`");
+
+ useEffect(() => {
+ // Load hotkey from localStorage on mount
+ const savedHotkey = localStorage.getItem("dictationKey");
+ if (savedHotkey) {
+ setHotkey(savedHotkey);
+ }
+ }, []);
+
+ return {
+ hotkey,
+ setHotkey,
+ };
+};
diff --git a/src/hooks/useWindowDrag.js b/src/hooks/useWindowDrag.js
new file mode 100644
index 000000000..b80189090
--- /dev/null
+++ b/src/hooks/useWindowDrag.js
@@ -0,0 +1,49 @@
+import { useState, useEffect } from "react";
+
+export const useWindowDrag = () => {
+ const [isDragging, setIsDragging] = useState(false);
+
+ const handleMouseDown = (e) => {
+ if (e.button === 0) {
+ // Left mouse button
+ setIsDragging(true);
+ window.electronAPI.startWindowDrag?.();
+ e.preventDefault();
+ }
+ };
+
+ const handleMouseUp = () => {
+ if (isDragging) {
+ setIsDragging(false);
+ window.electronAPI.stopWindowDrag?.();
+ }
+ };
+
+ const handleClick = (e) => {
+ // Prevent any click actions - use hotkey only
+ e.preventDefault();
+ };
+
+ // Set up global mouse up listener when dragging
+ useEffect(() => {
+ if (isDragging) {
+ const handleGlobalMouseUp = () => {
+ setIsDragging(false);
+ window.electronAPI.stopWindowDrag?.();
+ };
+
+ document.addEventListener("mouseup", handleGlobalMouseUp);
+
+ return () => {
+ document.removeEventListener("mouseup", handleGlobalMouseUp);
+ };
+ }
+ }, [isDragging]);
+
+ return {
+ isDragging,
+ handleMouseDown,
+ handleMouseUp,
+ handleClick,
+ };
+};