Skip to content

About

Swift package for macOS that types text like a human: natural rhythm, typos with corrections, key sounds, and live dictation streaming.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

15 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SimulatedTyping

A Swift package for macOS that types text the way a person does: uneven rhythm, slowdowns on awkward keys, optional typos with backspace corrections, and synthesized key sounds.

It was built for dictation apps: instead of pasting a transcript, type it, either all at once or live while partial transcripts arrive and get revised.

SimulatedTyping typing text, correcting typos and following revised dictation

Play with sound:

demo.mp4

Requirements

  • macOS 27, Swift 6.2 (Swift 6 language mode, strict concurrency).
  • No dependencies beyond Apple frameworks.
  • For typing into other apps: the Accessibility permission, and the host app must not be sandboxed. Typing into a text view of your own app needs neither.

Installation

Add the package with Swift Package Manager:

// Package.swift
dependencies: [
    .package(url: "https://github.com/atacan/SimulatedTyping.git", from: "0.2.0"),
],
targets: [
    .target(name: "MyApp", dependencies: [
        .product(name: "SimulatedTyping", package: "SimulatedTyping"),
    ]),
]

In Xcode: File > Add Package Dependencies…, enter https://github.com/atacan/SimulatedTyping.git, keep the default "Up to Next Major Version" rule, and add the SimulatedTyping library to the app target.

import SimulatedTyping gives you everything. The products are:

Product Use
SimulatedTyping The whole package. This is the one an app links.
SimulatedTypingCore Only the platform-free part (planner, session, protocols).
SimulatedTypingTestSupport RecordingOutput and VirtualClock for your own tests.

Quick start

import SimulatedTyping

// 1. Permission. Shows the system prompt the first time.
guard CGEventOutput.isTrusted(prompt: true) else { return }

// 2. A session that types into whichever app has keyboard focus.
let session = TypingSession.systemWide()        // call on the main actor

// 3. Type.
try await session.type("Hello, world.")

With sound and a few settings:

let sound = SynthesizedKeySoundPlayer(preset: .softLaptop, volume: 0.5)   // keep one for the app's lifetime
let session = TypingSession.systemWide(
    configuration: TypingConfiguration(speed: .fast, maxDuration: .seconds(4)),
    sound: sound
)

Integrating into a dictation app

Lifecycle: one session per utterance

A TypingSession remembers the text it has typed, and assumes the caret is still at the end of it. Create a new session for each utterance (they are cheap), or call await session.reset(). Keep the SynthesizedKeySoundPlayer and reuse it across sessions.

TypingSession.systemWide and .inApp are @MainActor factories. The session itself is an actor: call its methods from anywhere with await.

Mode 1: the whole transcript at once

func insert(_ transcript: String) async {
    let session = TypingSession.systemWide(configuration: .init(speed: .fast, maxDuration: .seconds(5)))
    do {
        try await session.type(transcript)
    } catch is CancellationError {
        // cancel() was called or the task was cancelled. Text typed so far stays.
    } catch {
        // Could not type (see "Errors"). Fall back to pasting what is missing.
        let done = await session.typedText
        paste(String(transcript.dropFirst(done.count)))
    }
}

maxDuration keeps long transcripts from taking long: typing speeds up to fit, and whatever still does not fit is inserted in one go at the end.

Mode 2: live streaming with revisions

Pass every partial transcript as the full text so far. The session works out the smallest edit: it backspaces to the longest common prefix with what it has typed and types the rest.

let session = TypingSession.systemWide()

for await partial in recognizer.partialTranscripts {    // "I scream" → "Ice cream is" → …
    await session.setTarget(partial)                    // returns at once; typing continues in the background
}
await session.setTarget(finalTranscript)
try await session.finish()                              // returns when the screen matches the target
  • setTarget never blocks. If targets arrive faster than typing, the session always heads for the latest one.
  • A revision that would need more than maxBackspaces (default 80) backspaces is not carried out. The session emits .revisionRejected, leaves the text alone, and finish() throws TypingError.backspaceLimitExceeded unless a later target is reachable again.
  • To end quickly when the user stops speaking, call try await session.flush() instead of finish(): it inserts everything that remains in one go.
  • maxDuration applies to each revision separately in this mode, not to the utterance.

Held modifier keys (push-to-talk)

With push-to-talk on right Option or right Command, the key can still be down when typing starts. The default policy .override sets the modifier flags explicitly on every event, so held keys do not turn letters into symbols or shortcuts. This was verified by hand while holding right Option and right Command.

