This commit is contained in:
2026-11-10 10:50:04 +08:00
commit 582dddabaa
25 changed files with 175352 additions and 0 deletions
+29
View File
@@ -0,0 +1,29 @@
#!/bin/bash
# Builds build/AutoZhuyin.app (release, ad-hoc signed).
set -euo pipefail
cd "$(dirname "$0")/.."
# Use the full Xcode toolchain (the Command Line Tools SDK may be incomplete).
export DEVELOPER_DIR="${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer}"
CONFIG="${CONFIG:-release}"
APP="build/AutoZhuyin.app"
# Universal binary: runs on both Apple Silicon and Intel Macs.
ARCH_FLAGS=(--arch arm64 --arch x86_64)
xcrun swift build -c "$CONFIG" "${ARCH_FLAGS[@]}" --product AutoZhuyin
BIN="$(xcrun swift build -c "$CONFIG" "${ARCH_FLAGS[@]}" --show-bin-path)/AutoZhuyin"
rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cp "$BIN" "$APP/Contents/MacOS/AutoZhuyin"
cp Resources/Info.plist "$APP/Contents/Info.plist"
cp Resources/lexicon.txt Resources/english-common.txt "$APP/Contents/Resources/"
if [ ! -f build/icon.tiff ]; then
xcrun swift scripts/make-icon.swift build/icon.tiff
fi
cp build/icon.tiff "$APP/Contents/Resources/icon.tiff"
codesign --force --sign - "$APP"
echo "Built $APP"
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Builds Resources/lexicon.txt from McBopomofo's raw data files (MIT License).
Only reads data files; it does not run any McBopomofo code. Inputs (from
McBopomofo's Source/Data): BPMFBase.txt, BPMFMappings.txt, phrase.occ,
heterophony{1,2,3}.list.
Score = log10(count / total), with multi-reading characters split by how
common each reading is (heterophony1 = main reading, 2 and 3 = secondary).
Usage: convert-mcbopomofo.py <McBopomofo/Source/Data> <seed lexicon> <output>
"""
import math
import sys
from collections import defaultdict
from pathlib import Path
data, seed, out = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])
def rows(name):
with open(data / name, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line and not line.startswith("#"):
yield line.split()
counts = defaultdict(int)
for cols in rows("phrase.occ"):
if len(cols) == 2 and cols[1].isdigit():
counts[cols[0]] += int(cols[1])
total = sum(counts.values())
# Rank of each (char, reading): 1 = main reading.
rank = {}
for r in (3, 2, 1):
for cols in rows(f"heterophony{r}.list"):
if len(cols) >= 2:
rank[(cols[0], cols[1])] = r
has_main = {ch for (ch, _), r in rank.items() if r == 1}
RANK_WEIGHT = {1: 1.0, 2: 0.25, 3: 0.08}
entries = {} # (reading, phrase) -> score
def add(reading, phrase, count):
score = round(math.log10((count + 0.3) / total), 4)
key = (reading, phrase)
if key not in entries or entries[key] < score:
entries[key] = score
# Single characters.
char_readings = defaultdict(list)
for cols in rows("BPMFBase.txt"):
if len(cols) >= 2:
char_readings[cols[0]].append(cols[1])
for ch, readings in char_readings.items():
readings = list(dict.fromkeys(readings))
c = counts.get(ch, 0)
for rd in readings:
if len(readings) == 1:
w = 1.0
elif (ch, rd) in rank:
w = RANK_WEIGHT[rank[(ch, rd)]]
elif ch in has_main:
w = 0.02
else:
w = 1.0 / len(readings)
add(rd, ch, c * w)
# Multi-character phrases.
for cols in rows("BPMFMappings.txt"):
if len(cols) >= 3 and len(cols[0]) == len(cols) - 1:
add("-".join(cols[1:]), cols[0], counts.get(cols[0], 0))
with open(out, "w", encoding="utf-8") as f:
f.write("# Generated by scripts/convert-mcbopomofo.py from McBopomofo data (MIT License,\n")
f.write("# https://github.com/openvanilla/McBopomofo). Format: <reading> <phrase> <log10 score>\n")
for (reading, phrase), score in sorted(entries.items()):
f.write(f"{reading} {phrase} {score}\n")
# Starter entries come last: the loader keeps the first copy of a duplicate.
f.write("\n")
f.write(seed.read_text(encoding="utf-8"))
print(f"{len(entries)} entries from McBopomofo, total occurrences {total}")
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
# Rebuilds Resources/lexicon.txt from the open-source McBopomofo data (MIT License,
# https://github.com/openvanilla/McBopomofo). Only McBopomofo's data files are
# downloaded and read; none of its code is run. Resources/lexicon-seed.txt (the
# hand-written starter lexicon) is appended so its entries stay available.
set -euo pipefail
cd "$(dirname "$0")/.."
SRC=build/mcbopomofo-src
if [ -d "$SRC/.git" ]; then
git -C "$SRC" pull -q --depth 1
else
rm -rf "$SRC"
git clone -q --depth 1 --filter=blob:none --sparse https://github.com/openvanilla/McBopomofo.git "$SRC"
git -C "$SRC" sparse-checkout set Source/Data
fi
python3 -I scripts/convert-mcbopomofo.py "$SRC/Source/Data" Resources/lexicon-seed.txt Resources/lexicon.txt
echo "Rebuild with scripts/install.sh"
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
# Builds and installs AutoZhuyin into ~/Library/Input Methods, restarting any running copy.
set -euo pipefail
cd "$(dirname "$0")/.."
./scripts/build.sh
DEST="$HOME/Library/Input Methods"
mkdir -p "$DEST"
# The running server keeps the old binary; kill it so macOS relaunches the new one.
pkill -x AutoZhuyin || true
rm -rf "$DEST/AutoZhuyin.app"
cp -R build/AutoZhuyin.app "$DEST/"
"$DEST/AutoZhuyin.app/Contents/MacOS/AutoZhuyin" --register
echo
echo "Installed to $DEST/AutoZhuyin.app"
echo "First install: System Settings → Keyboard → Text Input → Edit… → + → 繁體中文 → 自動注音"
echo "(If it does not appear, log out and back in once.)"
+22
View File
@@ -0,0 +1,22 @@
// Renders the menu-bar icon ("注" with a small "A") to a TIFF.
// Usage: swift scripts/make-icon.swift <output.tiff>
import AppKit
let out = CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "icon.tiff"
let reps: [NSBitmapImageRep] = [16, 32].map { size in
let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: size, pixelsHigh: size,
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
rep.size = NSSize(width: 16, height: 16)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
let font = NSFont.systemFont(ofSize: 13, weight: .semibold)
let text = NSAttributedString(string: "注", attributes: [.font: font, .foregroundColor: NSColor.black])
let s = text.size()
text.draw(at: NSPoint(x: (16 - s.width) / 2, y: (16 - s.height) / 2))
NSGraphicsContext.restoreGraphicsState()
return rep
}
let data = NSBitmapImageRep.tiffRepresentationOfImageReps(in: reps, using: .none, factor: 0)!
try! data.write(to: URL(fileURLWithPath: out))
print("wrote \(out)")
+41
View File
@@ -0,0 +1,41 @@
#!/bin/bash
# Builds build/AutoZhuyin-<version>.pkg: a universal (Apple Silicon + Intel) installer
# that puts AutoZhuyin.app into /Library/Input Methods for all users.
set -euo pipefail
cd "$(dirname "$0")/.."
./scripts/build.sh
VERSION="$(plutil -extract CFBundleShortVersionString raw Resources/Info.plist)"
ID="com.autozhuyin.inputmethod.pkg"
STAGE="build/pkgroot"
WORK="build/pkgwork"
OUT="build/AutoZhuyin-$VERSION.pkg"
rm -rf "$STAGE" "$WORK"
mkdir -p "$STAGE" "$WORK"
cp -R build/AutoZhuyin.app "$STAGE/"
chmod +x scripts/pkg/postinstall
# Always install to /Library/Input Methods, even if another copy exists elsewhere.
pkgbuild --analyze --root "$STAGE" "$WORK/component.plist" > "$WORK/analyze.log"
plutil -replace 0.BundleIsRelocatable -bool NO "$WORK/component.plist"
pkgbuild --root "$STAGE" \
--component-plist "$WORK/component.plist" \
--install-location "/Library/Input Methods" \
--scripts scripts/pkg \
--identifier "$ID" \
--version "$VERSION" \
"$WORK/AutoZhuyin-component.pkg"
# Distribution wrapper: productbuild declares both architectures (hostArchitectures), so
# Apple Silicon Macs don't ask for Rosetta. Add an installer title.
productbuild --synthesize --package "$WORK/AutoZhuyin-component.pkg" "$WORK/distribution.xml"
grep -q 'hostArchitectures="x86_64,arm64"' "$WORK/distribution.xml" \
|| sed -i '' 's#<options #<options hostArchitectures="x86_64,arm64" #' "$WORK/distribution.xml"
sed -i '' 's#<options #<title>自動注音 AutoZhuyin</title>\
<options #' "$WORK/distribution.xml"
productbuild --distribution "$WORK/distribution.xml" --package-path "$WORK" "$OUT"
echo "Built $OUT"
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
# Runs as root after the installer copies AutoZhuyin.app into /Library/Input Methods.
APP="/Library/Input Methods/AutoZhuyin.app"
# Stop a running (old) copy so macOS launches the new one on next use.
pkill -x AutoZhuyin || true
USER_NAME="$(stat -f%Su /dev/console)"
if [ -n "$USER_NAME" ] && [ "$USER_NAME" != "root" ]; then
USER_ID="$(id -u "$USER_NAME")"
USER_HOME="$(dscl . -read "/Users/$USER_NAME" NFSHomeDirectory | awk '{print $2}')"
# A per-user copy (from scripts/install.sh) would show up as a duplicate entry.
rm -rf "$USER_HOME/Library/Input Methods/AutoZhuyin.app"
# Register in the user's session so it appears in System Settings without logging out.
launchctl asuser "$USER_ID" sudo -u "$USER_NAME" "$APP/Contents/MacOS/AutoZhuyin" --register || true
fi
exit 0