read text aloud

This commit is contained in:
2026-10-23 09:40:20 +02:00
parent 281f5465a6
commit 92b90c0e13
20 changed files with 471 additions and 18 deletions
+21 -4
View File
@@ -41,8 +41,13 @@ public enum ContextAction: Sendable, Equatable {
case delete(String, isDirectory: Bool)
case copyTerminalSelection(TerminalKind)
case pasteIntoTerminal(TerminalKind)
/// Inserts `/wait-what` with the pane's selection into the agent composer.
case waitWhat(TerminalKind)
/// Inserts `/bouwen <name>` into the agent composer for an ontwikkeling folder.
case bouwen(String)
/// Reads a Markdown file's prose aloud.
case readAloudFile(String)
case readAloudText(String)
/// Destructive items read in amber-deep.
public var isDestructive: Bool {
@@ -81,14 +86,14 @@ public enum ContextActions {
return [
.action(.passOnReference(ref, code: hasCode ? code : nil), label: hasCode ? "Pass on selection" : "Pass on reference"),
.action(.copyReference(ref), label: "Copy reference"),
] + showDiff
] + (hasCode ? readAloudSelection(code ?? "", path: reference.path) : []) + showDiff
case .projectRoot:
return [
.action(.newFile(inDirectory: ""), label: "New file"),
.action(.revealInFinder(""), label: "Show in Finder"),
]
case let .file(path):
return fileHead(path) + [
return fileHead(path) + readAloudFile(path) + [
.separator,
.action(.rename(path, isDirectory: false), label: "Rename file"),
.action(.revealInFinder(path), label: "Show in Finder"),
@@ -109,10 +114,12 @@ public enum ContextActions {
.action(.delete(path, isDirectory: true), label: "Delete folder"),
]
case let .terminal(kind, hasSelection):
let waitWhat: [ContextMenuEntry] = hasSelection && kind == .agent
? [.separator, .action(.waitWhat(kind), label: "Wait what?")] : []
return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : [])
+ [.action(.pasteIntoTerminal(kind), label: "Paste")]
+ [.action(.pasteIntoTerminal(kind), label: "Paste")] + waitWhat
case let .gitRow(path, staged):
return fileHead(path) + [
return fileHead(path) + readAloudFile(path) + [
.separator,
staged ? .action(.unstage(path), label: "Unstage changes") : .action(.stage(path), label: "Stage changes"),
.action(.openDiff(path), label: "Open diff"),
@@ -128,6 +135,16 @@ public enum ContextActions {
return String(parts[1])
}
private static func readAloudFile(_ path: String) -> [ContextMenuEntry] {
FileType.isMarkdown(path) ? [.separator, .action(.readAloudFile(path), label: "Read aloud")] : []
}
/// Selected Markdown is read as prose; a selection with no prose left, such as one code block, is read as it is.
private static func readAloudSelection(_ code: String, path: String) -> [ContextMenuEntry] {
let prose = FileType.isMarkdown(path) ? MarkdownSpeech.plainText(MarkdownParser.parse(code)) : ""
return [.separator, .action(.readAloudText(prose.isEmpty ? code : prose), label: "Read aloud selection")]
}
private static func fileHead(_ path: String) -> [ContextMenuEntry] {
let name = PathUtils.basename(path)
return [
@@ -0,0 +1,62 @@
import Foundation
public enum MarkdownSpeech {
/// The prose of a document for a voice to read: one sentence per line, markup, URLs, code blocks and rules left out.
/// A line without closing punctuation gets a full stop, so the voice pauses between blocks.
public static func plainText(_ blocks: [MarkdownBlock]) -> String {
lines(blocks).joined(separator: "\n")
}
/// The text with each `$` that is not before a digit written as "dollar", so the voice does not say "dollar sign".
/// A `$` before a digit stays: the voice reads `$5` as "five dollars".
public static func spoken(_ text: String) -> String {
let characters = Array(text)
var result = ""
for (index, character) in characters.enumerated() {
let next = index + 1 < characters.count ? characters[index + 1] : nil
guard character == "$", !(next?.isNumber ?? false) else {
result.append(character)
continue
}
if let last = result.last, !last.isWhitespace { result.append(" ") }
result.append("dollar")
if let next, !next.isWhitespace { result.append(" ") }
}
return result
}
private static func lines(_ blocks: [MarkdownBlock]) -> [String] {
blocks.flatMap { block -> [String] in
switch block {
case let .heading(_, content), let .paragraph(content): [sentence(content)]
case let .quote(inner): lines(inner)
case let .list(_, items): items.map(sentence)
case let .table(header, _, rows):
([header] + rows).map { cells in sentence(cells.map(text).filter { !$0.isEmpty }.joined(separator: ", ")) }
case .code, .rule: []
}
}
.filter { !$0.isEmpty }
}
private static func sentence(_ inlines: [MarkdownInline]) -> String {
sentence(text(inlines))
}
private static func sentence(_ text: String) -> String {
let trimmed = text.split(whereSeparator: \.isWhitespace).joined(separator: " ")
guard let last = trimmed.last else { return "" }
return ".!?:;".contains(last) ? trimmed : trimmed + "."
}
private static func text(_ inlines: [MarkdownInline]) -> String {
inlines.map { inline in
switch inline {
case let .text(text), let .code(text): text
case let .strong(inner), let .emphasis(inner), let .strikethrough(inner), let .link(inner, _, _): text(inner)
case let .image(alt, _, _): alt
}
}
.joined()
}
}
@@ -0,0 +1,52 @@
import AVFoundation
import Foundation
@MainActor
public protocol SpeechServicing: AnyObject {
/// Called when the text was read to the end; never after `stop()`.
var onFinish: (() -> Void)? { get set }
/// Reads `text` aloud with the system voice, cutting off anything still being read.
func speak(_ text: String)
func stop()
}
/// Speech through `AVSpeechSynthesizer`.
@MainActor
public final class SpeechService: NSObject, SpeechServicing {
public var onFinish: (() -> Void)?
private lazy var synthesizer: AVSpeechSynthesizer = {
let synthesizer = AVSpeechSynthesizer()
synthesizer.delegate = self
return synthesizer
}()
/// The utterance now being read; a late finish of a replaced one must not end the new one.
private var current: ObjectIdentifier?
/// Nonisolated, so the shared `AppServices.live` can build it.
override public nonisolated init() {
super.init()
}
public func speak(_ text: String) {
stop()
let utterance = AVSpeechUtterance(string: text)
current = ObjectIdentifier(utterance)
synthesizer.speak(utterance)
}
public func stop() {
current = nil
synthesizer.stopSpeaking(at: .immediate)
}
}
extension SpeechService: AVSpeechSynthesizerDelegate {
nonisolated public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
let finished = ObjectIdentifier(utterance)
Task { @MainActor in
guard self.current == finished else { return }
self.current = nil
self.onFinish?()
}
}
}
@@ -108,10 +108,10 @@ struct ContextMenuOverlay: View {
nonisolated static func tint(for action: ContextAction) -> MenuIconTint {
switch action {
case .copyReference, .copyTerminalSelection, .pasteIntoTerminal: .plain
case .copyReference, .copyTerminalSelection, .pasteIntoTerminal, .readAloudFile, .readAloudText: .plain
case .newFile, .newFolder, .stage: .add
case .copyFileName, .unstage, .revealInFinder: .modify
case .passOnReference, .passOnFileName, .bouwen, .openDiff, .showDiff, .rename: .rename
case .passOnReference, .passOnFileName, .bouwen, .waitWhat, .openDiff, .showDiff, .rename: .rename
case .discard, .delete: .danger
}
}
@@ -120,6 +120,8 @@ struct ContextMenuOverlay: View {
switch action {
case .passOnReference, .passOnFileName: ContextMenuRow.spark
case .bouwen: "hammer"
case .waitWhat: "questionmark.bubble"
case .readAloudFile, .readAloudText: "speaker.wave.2"
case .copyReference, .copyFileName, .copyTerminalSelection: "doc.on.doc"
case .pasteIntoTerminal: "doc.on.clipboard"
case .newFile: "doc.badge.plus"
+5
View File
@@ -129,6 +129,11 @@ public enum Command: Equatable, Sendable {
/// The clean-copy popup's Copy and ⌘↩: copies its text and closes it.
case copyCleanCopy
// MARK: Read aloud
/// The title bar's Stop button.
case stopReading
// MARK: Project and window
/// ⌘O
+9 -1
View File
@@ -132,13 +132,14 @@ private struct PaneToggles: View {
}
/// Search ⌘F · Fluid ⌘L · Hidden ⌘. · Note ⌘N, then `?`. Search and Note are actions; Fluid and Hidden toggle.
/// While Helder reads aloud, a Stop toggle leads the group; switching it off stops the reading.
private struct TitleToolbar: View {
let model: WorkspaceModel
var body: some View {
let layout = model.layout
HStack(spacing: Metrics.toolbarIconGap) {
ButtonGroup([
ButtonGroup(stop + [
GroupItem("Search", keys: "⌘F", kind: .action,
tip: Text("Search the open file, the project and the file names.")) { model.perform(.showSearch(seed: "")) },
GroupItem("Fluid", keys: "⌘L", kind: .toggle(isOn: layout.fluid),
@@ -161,4 +162,11 @@ private struct TitleToolbar: View {
}
.fixedSize()
}
private var stop: [GroupItem] {
guard model.readAloud.isReading else { return [] }
return [GroupItem("Stop", kind: .toggle(isOn: true), tip: Tooltip.stated("Read aloud: ", "playing", ". Click to stop.")) {
model.perform(.stopReading)
}]
}
}
@@ -0,0 +1,32 @@
import Foundation
import HelderCore
import HelderServices
import Observation
/// Read aloud: whether Helder is reading, for the title bar's Stop button.
@Observable
@MainActor
public final class ReadAloudStore {
public private(set) var isReading = false
@ObservationIgnored private let speech: SpeechServicing
public init(speech: SpeechServicing) {
self.speech = speech
speech.onFinish = { [weak self] in self?.isReading = false }
}
/// Starts reading, replacing what is being read; false for blank text, which reads nothing.
@discardableResult
public func read(_ text: String) -> Bool {
guard !text.allSatisfy(\.isWhitespace) else { return false }
speech.speak(MarkdownSpeech.spoken(text))
isReading = true
return true
}
public func stop() {
speech.stop()
isReading = false
}
}
@@ -95,6 +95,14 @@ extension WorkspaceModel {
overlay.present(.passOn(PassOnRequest(reference: name, anchor: anchor)))
case let .bouwen(name):
passToAgent("/bouwen \(name)", toast: "/bouwen \(name)")
case let .waitWhat(kind):
if let text = terminal.selection(kind)?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty {
passToAgent("/wait-what `\(text)`", toast: "/wait-what")
}
case let .readAloudText(text):
readAloud.read(text)
case let .readAloudFile(path):
readAloudFile(path)
case let .newFile(directory):
overlay.present(.namePrompt(NamePromptRequest(purpose: .newFile(inDirectory: directory), anchor: anchor)))
case let .newFolder(directory):
@@ -129,6 +137,19 @@ extension WorkspaceModel {
}
}
/// The open file is read from its buffer, unsaved edits included; any other file from disk.
private func readAloudFile(_ path: String) {
let live = editor.flatMap { $0.activePath == path && $0.isLoaded(path) ? $0.text(for: path) : nil }
let files = services?.files
track {
var text = live
if text == nil, case let .text(disk)? = try? await files?.readText(path) { text = disk }
guard !Task.isCancelled else { return }
let prose = MarkdownSpeech.plainText(MarkdownParser.parse(text ?? ""))
if !self.readAloud.read(prose) { self.toasts.show("Nothing to read", detail: path) }
}
}
func submitName(_ name: String) {
guard case let .namePrompt(request) = overlay.current else { return }
overlay.dismiss()
@@ -115,7 +115,7 @@ extension WorkspaceModel {
}
/// Stops the watchers and polling, waits for the work still running against this project,
/// then saves the note and the session and ends the terminals.
/// then stops reading aloud, saves the note and the session and ends the terminals.
func closeProject() async {
watcher?.stop()
watcher = nil
@@ -132,6 +132,7 @@ extension WorkspaceModel {
await refresh?.value
await symbols?.value
for task in running { await task.value }
readAloud.stop()
await editor?.flushAutoSaves()
await note?.save()
await editor?.persist()
@@ -79,6 +79,7 @@ public final class WorkspaceModel {
public let layout: LayoutStore
public let overlay: OverlayStore
public let toasts: ToastStore
public let readAloud: ReadAloudStore
public internal(set) var sourceControl: SourceControlStore?
public internal(set) var explorer: ExplorerStore?
public internal(set) var editor: EditorStore?
@@ -114,6 +115,7 @@ public final class WorkspaceModel {
layout = LayoutStore(session: app.session, persistence: app.layouts)
overlay = OverlayStore()
toasts = ToastStore()
readAloud = ReadAloudStore(speech: app.speech)
terminal = TerminalStore()
wireTerminal()
overlay.onChange = { [weak self] old, new in self?.overlayChanged(from: old, to: new) }
@@ -189,6 +191,8 @@ public final class WorkspaceModel {
case .passNote: passNote()
case .copyCleanCopy: copyCleanCopy()
case .stopReading: readAloud.stop()
case .openFolder:
switchProject {
guard let url = await self.app.system.chooseFolder() else { return }
@@ -46,17 +46,19 @@ public struct AppServices {
public var layouts: LayoutPersisting
/// Dialogs, pasteboard, Finder.
public var system: SystemActing
public var speech: SpeechServicing
/// Builds the services for a project folder.
public var makeWorkspace: (URL) -> WorkspaceServices
public var makeWatcher: () -> FileWatching
/// Every store is passed in, so a test can never reach the user's real recents, sessions or layouts.
public init(recentProjects: RecentProjectsStoring, session: SessionStoring, layouts: LayoutPersisting, system: SystemActing,
makeWorkspace: @escaping (URL) -> WorkspaceServices, makeWatcher: @escaping () -> FileWatching) {
speech: SpeechServicing, makeWorkspace: @escaping (URL) -> WorkspaceServices, makeWatcher: @escaping () -> FileWatching) {
self.recentProjects = recentProjects
self.session = session
self.layouts = layouts
self.system = system
self.speech = speech
self.makeWorkspace = makeWorkspace
self.makeWatcher = makeWatcher
}
@@ -66,6 +68,7 @@ public struct AppServices {
session: SessionStore(),
layouts: UserDefaultsLayoutStore(),
system: LiveSystemActions(),
speech: SpeechService(),
makeWorkspace: WorkspaceServices.live(root:),
makeWatcher: { FSEventsWatcher() }
)