Isolate setup from tray and verify native clipboard acceptance
This commit is contained in:
parent
8d6dc1ab22
commit
a44d45f431
5 changed files with 98 additions and 10 deletions
|
|
@ -2,4 +2,4 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
__version__ = "0.3.0b6"
|
__version__ = "0.3.0b7"
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,12 @@ def main() -> None:
|
||||||
import tempfile
|
import tempfile
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory(prefix="voice-setup-smoke-") as directory:
|
from voice_dictation.ui.setup_acceptance import synthetic_clipboard
|
||||||
|
|
||||||
|
with (
|
||||||
|
synthetic_clipboard(),
|
||||||
|
tempfile.TemporaryDirectory(prefix="voice-setup-smoke-") as directory,
|
||||||
|
):
|
||||||
test_root = Path(directory)
|
test_root = Path(directory)
|
||||||
if not run_setup(
|
if not run_setup(
|
||||||
test_root, ConfigStore(test_root / "config.json"), smoke_test=True
|
test_root, ConfigStore(test_root / "config.json"), smoke_test=True
|
||||||
|
|
@ -43,6 +48,15 @@ def main() -> None:
|
||||||
raise RuntimeError("Setup smoke test failed to save synthetic settings")
|
raise RuntimeError("Setup smoke test failed to save synthetic settings")
|
||||||
return
|
return
|
||||||
setup_paths = AppPaths.default().ensure_exists()
|
setup_paths = AppPaths.default().ensure_exists()
|
||||||
|
if "--startup-setup-test" in sys.argv:
|
||||||
|
from voice_dictation.ui.setup_acceptance import synthetic_clipboard
|
||||||
|
|
||||||
|
with synthetic_clipboard():
|
||||||
|
if not run_setup(
|
||||||
|
setup_paths.root, ConfigStore(setup_paths.config_file), smoke_test=True
|
||||||
|
):
|
||||||
|
raise RuntimeError("Startup setup test failed")
|
||||||
|
else:
|
||||||
run_setup(setup_paths.root, ConfigStore(setup_paths.config_file))
|
run_setup(setup_paths.root, ConfigStore(setup_paths.config_file))
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
@ -98,9 +112,26 @@ def main() -> None:
|
||||||
config.splash_enabled = False
|
config.splash_enabled = False
|
||||||
config_store.save(config)
|
config_store.save(config)
|
||||||
if not (paths.root / "setup-complete").exists():
|
if not (paths.root / "setup-complete").exists():
|
||||||
from voice_dictation.ui.setup_wizard import run_setup
|
import os
|
||||||
|
import subprocess
|
||||||
|
|
||||||
if not run_setup(paths.root, config_store):
|
# Tk and pystray/AppKit must not share a process on macOS.
|
||||||
|
setup_command = (
|
||||||
|
[sys.executable, "setup"]
|
||||||
|
if getattr(sys, "frozen", False)
|
||||||
|
else [sys.executable, "-m", "voice_dictation", "setup"]
|
||||||
|
)
|
||||||
|
if "--startup-smoke-test" in sys.argv:
|
||||||
|
setup_command.append("--startup-setup-test")
|
||||||
|
setup_env = os.environ.copy()
|
||||||
|
setup_env["VOICE_DICTATION_HOME"] = str(paths.root)
|
||||||
|
try:
|
||||||
|
setup_result = subprocess.run(setup_command, env=setup_env, check=False)
|
||||||
|
except OSError:
|
||||||
|
logger.error("Не удалось открыть мастер настройки")
|
||||||
|
lock.release()
|
||||||
|
return
|
||||||
|
if setup_result.returncode or not (paths.root / "setup-complete").exists():
|
||||||
lock.release()
|
lock.release()
|
||||||
return
|
return
|
||||||
config = config_store.load()
|
config = config_store.load()
|
||||||
|
|
@ -314,6 +345,9 @@ def main() -> None:
|
||||||
hotkey_display = config.hotkey.replace("cmd", "⌘").replace("alt", "⌥").replace("ctrl", "⌃")
|
hotkey_display = config.hotkey.replace("cmd", "⌘").replace("alt", "⌥").replace("ctrl", "⌃")
|
||||||
print(f"Voice Dictation запущен в трее. Хоткей: {hotkey_display}")
|
print(f"Voice Dictation запущен в трее. Хоткей: {hotkey_display}")
|
||||||
|
|
||||||
|
if "--startup-smoke-test" in sys.argv:
|
||||||
|
threading.Timer(2.0, _quit).start()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
tray.run()
|
tray.run()
|
||||||
finally:
|
finally:
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,17 @@ import customtkinter as ctk
|
||||||
def paste_into(entry: ctk.CTkEntry, reader: Callable[[], str] | None = None) -> str:
|
def paste_into(entry: ctk.CTkEntry, reader: Callable[[], str] | None = None) -> str:
|
||||||
"""Paste without exposing clipboard data, replacing the current selection."""
|
"""Paste without exposing clipboard data, replacing the current selection."""
|
||||||
try:
|
try:
|
||||||
value = (reader or entry.clipboard_get)()
|
if reader is not None:
|
||||||
|
value = reader()
|
||||||
|
elif sys.platform == "darwin":
|
||||||
|
from AppKit import NSPasteboard, NSPasteboardTypeString
|
||||||
|
|
||||||
|
native_value = NSPasteboard.generalPasteboard().stringForType_(NSPasteboardTypeString)
|
||||||
|
if native_value is None:
|
||||||
|
return "break"
|
||||||
|
value = str(native_value)
|
||||||
|
else:
|
||||||
|
value = entry.clipboard_get()
|
||||||
if entry.select_present():
|
if entry.select_present():
|
||||||
entry.delete("sel.first", "sel.last")
|
entry.delete("sel.first", "sel.last")
|
||||||
entry.insert("insert", value)
|
entry.insert("insert", value)
|
||||||
|
|
|
||||||
33
src/voice_dictation/ui/setup_acceptance.py
Normal file
33
src/voice_dictation/ui/setup_acceptance.py
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
"""Native setup acceptance helpers using synthetic clipboard content only."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def synthetic_clipboard() -> Iterator[None]:
|
||||||
|
"""Temporarily replace and restore every native pasteboard representation."""
|
||||||
|
if sys.platform != "darwin":
|
||||||
|
raise RuntimeError("Native clipboard acceptance currently requires macOS")
|
||||||
|
from AppKit import NSPasteboard, NSPasteboardItem, NSPasteboardTypeString
|
||||||
|
|
||||||
|
board = NSPasteboard.generalPasteboard()
|
||||||
|
saved = []
|
||||||
|
for item in board.pasteboardItems() or []:
|
||||||
|
restored = NSPasteboardItem.alloc().init()
|
||||||
|
for kind in item.types():
|
||||||
|
data = item.dataForType_(kind)
|
||||||
|
if data is not None:
|
||||||
|
restored.setData_forType_(data, kind)
|
||||||
|
saved.append(restored)
|
||||||
|
board.clearContents()
|
||||||
|
board.setString_forType_("sk-test-not-a-real-key", NSPasteboardTypeString)
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
board.clearContents()
|
||||||
|
if saved:
|
||||||
|
board.writeObjects_(saved)
|
||||||
|
|
@ -34,9 +34,9 @@ def run_setup(root: Path, store: ConfigStore, *, smoke_test: bool = False) -> bo
|
||||||
ctk.CTkLabel(content, text="OpenAI API-ключ или строка OPENAI_API_KEY=…:").pack()
|
ctk.CTkLabel(content, text="OpenAI API-ключ или строка OPENAI_API_KEY=…:").pack()
|
||||||
key = ctk.CTkEntry(content, show="•", width=540, placeholder_text="Вставьте ключ здесь")
|
key = ctk.CTkEntry(content, show="•", width=540, placeholder_text="Вставьте ключ здесь")
|
||||||
key.pack(pady=6)
|
key.pack(pady=6)
|
||||||
test_reader = (lambda: "sk-test-not-a-real-key") if smoke_test else None
|
bind_paste(key)
|
||||||
bind_paste(key, test_reader)
|
paste_button = ctk.CTkButton(content, text="Вставить ключ", command=lambda: paste_into(key))
|
||||||
ctk.CTkButton(content, text="Вставить ключ", command=lambda: paste_into(key)).pack(pady=4)
|
paste_button.pack(pady=4)
|
||||||
ctk.CTkLabel(
|
ctk.CTkLabel(
|
||||||
content,
|
content,
|
||||||
text="Ключ сохраняется отдельно в вашем профиле с правами 0600.\n"
|
text="Ключ сохраняется отдельно в вашем профиле с правами 0600.\n"
|
||||||
|
|
@ -75,7 +75,7 @@ def run_setup(root: Path, store: ConfigStore, *, smoke_test: bool = False) -> bo
|
||||||
import sounddevice as sd
|
import sounddevice as sd
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with sd.InputStream(samplerate=16000, channels=1) as stream:
|
with sd.RawInputStream(samplerate=16000, channels=1, dtype="int16") as stream:
|
||||||
stream.read(1600)
|
stream.read(1600)
|
||||||
status.configure(text="Микрофон: запись доступна. Аудио не сохранено и не отправлено.")
|
status.configure(text="Микрофон: запись доступна. Аудио не сохранено и не отправлено.")
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|
@ -154,6 +154,11 @@ def run_setup(root: Path, store: ConfigStore, *, smoke_test: bool = False) -> bo
|
||||||
backend.set("OpenAI API")
|
backend.set("OpenAI API")
|
||||||
|
|
||||||
def test_paste() -> None:
|
def test_paste() -> None:
|
||||||
|
paste_button.invoke()
|
||||||
|
if key.get() != "sk-test-not-a-real-key":
|
||||||
|
raise RuntimeError("Native clipboard button test failed before keyboard test")
|
||||||
|
key.delete(0, "end")
|
||||||
|
window.focus_force()
|
||||||
key.focus_set()
|
key.focus_set()
|
||||||
window.update()
|
window.update()
|
||||||
focused = window.focus_get()
|
focused = window.focus_get()
|
||||||
|
|
@ -166,7 +171,13 @@ def run_setup(root: Path, store: ConfigStore, *, smoke_test: bool = False) -> bo
|
||||||
focused.event_generate("<Command-KeyPress-Cyrillic_em>")
|
focused.event_generate("<Command-KeyPress-Cyrillic_em>")
|
||||||
if key.get() != "sk-test-not-a-real-key":
|
if key.get() != "sk-test-not-a-real-key":
|
||||||
raise RuntimeError("Russian layout paste/selection test failed")
|
raise RuntimeError("Russian layout paste/selection test failed")
|
||||||
|
key.delete(0, "end")
|
||||||
|
paste_button.invoke()
|
||||||
|
if key.get() != "sk-test-not-a-real-key":
|
||||||
|
raise RuntimeError("Native clipboard button test failed")
|
||||||
finish()
|
finish()
|
||||||
|
if completed and read_api_key(root) != "sk-test-not-a-real-key":
|
||||||
|
raise RuntimeError("Saved key mismatch")
|
||||||
|
|
||||||
hotkey.delete(0, "end")
|
hotkey.delete(0, "end")
|
||||||
hotkey.insert(0, "cmd+space")
|
hotkey.insert(0, "cmd+space")
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue