Read chat replies aloud with word highlighting
An assistant reply gets Read aloud beside Copy; while it reads it becomes Pause/Resume and Stop, one reply at a time app-wide. The spoken word is highlighted in the rendered reply (across multi-part replies) and the transcript scrolls only when that word leaves the viewport. Reading stops when its chat closes or is swapped, another reply starts, or the app goes to the background. Markdown is spoken as sentences; code blocks are announced as "Code block.". Speech goes through a SpeechEngine seam with a flutter_tts implementation (Android, macOS, web; hidden on Linux) and a fake for tests. Settings has a Read aloud section: a voice picker grouped by language (device language first, a sample per voice), a rate slider and reset, saved per device. flutter_tts has no Swift package, so macOS/iOS gain the CocoaPods integration (Podfiles with the Runner deployment targets); Android declares the TTS_SERVICE query. The capture fixture gains ?speech=fake.
This commit is contained in:
@@ -63,6 +63,7 @@ import '../../../ui/layout/app_sheet_header.dart';
|
||||
import '../../../ui/layout/wheel_scroll_forwarding.dart';
|
||||
import 'chat_reading_width.dart';
|
||||
import '../ui/transcript/chat_copy_gutter.dart';
|
||||
import '../speech/speech.dart';
|
||||
import 'chat_pane_presentation.dart';
|
||||
import 'chat_thread_header.dart';
|
||||
import 'chat_transcript_anchor.dart';
|
||||
@@ -655,6 +656,12 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
@override
|
||||
void didUpdateWidget(covariant ChatThreadView oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.sessionId != widget.sessionId ||
|
||||
oldWidget.gateway != widget.gateway) {
|
||||
// A pane reused for another conversation stops reading the previous
|
||||
// one's reply, so neither its audio nor its highlight carries over.
|
||||
unawaited(speechController.stopScope(oldWidget.sessionId));
|
||||
}
|
||||
if (!identical(oldWidget.paneCommands, widget.paneCommands)) {
|
||||
oldWidget.paneCommands?.removeListener(_takeCommands);
|
||||
oldWidget.paneCommands?.setFinished(oldWidget.sessionId, false);
|
||||
@@ -751,6 +758,9 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
// Leaving or closing the conversation stops its reply reading aloud; a
|
||||
// reply another pane is reading carries on.
|
||||
unawaited(speechController.stopScope(widget.sessionId));
|
||||
_persistPosition();
|
||||
_saveTranscript(widget.transcripts, widget.sessionId);
|
||||
widget.paneCommands?.removeListener(_takeCommands);
|
||||
@@ -1715,7 +1725,16 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
[delivery, onRemove != null, _images, _controller, _composer, _shellRuns],
|
||||
() => ChatMessageView(
|
||||
row: row,
|
||||
textBuilder: chatMarkdownText,
|
||||
speechScope: widget.sessionId,
|
||||
// The same reader id as the reply's Read aloud button, so the spoken
|
||||
// word is highlighted in this reply's text.
|
||||
textBuilder: (context, text) => ChatMarkdownView(
|
||||
text: text,
|
||||
messageId: speechMessageId(
|
||||
widget.sessionId,
|
||||
'${row['key'] ?? row['id'] ?? ''}',
|
||||
),
|
||||
),
|
||||
footer: [
|
||||
...chips,
|
||||
if (delivery != null)
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_tts/flutter_tts.dart';
|
||||
|
||||
import 'speech_engine.dart';
|
||||
|
||||
/// [SpeechEngine] over the `flutter_tts` plugin (Android, Apple, web).
|
||||
/// The plugin is created on first use so merely building the UI opens no
|
||||
/// platform channel.
|
||||
class FlutterTtsSpeechEngine extends SpeechEngine {
|
||||
FlutterTts? _plugin;
|
||||
SpeechVoice? _applied;
|
||||
|
||||
@override
|
||||
bool get supported =>
|
||||
kIsWeb ||
|
||||
switch (defaultTargetPlatform) {
|
||||
TargetPlatform.android ||
|
||||
TargetPlatform.iOS ||
|
||||
TargetPlatform.macOS ||
|
||||
TargetPlatform.windows => true,
|
||||
TargetPlatform.linux || TargetPlatform.fuchsia => false,
|
||||
};
|
||||
|
||||
/// AVSpeechSynthesizer's normal rate is 0.5 on a 0..1 scale; Android's
|
||||
/// TextToSpeech and the Web Speech API use 1.0 as normal.
|
||||
bool get _appleScale =>
|
||||
!kIsWeb &&
|
||||
(defaultTargetPlatform == TargetPlatform.iOS ||
|
||||
defaultTargetPlatform == TargetPlatform.macOS);
|
||||
|
||||
FlutterTts get _tts => _plugin ??= _create();
|
||||
|
||||
FlutterTts _create() {
|
||||
final tts = FlutterTts();
|
||||
tts.setStartHandler(() => onStart?.call());
|
||||
tts.setPauseHandler(() => onPause?.call());
|
||||
tts.setContinueHandler(() => onResume?.call());
|
||||
tts.setCompletionHandler(() => onCompletion?.call());
|
||||
tts.setCancelHandler(() => onCancel?.call());
|
||||
tts.setErrorHandler((message) => onError?.call('$message'));
|
||||
tts.setProgressHandler(
|
||||
(utterance, start, end, _) => onProgress?.call(utterance, start, end),
|
||||
);
|
||||
return tts;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> speak(String text) async => _tts.speak(text);
|
||||
|
||||
@override
|
||||
Future<void> pause() async => _tts.pause();
|
||||
|
||||
@override
|
||||
Future<void> stop() async => _tts.stop();
|
||||
|
||||
@override
|
||||
Future<void> setRate(double rate) async =>
|
||||
_tts.setSpeechRate(_appleScale ? (rate * 0.5).clamp(0, 1) : rate);
|
||||
|
||||
@override
|
||||
Future<void> setVoice(SpeechVoice? voice) async {
|
||||
if (voice == _applied) return;
|
||||
if (voice != null) {
|
||||
await _tts.setVoice({'name': voice.name, 'locale': voice.locale});
|
||||
_applied = voice;
|
||||
return;
|
||||
}
|
||||
if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) {
|
||||
await _tts.clearVoice();
|
||||
_applied = null;
|
||||
return;
|
||||
}
|
||||
// Apple and web plugins cannot clear a chosen voice. After one was chosen
|
||||
// in this run (a sample, or a setting that was reset) the device
|
||||
// language's first voice stands in for the system default.
|
||||
final device = PlatformDispatcher.instance.locale.languageCode;
|
||||
final fallback = (await voices())
|
||||
.where((item) => item.language == device.toLowerCase())
|
||||
.firstOrNull;
|
||||
if (fallback == null) return;
|
||||
await _tts.setVoice({'name': fallback.name, 'locale': fallback.locale});
|
||||
_applied = null;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<SpeechVoice>> voices() async {
|
||||
var voices = await _readVoices();
|
||||
// Browsers load their voice list asynchronously after the first request.
|
||||
for (var attempt = 0; kIsWeb && voices.isEmpty && attempt < 4; attempt++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 250));
|
||||
voices = await _readVoices();
|
||||
}
|
||||
return voices;
|
||||
}
|
||||
|
||||
Future<List<SpeechVoice>> _readVoices() async {
|
||||
Object? raw;
|
||||
try {
|
||||
raw = await _tts.getVoices;
|
||||
} on PlatformException {
|
||||
return const [];
|
||||
} on MissingPluginException {
|
||||
return const [];
|
||||
}
|
||||
return [
|
||||
for (final item in raw is List ? raw : const [])
|
||||
if (item is Map && item['name'] != null && item['locale'] != null)
|
||||
SpeechVoice(name: '${item['name']}', locale: '${item['locale']}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export 'speech_controller.dart';
|
||||
export 'speech_document.dart';
|
||||
export 'speech_engine.dart';
|
||||
export 'speech_preferences.dart';
|
||||
@@ -0,0 +1,265 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'flutter_tts_speech_engine.dart';
|
||||
import 'speech_document.dart';
|
||||
import 'speech_engine.dart';
|
||||
import 'speech_preferences.dart';
|
||||
|
||||
enum SpeechState { idle, speaking, paused }
|
||||
|
||||
/// The app-wide reader: one reply speaks at a time. It notifies on state
|
||||
/// changes; the spoken word moves on the separate, frequent [word].
|
||||
class SpeechController extends ChangeNotifier with WidgetsBindingObserver {
|
||||
SpeechController({SpeechEngine? engine, SpeechPreferencesStore? store})
|
||||
: engine = engine ?? FlutterTtsSpeechEngine(),
|
||||
_store = store ?? const SharedSpeechPreferencesStore() {
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
this.engine
|
||||
..onStart = _started
|
||||
..onPause = (() => _set(SpeechState.paused))
|
||||
..onResume = (() => _set(SpeechState.speaking))
|
||||
..onCompletion = _ended
|
||||
..onCancel = _ended
|
||||
..onError = _failed
|
||||
..onProgress = _progress;
|
||||
}
|
||||
|
||||
final SpeechEngine engine;
|
||||
final SpeechPreferencesStore _store;
|
||||
|
||||
SpeechState _state = SpeechState.idle;
|
||||
String? _messageId;
|
||||
SpeechDocument? _document;
|
||||
Completer<void>? _stopping;
|
||||
Future<void>? _restoring;
|
||||
var _awaitingStart = false;
|
||||
|
||||
double _rate = defaultSpeechRate;
|
||||
SpeechVoice? _voice;
|
||||
bool saveFailed = false;
|
||||
|
||||
/// The range of the word being spoken in [document]'s text, or null.
|
||||
final word = ValueNotifier<SpeechRange?>(null);
|
||||
|
||||
bool get supported => engine.supported;
|
||||
SpeechState get state => _state;
|
||||
String? get messageId => _messageId;
|
||||
SpeechDocument? get document => _document;
|
||||
double get rate => _rate;
|
||||
SpeechVoice? get voice => _voice;
|
||||
bool get isDefault => _rate == defaultSpeechRate && _voice == null;
|
||||
|
||||
/// Loads the saved voice and rate once.
|
||||
Future<void> restore() => _restoring ??= _load();
|
||||
|
||||
Future<void> _load() async {
|
||||
final saved = await _store.load();
|
||||
if (saved == null) return;
|
||||
_rate = saved.rate.clamp(minSpeechRate, maxSpeechRate);
|
||||
_voice = saved.voice;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Reads reply [id] made of markdown [parts], stopping any other reading.
|
||||
Future<void> read(String id, List<String> parts) async {
|
||||
final document = speechDocumentFor(parts);
|
||||
await stop();
|
||||
await restore();
|
||||
if (document.text.isEmpty) return;
|
||||
await _speak(id, document, _voice);
|
||||
}
|
||||
|
||||
/// Speaks a short sample in [voice] (or the chosen one) at the chosen rate.
|
||||
Future<void> sample([SpeechVoice? voice]) async {
|
||||
await stop();
|
||||
await restore();
|
||||
await _speak(
|
||||
speechSampleId,
|
||||
speechDocumentFor(['This is how replies will sound when read aloud.']),
|
||||
voice ?? _voice,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _speak(String id, SpeechDocument document, SpeechVoice? voice) {
|
||||
_messageId = id;
|
||||
_document = document;
|
||||
_awaitingStart = true;
|
||||
word.value = null;
|
||||
_set(SpeechState.speaking);
|
||||
return _guard(() async {
|
||||
await engine.setRate(_rate);
|
||||
await engine.setVoice(voice);
|
||||
await engine.speak(document.text);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> pause() async {
|
||||
if (_state != SpeechState.speaking) return;
|
||||
_set(SpeechState.paused);
|
||||
await _guard(engine.pause);
|
||||
}
|
||||
|
||||
/// Continues a paused reply where it stopped; every platform resumes when
|
||||
/// the paused utterance's text is spoken again.
|
||||
Future<void> resume() async {
|
||||
final document = _document;
|
||||
if (_state != SpeechState.paused || document == null) return;
|
||||
_set(SpeechState.speaking);
|
||||
await _guard(() => engine.speak(document.text));
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
if (_state == SpeechState.idle) return;
|
||||
final stopping = _stopping = Completer<void>();
|
||||
await _guard(engine.stop);
|
||||
// Wait briefly for the platform's cancel so it cannot end the next reply
|
||||
// and so web speech is idle before the next utterance is queued.
|
||||
await stopping.future.timeout(
|
||||
const Duration(milliseconds: 400),
|
||||
onTimeout: () {},
|
||||
);
|
||||
if (identical(_stopping, stopping)) _stopping = null;
|
||||
_clear();
|
||||
}
|
||||
|
||||
/// Stops reading when the reply being read has an id under [scope].
|
||||
Future<void> stopScope(String scope) async {
|
||||
if (_messageId?.startsWith(speechScopePrefix(scope)) ?? false) {
|
||||
await stop();
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the rate for the next reading; [save] false previews a slider drag.
|
||||
Future<void> setRate(double value, {bool save = true}) async {
|
||||
_rate = value.clamp(minSpeechRate, maxSpeechRate);
|
||||
notifyListeners();
|
||||
if (save) await _save();
|
||||
}
|
||||
|
||||
Future<void> setVoice(SpeechVoice? value) async {
|
||||
_voice = value;
|
||||
notifyListeners();
|
||||
await _save();
|
||||
}
|
||||
|
||||
Future<void> reset() async {
|
||||
_rate = defaultSpeechRate;
|
||||
_voice = null;
|
||||
notifyListeners();
|
||||
await _save();
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
saveFailed = !await _store.save((rate: _rate, voice: _voice));
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<List<SpeechVoice>> voices() => engine.voices();
|
||||
|
||||
void _started() {
|
||||
_awaitingStart = false;
|
||||
if (_messageId != null) _set(SpeechState.speaking);
|
||||
}
|
||||
|
||||
void _ended() {
|
||||
final stopping = _stopping;
|
||||
if (stopping != null) {
|
||||
if (!stopping.isCompleted) stopping.complete();
|
||||
return;
|
||||
}
|
||||
// A late cancel from the previous utterance must not end the new one.
|
||||
if (_awaitingStart) return;
|
||||
_clear();
|
||||
}
|
||||
|
||||
void _failed(String message) {
|
||||
if (message == 'interrupted' || message == 'canceled') return _ended();
|
||||
final stopping = _stopping;
|
||||
if (stopping != null && !stopping.isCompleted) stopping.complete();
|
||||
_clear();
|
||||
}
|
||||
|
||||
void _progress(String utterance, int start, int end) {
|
||||
final document = _document;
|
||||
if (document == null || _state == SpeechState.idle) return;
|
||||
// After a resume a platform may speak only the remaining suffix.
|
||||
final base = document.text.endsWith(utterance)
|
||||
? document.text.length - utterance.length
|
||||
: 0;
|
||||
_awaitingStart = false;
|
||||
word.value = (start: start + base, end: end + base);
|
||||
}
|
||||
|
||||
Future<void> _guard(Future<void> Function() action) async {
|
||||
try {
|
||||
await action();
|
||||
} catch (error) {
|
||||
debugPrint('Read aloud failed: $error');
|
||||
_clear();
|
||||
}
|
||||
}
|
||||
|
||||
void _set(SpeechState value) {
|
||||
if (_state == value) return;
|
||||
_state = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _clear() {
|
||||
_awaitingStart = false;
|
||||
_messageId = null;
|
||||
_document = null;
|
||||
word.value = null;
|
||||
_state = SpeechState.idle;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
// Inactive is only a lost focus (a desktop window behind another, the
|
||||
// Android shade); hidden and paused mean the app is in the background.
|
||||
if (state == AppLifecycleState.hidden ||
|
||||
state == AppLifecycleState.paused ||
|
||||
state == AppLifecycleState.detached) {
|
||||
unawaited(stop());
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
engine
|
||||
..onStart = null
|
||||
..onPause = null
|
||||
..onResume = null
|
||||
..onCompletion = null
|
||||
..onCancel = null
|
||||
..onError = null
|
||||
..onProgress = null;
|
||||
if (_state != SpeechState.idle) unawaited(engine.stop().catchError((_) {}));
|
||||
word.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// The reader's id for the Settings voice sample.
|
||||
const speechSampleId = 'settings-sample';
|
||||
|
||||
/// The id prefix for replies of one conversation (see [speechMessageId]).
|
||||
String speechScopePrefix(String scope) => '$scope/';
|
||||
|
||||
/// A reply's id for the reader, unique across conversations.
|
||||
String speechMessageId(String scope, String rowId) => '$scope/$rowId';
|
||||
|
||||
SpeechController? _speechController;
|
||||
|
||||
/// The app's single reader.
|
||||
SpeechController get speechController =>
|
||||
_speechController ??= SpeechController();
|
||||
|
||||
/// Replaces the app's reader (a fake engine in tests and capture fixtures);
|
||||
/// null restores the platform one.
|
||||
set debugSpeechController(SpeechController? controller) =>
|
||||
_speechController = controller;
|
||||
@@ -0,0 +1,171 @@
|
||||
import '../ui/transcript/chat_markdown.dart';
|
||||
import '../ui/transcript/chat_markdown_cache.dart';
|
||||
|
||||
typedef SpeechRange = ({int start, int end});
|
||||
|
||||
/// Where one spoken character came from: an offset into one markdown part.
|
||||
typedef SpeechSource = ({int part, int offset});
|
||||
|
||||
/// A reply as spoken text, with the markdown source of every spoken character.
|
||||
/// A reply can have several text parts; each is rendered by its own view, so
|
||||
/// sources name the part as well as the offset within its trimmed text.
|
||||
class SpeechDocument {
|
||||
const SpeechDocument({
|
||||
required this.text,
|
||||
required this.parts,
|
||||
required this.sources,
|
||||
});
|
||||
|
||||
final String text;
|
||||
|
||||
/// The trimmed markdown of each part, in reading order.
|
||||
final List<String> parts;
|
||||
final List<SpeechSource> sources;
|
||||
|
||||
/// The index of the part whose markdown is [markdown], or -1.
|
||||
int partOf(String markdown) => parts.indexOf(markdown.trim());
|
||||
|
||||
/// The source range in [part] that the spoken [range] covers, or null when
|
||||
/// the spoken text there came from another part.
|
||||
SpeechRange? sourceRange(int part, SpeechRange range) {
|
||||
int? start;
|
||||
int? end;
|
||||
final last = range.end.clamp(0, sources.length);
|
||||
for (var index = range.start.clamp(0, last); index < last; index += 1) {
|
||||
final source = sources[index];
|
||||
if (source.part != part) continue;
|
||||
if (start == null || source.offset < start) start = source.offset;
|
||||
if (end == null || source.offset + 1 > end) end = source.offset + 1;
|
||||
}
|
||||
return start == null ? null : (start: start, end: end!);
|
||||
}
|
||||
}
|
||||
|
||||
SpeechDocument markdownToSpeech(String markdown) =>
|
||||
speechDocumentFor([markdown]);
|
||||
|
||||
/// Converts reply parts to natural speech: markup is dropped, blocks become
|
||||
/// sentences, and a fenced code block is announced as "Code block." rather
|
||||
/// than read out. Visible characters are located in order in the source, so
|
||||
/// repeated words map to their own occurrence.
|
||||
SpeechDocument speechDocumentFor(List<String> markdownParts) {
|
||||
final parts = [
|
||||
for (final part in markdownParts)
|
||||
if (part.trim().isNotEmpty) part.trim(),
|
||||
];
|
||||
final builder = _SpeechBuilder();
|
||||
for (var index = 0; index < parts.length; index += 1) {
|
||||
builder.addPart(index, parts[index]);
|
||||
}
|
||||
return SpeechDocument(
|
||||
text: builder.spoken.toString(),
|
||||
parts: parts,
|
||||
sources: builder.sources,
|
||||
);
|
||||
}
|
||||
|
||||
class _SpeechBuilder {
|
||||
final spoken = StringBuffer();
|
||||
final sources = <SpeechSource>[];
|
||||
String _markdown = '';
|
||||
var _part = 0;
|
||||
var _cursor = 0;
|
||||
|
||||
void addPart(int part, String markdown) {
|
||||
_part = part;
|
||||
_markdown = markdown;
|
||||
_cursor = 0;
|
||||
for (final block in chatMarkdownCache.blocksFor(markdown)) {
|
||||
switch (block) {
|
||||
case MarkdownHeading(text: final text):
|
||||
_visible(text);
|
||||
case MarkdownParagraph(text: final text):
|
||||
_visible(text);
|
||||
case MarkdownQuote(lines: final lines):
|
||||
lines.where((line) => line.trim().isNotEmpty).forEach(_visible);
|
||||
case MarkdownList(items: final items):
|
||||
items.forEach(_visible);
|
||||
case MarkdownTable(header: final header, rows: final rows):
|
||||
_phrase('Table.', _cursor);
|
||||
[...header, ...rows.expand((row) => row)].forEach(_visible);
|
||||
case MarkdownCode(code: final code):
|
||||
_skipCode(code);
|
||||
case MarkdownRule():
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the previous sentence so blocks are not read as one run-on line.
|
||||
void _sentenceBreak(int at) {
|
||||
if (spoken.isEmpty) return;
|
||||
if (!RegExp(r'[.!?:;]$').hasMatch(spoken.toString())) _write('.', at);
|
||||
_write(' ', at);
|
||||
}
|
||||
|
||||
void _write(String value, int at) {
|
||||
spoken.write(value);
|
||||
for (var index = 0; index < value.length; index += 1) {
|
||||
sources.add((part: _part, offset: at));
|
||||
}
|
||||
}
|
||||
|
||||
void _phrase(String value, int at) {
|
||||
_sentenceBreak(at);
|
||||
_write(value, at);
|
||||
}
|
||||
|
||||
void _visible(String blockText) {
|
||||
final value = _plain(blockText).trim();
|
||||
if (value.isEmpty) return;
|
||||
final start = _markdown.indexOf(blockText, _cursor);
|
||||
final blockStart = start < 0 ? _cursor : start;
|
||||
final blockEnd = start < 0 ? _markdown.length : start + blockText.length;
|
||||
_sentenceBreak(blockStart);
|
||||
var search = blockStart;
|
||||
for (var index = 0; index < value.length; index += 1) {
|
||||
final character = value[index];
|
||||
final found = search >= blockEnd
|
||||
? -1
|
||||
: _markdown.indexOf(character, search);
|
||||
final inBlock = found >= 0 && found < blockEnd;
|
||||
spoken.write(character);
|
||||
sources.add((part: _part, offset: inBlock ? found : search));
|
||||
if (inBlock) search = found + 1;
|
||||
}
|
||||
_cursor = start < 0 ? search : blockEnd;
|
||||
}
|
||||
|
||||
void _skipCode(String code) {
|
||||
final span = fencedCodeSpan(_markdown, _cursor, code);
|
||||
_phrase('Code block.', span.start);
|
||||
_cursor = span.end;
|
||||
}
|
||||
}
|
||||
|
||||
/// The source range of the fenced code block holding [code] that starts at or
|
||||
/// after [cursor] (``` or ~~~ fences); an unclosed fence runs to its code's end.
|
||||
SpeechRange fencedCodeSpan(String source, int cursor, String code) {
|
||||
int find(String marker) => source.indexOf(marker, cursor);
|
||||
final fences = [find('```'), find('~~~')].where((index) => index >= 0);
|
||||
if (fences.isEmpty) return (start: cursor, end: cursor);
|
||||
final opening = fences.reduce((a, b) => a < b ? a : b);
|
||||
final marker = source.substring(opening, opening + 3);
|
||||
final closing = source.indexOf(marker, opening + 3);
|
||||
if (closing >= 0) return (start: opening, end: closing + 3);
|
||||
final codeStart = source.indexOf(code, opening + 3);
|
||||
return (
|
||||
start: opening,
|
||||
end: codeStart < 0 ? opening + 3 : codeStart + code.length,
|
||||
);
|
||||
}
|
||||
|
||||
String _plain(String value) => parseInline(value).map(_inlinePlain).join();
|
||||
|
||||
String _inlinePlain(MarkdownInline span) => switch (span) {
|
||||
MarkdownPlain(text: final text) => text,
|
||||
MarkdownInlineCode(text: final text) => text,
|
||||
MarkdownStrong(spans: final spans) => spans.map(_inlinePlain).join(),
|
||||
MarkdownEmphasis(spans: final spans) => spans.map(_inlinePlain).join(),
|
||||
MarkdownLink(spans: final spans) => spans.map(_inlinePlain).join(),
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
/// One platform voice. [locale] is a BCP 47 tag such as `en-GB`.
|
||||
@immutable
|
||||
class SpeechVoice {
|
||||
const SpeechVoice({required this.name, required this.locale});
|
||||
|
||||
final String name;
|
||||
final String locale;
|
||||
|
||||
/// The primary language subtag (`en` for `en-GB`), lower case.
|
||||
String get language => locale.split(RegExp('[-_]')).first.toLowerCase();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is SpeechVoice && other.name == name && other.locale == locale;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(name, locale);
|
||||
}
|
||||
|
||||
/// The platform text-to-speech service the [SpeechController] drives.
|
||||
///
|
||||
/// [setRate] takes a multiplier where 1.0 is the platform's normal speed; an
|
||||
/// implementation maps it onto its own scale. [onProgress] reports the word
|
||||
/// being spoken as offsets into [utterance], the text the platform is actually
|
||||
/// speaking (after a resume that can be a suffix of the text passed to
|
||||
/// [speak]). Platforms without word boundaries never call it.
|
||||
abstract class SpeechEngine {
|
||||
/// Whether this platform can speak at all; the UI hides read aloud if not.
|
||||
bool get supported;
|
||||
|
||||
VoidCallback? onStart;
|
||||
VoidCallback? onPause;
|
||||
VoidCallback? onResume;
|
||||
VoidCallback? onCompletion;
|
||||
VoidCallback? onCancel;
|
||||
ValueChanged<String>? onError;
|
||||
void Function(String utterance, int start, int end)? onProgress;
|
||||
|
||||
/// Speaks [text]. Called with the same text while paused, it resumes.
|
||||
Future<void> speak(String text);
|
||||
Future<void> pause();
|
||||
Future<void> stop();
|
||||
|
||||
/// Selects [voice], or the platform default when null.
|
||||
Future<void> setVoice(SpeechVoice? voice);
|
||||
Future<void> setRate(double rate);
|
||||
Future<List<SpeechVoice>> voices();
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'speech_engine.dart';
|
||||
|
||||
const speechRateKey = 'pipelines.readAloud.rate.v1';
|
||||
const speechVoiceNameKey = 'pipelines.readAloud.voiceName.v1';
|
||||
const speechVoiceLocaleKey = 'pipelines.readAloud.voiceLocale.v1';
|
||||
|
||||
/// The normal speaking rate and the slider's bounds (a multiplier).
|
||||
const defaultSpeechRate = 1.0;
|
||||
const minSpeechRate = 0.5;
|
||||
const maxSpeechRate = 2.0;
|
||||
|
||||
typedef SpeechPreferences = ({double rate, SpeechVoice? voice});
|
||||
|
||||
/// Device-local read-aloud settings.
|
||||
abstract interface class SpeechPreferencesStore {
|
||||
Future<SpeechPreferences?> load();
|
||||
Future<bool> save(SpeechPreferences preferences);
|
||||
}
|
||||
|
||||
class SharedSpeechPreferencesStore implements SpeechPreferencesStore {
|
||||
const SharedSpeechPreferencesStore();
|
||||
|
||||
@override
|
||||
Future<SpeechPreferences?> load() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final name = prefs.getString(speechVoiceNameKey);
|
||||
final locale = prefs.getString(speechVoiceLocaleKey);
|
||||
return (
|
||||
rate: prefs.getDouble(speechRateKey) ?? defaultSpeechRate,
|
||||
voice: name == null || locale == null
|
||||
? null
|
||||
: SpeechVoice(name: name, locale: locale),
|
||||
);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> save(SpeechPreferences preferences) async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final voice = preferences.voice;
|
||||
final saved = [
|
||||
await prefs.setDouble(speechRateKey, preferences.rate),
|
||||
if (voice == null) ...[
|
||||
await prefs.remove(speechVoiceNameKey),
|
||||
await prefs.remove(speechVoiceLocaleKey),
|
||||
] else ...[
|
||||
await prefs.setString(speechVoiceNameKey, voice.name),
|
||||
await prefs.setString(speechVoiceLocaleKey, voice.locale),
|
||||
],
|
||||
];
|
||||
return !saved.contains(false);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,7 @@ class ChatCopyGutterRow extends StatefulWidget {
|
||||
required this.width,
|
||||
required this.copy,
|
||||
required this.child,
|
||||
this.pinned = false,
|
||||
});
|
||||
|
||||
final double width;
|
||||
@@ -59,6 +60,9 @@ class ChatCopyGutterRow extends StatefulWidget {
|
||||
final Widget? copy;
|
||||
final Widget child;
|
||||
|
||||
/// Keeps the buttons shown without hover (while the reply reads aloud).
|
||||
final bool pinned;
|
||||
|
||||
@override
|
||||
State<ChatCopyGutterRow> createState() => _ChatCopyGutterRowState();
|
||||
}
|
||||
@@ -89,7 +93,9 @@ class _ChatCopyGutterRowState extends State<ChatCopyGutterRow> {
|
||||
setState(() => _focused = focused),
|
||||
child: AnimatedOpacity(
|
||||
key: const Key('chat-copy-gutter-visibility'),
|
||||
opacity: !hover || _hovered || _focused ? 1 : 0,
|
||||
opacity: !hover || widget.pinned || _hovered || _focused
|
||||
? 1
|
||||
: 0,
|
||||
duration: const Duration(milliseconds: 120),
|
||||
alwaysIncludeSemantics: true,
|
||||
child: copy,
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
|
||||
import '../../speech/speech.dart';
|
||||
|
||||
/// Space kept between a revealed word and the transcript's edge.
|
||||
const double _revealMargin = 24;
|
||||
|
||||
/// The range of [text] (one part of reply [messageId]) that [speech] is
|
||||
/// speaking now, or null.
|
||||
SpeechRange? spokenSourceIn(
|
||||
SpeechController speech,
|
||||
String? messageId,
|
||||
String text,
|
||||
) {
|
||||
final document = speech.document;
|
||||
final word = speech.word.value;
|
||||
if (messageId == null || speech.messageId != messageId) return null;
|
||||
if (document == null || word == null) return null;
|
||||
final part = document.partOf(text);
|
||||
if (part < 0) return null;
|
||||
final range = document.sourceRange(part, word);
|
||||
if (range == null) return null;
|
||||
// Document parts are trimmed; the view's offsets include the lead.
|
||||
final lead = text.length - text.trimLeft().length;
|
||||
return (start: range.start + lead, end: range.end + lead);
|
||||
}
|
||||
|
||||
/// [text] as spans whose characters with source [offsets] inside [range] are
|
||||
/// filled with [fill]; plain text when nothing in it is spoken.
|
||||
TextSpan spokenTextSpan(
|
||||
String text,
|
||||
List<int> offsets,
|
||||
SpeechRange? range,
|
||||
Color fill,
|
||||
) {
|
||||
if (range == null || offsets.isEmpty) return TextSpan(text: text);
|
||||
bool spoken(int index) =>
|
||||
offsets[index] >= range.start && offsets[index] < range.end;
|
||||
final children = <InlineSpan>[];
|
||||
var runStart = 0;
|
||||
for (var index = 1; index <= text.length; index += 1) {
|
||||
if (index < text.length && spoken(index) == spoken(runStart)) continue;
|
||||
children.add(
|
||||
TextSpan(
|
||||
text: text.substring(runStart, index),
|
||||
style: spoken(runStart) ? TextStyle(backgroundColor: fill) : null,
|
||||
),
|
||||
);
|
||||
runStart = index;
|
||||
}
|
||||
return TextSpan(children: children);
|
||||
}
|
||||
|
||||
/// Scrolls [scroll] just enough to show the spoken [range] when it has left
|
||||
/// the viewport; a word already in view never moves the transcript.
|
||||
void revealSpokenWord(
|
||||
ScrollPosition scroll,
|
||||
List<MarkdownSpokenSegment> segments,
|
||||
SpeechRange range, {
|
||||
required bool reduceMotion,
|
||||
}) {
|
||||
if (!scroll.hasContentDimensions) return;
|
||||
final segment = segments
|
||||
.where(
|
||||
(item) => item.sourceStart < range.end && item.sourceEnd > range.start,
|
||||
)
|
||||
.firstOrNull;
|
||||
final paragraph = _paragraphIn(segment?.key.currentContext);
|
||||
if (segment == null || paragraph == null) return;
|
||||
final boxes = paragraph.getBoxesForSelection(
|
||||
TextSelection(
|
||||
baseOffset: segment.renderedStart,
|
||||
extentOffset: segment.renderedEnd,
|
||||
),
|
||||
);
|
||||
final viewport = RenderAbstractViewport.maybeOf(paragraph);
|
||||
if (boxes.isEmpty || viewport == null) return;
|
||||
final rect = boxes.first.toRect().inflate(_revealMargin);
|
||||
final leading = viewport.getOffsetToReveal(paragraph, 0, rect: rect).offset;
|
||||
final trailing = viewport.getOffsetToReveal(paragraph, 1, rect: rect).offset;
|
||||
final low = leading < trailing ? leading : trailing;
|
||||
final high = leading < trailing ? trailing : leading;
|
||||
final target = scroll.pixels
|
||||
.clamp(low, high)
|
||||
.clamp(scroll.minScrollExtent, scroll.maxScrollExtent);
|
||||
if ((target - scroll.pixels).abs() < 1) return;
|
||||
if (reduceMotion) {
|
||||
scroll.jumpTo(target);
|
||||
return;
|
||||
}
|
||||
unawaited(
|
||||
scroll.animateTo(
|
||||
target,
|
||||
duration: const Duration(milliseconds: 240),
|
||||
curve: Curves.easeOut,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// The paragraph a keyed [Text] draws; selectable text wraps it in a mouse
|
||||
/// region, so the keyed element's own render object is not it.
|
||||
RenderParagraph? _paragraphIn(BuildContext? context) {
|
||||
RenderParagraph? found;
|
||||
void visit(RenderObject object) {
|
||||
if (found != null) return;
|
||||
if (object is RenderParagraph) {
|
||||
found = object;
|
||||
} else {
|
||||
object.visitChildren(visit);
|
||||
}
|
||||
}
|
||||
|
||||
final root = context?.findRenderObject();
|
||||
if (root != null) visit(root);
|
||||
return found;
|
||||
}
|
||||
|
||||
/// Resolves visible inline leaves in order against the original block source.
|
||||
/// Searching from the previous match skips emphasis/link/code delimiters and
|
||||
/// keeps repeated words tied to their own occurrence.
|
||||
class MarkdownSourceCursor {
|
||||
MarkdownSourceCursor(this.source, int textStart, this.key)
|
||||
: _cursor = textStart;
|
||||
|
||||
final String source;
|
||||
|
||||
/// The paragraph these leaves render into.
|
||||
final GlobalKey key;
|
||||
var _cursor = 0;
|
||||
var visibleOffset = 0;
|
||||
|
||||
List<int> consume(String text) {
|
||||
final offsets = <int>[];
|
||||
for (var index = 0; index < text.length; index += 1) {
|
||||
_skipLinkDestination();
|
||||
final character = text.substring(index, index + 1);
|
||||
final searchStart = _cursor.clamp(0, source.length);
|
||||
final found = searchStart >= source.length
|
||||
? -1
|
||||
: source.indexOf(character, searchStart);
|
||||
final offset = found < 0 ? searchStart : found;
|
||||
offsets.add(offset);
|
||||
_cursor = found < 0 ? searchStart + 1 : found + 1;
|
||||
}
|
||||
return offsets;
|
||||
}
|
||||
|
||||
void _skipLinkDestination() {
|
||||
if (_cursor >= source.length || source[_cursor] != ']') return;
|
||||
if (_cursor + 1 >= source.length || source[_cursor + 1] != '(') return;
|
||||
var depth = 0;
|
||||
for (var index = _cursor + 1; index < source.length; index += 1) {
|
||||
if (source[index] == '(') depth += 1;
|
||||
if (source[index] == ')' && --depth == 0) {
|
||||
_cursor = index + 1;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One inline leaf: its source range and its character range in [key]'s
|
||||
/// rendered paragraph.
|
||||
class MarkdownSpokenSegment {
|
||||
const MarkdownSpokenSegment(
|
||||
this.key,
|
||||
this.sourceStart,
|
||||
this.sourceEnd,
|
||||
this.renderedStart,
|
||||
this.renderedEnd,
|
||||
);
|
||||
|
||||
final GlobalKey key;
|
||||
final int sourceStart;
|
||||
final int sourceEnd;
|
||||
final int renderedStart;
|
||||
final int renderedEnd;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/semantics.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
|
||||
import 'chat_transcript_selection.dart';
|
||||
import 'chat_code_hover.dart';
|
||||
@@ -10,7 +10,9 @@ import 'chat_link_launcher.dart';
|
||||
import 'chat_link_spans.dart';
|
||||
import 'chat_markdown.dart';
|
||||
import 'chat_markdown_cache.dart';
|
||||
import 'chat_markdown_speech.dart';
|
||||
import 'chat_message_bubble.dart';
|
||||
import '../../speech/speech.dart';
|
||||
|
||||
/// Renders one assistant text part with native text widgets and the host's own
|
||||
/// theme roles. Links (`http`, `https`, `mailto` and `www.` hosts only) open
|
||||
@@ -19,9 +21,15 @@ import 'chat_message_bubble.dart';
|
||||
/// dimension is overridden; code keeps its exact whitespace and scrolls
|
||||
/// sideways instead of widening the transcript.
|
||||
class ChatMarkdownView extends StatefulWidget {
|
||||
const ChatMarkdownView({super.key, required this.text, this.onOpenLink});
|
||||
const ChatMarkdownView({
|
||||
super.key,
|
||||
required this.text,
|
||||
this.messageId,
|
||||
this.onOpenLink,
|
||||
});
|
||||
|
||||
final String text;
|
||||
final String? messageId;
|
||||
final ValueChanged<String>? onOpenLink;
|
||||
|
||||
@override
|
||||
@@ -44,6 +52,14 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
final _codeHover = ChatCodeHover();
|
||||
ScrollPosition? _scroll;
|
||||
ModalRoute<dynamic>? _route;
|
||||
var _sourceCursor = 0;
|
||||
|
||||
/// The source range of [ChatMarkdownView.text] being spoken, while building.
|
||||
SpeechRange? _highlight;
|
||||
SpeechRange? _revealed;
|
||||
final _textKeys = <GlobalKey>[];
|
||||
var _textCount = 0;
|
||||
final _segments = <MarkdownSpokenSegment>[];
|
||||
|
||||
@override
|
||||
void didUpdateWidget(ChatMarkdownView oldWidget) {
|
||||
@@ -77,12 +93,35 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// A new token or usage update elsewhere in the turn must not reparse and
|
||||
// rebuild every earlier answer part, or disturb its text selection.
|
||||
if (_rendered != null) return _rendered!;
|
||||
// Keep the state subscribed to inherited styling even when the cached
|
||||
// subtree is returned without rebuilding its Markdown spans.
|
||||
Theme.of(context);
|
||||
final speech = speechController;
|
||||
return ListenableBuilder(
|
||||
listenable: Listenable.merge([speech, speech.word]),
|
||||
builder: (context, _) {
|
||||
final range = spokenSourceIn(speech, widget.messageId, widget.text);
|
||||
if (range == null) {
|
||||
_revealed = null;
|
||||
return _rendered ?? _buildRendered(context, null);
|
||||
}
|
||||
if (range != _revealed) {
|
||||
_revealed = range;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => _reveal(range));
|
||||
}
|
||||
return _buildRendered(context, range);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildRendered(BuildContext context, SpeechRange? range) {
|
||||
_sourceCursor = 0;
|
||||
_textCount = 0;
|
||||
_highlight = range;
|
||||
_segments.clear();
|
||||
final gap = chatParagraphGap(context);
|
||||
final blocks = chatMarkdownCache.blocksFor(widget.text);
|
||||
return _rendered = Listener(
|
||||
final rendered = Listener(
|
||||
onPointerDown: (_) => _codeHover.hide(),
|
||||
onPointerSignal: (_) => _codeHover.hide(),
|
||||
child: NotificationListener<ScrollNotification>(
|
||||
@@ -108,6 +147,8 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
),
|
||||
),
|
||||
);
|
||||
if (range == null) _rendered = rendered;
|
||||
return rendered;
|
||||
}
|
||||
|
||||
/// Blocks are separated by an empty line of body text, like paragraphs;
|
||||
@@ -196,6 +237,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
),
|
||||
);
|
||||
case MarkdownCode(language: final language, code: final code):
|
||||
_skipCodeBlock(code);
|
||||
final labelStyle = _roleStyle(
|
||||
context,
|
||||
Theme.of(context).textTheme.labelSmall,
|
||||
@@ -220,6 +262,14 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
}
|
||||
}
|
||||
|
||||
void _skipCodeBlock(String code) {
|
||||
_sourceCursor = fencedCodeSpan(
|
||||
widget.text,
|
||||
_sourceCursor,
|
||||
code,
|
||||
).end.clamp(0, widget.text.length);
|
||||
}
|
||||
|
||||
Widget _cell(BuildContext context, String text, {bool header = false}) {
|
||||
final style = header
|
||||
? _roleStyle(context, Theme.of(context).textTheme.labelLarge)
|
||||
@@ -234,43 +284,77 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
}
|
||||
|
||||
Widget _text(BuildContext context, String text, {TextStyle? style}) {
|
||||
if (text.isEmpty) return const SizedBox.shrink();
|
||||
final sourceStart = widget.text.indexOf(text, _sourceCursor);
|
||||
if (sourceStart >= 0) _sourceCursor = sourceStart + text.length;
|
||||
// Keys follow render order, which is stable for the same text, so the
|
||||
// revealed word's paragraph can be found after the frame.
|
||||
if (_textCount == _textKeys.length) _textKeys.add(GlobalKey());
|
||||
final key = _textKeys[_textCount++];
|
||||
final source = MarkdownSourceCursor(
|
||||
widget.text,
|
||||
sourceStart < 0 ? _sourceCursor : sourceStart,
|
||||
key,
|
||||
);
|
||||
return Builder(
|
||||
builder: (textContext) => Text.rich(
|
||||
TextSpan(children: _spans(textContext, parseInline(text))),
|
||||
key: key,
|
||||
TextSpan(children: _spans(textContext, parseInline(text), source)),
|
||||
style: style,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
List<InlineSpan> _spans(BuildContext context, List<MarkdownInline> spans) => [
|
||||
List<InlineSpan> _spans(
|
||||
BuildContext context,
|
||||
List<MarkdownInline> spans,
|
||||
MarkdownSourceCursor source,
|
||||
) => [
|
||||
for (final span in spans)
|
||||
switch (span) {
|
||||
MarkdownPlain(text: final text) => TextSpan(text: text),
|
||||
MarkdownInlineCode(text: final text) => _inlineCode(context, text),
|
||||
MarkdownPlain(text: final text) => _leaf(context, text, source),
|
||||
MarkdownInlineCode(text: final text) => _inlineCode(
|
||||
context,
|
||||
text,
|
||||
source,
|
||||
),
|
||||
MarkdownStrong(spans: final inner) => TextSpan(
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
children: _spans(context, inner),
|
||||
children: _spans(context, inner, source),
|
||||
),
|
||||
MarkdownEmphasis(spans: final inner) => TextSpan(
|
||||
style: const TextStyle(fontStyle: FontStyle.italic),
|
||||
children: _spans(context, inner),
|
||||
children: _spans(context, inner, source),
|
||||
),
|
||||
MarkdownLink(url: final url, spans: final inner) => _link(
|
||||
context,
|
||||
url,
|
||||
inner,
|
||||
source,
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
TextSpan _inlineCode(BuildContext context, String text) {
|
||||
TextSpan _leaf(
|
||||
BuildContext context,
|
||||
String text,
|
||||
MarkdownSourceCursor source,
|
||||
) => _highlightedText(context, text, source);
|
||||
|
||||
TextSpan _inlineCode(
|
||||
BuildContext context,
|
||||
String text,
|
||||
MarkdownSourceCursor source,
|
||||
) {
|
||||
final token = text;
|
||||
final highlighted = _highlightedText(context, text, source);
|
||||
return TextSpan(
|
||||
text: text,
|
||||
style: TextStyle(
|
||||
fontFamily: appMonospaceFamily,
|
||||
backgroundColor: _codeFill(context),
|
||||
),
|
||||
text: highlighted.text,
|
||||
children: highlighted.children,
|
||||
onEnter: (event) {
|
||||
if (_route?.isCurrent != false) {
|
||||
_codeHover.show(context, token, text, event.position);
|
||||
@@ -284,10 +368,11 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
BuildContext context,
|
||||
String url,
|
||||
List<MarkdownInline> spans,
|
||||
MarkdownSourceCursor source,
|
||||
) => _links.link(
|
||||
context,
|
||||
url,
|
||||
_spans(context, spans),
|
||||
_spans(context, spans, source),
|
||||
onOpen: (uri) {
|
||||
final onOpenLink = widget.onOpenLink;
|
||||
if (onOpenLink != null) return onOpenLink(uri.toString());
|
||||
@@ -295,6 +380,46 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
},
|
||||
);
|
||||
|
||||
/// A leaf's spans, recording where it renders so a spoken word in it can
|
||||
/// be revealed, with the spoken characters highlighted.
|
||||
TextSpan _highlightedText(
|
||||
BuildContext context,
|
||||
String text,
|
||||
MarkdownSourceCursor source,
|
||||
) {
|
||||
final offsets = source.consume(text);
|
||||
final renderedStart = source.visibleOffset;
|
||||
source.visibleOffset += text.length;
|
||||
if (offsets.isNotEmpty) {
|
||||
_segments.add(
|
||||
MarkdownSpokenSegment(
|
||||
source.key,
|
||||
offsets.first,
|
||||
offsets.last + 1,
|
||||
renderedStart,
|
||||
source.visibleOffset,
|
||||
),
|
||||
);
|
||||
}
|
||||
return spokenTextSpan(
|
||||
text,
|
||||
offsets,
|
||||
_highlight,
|
||||
Theme.of(context).colorScheme.primaryContainer,
|
||||
);
|
||||
}
|
||||
|
||||
void _reveal(SpeechRange range) {
|
||||
final scroll = _scroll;
|
||||
if (!mounted || range != _revealed || scroll == null) return;
|
||||
revealSpokenWord(
|
||||
scroll,
|
||||
_segments,
|
||||
range,
|
||||
reduceMotion: MediaQuery.maybeDisableAnimationsOf(context) ?? false,
|
||||
);
|
||||
}
|
||||
|
||||
/// Heading roles are a non-increasing sequence from the host's own text
|
||||
/// theme. H3–H6 share one title role, matching the web renderer's flat
|
||||
/// lower-heading treatment, and no level falls back to a body role, so a
|
||||
|
||||
@@ -14,6 +14,8 @@ import 'chat_message_bubble.dart';
|
||||
import 'chat_turn_activity_view.dart';
|
||||
import 'native_disclosure.dart';
|
||||
import 'chat_message_timestamp.dart';
|
||||
import 'chat_read_aloud_button.dart';
|
||||
import '../../speech/speech_controller.dart';
|
||||
|
||||
/// Builds an assistant text part; the default keeps the server's text exactly.
|
||||
typedef ChatMessageTextBuilder = Widget Function(BuildContext, String);
|
||||
@@ -27,9 +29,14 @@ class ChatMessageView extends StatelessWidget {
|
||||
this.textBuilder,
|
||||
this.footer = const [],
|
||||
this.images,
|
||||
this.speechScope = 'chat',
|
||||
});
|
||||
|
||||
final JsonMap row;
|
||||
|
||||
/// Names the conversation in the reader's message ids, so leaving it can
|
||||
/// stop only its own reply (see [speechMessageId]).
|
||||
final String speechScope;
|
||||
final ChatMessageTextBuilder? textBuilder;
|
||||
|
||||
/// Loads attached images for the operator's turn; without one, only images
|
||||
@@ -179,13 +186,41 @@ class ChatMessageView extends StatelessWidget {
|
||||
Widget answer,
|
||||
double gutter,
|
||||
) {
|
||||
final copyText = row['streaming'] == true ? '' : _answerText(_partsOf(row));
|
||||
final copy = copyText.isEmpty ? null : ChatCopyButton(text: copyText);
|
||||
if (gutter <= 0) return _agentTurn(context, content, answer, copy);
|
||||
return ChatCopyGutterRow(
|
||||
width: gutter,
|
||||
copy: copy,
|
||||
child: _agentTurn(context, content, answer, null),
|
||||
final answerParts = row['streaming'] == true
|
||||
? const <String>[]
|
||||
: _answerParts(_partsOf(row));
|
||||
final copyText = answerParts.join('\n\n');
|
||||
final id = speechMessageId(speechScope, '${row['key'] ?? row['id'] ?? ''}');
|
||||
Widget? actions(Axis direction) => copyText.isEmpty
|
||||
? null
|
||||
: Flex(
|
||||
direction: direction,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
verticalDirection: VerticalDirection.up,
|
||||
children: [
|
||||
ChatCopyButton(text: copyText),
|
||||
ChatReadAloudButton(
|
||||
messageId: id,
|
||||
parts: answerParts,
|
||||
direction: direction,
|
||||
),
|
||||
],
|
||||
);
|
||||
if (gutter <= 0) {
|
||||
return _agentTurn(context, content, answer, actions(Axis.horizontal));
|
||||
}
|
||||
// The gutter is one button wide: Read aloud stacks above Copy, and stays
|
||||
// shown on a desktop while this reply reads.
|
||||
final turn = _agentTurn(context, content, answer, null);
|
||||
return ListenableBuilder(
|
||||
listenable: speechController,
|
||||
child: turn,
|
||||
builder: (context, child) => ChatCopyGutterRow(
|
||||
width: gutter,
|
||||
copy: actions(Axis.vertical),
|
||||
pinned: speechController.messageId == id,
|
||||
child: child!,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -267,13 +302,13 @@ class ChatMessageView extends StatelessWidget {
|
||||
|
||||
/// The answer as the operator reads it: the turn's text parts in order,
|
||||
/// without reasoning, tools or attachments.
|
||||
String _answerText(List<JsonMap> parts) => [
|
||||
List<String> _answerParts(List<JsonMap> parts) => [
|
||||
for (final part in parts)
|
||||
if ((part['type'] == null || part['type'] == 'text') &&
|
||||
part['text'] is String &&
|
||||
(part['text'] as String).trim().isNotEmpty)
|
||||
(part['text'] as String).trim(),
|
||||
].join('\n\n');
|
||||
];
|
||||
|
||||
List<Widget> _agentParts(BuildContext context) {
|
||||
final widgets = <Widget>[];
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../speech/speech.dart';
|
||||
|
||||
const chatReadAloudLabel = 'Read aloud';
|
||||
const chatPauseReadingLabel = 'Pause reading';
|
||||
const chatResumeReadingLabel = 'Resume reading';
|
||||
const chatStopReadingLabel = 'Stop reading';
|
||||
|
||||
/// Read aloud for one reply, styled like its Copy button. While this reply
|
||||
/// reads it becomes Pause (or Resume) and Stop, laid out along [direction]
|
||||
/// (a column in the narrow copy gutter). Absent where speech is unsupported.
|
||||
class ChatReadAloudButton extends StatelessWidget {
|
||||
const ChatReadAloudButton({
|
||||
super.key,
|
||||
required this.messageId,
|
||||
required this.parts,
|
||||
this.direction = Axis.horizontal,
|
||||
});
|
||||
|
||||
final String messageId;
|
||||
|
||||
/// The reply's markdown text parts, in order.
|
||||
final List<String> parts;
|
||||
final Axis direction;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final speech = speechController;
|
||||
if (!speech.supported) return const SizedBox.shrink();
|
||||
return ListenableBuilder(
|
||||
listenable: speech,
|
||||
builder: (context, _) {
|
||||
if (speech.messageId != messageId) {
|
||||
return IconButton(
|
||||
key: const Key('chat-message-read-aloud'),
|
||||
tooltip: chatReadAloudLabel,
|
||||
onPressed: () => unawaited(speech.read(messageId, parts)),
|
||||
icon: const Icon(Icons.volume_up_outlined),
|
||||
);
|
||||
}
|
||||
final paused = speech.state == SpeechState.paused;
|
||||
return Flex(
|
||||
direction: direction,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
IconButton(
|
||||
key: const Key('chat-message-read-aloud-pause'),
|
||||
tooltip: paused ? chatResumeReadingLabel : chatPauseReadingLabel,
|
||||
onPressed: () =>
|
||||
unawaited(paused ? speech.resume() : speech.pause()),
|
||||
icon: Icon(
|
||||
paused ? Icons.play_arrow_outlined : Icons.pause_outlined,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
key: const Key('chat-message-read-aloud-stop'),
|
||||
tooltip: chatStopReadingLabel,
|
||||
onPressed: () => unawaited(speech.stop()),
|
||||
icon: const Icon(Icons.stop_outlined),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,13 @@ extension _SettingsPageSections on _SettingsScreenState {
|
||||
keywords: 'text size scale zoom large small font',
|
||||
builder: (_) => const SettingsScaleSection(),
|
||||
),
|
||||
if (speechController.supported)
|
||||
const SettingsSection(
|
||||
id: 'read-aloud',
|
||||
title: 'Read aloud',
|
||||
keywords: 'speech voice audio speaking rate read aloud',
|
||||
builder: _readAloudBuilder,
|
||||
),
|
||||
SettingsSection(
|
||||
id: 'animations',
|
||||
title: 'Animations',
|
||||
@@ -216,6 +223,9 @@ extension _SettingsPageSections on _SettingsScreenState {
|
||||
];
|
||||
}
|
||||
|
||||
static Widget _readAloudBuilder(BuildContext _) =>
|
||||
const SettingsReadAloudSection();
|
||||
|
||||
/// A group holding one free-form block (a form, a status with buttons).
|
||||
Widget _single(String title, Widget child) => SettingsGroup(
|
||||
title: title,
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../chat/speech/speech.dart';
|
||||
import 'settings_group.dart';
|
||||
import 'settings_row.dart';
|
||||
import 'settings_theme.dart';
|
||||
import 'settings_voice_picker.dart';
|
||||
|
||||
/// Read aloud: the voice and speaking rate replies are read with, saved on
|
||||
/// this device, with a sample and a reset to the system voice at normal speed.
|
||||
class SettingsReadAloudSection extends StatefulWidget {
|
||||
const SettingsReadAloudSection({super.key, this.controller});
|
||||
|
||||
/// The reader; the app's own by default.
|
||||
final SpeechController? controller;
|
||||
|
||||
@override
|
||||
State<SettingsReadAloudSection> createState() =>
|
||||
_SettingsReadAloudSectionState();
|
||||
}
|
||||
|
||||
class _SettingsReadAloudSectionState extends State<SettingsReadAloudSection> {
|
||||
SpeechController get _speech => widget.controller ?? speechController;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
unawaited(_speech.restore());
|
||||
}
|
||||
|
||||
Future<void> _pickVoice() async {
|
||||
final choice = await showSpeechVoicePicker(context, _speech);
|
||||
if (choice != null) await _speech.setVoice(choice.voice);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: _speech,
|
||||
builder: (context, _) {
|
||||
final rate = _speech.rate;
|
||||
final label = '${rate.toStringAsFixed(1)}×';
|
||||
final voice = _speech.voice;
|
||||
final sampling = _speech.messageId == speechSampleId;
|
||||
return SettingsGroup(
|
||||
title: 'Read aloud',
|
||||
footer: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text(
|
||||
'Saved on this device. Replies are read with this voice and rate.',
|
||||
),
|
||||
if (_speech.saveFailed)
|
||||
Text(
|
||||
'Could not save; applies until reload.',
|
||||
style: TextStyle(color: settingsErrorColor(context)),
|
||||
),
|
||||
],
|
||||
),
|
||||
children: [
|
||||
SettingsRow(
|
||||
key: const Key('settings-read-aloud-voice'),
|
||||
leading: const Icon(Icons.record_voice_over_outlined),
|
||||
title: const Text('Voice'),
|
||||
subtitle: Text(
|
||||
voice == null
|
||||
? 'System default'
|
||||
: '${voice.name} · ${voice.locale}',
|
||||
),
|
||||
chevron: true,
|
||||
onTap: () => unawaited(_pickVoice()),
|
||||
),
|
||||
SettingsGroupItem(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
'Speaking rate $label',
|
||||
style: settingsTextStyle(context, title: true),
|
||||
),
|
||||
Semantics(
|
||||
label: 'Speaking rate',
|
||||
child: Slider(
|
||||
key: const Key('settings-read-aloud-rate'),
|
||||
value: rate,
|
||||
min: minSpeechRate,
|
||||
max: maxSpeechRate,
|
||||
divisions: 15,
|
||||
label: label,
|
||||
semanticFormatterCallback: (value) =>
|
||||
'${value.toStringAsFixed(1)} times',
|
||||
onChanged: (value) =>
|
||||
unawaited(_speech.setRate(value, save: false)),
|
||||
onChangeEnd: (value) => unawaited(_speech.setRate(value)),
|
||||
),
|
||||
),
|
||||
const Wrap(
|
||||
alignment: WrapAlignment.spaceBetween,
|
||||
children: [Text('0.5× · Slower'), Text('2.0× · Faster')],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
SettingsGroupItem(
|
||||
child: Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
FilledButton.tonalIcon(
|
||||
key: const Key('settings-read-aloud-sample'),
|
||||
onPressed: () =>
|
||||
unawaited(sampling ? _speech.stop() : _speech.sample()),
|
||||
icon: Icon(
|
||||
sampling ? Icons.stop_outlined : Icons.play_arrow_outlined,
|
||||
),
|
||||
label: Text(sampling ? 'Stop sample' : 'Play sample'),
|
||||
),
|
||||
TextButton(
|
||||
key: const Key('settings-read-aloud-reset'),
|
||||
onPressed: _speech.isDefault
|
||||
? null
|
||||
: () => unawaited(_speech.reset()),
|
||||
child: const Text('Reset to defaults'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -40,6 +40,8 @@ import 'managed_connection_section.dart';
|
||||
import 'settings_keyboard_shortcuts_section.dart';
|
||||
import 'settings_keys.dart';
|
||||
import 'settings_row.dart';
|
||||
import 'settings_read_aloud_section.dart';
|
||||
import '../chat/speech/speech_controller.dart';
|
||||
|
||||
part 'settings_page_sections.dart';
|
||||
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../chat/speech/speech.dart';
|
||||
|
||||
/// The picker's answer: a voice, or null for the system default.
|
||||
typedef SpeechVoiceChoice = ({SpeechVoice? voice});
|
||||
|
||||
/// Lists the platform's voices grouped by language, the device's language
|
||||
/// first, each with a sample. Resolves to null when dismissed.
|
||||
Future<SpeechVoiceChoice?> showSpeechVoicePicker(
|
||||
BuildContext context,
|
||||
SpeechController speech,
|
||||
) async {
|
||||
final choice = await showDialog<SpeechVoiceChoice>(
|
||||
context: context,
|
||||
builder: (_) => _VoicePickerDialog(speech: speech),
|
||||
);
|
||||
if (speech.messageId == speechSampleId) unawaited(speech.stop());
|
||||
return choice;
|
||||
}
|
||||
|
||||
/// Voices grouped by language subtag, the [device] language first and the
|
||||
/// rest by name; voices within a group by name.
|
||||
List<({String language, List<SpeechVoice> voices})> groupSpeechVoices(
|
||||
List<SpeechVoice> voices,
|
||||
String device,
|
||||
) {
|
||||
final groups = <String, List<SpeechVoice>>{};
|
||||
for (final voice in voices) {
|
||||
(groups[voice.language] ??= []).add(voice);
|
||||
}
|
||||
final languages = groups.keys.toList()
|
||||
..sort((a, b) {
|
||||
if (a == device.toLowerCase()) return -1;
|
||||
if (b == device.toLowerCase()) return 1;
|
||||
return speechLanguageName(a).compareTo(speechLanguageName(b));
|
||||
});
|
||||
return [
|
||||
for (final language in languages)
|
||||
(
|
||||
language: language,
|
||||
voices: groups[language]!
|
||||
..sort((a, b) {
|
||||
final name = a.name.compareTo(b.name);
|
||||
return name != 0 ? name : a.locale.compareTo(b.locale);
|
||||
}),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/// An English name for common language subtags; others show their code.
|
||||
String speechLanguageName(String language) =>
|
||||
_languageNames[language] ?? language.toUpperCase();
|
||||
|
||||
const _languageNames = {
|
||||
'ar': 'Arabic',
|
||||
'bg': 'Bulgarian',
|
||||
'ca': 'Catalan',
|
||||
'cs': 'Czech',
|
||||
'da': 'Danish',
|
||||
'de': 'German',
|
||||
'el': 'Greek',
|
||||
'en': 'English',
|
||||
'es': 'Spanish',
|
||||
'fi': 'Finnish',
|
||||
'fr': 'French',
|
||||
'he': 'Hebrew',
|
||||
'hi': 'Hindi',
|
||||
'hr': 'Croatian',
|
||||
'hu': 'Hungarian',
|
||||
'id': 'Indonesian',
|
||||
'it': 'Italian',
|
||||
'ja': 'Japanese',
|
||||
'ko': 'Korean',
|
||||
'ms': 'Malay',
|
||||
'nb': 'Norwegian',
|
||||
'nl': 'Dutch',
|
||||
'pl': 'Polish',
|
||||
'pt': 'Portuguese',
|
||||
'ro': 'Romanian',
|
||||
'ru': 'Russian',
|
||||
'sk': 'Slovak',
|
||||
'sv': 'Swedish',
|
||||
'th': 'Thai',
|
||||
'tr': 'Turkish',
|
||||
'uk': 'Ukrainian',
|
||||
'vi': 'Vietnamese',
|
||||
'zh': 'Chinese',
|
||||
};
|
||||
|
||||
class _VoicePickerDialog extends StatefulWidget {
|
||||
const _VoicePickerDialog({required this.speech});
|
||||
|
||||
final SpeechController speech;
|
||||
|
||||
@override
|
||||
State<_VoicePickerDialog> createState() => _VoicePickerDialogState();
|
||||
}
|
||||
|
||||
class _VoicePickerDialogState extends State<_VoicePickerDialog> {
|
||||
late final Future<List<SpeechVoice>> _voices = widget.speech.voices();
|
||||
|
||||
String _keyOf(SpeechVoice? voice) =>
|
||||
voice == null ? '' : '${voice.name}\n${voice.locale}';
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final device = View.of(context).platformDispatcher.locale.languageCode;
|
||||
return AlertDialog(
|
||||
title: const Text('Voice'),
|
||||
contentPadding: const EdgeInsets.symmetric(vertical: 16),
|
||||
// A list needs a definite width; keep it to a readable dialog measure.
|
||||
content: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 560),
|
||||
child: SizedBox(
|
||||
width: double.maxFinite,
|
||||
child: FutureBuilder<List<SpeechVoice>>(
|
||||
future: _voices,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState != ConnectionState.done) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
final voices = snapshot.data ?? const <SpeechVoice>[];
|
||||
return _list(context, groupSpeechVoices(voices, device));
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _list(
|
||||
BuildContext context,
|
||||
List<({String language, List<SpeechVoice> voices})> groups,
|
||||
) {
|
||||
final theme = Theme.of(context);
|
||||
final header = theme.textTheme.titleSmall?.copyWith(
|
||||
color: theme.colorScheme.primary,
|
||||
);
|
||||
return RadioGroup<String>(
|
||||
groupValue: _keyOf(widget.speech.voice),
|
||||
onChanged: (key) {
|
||||
final voice = [
|
||||
for (final group in groups) ...group.voices,
|
||||
].where((voice) => _keyOf(voice) == key).firstOrNull;
|
||||
Navigator.of(context).pop((voice: voice));
|
||||
},
|
||||
child: ListView(
|
||||
shrinkWrap: true,
|
||||
children: [
|
||||
const RadioListTile<String>(value: '', title: Text('System default')),
|
||||
if (groups.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
|
||||
child: Text(
|
||||
'This device offers no other voices.',
|
||||
style: TextStyle(color: theme.colorScheme.onSurfaceVariant),
|
||||
),
|
||||
),
|
||||
for (final group in groups) ...[
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(24, 16, 24, 4),
|
||||
child: Semantics(
|
||||
header: true,
|
||||
child: Text(speechLanguageName(group.language), style: header),
|
||||
),
|
||||
),
|
||||
for (final voice in group.voices)
|
||||
// The sample is its own control beside the choice, not merged
|
||||
// into the radio tile's semantics.
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: RadioListTile<String>(
|
||||
value: _keyOf(voice),
|
||||
title: Text(voice.name),
|
||||
subtitle: Text(voice.locale),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.only(end: 12),
|
||||
child: IconButton(
|
||||
tooltip: 'Play sample of ${voice.name}',
|
||||
onPressed: () => unawaited(widget.speech.sample(voice)),
|
||||
icon: const Icon(Icons.play_arrow_outlined),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user