The alternative waits until the user lets go:

TypingSession.systemWide(output: .init(modifierPolicy: .waitForRelease))

It gives up with TypingError.modifierKeysHeld after modifierReleaseTimeout (default 10 s). CGEventOutput.areModifiersHeld tells you the current state.

Real user input while typing

If the user clicks elsewhere or types during a session, synthetic keys follow the caret and streamed revisions backspace the wrong text. The package cannot detect this; the host must. In your event tap, tell real events from this package's events by the tag every synthetic event carries:

let isSynthetic = event.getIntegerValueField(.eventSourceUserData) == CGEventOutput.syntheticEventTag
if !isSynthetic {
    Task { await session.cancel() }     // or pause(), or try await flush()
}

Also ignore tagged events in your own hotkey handling, so typed text cannot trigger your shortcuts. Synthetic Shift and Option presses use the left-hand key codes (56 and 58), never the right-hand ones.

Secure input (password fields)

Password fields and terminals with secure keyboard entry drop synthetic events. The session checks before every key and throws TypingError.secureInputEnabled rather than failing silently. You can also check up front:

if CGEventOutput.isSecureInputEnabled { /* use another insertion path */ }

Microphone feedback

Key sounds from the speakers can reach a live microphone and disturb recognition. The package does not decide this for you: set sound.isMuted = true while listening, unless output goes to headphones or echo cancellation is active. isMuted and volume can be changed at any time, from any thread.

Stopping

Call Effect
pause() / resume() Stops and continues between keys, never between a key down and its key up.
cancel() Stops. Text typed so far stays. A typo on screen is removed first. type/finish throw CancellationError.
flush() Removes any pending typo, then inserts everything that remains in one go.
Cancelling the task that awaits type/finish Same as cancel().
reset() Cancels and forgets the typed text. Nothing is deleted from the screen.

Typing into your own text view

No permission, works sandboxed:

let session = TypingSession.inApp(client: textView)     // any NSTextInputClient, held weakly

Recommended settings for dictation

TypingConfiguration(
    speed: .fast,                 // 300 WPM with human rhythm
    accuracy: 1.0,                // no typos: dictation should not look unsure
    maxDuration: .seconds(5)      // all-at-once mode; omit for streaming
)

API reference

TypingSession (actor)

init(output: any TypingOutput,
     configuration: TypingConfiguration = .init(),
     geometry: any KeyGeometry = .ansiQWERTY,
     sound: (any KeySoundPlayer)? = nil,
     clock: any Clock<Duration> = ContinuousClock())

@MainActor static func systemWide(configuration:output:sound:) -> TypingSession
@MainActor static func inApp(client:configuration:sound:) -> TypingSession

func type(_ text: String) async throws      // appends to what was typed before; returns when done
func setTarget(_ text: String)              // replaces the full wanted text
func finish() async throws                  // returns when the screen matches the target
func pause(); func resume(); func cancel()
func flush() async throws
func reset() async

var typedText: String                       // what the session has put on screen
var targetText: String                      // what it is working towards
var isTyping: Bool
var isPaused: Bool
nonisolated let events: AsyncStream<TypingEvent>

TypingConfiguration

Property Default Meaning
speed .fast .fast (300 WPM), .realistic (60 WPM) or .custom(wpm:variability:).
accuracy 1.0 Chance a letter is right first time, 0...1. Below 1, typos appear and are always corrected.
maxDuration nil Time cap. Typing speeds up to fit; the rest is inserted in one go.
seed nil Same text, configuration and seed give the same plan. nil is random.
maxBackspaces 80 Largest streamed revision the session carries out.
timing TimingParameters() Constants of the timing model (pauses, per-key factors, hold times).
typos TypoParameters() Typo kinds and their weights, and how often spelling rules apply.
languages LanguageProfile.builtIn Languages the text may be in; see Languages.

Languages

Slips of the finger need no language data. Spelling mistakes do, and a LanguageProfile supplies them: a short list of commonly misspelled words, rules that misspell any word (a dropped accent, a doubled letter typed once, ß typed as ss), and the very common words that are typed a little faster.

Profiles ship for English, German, French, Spanish, Italian, Portuguese, Dutch and Turkish. Each text is matched to one of configuration.languages by its common words and distinctive letters; a streaming session looks at the whole target text. With no evidence, the first profile in the list is used.

