Doubao-powered voice input for Linux, Wayland and Omarchy
feat(ui): add listening waveform styles and basketball rhythm (#8)
Leyang6589e1bb2f52
diff --git a/README.md b/README.mdindex 28d2121..4862352 100644--- a/README.md+++ b/README.md@@ -74,7 +74,19 @@ Your keyboard must report Fn as a Linux key; otherwise choose another key.- Press the active trigger twice to send Enter without dictation. This can submit messages or execute terminal commands.- Configure the hold threshold, double-tap interval, Enter gesture and startup.-The bottom overlay shows an audio-driven blue mirrored waveform and live text.+The bottom overlay shows an audio-driven waveform and live text.+Choose Classic bars, Soft waves, Concentric ripples, or Basketball rhythm+under Settings → Appearance → Listening waveform. The basketball theme uses an+fine wave strands that subtly form a dribbling figure and an orange ball.+The figure stays at a fixed size with planted feet, a rhythmic rightward+shoulder pop, and a hand that leads the bouncing ball. The phrase alternates+anticipation, a fast downward push, a squashed impact, a shoulder snap with+delayed head turn, a short hold and recovery.+Dribbling speed follows an estimate of speech cadence from audio energy onsets,+not volume or recognized words per minute. Pauses freeze the pose; volume only+affects brightness. No solid character or ball outlines are drawn. Changes save automatically; use Preview appearance to try them.+Classic bars remains the default. Reduced updates also stop travelling and+bouncing motion in the new styles while retaining volume feedback.Final text is pasted after recording ends; target fields are not revised live.No green volume/progress bar is shown.The system tray waveform opens the existing app when clicked: blue when ready,diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 545062d..75b213c 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -59,7 +59,11 @@ API Key 通过仅限当前用户读取的独立文件保存,不进入诊断信- 连续按两次当前触发快捷键会在不听写的情况下发送回车,可能发送消息或执行终端命令。- 长按阈值、双击间隔、双击回车开关和自启动均可设置。-底部悬浮窗显示声音驱动的蓝色镜像波形和实时文字。+底部悬浮窗显示声音驱动的波纹和实时文字。+在「设置 → 外观 → 聆听波纹样式」中,可切换经典声柱、柔和声浪、同心涟漪和+「篮球律动」。篮球主题由细密声波隐约拼出人形和橙色球,人物尺寸固定、双脚站稳,随运球节奏向右顶肩再收回,手提前下压再回收,并带有触地涟漪。动作按「屈膝蓄力 → 拍球 → 触地压扁 → 顶肩、头部滞后 → 短暂停顿 → 收回」循环。拍球速度由声音起伏估计的说话节奏控制(不是音量,也不是识别后的每分钟字数);停顿时定格,音量只影响明暗,不绘制实心人物或球的轮廓。+更改自动保存,可点击「预览外观」查看;默认仍为经典声柱。+开启「减少波形更新」后,新样式会停止行进和弹跳动画,保留音量反馈。最终文字在录音结束后粘贴,目标输入框不会边说边更新。没有绿色音量条或进度条。单击系统托盘的波形图标会打开已有应用窗口:就绪时蓝色、录音时红色、转写时黄色。部分桌面会将托盘图标收纳在可展开的区域中。diff --git a/src/doubao_input/app.py b/src/doubao_input/app.pyindex 2e8fd0a..c9a7ad6 100644--- a/src/doubao_input/app.py+++ b/src/doubao_input/app.py@@ -188,6 +188,7 @@ class DoubaoInputApp(Gtk.Application):self._audio_capture = AudioCapture(on_rms=self._on_audio_rms)self._audio_capture.device = self.settings.microphoneself._overlay.reduced_motion = self.settings.reduced_motion+ self._overlay.waveform_style = self.settings.waveform_styletm.audio_capture = self._audio_capturetm.on_show_login = self._show_login@@ -310,6 +311,7 @@ class DoubaoInputApp(Gtk.Application):self._triggers.configure(value, strict=strict)self._audio_capture.device = value.microphoneself._overlay.reduced_motion = value.reduced_motion+ self._overlay.waveform_style = value.waveform_styleapply_preferences(previous, settings,lambda value: apply_runtime(value, True),diff --git a/src/doubao_input/settings.py b/src/doubao_input/settings.pyindex 2a35016..bdc3928 100644--- a/src/doubao_input/settings.py+++ b/src/doubao_input/settings.py@@ -153,6 +153,9 @@ def write_atomic(path, data, mode=0o600):temporary.unlink(missing_ok=True)+WAVEFORM_STYLES = ("bars", "waves", "ripples", "basketball")++@dataclassclass Settings:version: int = 1@@ -165,6 +168,7 @@ class Settings:autostart: bool = Falsemicrophone: str = ""reduced_motion: bool = False+ waveform_style: str = "bars"polish_enabled: bool = Falsepolish_base_url: str = "https://api.openai.com/v1"polish_model: str = "gpt-4o-mini"@@ -173,6 +177,8 @@ class Settings:onboarding_complete: bool = Falsedef validate(self):+ if self.waveform_style not in WAVEFORM_STYLES:+ raise ValueError(tr("Unsupported waveform style", "不支持的波纹样式"))if self.language not in LANGUAGES:raise ValueError("Unsupported language")if not isinstance(self.microphone, str) or len(self.microphone) > 256 or any(c in self.microphone for c in '\n\r\x00'):diff --git a/src/doubao_input/setup_session.py b/src/doubao_input/setup_session.pyindex e8ae63b..7208118 100644--- a/src/doubao_input/setup_session.py+++ b/src/doubao_input/setup_session.py@@ -1,6 +1,7 @@"""Own onboarding microphone/voice tests and temporary appearance previews."""from enum import Enum, autoimport threading+import mathfrom doubao_input.i18n import trfrom doubao_input.timers import TimerScope@@ -47,7 +48,12 @@ class SetupSession:self.mode = SetupMode.APPEARANCEself.overlay.show(tr("Appearance preview · microphone off", "外观预览 · 麦克风未开启"))self.overlay.set_text(tr("Your words appear here", "识别文字显示在这里"))- self._timers.later(2000, self.dismiss)+ # Synthetic levels demonstrate motion without opening the microphone.+ self.overlay.push_rms(0.02)+ for frame in range(1, 30):+ level = 0.003 + 0.06 * math.sin(frame * math.pi / 15) ** 2+ self._timers.later(frame * 100, lambda rms=level: self.overlay.push_rms(rms))+ self._timers.later(3000, self.dismiss)def begin_voice(self):self.dismiss()diff --git a/src/doubao_input/ui/basketball_motion.py b/src/doubao_input/ui/basketball_motion.pynew file mode 100644index 0000000..4add13b--- /dev/null+++ b/src/doubao_input/ui/basketball_motion.py@@ -0,0 +1,39 @@+"""A timed dribble phrase; speech cadence controls playback, not body scale."""+from dataclasses import dataclass+import math+++@dataclass(frozen=True)+class BasketballPose:+ crouch: float+ twist: float+ head_turn: float+ hand_y: float+ ball_y: float+ squash: float+++# time, crouch, shoulder twist, delayed head turn, hand Y, ball Y, ball squash+# Anticipation → push → impact → shoulder snap → hold → release.+KEYFRAMES = (+ (0.00, 0.10, 0.00, 0.00, -7.0, -3.0, 0.00),+ (0.16, 1.00, -0.25, -0.10, -6.0, -3.0, 0.00),+ (0.29, 0.75, 0.15, -0.15, 3.0, 5.0, 0.00),+ (0.34, 0.65, 0.40, -0.15, 1.0, 11.6, 1.00),+ (0.40, 0.45, 0.65, -0.10, -1.0, 8.0, 0.00),+ (0.52, 0.15, 1.00, 0.10, -5.0, -1.0, 0.00),+ (0.60, 0.15, 1.00, 0.55, -7.0, -3.0, 0.00),+ (0.68, 0.15, 1.00, 0.55, -7.0, -3.0, 0.00),+ (0.84, 0.30, 0.10, 0.35, -7.0, -3.0, 0.00),+ (1.00, 0.10, 0.00, 0.00, -7.0, -3.0, 0.00),+)+++def basketball_pose(phase):+ cycle = (phase / math.pi) % 1+ for left, right in zip(KEYFRAMES, KEYFRAMES[1:]):+ if cycle <= right[0]:+ t = (cycle - left[0]) / (right[0] - left[0])+ ease = t * t * (3 - 2 * t)+ return BasketballPose(*(a + (b - a) * ease for a, b in zip(left[1:], right[1:])))+ return BasketballPose(*KEYFRAMES[-1][1:])diff --git a/src/doubao_input/ui/overlay.py b/src/doubao_input/ui/overlay.pyindex 1afa83e..5b74237 100644--- a/src/doubao_input/ui/overlay.py+++ b/src/doubao_input/ui/overlay.py@@ -17,6 +17,7 @@ from pathlib import Pathfrom typing import TYPE_CHECKINGfrom doubao_input.i18n import trfrom doubao_input.ui.voice_motion import VoiceMotion+from doubao_input.ui.waveform import draw_waveformfrom doubao_input.product import VERSIONimport cairo@@ -46,11 +47,6 @@ CORNER_PX = 12CANVAS_WIDTH = 368CANVAS_HEIGHT = 31-WAVE_HEIGHT = 24-WAVE_SAMPLES = 48-WAVE_BAR_WIDTH = 4-WAVE_BAR_GAP = 3-TICK_MS = 16PEAK_DECAY_DB_PER_SECOND = 6.0RMS_FLOOR_DB = -48.0@@ -79,6 +75,7 @@ class Overlay:def __init__(self, app_state: AppState | None = None) -> None:self._main_thread_id = threading.get_ident()self.reduced_motion = False+ self.waveform_style = "bars"self._app_state = app_stateself._window: Gtk.Window | None = Noneself._label: Gtk.Label | None = None@@ -383,7 +380,9 @@ class Overlay:def _arm_ticker(self) -> None:if self._ticker_src is None and self._visible:self._last_peak_tick = time.monotonic()- self._ticker_src = GLib.timeout_add(250 if self.reduced_motion else TICK_MS, self._tick)+ self._ticker_src = GLib.timeout_add(+ 250 if self.reduced_motion else (33 if self.waveform_style == "basketball" else TICK_MS),+ self._tick)def _tick(self) -> bool:if not self._visible or self._window is None or self._canvas is None:@@ -414,8 +413,6 @@ class Overlay:if self._canvas is None:returntry:- samples = self._motion.bars(WAVE_SAMPLES)-surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, CANVAS_WIDTH, CANVAS_HEIGHT)@@ -426,31 +423,9 @@ class Overlay:accent = _hex_to_unit_rgb(self._theme["accent"])foreground = _hex_to_unit_rgb(self._theme["bright_foreground"])- gradient = cairo.LinearGradient(0, 0, 0, WAVE_HEIGHT)- gradient.add_color_stop_rgba(0, *accent, 0.55)- gradient.add_color_stop_rgba(0.5, *foreground, 0.95)- gradient.add_color_stop_rgba(1, *accent, 0.55)- wave_width = WAVE_SAMPLES * (WAVE_BAR_WIDTH + WAVE_BAR_GAP)- start_x = (CANVAS_WIDTH - wave_width + WAVE_BAR_GAP) / 2- centre_y = WAVE_HEIGHT / 2- for index, sample in enumerate(samples):- amplitude = 0.85 + sample * (WAVE_HEIGHT / 2 - 2)- x = start_x + index * (WAVE_BAR_WIDTH + WAVE_BAR_GAP)- # A restrained halo follows actual energy, never idle breathing.- cr.set_source_rgba(*accent, self._motion.level * 0.18)- _rounded_rect(cr, x - 1.5, centre_y - amplitude - 1.5,- WAVE_BAR_WIDTH + 3, amplitude * 2 + 3, 3)- cr.fill()- cr.set_source(gradient)- _rounded_rect(- cr,- x,- centre_y - amplitude,- WAVE_BAR_WIDTH,- amplitude * 2,- WAVE_BAR_WIDTH / 2,- )- cr.fill()+ draw_waveform(cr, self.waveform_style, self._motion,+ CANVAS_WIDTH, CANVAS_HEIGHT, accent, foreground,+ reduced_motion=self.reduced_motion)texture = _image_surface_to_texture(surface)self._canvas.set_paintable(texture)@@ -519,17 +494,3 @@ def _image_surface_to_texture(surface: cairo.ImageSurface) -> Gdk.Texture:GLib.Bytes.new(bytes(data)),stride,)---def _rounded_rect(- cr, x: float, y: float, width: float, height: float, radius: float-) -> None:- if width <= 0 or height <= 0:- return- radius = min(radius, width / 2, height / 2)- cr.new_sub_path()- cr.arc(x + width - radius, y + radius, radius, -math.pi / 2, 0)- cr.arc(x + width - radius, y + height - radius, radius, 0, math.pi / 2)- cr.arc(x + radius, y + height - radius, radius, math.pi / 2, math.pi)- cr.arc(x + radius, y + radius, radius, math.pi, 3 * math.pi / 2)- cr.close_path()diff --git a/src/doubao_input/ui/settings_window.py b/src/doubao_input/ui/settings_window.pyindex d407ba9..74948d5 100644--- a/src/doubao_input/ui/settings_window.py+++ b/src/doubao_input/ui/settings_window.py@@ -6,6 +6,7 @@ from doubao_input.i18n import LANGUAGES, trfrom doubao_input.doubao.devices import microphonesfrom doubao_input.diagnostics import reportfrom doubao_input.product import VERSION+from doubao_input.settings import WAVEFORM_STYLESfrom doubao_input.ui.style import apply_window_style@@ -112,6 +113,13 @@ class SettingsWindow:"更改会自动保存;可在引导页检查麦克风。")))section(tr("Appearance", "外观"))+ self.waveform_style = Gtk.DropDown.new_from_strings([+ tr("Classic bars", "经典声柱"), tr("Soft waves", "柔和声浪"),+ tr("Concentric ripples", "同心涟漪"),+ tr("Basketball rhythm", "篮球律动"),+ ])+ self.waveform_style.set_selected(WAVEFORM_STYLES.index(settings.waveform_style))+ row(tr("Listening waveform", "聆听波纹样式"), self.waveform_style)self.motion = row(tr("Reduce waveform updates", "减少波形更新"),Gtk.Switch(active=settings.reduced_motion))button(tr("Preview appearance", "预览外观"), preview)@@ -170,6 +178,7 @@ class SettingsWindow:self.hold.connect("value-changed", self._changed)self.double.connect("value-changed", self._changed)self.microphone.connect("notify::selected", self._changed)+ self.waveform_style.connect("notify::selected", self._changed)self.motion.connect("notify::active", self._changed)def _value(self):@@ -182,7 +191,8 @@ class SettingsWindow:double_enter=self.enter.get_active(),autostart=self.autostart.get_active(),microphone=self.sources[self.microphone.get_selected()][0],- reduced_motion=self.motion.get_active())+ reduced_motion=self.motion.get_active(),+ waveform_style=WAVEFORM_STYLES[self.waveform_style.get_selected()])def _restore_controls(self):self._updating = True@@ -195,6 +205,7 @@ class SettingsWindow:self.microphone.set_selected([key for key, _ in self.sources].index(self._settings.microphone))self.motion.set_active(self._settings.reduced_motion)+ self.waveform_style.set_selected(WAVEFORM_STYLES.index(self._settings.waveform_style))finally:self._updating = Falsediff --git a/src/doubao_input/ui/voice_motion.py b/src/doubao_input/ui/voice_motion.pyindex a4681c3..dad819e 100644--- a/src/doubao_input/ui/voice_motion.py+++ b/src/doubao_input/ui/voice_motion.py@@ -6,9 +6,11 @@ class VoiceMotion:def __init__(self):self.level = 0.0self.phase = 0.0+ self.cadence = SpeechCadence()def advance(self, rms, age, elapsed):rms = rms if math.isfinite(rms) else 0.0+ self.cadence.advance(rms, age, elapsed)# Speech is normally far below full scale: map -54…-16 dB to visuals.db = 20 * math.log10(max(1e-9, rms))target = max(0.0, min(1.0, (db + 54) / 38)) ** 0.85@@ -27,3 +29,45 @@ class VoiceMotion:+ 0.16 * math.sin(x * 17 + self.phase * 1.3))values.append(self.level * shape * ripple)return values+++class SpeechCadence:+ """Estimate syllabic cadence from relative energy onsets, not loudness.++ This is an audio-envelope approximation, not a words-per-minute estimate.+ Fast/slow envelopes make onset timing largely independent of microphone gain.+ """+ def __init__(self):+ self.phase = 0.0+ self.speed = 1.2 # dribbles per second until two onsets establish cadence+ self._target_speed = 1.2+ self._fast = self._slow = self._time = 0.0+ self._last_onset = None+ self._last_voice = -10.0+ self._armed = True++ def advance(self, rms, age, elapsed):+ elapsed = max(0.0, min(elapsed, 0.5))+ self._time += elapsed+ energy = max(0.0, rms) if age <= 0.3 else 0.0+ self._fast += (energy - self._fast) * (1 - math.exp(-elapsed / 0.035))+ self._slow += (energy - self._slow) * (1 - math.exp(-elapsed / 0.25))+ if energy > 0.0025:+ self._last_voice = self._time+ if self._fast < self._slow * 1.05:+ self._armed = True+ if self._armed and self._fast > max(0.0025, self._slow * 1.3):+ interval = None if self._last_onset is None else self._time - self._last_onset+ if interval is None or interval >= 0.14:+ if interval is not None and interval <= 1.5:+ self._target_speed = max(0.65, min(3.2, 0.55 / interval))+ self._last_onset = self._time+ self._armed = False+ if self._time - self._last_voice > 0.3:+ # Freeze in place, without a jump to a default pose during pauses.+ self._last_onset = None+ self._target_speed = self.speed = 1.2+ return+ self.speed += (self._target_speed - self.speed) * (1 - math.exp(-elapsed / 0.35))+ # The renderer completes one down/up cycle per pi radians.+ self.phase = (self.phase + elapsed * math.pi * self.speed) % math.taudiff --git a/src/doubao_input/ui/waveform.py b/src/doubao_input/ui/waveform.pynew file mode 100644index 0000000..15fafa7--- /dev/null+++ b/src/doubao_input/ui/waveform.py@@ -0,0 +1,198 @@+"""Cairo listening styles, usable without a GTK display or microphone."""+import math++import cairo++from doubao_input.ui.basketball_motion import basketball_pose+++def draw_waveform(cr, style, motion, width, height, accent, foreground, *, reduced_motion=False):+ cr.save()+ cr.rectangle(0, 0, width, height)+ cr.clip()+ # Reduced motion keeps audio feedback but removes travelling/bouncing motion.+ phase = 0.0 if reduced_motion or motion.level < 0.001 else motion.phase+ if style == "waves":+ draw_waves(cr, motion.level, phase, width, height, accent)+ elif style == "ripples":+ draw_ripples(cr, motion.level, phase, width / 2, height / 2,+ width * 0.44, height * 0.43, accent)+ elif style == "basketball":+ draw_basketball(cr, motion.level, 0.0 if reduced_motion else motion.cadence.phase,+ width, height, accent, foreground)+ else:+ draw_bars(cr, motion, width, accent, foreground)+ cr.restore()+++def draw_bars(cr, motion, width, accent, foreground):+ samples = motion.bars(48)+ gradient = cairo.LinearGradient(0, 0, 0, 24)+ gradient.add_color_stop_rgba(0, *accent, 0.55)+ gradient.add_color_stop_rgba(0.5, *foreground, 0.95)+ gradient.add_color_stop_rgba(1, *accent, 0.55)+ wave_width = 48 * (4 + 3)+ start_x = (width - wave_width + 3) / 2+ centre_y = 24 / 2+ for index, sample in enumerate(samples):+ amplitude = 0.85 + sample * (24 / 2 - 2)+ x = start_x + index * (4 + 3)+ # A restrained halo follows actual energy, never idle breathing.+ cr.set_source_rgba(*accent, motion.level * 0.18)+ rounded_rect(cr, x - 1.5, centre_y - amplitude - 1.5,+ 4 + 3, amplitude * 2 + 3, 3)+ cr.fill()+ cr.set_source(gradient)+ rounded_rect(+ cr,+ x,+ centre_y - amplitude,+ 4,+ amplitude * 2,+ 4 / 2,+ )+ cr.fill()+++def rounded_rect(+ cr, x: float, y: float, width: float, height: float, radius: float+) -> None:+ if width <= 0 or height <= 0:+ return+ radius = min(radius, width / 2, height / 2)+ cr.new_sub_path()+ cr.arc(x + width - radius, y + radius, radius, -math.pi / 2, 0)+ cr.arc(x + width - radius, y + height - radius, radius, 0, math.pi / 2)+ cr.arc(x + radius, y + height - radius, radius, math.pi / 2, math.pi)+ cr.arc(x + radius, y + radius, radius, math.pi, 3 * math.pi / 2)+ cr.close_path()+++def draw_waves(cr, level, phase, width, height, accent):+ for layer in range(3):+ cr.set_source_rgba(*accent, 0.85 - layer * 0.24)+ cr.set_line_width(1.6 - layer * 0.25)+ for i in range(121):+ x = i / 120+ envelope = math.sin(math.pi * x) ** 1.2+ y = height / 2 + level * (height / 2 - 3) * envelope * math.sin(+ x * math.tau * 2 + phase + layer * 0.8)+ if i == 0:+ cr.move_to(12 + x * (width - 24), y)+ else:+ cr.line_to(12 + x * (width - 24), y)+ cr.stroke()+++def draw_ripples(cr, level, phase, x, y, rx, ry, color):+ for ring in range(4):+ progress = (phase / math.tau + ring / 4) % 1+ scale = 0.12 + 0.88 * progress+ cr.save()+ cr.translate(x, y)+ cr.scale(rx, ry)+ cr.set_source_rgba(*color, (0.12 + level * 0.75) * (1 - progress))+ cr.set_line_width(0.07)+ cr.arc(0, 0, scale, 0, math.tau)+ cr.stroke()+ cr.restore()+++def draw_basketball(cr, level, phase, width, height, accent, foreground):+ """Wave strands briefly resolve into a dribbling figure and a separate ball."""+ cr.save()+ cr.translate(width / 2, height / 2)+ cr.scale(1, height / 31)+ pose = basketball_pose(phase)+ neck = (-11 + 3 * pose.twist, -5 + 1.7 * pose.crouch)+ back = (-16 + 2 * pose.twist, -4 + 2 * pose.crouch)+ shoulder = (-6 + 7 * pose.twist, -5 + 2 * pose.crouch - pose.twist)+ hip = (-13 - 1.5 * pose.twist, 3 + 1.6 * pose.crouch)+ elbow = (6 + 2 * pose.twist, -2 + pose.crouch)+ hand = (16, pose.hand_y)+ ball = (18, pose.ball_y)++ # One shared wave texture, with brighter shoulder/arm strands conveying+ # the turn. All silhouette paths are masks, never solid character fills.+ threads = _wave_thread_pattern(cr, phase, width)+ _paint_wave_threads(cr, threads, level, width, accent, 0.05)+ cr.save()+ cr.new_path()+ cr.arc(-10 + 2 * pose.head_turn, -10 + 1.5 * pose.crouch, 3.2, 0, math.tau)+ _wave_limb(cr, neck, hip, 3.3)+ _wave_limb(cr, back, shoulder, 2.0)+ _wave_limb(cr, back, (-22 + pose.twist, 1 + pose.crouch), 1.5)+ _wave_limb(cr, (-22 + pose.twist, 1 + pose.crouch), (-14, 2), 1.3)+ _wave_limb(cr, shoulder, elbow, 1.5)+ _wave_limb(cr, elbow, hand, 1.2)+ _wave_limb(cr, hip, (-23 - pose.crouch, 8), 1.9)+ _wave_limb(cr, (-23 - pose.crouch, 8), (-20, 13), 1.6)+ _wave_limb(cr, hip, (-4 + pose.crouch, 8), 1.9)+ _wave_limb(cr, (-4 + pose.crouch, 8), (3, 13), 1.6)+ cr.clip()+ _paint_wave_threads(cr, threads, level, width, foreground, 0.62)+ cr.restore()++ cr.save()+ cr.new_path()+ _wave_limb(cr, back, shoulder, 2.0)+ _wave_limb(cr, shoulder, elbow, 1.5)+ _wave_limb(cr, elbow, hand, 1.2)+ cr.clip()+ _paint_wave_threads(cr, threads, level, width, foreground, 0.50)+ cr.restore()++ cr.save()+ cr.new_path()+ # Preserve the wave texture's coordinates while squashing only the mask.+ cr.save()+ cr.translate(*ball)+ cr.scale(1 + 0.25 * pose.squash, 1 - 0.40 * pose.squash)+ cr.arc(0, 0, 4.1, 0, math.tau)+ cr.restore()+ cr.clip()+ _paint_wave_threads(cr, threads, level, width, (1.0, 0.64, 0.34), 0.85)+ cr.restore()+ cr.restore()+ impact_age = ((phase / math.pi) % 1 - 0.34) % 1+ if level > 0.001 and impact_age < 0.3:+ draw_ripples(cr, level * (1 - impact_age / 0.3), impact_age * math.tau,+ width / 2 + ball[0], height - 2,+ width * 0.31, 1.5, accent)+++def _wave_limb(cr, start, end, radius):+ """Append a capsule to a clipping path without painting a solid limb."""+ angle = math.atan2(end[1] - start[1], end[0] - start[0])+ cr.new_sub_path()+ cr.arc(*start, radius, angle + math.pi / 2, angle + 3 * math.pi / 2)+ cr.arc(*end, radius, angle - math.pi / 2, angle + math.pi / 2)+ cr.close_path()+++def _wave_thread_pattern(cr, phase, width):+ """Rasterize once before applying the expensive silhouette clips."""+ cr.push_group_with_content(cairo.CONTENT_ALPHA)+ cr.set_source_rgba(1, 1, 1, 1)+ cr.set_line_width(0.65)+ cr.new_path()+ for row in range(19):+ baseline = -15 + row * 1.65+ for i in range(93):+ x = (i / 92 - 0.5) * (width - 24)+ y = baseline + 0.65 * math.sin(x * 0.28 - phase * 2 + row * 0.65)+ if i == 0:+ cr.move_to(x, y)+ else:+ cr.line_to(x, y)+ cr.stroke()+ return cr.pop_group()+++def _paint_wave_threads(cr, threads, level, width, color, opacity):+ gradient = cairo.LinearGradient(-width / 2, 0, width / 2, 0)+ alpha = opacity * (0.25 + 0.75 * level)+ for position, strength in ((0, 0), (0.3, 0.12), (0.43, 1), (0.57, 1), (0.7, 0.12), (1, 0)):+ gradient.add_color_stop_rgba(position, *color, alpha * strength)+ cr.set_source(gradient)+ cr.mask(threads)diff --git a/tests/manual_refactor_smoke.py b/tests/manual_refactor_smoke.pyindex 7652224..16705e4 100644--- a/tests/manual_refactor_smoke.py+++ b/tests/manual_refactor_smoke.py@@ -15,7 +15,7 @@ gi.require_version("Gtk", "4.0")from gi.repository import GLib, Gtkfrom doubao_input.app import DoubaoInputAppfrom doubao_input.i18n import set_language-from doubao_input.settings import Settings+from doubao_input.settings import Settings, WAVEFORM_STYLESfrom doubao_input.ui.settings_window import SettingsWindow@@ -52,6 +52,11 @@ def main():capture_key=app._begin_key_capture, cancel_capture=app._end_key_capture,apply_key=app._apply_trigger_key)window.window.realize()+ for index, style in enumerate(WAVEFORM_STYLES):+ window.waveform_style.set_selected(index)+ assert app.settings.waveform_style == style+ assert app._overlay.waveform_style == style+ assert Settings.load().waveform_style == stylepicker = window.trigger_pickerpreset = 29 if app.settings.doubao_key != 29 else 56preset_index = [entry[1] for entry in picker.entries].index(preset)diff --git a/tests/manual_waveform_performance.py b/tests/manual_waveform_performance.pynew file mode 100644index 0000000..3c34018--- /dev/null+++ b/tests/manual_waveform_performance.py@@ -0,0 +1,63 @@+"""Opt-in real GTK animation budget check; no capture, ASR or keyboard input.++Run with LD_PRELOAD=libgtk4-layer-shell.so GTK_A11Y=none PYTHONPATH=src+timeout -k 5s 15s dbus-run-session --+python tests/manual_waveform_performance.py. Requires a desktop display.+"""+import math+import time++import gi++gi.require_version('Gtk', '4.0')+from gi.repository import GLib, Gtk+from doubao_input.ui.overlay import Overlay+from manual_safety import hard_deadline+++def main():+ Gtk.init()+ overlay = Overlay()+ overlay.waveform_style = 'basketball'+ loop = GLib.MainLoop()+ heartbeats = []+ start = time.monotonic()+ cpu = time.process_time()++ def sample():+ overlay.push_rms(0.03 + 0.02 * math.sin(time.monotonic() * 3))+ return GLib.SOURCE_CONTINUE++ def heartbeat():+ heartbeats.append(time.monotonic())+ return GLib.SOURCE_CONTINUE++ def finish():+ loop.quit()+ return GLib.SOURCE_REMOVE++ sources = []+ try:+ overlay.show('Waveform performance check · microphone off')+ sources.append(GLib.timeout_add(80, sample))+ sources.append(GLib.timeout_add(100, heartbeat, priority=GLib.PRIORITY_DEFAULT_IDLE))+ GLib.timeout_add(4000, finish)+ loop.run()+ elapsed = time.monotonic() - start+ utilization = (time.process_time() - cpu) / elapsed+ gaps = [b - a for a, b in zip([start, *heartbeats], [*heartbeats, time.monotonic()])]+ assert len(heartbeats) >= 25, 'GTK low-priority callbacks starved'+ assert max(gaps) < 0.4, f'GTK unresponsive for {max(gaps):.3f}s'+ assert utilization < 0.45, f'Animation consumed {utilization:.0%} of one CPU'+ print(f'PASS: CPU {utilization:.1%}, {len(heartbeats)} UI heartbeats, max gap {max(gaps):.3f}s')+ finally:+ for source in sources:+ GLib.source_remove(source)+ overlay.hide()+ if overlay._window:+ overlay._window.destroy()+++if __name__ == '__main__':+ with hard_deadline(12):+ main()diff --git a/tests/test_basketball_motion.py b/tests/test_basketball_motion.pynew file mode 100644index 0000000..989fa06--- /dev/null+++ b/tests/test_basketball_motion.py@@ -0,0 +1,35 @@+import math+import unittest++from doubao_input.ui.basketball_motion import basketball_pose+++class BasketballMotionTest(unittest.TestCase):+ def pose(self, cycle):+ return basketball_pose(cycle * math.pi)++ def test_phrase_loops_without_a_pose_jump(self):+ self.assertEqual(self.pose(0), self.pose(1))+ start, end = self.pose(0), self.pose(1 - 1e-6)+ self.assertAlmostEqual(start.twist, end.twist, places=6)+ self.assertAlmostEqual(start.crouch, end.crouch, places=6)++ def test_shoulder_holds_and_head_follows_late(self):+ snap, hold = self.pose(0.52), self.pose(0.64)+ self.assertEqual(snap.twist, hold.twist)+ self.assertGreater(hold.head_turn, snap.head_turn)+ self.assertEqual(self.pose(0.62), self.pose(0.66))++ def test_hand_leads_ball_and_impact_squashes_at_floor(self):+ push, impact = self.pose(0.29), self.pose(0.34)+ self.assertLess(impact.hand_y, push.hand_y)+ self.assertGreater(impact.ball_y, push.ball_y)+ self.assertEqual(impact.squash, 1)+ self.assertAlmostEqual(impact.ball_y + 4.1 * (1 - .4 * impact.squash), 14.06)+ self.assertEqual(self.pose(0.6).squash, 0)++ def test_pose_stays_inside_canvas_across_cycle(self):+ for frame in range(300):+ pose = self.pose(frame / 300)+ self.assertLessEqual(pose.ball_y + 4.1 * (1 - .4 * pose.squash), 14.1)+ self.assertGreaterEqual(pose.ball_y - 4.1, -15.5)diff --git a/tests/test_setup_session.py b/tests/test_setup_session.pyindex a02254a..4ab7fa0 100644--- a/tests/test_setup_session.py+++ b/tests/test_setup_session.py@@ -73,3 +73,16 @@ class SetupSessionTest(TestCase):self.session.cancel_voice()self.cancel_voice.assert_called_once()self.assertFalse(self.session.voice_active)++ def test_appearance_uses_synthetic_audio_and_cancels_stale_frames(self):+ self.session.show_appearance()+ self.audio.start.assert_not_called()+ self.overlay.push_rms.assert_called_with(0.02)+ frames = [callback for _, callback in self.timers[:-1]]+ frames[0]()+ self.assertGreater(self.overlay.push_rms.call_count, 1)+ self.session.dismiss()+ self.overlay.push_rms.reset_mock()+ for callback in frames[1:]:+ callback()+ self.overlay.push_rms.assert_not_called()diff --git a/tests/test_voice_motion.py b/tests/test_voice_motion.pyindex 93d5094..07fb288 100644--- a/tests/test_voice_motion.py+++ b/tests/test_voice_motion.py@@ -29,3 +29,40 @@ class MotionTest(unittest.TestCase):for rms in (0, 0.02, 1, float('nan')):values = self.run_level(rms).bars(48)self.assertTrue(all(0 <= x <= 1 for x in values))+++class CadenceTest(unittest.TestCase):+ def speech(self, syllables_per_second, gain=0.03):+ motion = VoiceMotion()+ for frame in range(600):+ t = frame / 60+ rms = gain if (t * syllables_per_second) % 1 < 0.4 else gain * 0.02+ motion.advance(rms, 0, 1 / 60)+ return motion++ def test_faster_speech_dribbles_faster(self):+ slow = self.speech(2).cadence.speed+ fast = self.speech(5).cadence.speed+ self.assertGreater(fast, slow * 1.5)++ def test_gain_does_not_control_dribble_speed(self):+ quiet = self.speech(4, 0.01).cadence.speed+ loud = self.speech(4, 0.1).cadence.speed+ self.assertAlmostEqual(quiet, loud, delta=0.1)++ def test_pause_freezes_pose_and_stale_samples_stop_motion(self):+ for stale in (False, True):+ motion = self.speech(4)+ for _ in range(120):+ motion.advance(0.1 if stale else 0, 5 if stale else 0, 1 / 60)+ phase = motion.cadence.phase+ for _ in range(60):+ motion.advance(0.1 if stale else 0, 5 if stale else 0, 1 / 60)+ self.assertEqual(motion.cadence.phase, phase)++ def test_constant_volume_does_not_accelerate(self):+ for gain in (0.01, 0.1):+ motion = VoiceMotion()+ for _ in range(600):+ motion.advance(gain, 0, 1 / 60)+ self.assertAlmostEqual(motion.cadence.speed, 1.2)diff --git a/tests/test_waveform.py b/tests/test_waveform.pynew file mode 100644index 0000000..7df2e24--- /dev/null+++ b/tests/test_waveform.py@@ -0,0 +1,55 @@+"""Exercise real Cairo frames without opening a window or capturing audio."""+import tempfile+import unittest+from unittest.mock import patch++import cairo++from doubao_input.settings import Settings, WAVEFORM_STYLES+from doubao_input.ui.voice_motion import VoiceMotion+from doubao_input.ui.waveform import draw_waveform+++class WaveformTest(unittest.TestCase):+ def frame(self, style, level, phase=1.2, reduced=False):+ motion = VoiceMotion()+ motion.level, motion.phase = level, phase+ motion.cadence.phase = phase if level else 0+ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 368, 31)+ draw_waveform(cairo.Context(surface), style, motion, 368, 31,+ (0.48, 0.64, 0.97), (0.75, 0.79, 0.96), reduced_motion=reduced)+ surface.flush()+ return bytes(surface.get_data())++ def test_styles_are_visible_distinct_and_audio_reactive(self):+ frames = []+ for style in WAVEFORM_STYLES:+ with self.subTest(style=style):+ quiet = self.frame(style, 0)+ loud = self.frame(style, 0.9)+ self.assertTrue(any(quiet))+ self.assertNotEqual(quiet, loud)+ frames.append(loud)+ self.assertEqual(len(set(frames)), len(WAVEFORM_STYLES))++ def test_silent_styles_do_not_animate(self):+ for style in WAVEFORM_STYLES:+ self.assertEqual(self.frame(style, 0, 1), self.frame(style, 0, 2))++ def test_reduced_motion_stops_new_styles_travelling(self):+ for style in WAVEFORM_STYLES[1:]:+ self.assertNotEqual(self.frame(style, 0.8, 1), self.frame(style, 0.8, 2))+ self.assertEqual(self.frame(style, 0.8, 1, True), self.frame(style, 0.8, 2, True))++ def test_settings_round_trip_and_legacy_default(self):+ with tempfile.TemporaryDirectory() as directory, patch.dict(+ 'os.environ', {'XDG_CONFIG_HOME': directory}):+ self.assertEqual(Settings.load().waveform_style, 'bars')+ for style in WAVEFORM_STYLES:+ Settings(waveform_style=style).save()+ self.assertEqual(Settings.load().waveform_style, style)++ def test_invalid_style_rejected(self):+ for style in ('unknown', None, 1, []):+ with self.assertRaises(ValueError):+ Settings(waveform_style=style).validate()