Compare commits

..
10 Commits
Author SHA1 Message Date
ays953 e98103b1f8 Release v0.14.1 2026-11-17 10:49:48 +08:00
ays953andClaude Opus 5.5 ec3ee4ba11 Hold words typed with digit keys; one Tab undoes a wrong learned preference
"0 5j; " (安裝) committed "0 " at once: "0" had been learned as literal, and
the space hold only considered words made of letters. Any Dachen keys now count
(0 = ㄢ, 5j; = ㄓㄨㄤ). A Tab correction against a learned preference replaces it
instead of stepping by one, and only the keys present at the Tab are learned, not
everything typed after them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:49:28 +08:00
ays953 ebcf554a6f Release v0.14.0 2026-11-17 08:39:43 +08:00
ays953andClaude Opus 5.5 fbdf64f64e Back to a single macOS input source; show 中/A by the cursor instead
The two input modes (中英自動 / 英文) made English mode a separate input source,
and switching between them still brought up System Settings. Info.plist has one
input source again, the Shift tap no longer calls Text Input Sources, and English
mode is shown by a short 中 / A badge under the cursor. The input menu gets an
英文模式 item. Windows and Linux keep their icon switch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:39:24 +08:00
ays953 cfd095b3b0 Release v0.13.2 2026-11-13 17:08:09 +08:00
ays953andClaude Opus 5.5 f323a29552 Don't open Keyboard settings on every Shift tap
InputModes.select called TISEnableInputSource before every switch, and macOS
opens System Settings > Keyboard whenever a source is enabled, even one that is
already enabled. Enable only when the mode is not enabled yet (also in
--register).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 17:07:49 +08:00
ays953 aa00b793ce Release v0.13.1 2026-11-13 17:03:26 +08:00
ays953andClaude Opus 5.5 b3b7589379 Name the input modes in System Settings
The modes showed their raw IDs (com.autozhuyin.inputmethod.AutoZhuyin.Auto).
InfoPlist.strings (zh-Hant, en, Base) now name them 自動注音(中英自動) and
自動注音(英文); build.sh copies the .lproj folders into the app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 17:03:07 +08:00
ays953 c440cd7177 Release v0.13.0 2026-11-13 16:56:27 +08:00
ays953andClaude Opus 5.5 6443f771a0 Show English mode in the input method icon
macOS: the input method now has two input modes in Info.plist, 中英自動 ("注")
and 英文 ("A"), each with its own menu-bar icon. A Shift tap with nothing typed
switches the mode (TISSelectInputSource), and choosing a mode in the menu bar
switches the engine (setValue:forTag:). --register enables both modes.
Windows: the taskbar IME icon switches between icon.ico and icon-en.ico.
Linux: the IBus mode property also switches its icon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 16:56:08 +08:00
26 changed files with 223 additions and 21 deletions
+4 -2
View File
@@ -12,7 +12,7 @@
- **中英自動判斷**:每按一個鍵就重新判斷,組字區即時顯示結果(Mac 版英文以藍字顯示) - **中英自動判斷**:每按一個鍵就重新判斷,組字區即時顯示結果(Mac 版英文以藍字顯示)
- **中英混打不用空白**:`ji3hello` → 我hello、`hellosu3cl3` → hello你好,同一段內會自動切分 - **中英混打不用空白**:`ji3hello` → 我hello、`hellosu3cl3` → hello你好,同一段內會自動切分
- **判斷錯了按 Tab**:在中/英之間翻轉,輸入法會記住這組按鍵,下次自動判斷對 - **判斷錯了按 Tab**:在中/英之間翻轉,輸入法會記住這組按鍵,下次自動判斷對
- **單按 Shift 切換英文模式**:英文模式下按鍵直接送出、保持小寫、不顯示底線,再單按一次 Shift 回到中英自動判斷 - **單按 Shift 切換英文模式**:英文模式下按鍵直接送出、保持小寫、不顯示底線,再單按一次 Shift 回到中英自動判斷;切換時游標旁會短暫顯示「A」或「中」(Windows、Linux 的輸入法圖示也會變成「A」)
- **注音順序打錯也能修正**:`ㄧㄒㄠˇ`、`ㄒㄠㄧˇ` 都會變成 `ㄒㄧㄠˇ`(小) - **注音順序打錯也能修正**:`ㄧㄒㄠˇ`、`ㄒㄠㄧˇ` 都會變成 `ㄒㄧㄠˇ`(小)
- **可省略聲調**:`jiap7`(ㄨㄛ ㄇㄣ˙)一樣能打出「我們」 - **可省略聲調**:`jiap7`(ㄨㄛ ㄇㄣ˙)一樣能打出「我們」
- **候選字**:用 ← → 把游標移到要改的字後面,按 ↓ 選字;選過的會固定下來 - **候選字**:用 ← → 把游標移到要改的字後面,按 ↓ 選字;選過的會固定下來
@@ -34,6 +34,8 @@
2. 系統設定 → 鍵盤 → 文字輸入 → 編輯… → + → 繁體中文 → **自動注音**。 2. 系統設定 → 鍵盤 → 文字輸入 → 編輯… → + → 繁體中文 → **自動注音**。
3. 清單裡沒出現的話,登出再登入一次。 3. 清單裡沒出現的話,登出再登入一次。
從 0.13.x 更新:0.13 把輸入法拆成「中英自動」和「英文」兩個項目,0.14 起改回單一個「自動注音」。更新後如果輸入法清單裡沒有「自動注音」,到「系統設定 → 鍵盤 → 輸入方式」重新加入即可。
PKG 會裝到 `/Library/Input Methods/`,系統上所有使用者都能用。 PKG 會裝到 `/Library/Input Methods/`,系統上所有使用者都能用。
### Windows ### Windows
@@ -67,7 +69,7 @@ SmartScreen 出現警告時,按「其他資訊 → 仍要執行」。解除安
| ← → | 在組字區移動游標(最左停在第一個中文字後面)。游標在中間時:直接打注音會**插入**新字,Backspace 刪掉游標前的字,↓ 選游標前的字 | | ← → | 在組字區移動游標(最左停在第一個中文字後面)。游標在中間時:直接打注音會**插入**新字,Backspace 刪掉游標前的字,↓ 選游標前的字 |
| ↓ | 開啟游標前那個字或詞的候選字(游標預設在最後),數字鍵 1–9 選字,Esc 關閉 | | ↓ | 開啟游標前那個字或詞的候選字(游標預設在最後),數字鍵 1–9 選字,Esc 關閉 |
| Esc | 取消組字 | | Esc | 取消組字 |
| **單按 Shift** | 沒在打字時:切換**英文模式**,按鍵直接送出、保持小寫、沒有底線,一直維持到再單按一次 Shift 才回到中英自動判斷。打到一半時:同 Tab,整段翻轉 | | **單按 Shift** | 沒在打字時:切換**英文模式**,按鍵直接送出、保持小寫、沒有底線,一直維持到再單按一次 Shift 才回到中英自動判斷,Mac 會在游標旁短暫顯示「A」/「中」,Windows 的工作列和 Linux 的 IBus 狀態圖示會變成「A」;Mac 也可以從輸入法選單的「英文模式」切換。打到一半時:同 Tab,整段翻轉 |
| Shift + 字母 | 打大寫字母(也會強制英文) | | Shift + 字母 | 打大寫字母(也會強制英文) |
| `< > ? ! : ( ) [ ]` | 中文語境下自動轉成全形 `,。?!:()「」` | | `< > ? ! : ( ) [ ]` | 中文語境下自動轉成全形 `,。?!:()「」` |
| `, . / ; -` | 英文單字後是標點;在注音中是 ㄝ ㄡ ㄥ ㄤ ㄦ(例如 `2;3` = 檔) | | `, . / ; -` | 英文單字後是標點;在注音中是 ㄝ ㄡ ㄥ ㄤ ㄦ(例如 `2;3` = 檔) |
+4
View File
@@ -0,0 +1,4 @@
/* Names shown in System Settings and the input menu. */
CFBundleName = "自動注音";
CFBundleDisplayName = "自動注音";
"com.autozhuyin.inputmethod.AutoZhuyin" = "自動注音";
+2 -2
View File
@@ -15,9 +15,9 @@
<key>CFBundlePackageType</key> <key>CFBundlePackageType</key>
<string>APPL</string> <string>APPL</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
<string>0.12.0</string> <string>0.14.1</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>20</string> <string>25</string>
<key>InputMethodConnectionName</key> <key>InputMethodConnectionName</key>
<string>com.autozhuyin.inputmethod.AutoZhuyin_Connection</string> <string>com.autozhuyin.inputmethod.AutoZhuyin_Connection</string>
<key>InputMethodServerControllerClass</key> <key>InputMethodServerControllerClass</key>
+4
View File
@@ -0,0 +1,4 @@
/* Names shown in System Settings and the input menu. */
CFBundleName = "AutoZhuyin";
CFBundleDisplayName = "AutoZhuyin";
"com.autozhuyin.inputmethod.AutoZhuyin" = "AutoZhuyin";
@@ -0,0 +1,4 @@
/* Names shown in System Settings and the input menu. */
CFBundleName = "自動注音";
CFBundleDisplayName = "自動注音";
"com.autozhuyin.inputmethod.AutoZhuyin" = "自動注音";
+12
View File
@@ -1,3 +1,4 @@
import Carbon
import Cocoa import Cocoa
import InputMethodKit import InputMethodKit
import AutoZhuyinCore import AutoZhuyinCore
@@ -74,8 +75,11 @@ final class InputController: IMKInputController {
otherModifiers: !flags.intersection([.command, .control, .option, .function]).isEmpty, otherModifiers: !flags.intersection([.command, .control, .option, .function]).isEmpty,
time: event.timestamp) time: event.timestamp)
if tapped { if tapped {
let idle = engine.keys.isEmpty
_ = engine.handle(.shiftTap) _ = engine.handle(.shiftTap)
updateComposition(client) updateComposition(client)
// English mode on/off: show 中 / A by the cursor.
if idle { ModeIndicator.show(english: engine.isEnglishMode, client: client) }
} }
return false return false
} }
@@ -186,6 +190,9 @@ final class InputController: IMKInputController {
override func menu() -> NSMenu! { override func menu() -> NSMenu! {
let menu = NSMenu() let menu = NSMenu()
let english = menu.addItem(withTitle: "英文模式(單按 Shift)", action: #selector(toggleEnglish(_:)), keyEquivalent: "")
english.state = engine.isEnglishMode ? .on : .off
menu.addItem(.separator())
let modes: [(Reranker.Mode, String, Selector)] = [ let modes: [(Reranker.Mode, String, Selector)] = [
(.off, "AI 選字:關閉", #selector(aiOff(_:))), (.off, "AI 選字:關閉", #selector(aiOff(_:))),
(.saver, "AI 選字:省電", #selector(aiSaver(_:))), (.saver, "AI 選字:省電", #selector(aiSaver(_:))),
@@ -205,6 +212,11 @@ final class InputController: IMKInputController {
return menu return menu
} }
@objc private func toggleEnglish(_ sender: Any?) {
if let client = client() { commitComposition(client) }
engine.setEnglishMode(!engine.isEnglishMode)
}
@objc private func aiOff(_ sender: Any?) { AI.setMode(.off) } @objc private func aiOff(_ sender: Any?) { AI.setMode(.off) }
@objc private func aiSaver(_ sender: Any?) { AI.setMode(.saver) } @objc private func aiSaver(_ sender: Any?) { AI.setMode(.saver) }
@objc private func aiStandard(_ sender: Any?) { AI.setMode(.standard) } @objc private func aiStandard(_ sender: Any?) { AI.setMode(.standard) }
+67
View File
@@ -0,0 +1,67 @@
import Cocoa
import InputMethodKit
/// A small "中" / "A" badge shown under the text cursor for a moment when English mode is
/// switched on or off (the menu-bar icon of an input method can't change on its own).
enum ModeIndicator {
private static var panel: NSPanel?
private static var label: NSTextField?
private static var hideWork: DispatchWorkItem?
static func show(english: Bool, client: IMKTextInput) {
let (panel, label) = makePanel()
label.stringValue = english ? "A" : "中"
var lineRect = NSRect.zero
_ = client.attributes(forCharacterIndex: 0, lineHeightRectangle: &lineRect)
let size = panel.frame.size
var origin = NSPoint(x: lineRect.minX, y: lineRect.minY - size.height - 4)
if lineRect == .zero, let screen = NSScreen.main { // the app gave no caret position
origin = NSPoint(x: screen.visibleFrame.midX - size.width / 2, y: screen.visibleFrame.midY)
}
panel.setFrameOrigin(origin)
panel.alphaValue = 1
panel.orderFrontRegardless()
hideWork?.cancel()
let work = DispatchWorkItem {
NSAnimationContext.runAnimationGroup({ ctx in
ctx.duration = 0.25
panel.animator().alphaValue = 0
}, completionHandler: { panel.orderOut(nil) })
}
hideWork = work
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8, execute: work)
}
private static func makePanel() -> (NSPanel, NSTextField) {
if let panel, let label { return (panel, label) }
let side: CGFloat = 28
let p = NSPanel(contentRect: NSRect(x: 0, y: 0, width: side, height: side),
styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: true)
p.level = .popUpMenu
p.isOpaque = false
p.backgroundColor = .clear
p.hasShadow = true
p.ignoresMouseEvents = true
p.collectionBehavior = [.canJoinAllSpaces, .transient, .ignoresCycle]
let background = NSVisualEffectView(frame: p.contentView!.bounds)
background.material = .hudWindow
background.state = .active
background.wantsLayer = true
background.layer?.cornerRadius = 6
background.layer?.masksToBounds = true
background.autoresizingMask = [.width, .height]
let l = NSTextField(labelWithString: "")
l.font = .systemFont(ofSize: 15, weight: .semibold)
l.alignment = .center
l.frame = NSRect(x: 0, y: (side - 20) / 2, width: side, height: 20)
background.addSubview(l)
p.contentView = background
panel = p
label = l
return (p, l)
}
}
+3 -1
View File
@@ -37,7 +37,9 @@ public final class LearnedPreferences {
public func record(_ keys: String, as mode: InputMode) { public func record(_ keys: String, as mode: InputMode) {
let delta = mode == .zhuyin ? 1 : -1 let delta = mode == .zhuyin ? 1 : -1
weights[keys] = max(-3, min(3, (weights[keys] ?? 0) + delta)) let old = weights[keys] ?? 0
// A correction against what was learned replaces it, so one Tab is enough to undo it.
weights[keys] = old * delta < 0 ? delta : max(-3, min(3, old + delta))
onChange(weights) onChange(weights)
} }
+18 -3
View File
@@ -38,6 +38,9 @@ public final class CompositionEngine {
/// Set by Tab / a Shift tap while typing: overrides the classifier for the whole /// Set by Tab / a Shift tap while typing: overrides the classifier for the whole
/// buffer. It is a correction, learned on commit. /// buffer. It is a correction, learned on commit.
public private(set) var forcedMode: InputMode? public private(set) var forcedMode: InputMode?
/// How many keys there were when the user flipped: that word is what gets learned, not
/// whatever was typed after it.
private var forcedCount = 0
/// English mode, toggled by a Shift tap when nothing is being typed. Keys go straight /// English mode, toggled by a Shift tap when nothing is being typed. Keys go straight
/// to the app (no composition, no underline) until Shift is tapped again. /// to the app (no composition, no underline) until Shift is tapped again.
public private(set) var isEnglishMode = false public private(set) var isEnglishMode = false
@@ -120,9 +123,10 @@ public final class CompositionEngine {
return Features.dot(w, zhWhole) >= Features.dot(w, word) + Features.dot(w, zhRest) return Features.dot(w, zhWhole) >= Features.dot(w, word) + Features.dot(w, zhRest)
} }
/// Whether keys + space also read as a common Chinese syllable (see `held`). /// Whether keys + space also read as a common Chinese syllable (see `held`). Any Dachen
/// keys count, not only letters: "0" is ㄢ (安), "5j;" is ㄓㄨㄤ (裝).
private func isAmbiguousWord(_ keys: [Character]) -> Bool { private func isAmbiguousWord(_ keys: [Character]) -> Bool {
guard keys.allSatisfy({ $0.isASCII && $0.isLetter }) else { return false } guard keys.allSatisfy(DachenLayout.isZhuyinKey) else { return false }
let p = ZhuyinParser.parse(keys + [" "]) let p = ZhuyinParser.parse(keys + [" "])
guard p.pending == nil, !p.syllables.isEmpty, p.strayTones == 0, p.foreignKeys == 0 else { return false } guard p.pending == nil, !p.syllables.isEmpty, p.strayTones == 0, p.foreignKeys == 0 else { return false }
var best: [Double] = [] var best: [Double] = []
@@ -417,9 +421,20 @@ public final class CompositionEngine {
} }
} }
/// Turns English mode on or off directly (e.g. the input mode was switched in the menu
/// bar). Commit any composition first.
public func setEnglishMode(_ on: Bool) {
guard on != isEnglishMode else { return }
reset()
isEnglishMode = on
previousMode = on ? .literal : nil
previousCommitTime = now()
}
/// Forces the whole buffer into the other mode (a correction that is learned). /// Forces the whole buffer into the other mode (a correction that is learned).
private func flip() { private func flip() {
forcedMode = (mode == .zhuyin) ? .literal : .zhuyin forcedMode = (mode == .zhuyin) ? .literal : .zhuyin
forcedCount = keys.count
} }
private func handleCharacter(_ c: Character) -> KeyResult { private func handleCharacter(_ c: Character) -> KeyResult {
@@ -556,7 +571,7 @@ public final class CompositionEngine {
rememberPicks(segs) rememberPicks(segs)
recentText = String((rerankContext + text).suffix(20)) recentText = String((rerankContext + text).suffix(20))
if let forced = forcedMode { if let forced = forcedMode {
classifier.learned.record(String(keys), as: forced) classifier.learned.record(String(keys.prefix(forcedCount)), as: forced)
} }
previousMode = segs.last?.mode previousMode = segs.last?.mode
previousCommitTime = now() previousCommitTime = now()
@@ -133,6 +133,16 @@ final class EngineTests: XCTestCase {
return out return out
} }
/// The menu-bar input mode can switch English mode directly.
func testSetEnglishMode() {
let e = makeEngine()
e.setEnglishMode(true)
XCTAssertTrue(e.isEnglishMode)
XCTAssertEqual(e.handle(.character("a")).handled, false) // goes to the app
e.setEnglishMode(false)
XCTAssertEqual(type("su3cl3 ", into: e), "你好")
}
func testMixedSentence() { func testMixedSentence() {
let e = makeEngine() let e = makeEngine()
// 我 + "hello world " + 你好 // 我 + "hello world " + 你好
@@ -477,7 +487,7 @@ final class HeldWordTests: XCTestCase {
func type(_ s: String, into e: CompositionEngine) -> String { func type(_ s: String, into e: CompositionEngine) -> String {
var out = "" var out = ""
for c in s { for c in s {
let key: KeyInput = c == "\n" ? .enter : .character(c) let key: KeyInput = c == "\n" ? .enter : c == "\t" ? .tab : .character(c)
let r = e.handle(key) let r = e.handle(key)
if let t = r.commit { out += t } else if !r.handled { out.append(c) } if let t = r.commit { out += t } else if !r.handled { out.append(c) }
} }
@@ -501,6 +511,24 @@ final class HeldWordTests: XCTestCase {
XCTAssertEqual(e.markedText, "up") XCTAssertEqual(e.markedText, "up")
XCTAssertEqual(type(" the ", into: e), "up the ") XCTAssertEqual(type(" the ", into: e), "up the ")
} }
/// Words with digits / punctuation keys are held too: "0 " is 安, "5j; " is 裝.
func testHeldWordWithDigitKeys() {
let learned = LearnedPreferences(weights: ["0": -2]) // "0" once learned as a number
let c = Classifier(lexicon: sharedLexicon, english: sharedEnglish, learned: learned, weights: sharedWeights)
XCTAssertEqual(type("0 5j; \n", into: CompositionEngine(classifier: c)), "安裝")
XCTAssertEqual(type("0 \n", into: CompositionEngine(classifier: c)), "0 ")
}
/// One Tab undoes a wrong learned preference, and only the word flipped is learned.
func testTabOverridesLearned() {
let learned = LearnedPreferences(weights: ["0": -2])
let c = Classifier(lexicon: sharedLexicon, english: sharedEnglish, learned: learned, weights: sharedWeights)
XCTAssertEqual(type("0\t 5j; \n", into: CompositionEngine(classifier: c)), "安裝")
XCTAssertEqual(learned.weights["0"], 1)
XCTAssertNil(learned.weights["0 5j; "])
XCTAssertEqual(type("hello 0 5j; \n", into: CompositionEngine(classifier: c)), "hello 安裝")
}
} }
final class BacktickSymbolTests: XCTestCase { final class BacktickSymbolTests: XCTestCase {
+3
View File
@@ -345,6 +345,9 @@ class AutoZhuyinEngine(IBus.Engine):
english = self.engine.english_mode english = self.engine.english_mode
self.mode_prop.set_label(IBus.Text.new_from_string("英文" if english else "中英自動")) self.mode_prop.set_label(IBus.Text.new_from_string("英文" if english else "中英自動"))
self.mode_prop.set_symbol(IBus.Text.new_from_string("英" if english else "自")) self.mode_prop.set_symbol(IBus.Text.new_from_string("英" if english else "自"))
icon = os.path.join(HERE, "icon-en.png" if english else "icon.png")
if os.path.exists(icon):
self.mode_prop.set_icon(icon) # panels that show property icons
self.update_property(self.mode_prop) self.update_property(self.mode_prop)
+1 -1
View File
@@ -33,7 +33,7 @@
↓ 開啟游標前那個字或詞的候選字,按數字鍵 1–9 選字; ↓ 開啟游標前那個字或詞的候選字,按數字鍵 1–9 選字;
選過的字會被記住,下次優先出現 選過的字會被記住,下次優先出現
Esc 取消組字 Esc 取消組字
單按 Shift 切換英文模式(按鍵直接送出),再單按一次回到中英自動判斷 單按 Shift 切換英文模式(按鍵直接送出,狀態圖示變成「英」),再單按一次回到中英自動判斷
Shift+字母 打大寫字母(也會強制英文) Shift+字母 打大寫字母(也會強制英文)
` + 標點 強制全形標點,例如 `< 或 `, = , `. = 。 `/ = ? `; = ; ` + 標點 強制全形標點,例如 `< 或 `, = , `. = 。 `/ = ? `; = ;
+1 -1
View File
@@ -31,7 +31,7 @@ fi
rm -rf "$DEST" rm -rf "$DEST"
mkdir -p "$DEST" mkdir -p "$DEST"
cp -R autozhuyin autozhuyin_ibus.py version.txt tools "$DEST/" cp -R autozhuyin autozhuyin_ibus.py version.txt tools "$DEST/"
for f in icon.png THIRD_PARTY_LICENSES.txt GPL-3.0.txt; do [ -f "$f" ] && cp "$f" "$DEST/"; done for f in icon.png icon-en.png THIRD_PARTY_LICENSES.txt GPL-3.0.txt; do [ -f "$f" ] && cp "$f" "$DEST/"; done
[ -n "$VENDOR_BACKUP" ] && mv "$VENDOR_BACKUP/vendor" "$DEST/" && rmdir "$VENDOR_BACKUP" [ -n "$VENDOR_BACKUP" ] && mv "$VENDOR_BACKUP/vendor" "$DEST/" && rmdir "$VENDOR_BACKUP"
chmod +x "$DEST/autozhuyin_ibus.py" chmod +x "$DEST/autozhuyin_ibus.py"
+1
View File
@@ -58,6 +58,7 @@ class Property:
def set_label(self, t): self.label = t.text def set_label(self, t): self.label = t.text
def set_symbol(self, t): pass def set_symbol(self, t): pass
def set_state(self, s): self.state = s def set_state(self, s): self.state = s
def set_icon(self, path): self.icon = path
class Engine: class Engine:
+2
View File
@@ -18,6 +18,8 @@ rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cp "$BIN" "$APP/Contents/MacOS/AutoZhuyin" cp "$BIN" "$APP/Contents/MacOS/AutoZhuyin"
cp Resources/Info.plist "$APP/Contents/Info.plist" cp Resources/Info.plist "$APP/Contents/Info.plist"
# Localized names of the input method and its modes (System Settings, input menu).
cp -R Resources/*.lproj "$APP/Contents/Resources/"
cp Resources/lexicon.txt Resources/english-common.txt Resources/classifier-weights.json "$APP/Contents/Resources/" cp Resources/lexicon.txt Resources/english-common.txt Resources/classifier-weights.json "$APP/Contents/Resources/"
cp THIRD_PARTY_LICENSES.txt "$APP/Contents/Resources/" cp THIRD_PARTY_LICENSES.txt "$APP/Contents/Resources/"
# "AI 選字" language model (CKIP gpt2-tiny-chinese, GPL-3.0), fetched and converted once. # "AI 選字" language model (CKIP gpt2-tiny-chinese, GPL-3.0), fetched and converted once.
+4 -3
View File
@@ -1,8 +1,9 @@
// Renders the menu-bar icon ("注" with a small "A") to a TIFF. // Renders a menu-bar icon (one character, "注" by default; "A" for English mode) to a TIFF.
// Usage: swift scripts/make-icon.swift <output.tiff> // Usage: swift scripts/make-icon.swift <output.tiff> [character]
import AppKit import AppKit
let out = CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "icon.tiff" let out = CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "icon.tiff"
let glyph = CommandLine.arguments.count > 2 ? CommandLine.arguments[2] : "注"
let reps: [NSBitmapImageRep] = [16, 32].map { size in let reps: [NSBitmapImageRep] = [16, 32].map { size in
let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: size, pixelsHigh: size, let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: size, pixelsHigh: size,
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
@@ -11,7 +12,7 @@ let reps: [NSBitmapImageRep] = [16, 32].map { size in
NSGraphicsContext.saveGraphicsState() NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep) NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
let font = NSFont.systemFont(ofSize: 13, weight: .semibold) let font = NSFont.systemFont(ofSize: 13, weight: .semibold)
let text = NSAttributedString(string: "注", attributes: [.font: font, .foregroundColor: NSColor.black]) let text = NSAttributedString(string: glyph, attributes: [.font: font, .foregroundColor: NSColor.black])
let s = text.size() let s = text.size()
text.draw(at: NSPoint(x: (16 - s.width) / 2, y: (16 - s.height) / 2)) text.draw(at: NSPoint(x: (16 - s.width) / 2, y: (16 - s.height) / 2))
NSGraphicsContext.restoreGraphicsState() NSGraphicsContext.restoreGraphicsState()
+2
View File
@@ -27,6 +27,8 @@ mkdir -p "$OUT/tools"
cp windows/tools/fetch_numpy.py "$OUT/tools/" # install.sh downloads numpy if the system has none cp windows/tools/fetch_numpy.py "$OUT/tools/" # install.sh downloads numpy if the system has none
echo "$VERSION" > "$OUT/version.txt" echo "$VERSION" > "$OUT/version.txt"
sips -s format png -z 64 64 build/icon.tiff --out "$OUT/icon.png" >/dev/null sips -s format png -z 64 64 build/icon.tiff --out "$OUT/icon.png" >/dev/null
[ -f build/icon-en.tiff ] || DEVELOPER_DIR="${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer}" xcrun swift scripts/make-icon.swift build/icon-en.tiff A
sips -s format png -z 64 64 build/icon-en.tiff --out "$OUT/icon-en.png" >/dev/null
chmod +x "$OUT/install.sh" "$OUT/uninstall.sh" "$OUT/autozhuyin_ibus.py" chmod +x "$OUT/install.sh" "$OUT/uninstall.sh" "$OUT/autozhuyin_ibus.py"
# Plain ustar without macOS extended attributes, so GNU tar doesn't warn. # Plain ustar without macOS extended attributes, so GNU tar doesn't warn.
+4
View File
@@ -18,6 +18,10 @@ if [ ! -f build/icon.tiff ]; then
fi fi
sips -s format png -z 32 32 build/icon.tiff --out build/icon-32.png >/dev/null sips -s format png -z 32 32 build/icon.tiff --out build/icon-32.png >/dev/null
python3 -I windows/tools/png_to_ico.py build/icon-32.png windows/autozhuyin/icon.ico python3 -I windows/tools/png_to_ico.py build/icon-32.png windows/autozhuyin/icon.ico
# English-mode icon ("A") for the taskbar while English mode is on.
[ -f build/icon-en.tiff ] || DEVELOPER_DIR="${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer}" xcrun swift scripts/make-icon.swift build/icon-en.tiff A
sips -s format png -z 32 32 build/icon-en.tiff --out build/icon-en-32.png >/dev/null
python3 -I windows/tools/png_to_ico.py build/icon-en-32.png windows/autozhuyin/icon-en.ico
rm -rf "$OUT" "$OUT.zip" rm -rf "$OUT" "$OUT.zip"
mkdir -p "$OUT" mkdir -p "$OUT"
+19 -1
View File
@@ -40,6 +40,7 @@ _ai = None
ID_MODE_ICON, ID_AUTO_PAUSE, ID_STATUS, ID_CLEAR = 1, 2, 3, 4 ID_MODE_ICON, ID_AUTO_PAUSE, ID_STATUS, ID_CLEAR = 1, 2, 3, 4
ID_AI_MODE = {mode: 10 + i for i, mode in enumerate(MODES)} # 10..13 ID_AI_MODE = {mode: 10 + i for i, mode in enumerate(MODES)} # 10..13
_ICON = os.path.join(_HERE, "icon.ico") _ICON = os.path.join(_HERE, "icon.ico")
_ICON_EN = os.path.join(_HERE, "icon-en.ico") # shown while English mode is on
def _save_json(path, data): def _save_json(path, data):
@@ -114,7 +115,8 @@ class AutoZhuyinTextService(TextService):
self.setSelKeys("123456789") self.setSelKeys("123456789")
self.customizeUI(candFontSize=16, candPerRow=1, candUseCursor=True) self.customizeUI(candFontSize=16, candPerRow=1, candUseCursor=True)
# Taskbar IME icon (Windows 8+) and language bar button; both open the settings menu. # Taskbar IME icon (Windows 8+) and language bar button; both open the settings menu.
self.addButton("windows-mode-icon", icon=_ICON, tooltip="自動注音(右鍵:設定)", self._icon_english = self.engine.english_mode
self.addButton("windows-mode-icon", icon=self._mode_icon(), tooltip=self._mode_tooltip(),
commandId=ID_MODE_ICON) commandId=ID_MODE_ICON)
self.addButton("autozhuyin-settings", icon=_ICON, tooltip="自動注音設定", type="menu") self.addButton("autozhuyin-settings", icon=_ICON, tooltip="自動注音設定", type="menu")
@@ -124,6 +126,20 @@ class AutoZhuyinTextService(TextService):
self.removeButton("autozhuyin-settings") self.removeButton("autozhuyin-settings")
TextService.onDeactivate(self) TextService.onDeactivate(self)
# --- taskbar icon: "注" for 中英自動, "A" for English mode ---
def _mode_icon(self):
return _ICON_EN if self.engine.english_mode and os.path.exists(_ICON_EN) else _ICON
def _mode_tooltip(self):
return ("英文模式" if self.engine.english_mode else "中英自動") + "(左鍵切換,右鍵設定)"
def _update_mode_icon(self):
if getattr(self, "_icon_english", None) == self.engine.english_mode:
return
self._icon_english = self.engine.english_mode
self.changeButton("windows-mode-icon", icon=self._mode_icon(), tooltip=self._mode_tooltip())
# --- menu (AI 選字 settings) --- # --- menu (AI 選字 settings) ---
def onMenu(self, buttonId): def onMenu(self, buttonId):
@@ -145,6 +161,7 @@ class AutoZhuyinTextService(TextService):
ai = _shared_ai() ai = _shared_ai()
if commandId == ID_MODE_ICON and commandType == COMMAND_LEFT_CLICK and not self.engine.keys: if commandId == ID_MODE_ICON and commandType == COMMAND_LEFT_CLICK and not self.engine.keys:
self.engine.handle(SHIFT_TAP) # left click: English mode on / off self.engine.handle(SHIFT_TAP) # left click: English mode on / off
self._update_mode_icon()
self.showMessage("英文" if self.engine.english_mode else "中英自動", 1) self.showMessage("英文" if self.engine.english_mode else "中英自動", 1)
return return
for mode, cid in ID_AI_MODE.items(): for mode, cid in ID_AI_MODE.items():
@@ -219,6 +236,7 @@ class AutoZhuyinTextService(TextService):
return False return False
self.engine.handle(SHIFT_TAP) self.engine.handle(SHIFT_TAP)
self._update(None) self._update(None)
self._update_mode_icon()
if not self.engine.keys: if not self.engine.keys:
self.showMessage("英文" if self.engine.english_mode else "中英自動", 1) self.showMessage("英文" if self.engine.english_mode else "中英自動", 1)
return True return True
+3 -1
View File
@@ -19,7 +19,9 @@ class LearnedPreferences:
def record(self, keys, mode): def record(self, keys, mode):
delta = 1 if mode == ZHUYIN else -1 delta = 1 if mode == ZHUYIN else -1
self.weights[keys] = max(-3, min(3, self.weights.get(keys, 0) + delta)) old = self.weights.get(keys, 0)
# A correction against what was learned replaces it, so one Tab is enough to undo it.
self.weights[keys] = delta if old * delta < 0 else max(-3, min(3, old + delta))
self._on_change(self.weights) self._on_change(self.weights)
def clear(self): def clear(self):
+6 -3
View File
@@ -50,6 +50,7 @@ class CompositionEngine:
self.now = now self.now = now
self.keys = [] self.keys = []
self.forced_mode = None self.forced_mode = None
self.forced_count = 0
# English mode, toggled by a Shift tap when nothing is being typed: keys go straight # English mode, toggled by a Shift tap when nothing is being typed: keys go straight
# to the app (no composition, no underline) until Shift is tapped again. # to the app (no composition, no underline) until Shift is tapped again.
self.english_mode = False self.english_mode = False
@@ -117,8 +118,9 @@ class CompositionEngine:
return dot(w, zh_whole) >= dot(w, word) + dot(w, zh_rest) return dot(w, zh_whole) >= dot(w, word) + dot(w, zh_rest)
def _is_ambiguous_word(self, keys): def _is_ambiguous_word(self, keys):
"""Whether keys + space also read as a common Chinese syllable (see HOLD_MIN_SCORE).""" """Whether keys + space also read as a common Chinese syllable (see HOLD_MIN_SCORE).
if not all(k.isascii() and k.isalpha() for k in keys): Any Dachen keys count, not only letters: "0" is ㄢ (安), "5j;" is ㄓㄨㄤ (裝)."""
if not all(bopomofo.is_zhuyin_key(k) for k in keys):
return False return False
p = bopomofo.parse(list(keys) + [" "]) p = bopomofo.parse(list(keys) + [" "])
if p.pending is not None or not p.syllables or p.stray_tones or p.foreign_keys: if p.pending is not None or not p.syllables or p.stray_tones or p.foreign_keys:
@@ -365,6 +367,7 @@ class CompositionEngine:
def _flip(self): def _flip(self):
"""Forces the whole buffer into the other mode (a correction that is learned).""" """Forces the whole buffer into the other mode (a correction that is learned)."""
self.forced_mode = LITERAL if self.mode == ZHUYIN else ZHUYIN self.forced_mode = LITERAL if self.mode == ZHUYIN else ZHUYIN
self.forced_count = len(self.keys) # that word is learned, not what is typed after it
def wants(self, key): def wants(self, key):
"""Whether handle(key) would consume the key, without changing state.""" """Whether handle(key) would consume the key, without changing state."""
@@ -567,7 +570,7 @@ class CompositionEngine:
self._remember_picks(segs) self._remember_picks(segs)
self._recent_text = (self._rerank_context() + text)[-20:] self._recent_text = (self._rerank_context() + text)[-20:]
if self.forced_mode: if self.forced_mode:
self.classifier.learned.record("".join(self.keys), self.forced_mode) self.classifier.learned.record("".join(self.keys[:self.forced_count]), self.forced_mode)
self._previous_mode = segs[-1][2] if segs else None self._previous_mode = segs[-1][2] if segs else None
self._previous_time = self.now() self._previous_time = self.now()
self.reset() self.reset()
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "自動注音 AutoZhuyin", "name": "自動注音 AutoZhuyin",
"version": "0.12.0", "version": "0.14.1",
"guid": "{3895C6E3-6D40-4B4B-B4EA-CEEC75382D23}", "guid": "{3895C6E3-6D40-4B4B-B4EA-CEEC75382D23}",
"locale": "zh-Hant-TW", "locale": "zh-Hant-TW",
"fallbackLocale": "zh-TW", "fallbackLocale": "zh-TW",
+1 -1
View File
@@ -31,7 +31,7 @@
↓ 開啟游標前那個字或詞的候選字,按數字鍵 1–9 選字; ↓ 開啟游標前那個字或詞的候選字,按數字鍵 1–9 選字;
選過的字會被記住,下次優先出現 選過的字會被記住,下次優先出現
Esc 取消組字 Esc 取消組字
單按 Shift 切換英文模式(按鍵直接送出、保持小寫、沒有底線), 單按 Shift 切換英文模式(按鍵直接送出、保持小寫、沒有底線,工作列圖示變成 A),
再單按一次回到中英自動判斷,會出現「英文」/「中英自動」小提示; 再單按一次回到中英自動判斷,會出現「英文」/「中英自動」小提示;
打到一半時按,同 Tab 整段翻轉 打到一半時按,同 Tab 整段翻轉
Shift+字母 打大寫字母(也會強制英文) Shift+字母 打大寫字母(也會強制英文)
+17
View File
@@ -340,6 +340,23 @@ class HeldWordTests(unittest.TestCase):
self.assertEqual(e.marked_text, "up") self.assertEqual(e.marked_text, "up")
self.assertEqual(type_keys(" the ", e), "up the ") self.assertEqual(type_keys(" the ", e), "up the ")
def _engine(self, learned):
return CompositionEngine(Classifier(LEX, ENG, learned, weights=WEIGHTS))
def test_held_word_with_digit_keys(self):
"""Words with digits / punctuation keys are held too: "0 " is 安, "5j; " is 裝."""
learned = LearnedPreferences({"0": -2}) # "0" once learned as a number
self.assertEqual(type_keys("0 5j; \n", self._engine(learned)), "安裝")
self.assertEqual(type_keys("0 \n", self._engine(learned)), "0 ")
def test_tab_overrides_learned(self):
"""One Tab undoes a wrong learned preference, and only the word flipped is learned."""
learned = LearnedPreferences({"0": -2})
self.assertEqual(type_keys("0\t 5j; \n", self._engine(learned)), "安裝")
self.assertEqual(learned.weights["0"], 1)
self.assertNotIn("0 5j; ", learned.weights)
self.assertEqual(type_keys("hello 0 5j; \n", self._engine(learned)), "hello 安裝")
class BacktickSymbolTests(unittest.TestCase): class BacktickSymbolTests(unittest.TestCase):
def test_forced_symbols(self): def test_forced_symbols(self):
+11
View File
@@ -42,6 +42,7 @@ class FakeTextService:
def showMessage(self, message, duration=3): self.reply["showMessage"] = message def showMessage(self, message, duration=3): self.reply["showMessage"] = message
def addButton(self, button_id, **kw): self.reply.setdefault("addButton", []).append(button_id) def addButton(self, button_id, **kw): self.reply.setdefault("addButton", []).append(button_id)
def removeButton(self, button_id): self.reply.setdefault("removeButton", []).append(button_id) def removeButton(self, button_id): self.reply.setdefault("removeButton", []).append(button_id)
def changeButton(self, button_id, **kw): self.reply.setdefault("changeButton", []).append((button_id, kw))
def setShowCandidates(self, show): def setShowCandidates(self, show):
self.showCandidates = show self.showCandidates = show
@@ -131,8 +132,12 @@ class WrapperTests(unittest.TestCase):
self.assertIsNone(self.svc.onMenu("other")) self.assertIsNone(self.svc.onMenu("other"))
def test_mode_icon_click_toggles_english(self): def test_mode_icon_click_toggles_english(self):
self.svc.reply = {}
self.svc.onCommand(1, 0) self.svc.onCommand(1, 0)
self.assertTrue(self.svc.engine.english_mode) self.assertTrue(self.svc.engine.english_mode)
(button, kw), = self.svc.reply["changeButton"]
self.assertEqual(button, "windows-mode-icon")
self.assertTrue(kw["icon"].endswith("icon-en.ico") or kw["icon"].endswith("icon.ico"))
self.svc.onCommand(1, 0) self.svc.onCommand(1, 0)
self.assertFalse(self.svc.engine.english_mode) self.assertFalse(self.svc.engine.english_mode)
@@ -174,6 +179,12 @@ class ShiftTapWrapperTests(unittest.TestCase):
self.svc = AutoZhuyinTextService(client=None) self.svc = AutoZhuyinTextService(client=None)
self.svc.onActivate() self.svc.onActivate()
def test_shift_tap_changes_icon(self):
tap_shift(self.svc)
self.assertEqual(self.svc.reply["changeButton"][0][0], "windows-mode-icon")
tap_shift(self.svc)
self.assertIn("changeButton", self.svc.reply)
def test_tap_forces_english_lowercase(self): def test_tap_forces_english_lowercase(self):
reply = tap_shift(self.svc) reply = tap_shift(self.svc)
self.assertEqual(reply.get("showMessage"), "英文") self.assertEqual(reply.get("showMessage"), "英文")