configuration.languages = [.german]                 // fix the language
configuration.languages = [.english, .turkish]      // detect between two
configuration.languages = []                        // slips of the finger only

var french = LanguageProfile.french                 // extend a built-in profile
french.misspellings["dilemme"] = "dilemne"
french.rules.append(.replace("ph", with: "f"))

let polish = LanguageProfile(                       // or add a language
    code: "pl",
    commonWords: ["i", "w", "nie", "na", "to", "że", "się", "jest"],
    misspellings: ["wziąć": "wziąść"],
    rules: [.dropDiacritic, .replace("ł", with: "l"), .replace("rz", with: "ż")],
    distinctiveCharacters: ["ł", "ż", "ą", "ę"]
)
configuration.languages = LanguageProfile.builtIn + [polish]

LanguageProfile.detect(_:among:) returns the profile a text would get.

CGEventOutput.Configuration

Property Default Meaning
modifierPolicy .override .override or .waitForRelease.
minimumInterval 2 ms Smallest time between key presses, even under a time cap. Raise it if an app loses keys.
minimumHold 2 ms Shortest key hold.
postsModifierKeyEvents true Send real Shift/Option key events around a key, as a keyboard does.
modifierReleaseTimeout 10 s How long .waitForRelease waits.
immediateChunkSize 20 UTF-16 units per event for immediate insertion.

Static helpers: CGEventOutput.isTrusted(prompt:), .isSecureInputEnabled, .areModifiersHeld, .syntheticEventTag.

TypingEvent

events is a single-consumer stream; if nobody reads it, only the latest few thousand events are kept.

Event When
.started Typing began, or picked up again after being idle.
.typed(Character) A key went down.
.deleted A backspace went down.
.insertedImmediately(String) Text went in at once (flush or time cap).
.paused / .resumed
.revisionRejected(required:limit:) A revision needed too many backspaces.
.finished The screen matches the target. In streaming this fires each time typing catches up.
.cancelled Stopped by cancel().
.failed(any Error) The output failed.

Errors

type, finish and flush throw CancellationError or a TypingError:

TypingError Meaning What to do
.accessibilityNotTrusted No Accessibility permission. Call CGEventOutput.isTrusted(prompt: true), guide the user.
.secureInputEnabled A password field or secure keyboard entry is active. Use another insertion path, or do nothing.
.modifierKeysHeld .waitForRelease timed out. Ask the user to release the key, or use .override.
.backspaceLimitExceeded(required:limit:) A streamed revision reached too far back. Send a later target, raise maxBackspaces, or accept the text as is.
.outputUnavailable The in-app text view was deallocated.
.eventCreationFailed The system refused to create a key event.

After a failure or a cancel, the session's target becomes whatever is on screen (typedText), and the session can be used again.

SynthesizedKeySoundPlayer

init(preset: KeySoundPreset = .softLaptop, volume: Float = 0.6, voiceCount: Int = 8,
     variantsPerKind: Int = 6, idleTimeout: TimeInterval = 3, seed: UInt64? = nil)

var preset: KeySoundPreset     // .softLaptop, .mechanical, .typewriter
var volume: Float              // 0...1
var isMuted: Bool

The audio engine starts when typing starts and stops after idleTimeout seconds of silence. To supply your own sounds, conform a class to KeySoundPlayer.

Extension points

Protocol Implement it to
TypingOutput Send keystrokes somewhere else. Three requirements: minimumInterval, perform(_:hold:), insertImmediately(_:); optional prepare().
KeySoundPlayer Play your own key sounds.
KeyGeometry Describe a different physical keyboard to the planner.

The planner is usable on its own, without a session: TypingPlanner(configuration:).plan(text, using: &generator) returns a TypingPlan of timed steps and performs no I/O.

Testing your integration

SimulatedTypingTestSupport lets you test code that drives a session without real key events or real waiting:

import SimulatedTypingCore
import SimulatedTypingTestSupport

let clock = VirtualClock()                           // sleeping returns at once and advances virtual time
let output = RecordingOutput(clock: clock)           // types into memory
let session = TypingSession(output: output, configuration: .init(seed: 1), clock: clock)

await session.setTarget("I scream")
await session.setTarget("Ice cream")
try await session.finish()

#expect(output.text == "Ice cream")
#expect(output.actions.contains(.backspace))

RecordingOutput.setHook runs a closure before each key, to cancel, pause or change the target at an exact point. fail(atRecord:with:) and failPrepare(with:) simulate output errors such as secure input.

