diff --git a/README.md b/README.md index bb757a8..61fdbe3 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ - **中英自動判斷**:每按一個鍵就重新判斷,組字區即時顯示結果(Mac 版英文以藍字顯示) - **中英混打不用空白**:`ji3hello` → 我hello、`hellosu3cl3` → hello你好,同一段內會自動切分 - **判斷錯了按 Tab**:在中/英之間翻轉,輸入法會記住這組按鍵,下次自動判斷對 -- **單按 Shift 切換英文模式**:英文模式下按鍵直接送出、保持小寫、不顯示底線,再單按一次 Shift 回到中英自動判斷 +- **單按 Shift 切換英文模式**:英文模式下按鍵直接送出、保持小寫、不顯示底線,再單按一次 Shift 回到中英自動判斷;英文模式時輸入法圖示會從「注」變成「A」 - **注音順序打錯也能修正**:`ㄧㄒㄠˇ`、`ㄒㄠㄧˇ` 都會變成 `ㄒㄧㄠˇ`(小) - **可省略聲調**:`jiap7`(ㄨㄛ ㄇㄣ˙)一樣能打出「我們」 - **候選字**:用 ← → 把游標移到要改的字後面,按 ↓ 選字;選過的會固定下來 @@ -34,6 +34,8 @@ 2. 系統設定 → 鍵盤 → 文字輸入 → 編輯… → + → 繁體中文 → **自動注音**。 3. 清單裡沒出現的話,登出再登入一次。 +從 0.12 以前的版本更新:輸入法現在分成「中英自動」和「英文」兩個模式(各有圖示),安裝時會自動加入。如果輸入法清單裡還留著舊的「自動注音」項目,把它移除即可。 + PKG 會裝到 `/Library/Input Methods/`,系統上所有使用者都能用。 ### Windows @@ -67,7 +69,7 @@ SmartScreen 出現警告時,按「其他資訊 → 仍要執行」。解除安 | ← → | 在組字區移動游標(最左停在第一個中文字後面)。游標在中間時:直接打注音會**插入**新字,Backspace 刪掉游標前的字,↓ 選游標前的字 | | ↓ | 開啟游標前那個字或詞的候選字(游標預設在最後),數字鍵 1–9 選字,Esc 關閉 | | Esc | 取消組字 | -| **單按 Shift** | 沒在打字時:切換**英文模式**,按鍵直接送出、保持小寫、沒有底線,一直維持到再單按一次 Shift 才回到中英自動判斷。打到一半時:同 Tab,整段翻轉 | +| **單按 Shift** | 沒在打字時:切換**英文模式**,按鍵直接送出、保持小寫、沒有底線,一直維持到再單按一次 Shift 才回到中英自動判斷,圖示會變成「A」(Mac 的選單列、Windows 的工作列、Linux 的 IBus 狀態)。Mac 也可以直接在選單列選「英文」模式。打到一半時:同 Tab,整段翻轉 | | Shift + 字母 | 打大寫字母(也會強制英文) | | `< > ? ! : ( ) [ ]` | 中文語境下自動轉成全形 `,。?!:()「」` | | `, . / ; -` | 英文單字後是標點;在注音中是 ㄝ ㄡ ㄥ ㄤ ㄦ(例如 `2;3` = 檔) | diff --git a/Resources/Info.plist b/Resources/Info.plist index 28237fb..ad402da 100644 --- a/Resources/Info.plist +++ b/Resources/Info.plist @@ -18,6 +18,67 @@ 0.12.0 CFBundleVersion 20 + ComponentInputModeDict + + tsInputModeListKey + + com.autozhuyin.inputmethod.AutoZhuyin.Auto + + TISInputSourceID + com.autozhuyin.inputmethod.AutoZhuyin.Auto + TISIntendedLanguage + zh-Hant + tsInputModeAlternateMenuIconFileKey + icon.tiff + tsInputModeCharacterRepertoireKey + + Hant + + tsInputModeDefaultStateKey + + tsInputModeIsVisibleKey + + tsInputModeMenuIconFileKey + icon.tiff + tsInputModePaletteIconFileKey + icon.tiff + tsInputModePrimaryInScriptKey + + tsInputModeScriptKey + smTradChinese + + com.autozhuyin.inputmethod.AutoZhuyin.English + + TISInputSourceID + com.autozhuyin.inputmethod.AutoZhuyin.English + TISIntendedLanguage + zh-Hant + tsInputModeAlternateMenuIconFileKey + icon-en.tiff + tsInputModeCharacterRepertoireKey + + Hant + + tsInputModeDefaultStateKey + + tsInputModeIsVisibleKey + + tsInputModeMenuIconFileKey + icon-en.tiff + tsInputModePaletteIconFileKey + icon-en.tiff + tsInputModePrimaryInScriptKey + + tsInputModeScriptKey + smTradChinese + + + tsVisibleInputModeOrderedArrayKey + + com.autozhuyin.inputmethod.AutoZhuyin.Auto + com.autozhuyin.inputmethod.AutoZhuyin.English + + InputMethodConnectionName com.autozhuyin.inputmethod.AutoZhuyin_Connection InputMethodServerControllerClass diff --git a/Sources/AutoZhuyin/InputController.swift b/Sources/AutoZhuyin/InputController.swift index f82d306..03eeb99 100644 --- a/Sources/AutoZhuyin/InputController.swift +++ b/Sources/AutoZhuyin/InputController.swift @@ -1,3 +1,4 @@ +import Carbon import Cocoa import InputMethodKit import AutoZhuyinCore @@ -74,8 +75,11 @@ final class InputController: IMKInputController { otherModifiers: !flags.intersection([.command, .control, .option, .function]).isEmpty, time: event.timestamp) if tapped { + let idle = engine.keys.isEmpty _ = engine.handle(.shiftTap) updateComposition(client) + // English mode on/off: switch input mode so the menu-bar icon shows it. + if idle { InputModes.select(english: engine.isEnglishMode) } } return false } @@ -152,6 +156,18 @@ final class InputController: IMKInputController { } } + /// The input mode changed (menu bar, keyboard shortcut, or our own Shift tap). + override func setValue(_ value: Any!, forTag tag: Int, client sender: Any!) { + if tag == kTextServiceInputModePropertyTag, let id = value as? String { + let english = InputModes.isEnglish(id) + if english != engine.isEnglishMode { + commitComposition(sender) + engine.setEnglishMode(english) + } + } + super.setValue(value, forTag: tag, client: sender) + } + override func commitComposition(_ sender: Any!) { guard let client = sender as? IMKTextInput else { return } commit(engine.commitAll(), to: client) diff --git a/Sources/AutoZhuyin/InputModes.swift b/Sources/AutoZhuyin/InputModes.swift new file mode 100644 index 0000000..8c049d5 --- /dev/null +++ b/Sources/AutoZhuyin/InputModes.swift @@ -0,0 +1,32 @@ +import Carbon +import Foundation + +/// The two input modes declared in Info.plist (ComponentInputModeDict). Each has its own +/// menu-bar icon, so switching modes is how the icon shows "中英自動" vs "英文". +enum InputModes { + static let auto = "com.autozhuyin.inputmethod.AutoZhuyin.Auto" + static let english = "com.autozhuyin.inputmethod.AutoZhuyin.English" + + static func isEnglish(_ modeID: String) -> Bool { modeID == english } + + private static func source(_ id: String) -> TISInputSource? { + let filter = [kTISPropertyInputSourceID as String: id] as CFDictionary + guard let list = TISCreateInputSourceList(filter, true)?.takeRetainedValue() as? [TISInputSource] else { return nil } + return list.first + } + + /// Makes the given mode current (enabling it first if needed). Returns false on failure. + @discardableResult + static func select(english: Bool) -> Bool { + guard let src = source(english ? InputModes.english : InputModes.auto) else { return false } + TISEnableInputSource(src) + return TISSelectInputSource(src) == noErr + } + + /// Called by `--register`: enable both modes so they are in the input menu. + static func enableAll() { + for id in [auto, english] { + if let src = source(id) { TISEnableInputSource(src) } + } + } +} diff --git a/Sources/AutoZhuyin/main.swift b/Sources/AutoZhuyin/main.swift index 3d16cd3..a86d481 100644 --- a/Sources/AutoZhuyin/main.swift +++ b/Sources/AutoZhuyin/main.swift @@ -6,6 +6,7 @@ import InputMethodKit // in System Settings without logging out (used by the installer's postinstall script). if CommandLine.arguments.contains("--register") { let status = TISRegisterInputSource(Bundle.main.bundleURL as CFURL) + if status == noErr { InputModes.enableAll() } // "中英自動" and "英文" (menu-bar icons) print(status == noErr ? "Registered \(Bundle.main.bundlePath)" : "TISRegisterInputSource failed: \(status)") exit(status == noErr ? 0 : 1) } diff --git a/Sources/AutoZhuyinCore/CompositionEngine.swift b/Sources/AutoZhuyinCore/CompositionEngine.swift index 41342f5..6f63647 100644 --- a/Sources/AutoZhuyinCore/CompositionEngine.swift +++ b/Sources/AutoZhuyinCore/CompositionEngine.swift @@ -417,6 +417,16 @@ 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). private func flip() { forcedMode = (mode == .zhuyin) ? .literal : .zhuyin diff --git a/Tests/AutoZhuyinCoreTests/AutoZhuyinCoreTests.swift b/Tests/AutoZhuyinCoreTests/AutoZhuyinCoreTests.swift index af0f2e8..eeb93f5 100644 --- a/Tests/AutoZhuyinCoreTests/AutoZhuyinCoreTests.swift +++ b/Tests/AutoZhuyinCoreTests/AutoZhuyinCoreTests.swift @@ -133,6 +133,16 @@ final class EngineTests: XCTestCase { 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() { let e = makeEngine() // 我 + "hello world " + 你好 diff --git a/linux/autozhuyin_ibus.py b/linux/autozhuyin_ibus.py index 0d56479..d1c3b9f 100644 --- a/linux/autozhuyin_ibus.py +++ b/linux/autozhuyin_ibus.py @@ -345,6 +345,9 @@ class AutoZhuyinEngine(IBus.Engine): english = self.engine.english_mode 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 "自")) + 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) diff --git a/linux/installer/README.txt b/linux/installer/README.txt index dec75b3..cf678b7 100644 --- a/linux/installer/README.txt +++ b/linux/installer/README.txt @@ -33,7 +33,7 @@ ↓ 開啟游標前那個字或詞的候選字,按數字鍵 1–9 選字; 選過的字會被記住,下次優先出現 Esc 取消組字 - 單按 Shift 切換英文模式(按鍵直接送出),再單按一次回到中英自動判斷 + 單按 Shift 切換英文模式(按鍵直接送出,狀態圖示變成「英」),再單按一次回到中英自動判斷 Shift+字母 打大寫字母(也會強制英文) ` + 標點 強制全形標點,例如 `< 或 `, = , `. = 。 `/ = ? `; = ; diff --git a/linux/installer/install.sh b/linux/installer/install.sh index f01107c..2e9b8a2 100755 --- a/linux/installer/install.sh +++ b/linux/installer/install.sh @@ -31,7 +31,7 @@ fi rm -rf "$DEST" mkdir -p "$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" chmod +x "$DEST/autozhuyin_ibus.py" diff --git a/linux/tests/test_ibus_engine.py b/linux/tests/test_ibus_engine.py index 8efef7b..df59787 100644 --- a/linux/tests/test_ibus_engine.py +++ b/linux/tests/test_ibus_engine.py @@ -58,6 +58,7 @@ class Property: def set_label(self, t): self.label = t.text def set_symbol(self, t): pass def set_state(self, s): self.state = s + def set_icon(self, path): self.icon = path class Engine: diff --git a/scripts/build.sh b/scripts/build.sh index d5ca251..713f3f2 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -31,6 +31,9 @@ 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" +# English-mode icon ("A"), shown in the menu bar while English mode is on. +[ -f build/icon-en.tiff ] || xcrun swift scripts/make-icon.swift build/icon-en.tiff A +cp build/icon-en.tiff "$APP/Contents/Resources/icon-en.tiff" codesign --force --sign - "$APP" echo "Built $APP" diff --git a/scripts/make-icon.swift b/scripts/make-icon.swift index d518b78..46e0756 100644 --- a/scripts/make-icon.swift +++ b/scripts/make-icon.swift @@ -1,8 +1,9 @@ -// Renders the menu-bar icon ("注" with a small "A") to a TIFF. -// Usage: swift scripts/make-icon.swift +// Renders a menu-bar icon (one character, "注" by default; "A" for English mode) to a TIFF. +// Usage: swift scripts/make-icon.swift [character] import AppKit 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 rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: size, pixelsHigh: size, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, @@ -11,7 +12,7 @@ let reps: [NSBitmapImageRep] = [16, 32].map { size in 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 text = NSAttributedString(string: glyph, 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() diff --git a/scripts/package-linux.sh b/scripts/package-linux.sh index 85e2725..164f163 100755 --- a/scripts/package-linux.sh +++ b/scripts/package-linux.sh @@ -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 echo "$VERSION" > "$OUT/version.txt" 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" # Plain ustar without macOS extended attributes, so GNU tar doesn't warn. diff --git a/scripts/package-windows.sh b/scripts/package-windows.sh index 80d3cf7..a95ec58 100755 --- a/scripts/package-windows.sh +++ b/scripts/package-windows.sh @@ -18,6 +18,10 @@ if [ ! -f build/icon.tiff ]; then fi 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 +# 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" mkdir -p "$OUT" diff --git a/windows/autozhuyin/autozhuyin_ime.py b/windows/autozhuyin/autozhuyin_ime.py index ff6a89b..44052fc 100644 --- a/windows/autozhuyin/autozhuyin_ime.py +++ b/windows/autozhuyin/autozhuyin_ime.py @@ -40,6 +40,7 @@ _ai = None 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 _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): @@ -114,7 +115,8 @@ class AutoZhuyinTextService(TextService): self.setSelKeys("123456789") self.customizeUI(candFontSize=16, candPerRow=1, candUseCursor=True) # 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) self.addButton("autozhuyin-settings", icon=_ICON, tooltip="自動注音設定", type="menu") @@ -124,6 +126,20 @@ class AutoZhuyinTextService(TextService): self.removeButton("autozhuyin-settings") 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) --- def onMenu(self, buttonId): @@ -145,6 +161,7 @@ class AutoZhuyinTextService(TextService): ai = _shared_ai() 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._update_mode_icon() self.showMessage("英文" if self.engine.english_mode else "中英自動", 1) return for mode, cid in ID_AI_MODE.items(): @@ -219,6 +236,7 @@ class AutoZhuyinTextService(TextService): return False self.engine.handle(SHIFT_TAP) self._update(None) + self._update_mode_icon() if not self.engine.keys: self.showMessage("英文" if self.engine.english_mode else "中英自動", 1) return True diff --git a/windows/autozhuyin/icon-en.ico b/windows/autozhuyin/icon-en.ico new file mode 100644 index 0000000..834c31d Binary files /dev/null and b/windows/autozhuyin/icon-en.ico differ diff --git a/windows/installer/README.txt b/windows/installer/README.txt index 552f5c3..7682600 100644 --- a/windows/installer/README.txt +++ b/windows/installer/README.txt @@ -31,7 +31,7 @@ ↓ 開啟游標前那個字或詞的候選字,按數字鍵 1–9 選字; 選過的字會被記住,下次優先出現 Esc 取消組字 - 單按 Shift 切換英文模式(按鍵直接送出、保持小寫、沒有底線), + 單按 Shift 切換英文模式(按鍵直接送出、保持小寫、沒有底線,工作列圖示變成 A), 再單按一次回到中英自動判斷,會出現「英文」/「中英自動」小提示; 打到一半時按,同 Tab 整段翻轉 Shift+字母 打大寫字母(也會強制英文) diff --git a/windows/tests/test_pime_wrapper.py b/windows/tests/test_pime_wrapper.py index d5fe67e..29d5da6 100644 --- a/windows/tests/test_pime_wrapper.py +++ b/windows/tests/test_pime_wrapper.py @@ -42,6 +42,7 @@ class FakeTextService: def showMessage(self, message, duration=3): self.reply["showMessage"] = message 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 changeButton(self, button_id, **kw): self.reply.setdefault("changeButton", []).append((button_id, kw)) def setShowCandidates(self, show): self.showCandidates = show @@ -131,8 +132,12 @@ class WrapperTests(unittest.TestCase): self.assertIsNone(self.svc.onMenu("other")) def test_mode_icon_click_toggles_english(self): + self.svc.reply = {} self.svc.onCommand(1, 0) 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.assertFalse(self.svc.engine.english_mode) @@ -174,6 +179,12 @@ class ShiftTapWrapperTests(unittest.TestCase): self.svc = AutoZhuyinTextService(client=None) 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): reply = tap_shift(self.svc) self.assertEqual(reply.get("showMessage"), "英文")