Limitations

  • Caret movement is invisible. The package assumes the caret stays at the end of what it typed. See Real user input while typing.
  • Target apps that change text. Autocorrect, smart quotes and bracket pairing break the assumption that the screen shows what was typed, so streamed revisions may delete the wrong characters. Not detected in version 1.
  • Latin layouts only. Characters with no key on the active layout (emoji, other scripts) are injected as Unicode text; they arrive correctly but do not look like real key presses to the target app.
  • Spelling mistakes cover eight languages. Other languages get slips of the finger (wrong neighbour key, swapped letters) and the rules of the first profile in languages, unless you add a LanguageProfile. The built-in word lists are short, and language detection is a word count, so it can misjudge a text of only a few words.
  • Minimum interval is lightly measured. TextEdit and one Electron app kept every key at 1 ms; other apps were not measured at that rate.
  • No pasteboard insertion. Immediate insertion uses Unicode key events. Keep your own paste path as a fallback.

Developing the package

Module Contents
SimulatedTypingCore Pure Swift: TypingPlanner, timing and typo models, StreamReconciler, TypingSession, and the protocols.
SimulatedTypingLayout KeyboardLayout: character to key strokes for the active input source, including dead keys.
SimulatedTypingOutput CGEventOutput and TextInputOutput.
SimulatedTypingSound SynthesizedKeySoundPlayer and the sound recipes.
SimulatedTyping Re-exports the above; adds TypingSession.systemWide and .inApp.
SimulatedTypingTestSupport RecordingOutput, VirtualClock.
swift test
SIMULATEDTYPING_AUDIO_TESTS=1 swift test --filter KeySoundPlayerTests   # plays a few clicks
SIMULATEDTYPING_RENDER_DIR=/tmp/keys swift test --filter KeySoundAuditionTests   # writes one WAV per preset

The last command is for tuning the sound recipes in KeySoundSynthesizer.swift: each file plays the single keys slowly, then two typed lines. Listen with afplay /tmp/keys/typewriter.wav.

Demo app and manual checklist

Key events and sound cannot be unit tested, so the demo app is a guided checklist.

swift run --package-path Demo     # uses the terminal's Accessibility permission
Demo/make-app.sh                  # or build Demo/build/SimulatedTypingDemo.app with its own permission

Pick a scenario: it loads a sample text and the right settings and says what to do and what a pass looks like. Press Run and click into the target app within three seconds. To check the result, select all and copy in the target app, then press Check clipboard.

Run the scenarios in TextEdit, Notes, a Safari text field, Terminal, VS Code and an Electron app; scenarios 3 and 4 also on a second Latin layout.

Scenario Checks
1. Basics: pangram Typing works at all
2. Paragraph at human speed Rhythm, punctuation, digits, a line break
3. Every ASCII key Shift and Option layers, non-US layouts
4. Accents and dead keys Two-stroke accents
5. Emoji and symbols without a key Unicode injection
6. Typos and corrections Mistakes appear and are fixed
7. Streaming with revisions Backspace and retype on revised partials
8. Pause, resume, flush, cancel Session control
9. Held modifiers Right Option and right Command held while typing
10. Password field Secure input is detected, nothing is typed
11. Time cap Speeds up, then inserts the rest at once
12. Sound check Sync, presets, distinct space, return and backspace
13. Rate test Smallest interval each app handles

Demo video

The video at the top is rendered by the package itself, without screen recording: real sessions type each scene on a virtual clock, and the key sounds are mixed in at the key-down times.

swift run --package-path Video            # writes Video/build/demo.mp4 (with sound) and demo.gif
cp Video/build/demo.gif Media/demo.gif

The scenes are in Video/Sources/MakeVideo/Storyboard.swift.

Releasing

From a clean, up-to-date main, with gh logged in:

scripts/release.sh 0.2.0                # runs swift test, asks before pushing
scripts/release.sh 0.2.0 --skip-tests --draft --yes

The script checks the branch and tag, runs the tests, sets the version in the installation snippet above, commits it as "Release 0.2.0", creates and pushes the tag, and publishes a GitHub release with generated notes. A version with a suffix, such as 1.0.0-beta.1, is marked as a pre-release.

License

SimulatedTyping is available under the MIT License. See LICENSE.

About

Swift package for macOS that types text like a human: natural rhythm, typos with corrections, key sounds, and live dictation streaming.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages