<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shiki Suen on Medium]]></title>
        <description><![CDATA[Stories by Shiki Suen on Medium]]></description>
        <link>https://medium.com/@shikisuen?source=rss-747d4432e418------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*91FFx9T0NyGzFN4zSqL5iA.png</url>
            <title>Stories by Shiki Suen on Medium</title>
            <link>https://medium.com/@shikisuen?source=rss-747d4432e418------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:04:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shikisuen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[吐槽一下最近 macOS 使用者群體內掀起的「紛紛各自砸大錢用 LLM 修復奇摩輸入法」的現象]]></title>
            <link>https://shikisuen.medium.com/%E5%90%90%E6%A7%BD%E4%B8%80%E4%B8%8B%E6%9C%80%E8%BF%91-macos-%E4%BD%BF%E7%94%A8%E8%80%85%E7%BE%A4%E9%AB%94%E5%85%A7%E6%8E%80%E8%B5%B7%E7%9A%84-%E7%B4%9B%E7%B4%9B%E5%90%84%E8%87%AA%E7%A0%B8%E5%A4%A7%E9%8C%A2%E7%94%A8-llm-%E4%BF%AE%E5%BE%A9%E5%A5%87%E6%91%A9%E8%BC%B8%E5%85%A5%E6%B3%95-%E7%9A%84%E7%8F%BE%E8%B1%A1-b1c2c7a2d7c7?source=rss-747d4432e418------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1c2c7a2d7c7</guid>
            <dc:creator><![CDATA[Shiki Suen]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 18:19:17 GMT</pubDate>
            <atom:updated>2026-09-20T18:22:07.975Z</atom:updated>
            <content:encoded><![CDATA[<p>這篇是酒後亂言，寫在唯音輸入法 v4.8.3（大幅強化中英文混打功能的一版）發版當夜。</p><p>這早已經不是唯音與小麥的使用者群體吸引競爭了，而是唯音與奇摩輸入法的公開對決。但唯音可能還是打不嬴，哪怕唯音輸入法的偏好設定選項數量已經超過一百了、允許使用者自訂很多細節體驗。</p><p>奇摩成了象徵。哪怕奇摩的功能並不多、可能有功能設計上的硬傷（比如 Lithoglyphs 特色的「選字窗出現跨游標的候選字」），奇摩的很多舊使用者們也仍舊頭鐵地非用奇摩不可，甚至連奇摩的嫡系續作（小麥注音）都懶得管。</p><p>總之現在是「互相爭搶著自己掏大錢用 AI 修復奇摩」的群龍亂舞的場面，一個個地都是：「我反正要用奇摩，我懶得找其他人有沒有修過，我也不要管自己是否重複花冤枉錢，反正自己先把錢花給 Claude 修了奇摩再說。」</p><p>社群救濟是正常現象。但當大家都在爭先恐後地做同一件重複無用功的時候就怪了。</p><p>FOSS 輸入法都競爭成這樣，收費的個人開發者連關注度都很少有、很難回本，更遑論既有的商業大牌（自然輸入法）也怕是再難賺到錢了。更慘的是，Apple 不允許 macOS 輸入法上架到 Mac App Store 營利。</p><p>先有三四十年打字肌肉記憶難改的（從倚天中文 DOS 系統至今的）ㄅ半戰士，後有十幾年甚至二十幾年來（從 macOS 10.4 開始至今）的奇摩戰士，然後是現在剛開始燃起來（從華碩電腦自帶的華碩智慧輸入法開始接觸電腦打字）的「連需要手動切換中英文都忍不下去」的華碩戰士們。</p><p>日子真難。</p><p>$ EOF.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1c2c7a2d7c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MadTunes, a dedicated music app for listening mix references.]]></title>
            <link>https://shikisuen.medium.com/madtunes-a-dedicated-music-app-for-listening-mix-references-303a3cc87ca5?source=rss-747d4432e418------2</link>
            <guid isPermaLink="false">https://medium.com/p/303a3cc87ca5</guid>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[music]]></category>
            <dc:creator><![CDATA[Shiki Suen]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 00:10:37 GMT</pubDate>
            <atom:updated>2026-03-21T00:11:46.157Z</atom:updated>
            <content:encoded><![CDATA[<p>For anyone who gets confused about audio playback fidelity issues happened with Foobar2000 on macOS, here’s a better app: I wrote “MadTunes”. It’s precompiled binary is <a href="https://apps.apple.com/tw/app/madtunes/id6760667980">available today for CAD25 / USD25 on App Store</a>.</p><blockquote><em>It’s only free if you have Xcode to compile the source code hosted at `</em><a href="https://github.com/ShikiSuen/MadTunes"><em>ShikiSuen/MadTunes</em></a><em>` on GitHub.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cQ1KdLaHlbsPZgYt" /></figure><p><strong>Why MadTunes?</strong></p><p>As a music creator, you need playback tools that accurately reveal mixing details. Validated through over 100 rigorous tests, only the system-native AVPlayer ensures optimal audio quality on macOS. MadTunes builds upon this foundation, faithfully presenting original audio without additional sound processing, letting you hear the true studio-grade sound.</p><p><strong>Key Features:</strong></p><p>• Broad Format Support — MP3, FLAC, AAC, WAV, AIFF, Ogg Vorbis, Opus, and more mainstream audio formats (audio files only);<br>• Pace-Uninterrupted Loop Playback — Designed for loopable audio, pace-uninterrupted transition at loop points;<br>• Accurate Stereo — Faithfully reproduces original mixing, no HRTF interference;<br>• Powerful Keyboard Navigation — Full keyboard support, from grid navigation to queue management without mouse;<br>• Smart Search &amp; Filter — Keyword search + three-column cascading filter (Genre/Artist/Album);<br>• Flexible Playing Queue — Drag to reorder, play next, shuffle, complete playback control;<br>• Playlist Management — Create personal playlists to organize your music collection;<br>• Classic Grid Layout — Late-2012 iTunes 11-style album grid you are missing since macOS 10.15 Catalina: click to expand, double-click to play, intuitive and efficient.</p><p><strong>Optimized for macOS:</strong></p><p>• System-built-in native Apple AVPlayer core — validated through over 100 tests to ensure best audio quality on macOS;<br>• Adaptive HAL buffer to eliminate audio jitter;<br>• Security-scoped bookmarks for persistent file access;<br>• Native SwiftUI interface with smooth animations and Liquid Glass effects; • Full support for macOS 15 Sequoia and later.</p><p>MadTunes collects no user data. All music files are processed locally — your privacy is fully protected.</p><p><strong>Supported Formats:</strong> MP3, FLAC, AAC, M4A, WAV, AIFF, Ogg Vorbis, Opus, CAF</p><blockquote><em>CoreAudio may support new formats per certain macOS releases. Please file issues if new formats are implementable in MadTunes.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d1Roxftl1K0bDT2l" /></figure><h3>Motives​</h3><p>I used Foobar 2000 on macOS for a long time. However, after more than four years of use, I realized it had significant audio performance issues. As a music creator, I also tried mixing my own work. However, my mixes were often criticized as “terrible”, yet when listening in that player it was always hard to tell the difference between my work and commercially released soundtrack albums in terms of mix quality. Over time, this misleading listening reference prevented me from accurately understanding the sonic characteristics of professional mixes, making it difficult to attract clients. I had to keep creating while also learning programming part-time as a second source of income. Later, when I took over maintenance of R128x (an audio loudness analysis tool) and added a listening feature, I realized for the first time that an ordinary Mac can sound this good. It was at that moment that I understood I had been misled by that player for years, and I was furious. The name MadTunes is both “Mad + Tunes” and a pun on “媽的 Tunes” (damn Tunes), meant to express that sentiment.</p><h3>Concepts​</h3><p>Although MadTunes’ UI operation experience on macOS and iPad (FullScreen) may resemble iTunes 11 (released in 2012) in some respects, its design goals are completely different from the consumer-market focus of Apple Music / iTunes. Apple’s player usually applies slight spatial processing during stereo playback, which can feel more “immersive” for general listening, but for learners who need to analyze album mixing characteristics it interferes with accurately judging imaging and mixing detail. Additionally, some audio material (for example, game or ambient music) is designed to loop seamlessly end-to-end. In many players, single-track repeat playback often introduces a brief gap at the transition point, interrupting the overall beat pace. MadTunes includes dedicated handling for these cases to ensure truly pace-uninterrupted loop playback.</p><p>The UI design for iPhone and small-window iPad follows the UI design language used in Windows Phone 7 / 8 around 2012, making things simpler to handle on iPhone.</p><h3>Technical Notes​</h3><p>When writing an audiophile audio player for Mac, you must use AVPlayer (from macOS built-in AVFoundation Framework); AVAudioEngine has no way to achieve the same playback fidelity. This conclusion comes from over a hundred trials and errors during development. These albums / tracks are used during the tests.</p><ul><li>KATOU Tatsuya: Shokugeki no Souma (TV Anime Soundtrack)</li><li>Fish Leong: Courage</li><li>FLOW: Go!!! &amp; Sign</li><li>Zutomayo: Hunch Grey</li><li>Gene Fang (all albums mixed by Michael Chang)</li></ul><p>$ EOF.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=303a3cc87ca5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[macOS Input Method Development Guidelines for 2026]]></title>
            <link>https://shikisuen.medium.com/macos-input-method-development-guidelines-for-2026-5123461fa53b?source=rss-747d4432e418------2</link>
            <guid isPermaLink="false">https://medium.com/p/5123461fa53b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[appkit]]></category>
            <category><![CDATA[mac]]></category>
            <dc:creator><![CDATA[Shiki Suen]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 14:17:09 GMT</pubDate>
            <atom:updated>2026-10-21T16:24:17.217Z</atom:updated>
            <content:encoded><![CDATA[<p>(Amended on 2026–10–22)</p><p>The Input Method Kit (IMK) framework emerged during the macOS 10.5 Leopard era — predating Objective-C ARC, XPC communication, and the Sandbox (all introduced in macOS 10.7). Naturally, it also came before Swift 5 and SwiftUI gained popularity. In other words, InputMethodKit is a legacy framework that has spanned two generations of technology paradigm shifts. Apple’s original reference manual for macOS 10.5 Leopard, the <a href="https://leopard-adc.pepas.com/documentation/Cocoa/Reference/InputMethodKitFrameworkRef/InputMethodKitFrameworkRef.pdf"><em>Input Method Kit Framework Reference</em></a> (henceforth “IMKFR”), no longer meets the requirements imposed by these shifts — particularly those of Swift 6 Concurrency. Based on my experience developing the <a href="https://vchewing.github.io/">vChewing input method (targeting macOS 10.09 Mavericks to the latest macOS 27)</a>, I’ve compiled these guidelines for other engineers seeking to develop input methods for macOS.</p><blockquote><em>I also developed the </em><a href="https://github.com/vChewing/IMKSwift"><em>IMKSwift</em></a><em> package to make it easier for Swift developers to write IMK input methods. IMKSwift provides the IMKInputSessionController base type, which replaces the ObjC header definitions of IMKInputController with expressions more friendly to Modern Swift Concurrency. The package also ships the MRC private-surface layer described in §5, so that section can be read as a reference implementation rather than a to-do list.</em></blockquote><h3>1. NSConnection Naming</h3><p>The IMKFR doesn’t cover this, but there’s only one correct answer: the InputMethodConnectionName key in the input method&#39;s Info.plist can only be set to $(PRODUCT_BUNDLE_IDENTIFIER)_Connection.</p><blockquote><em>⚠️ This is the NSConnection naming convention that macOS 10.7 Lion introduced.</em></blockquote><blockquote><em>If you don’t follow this convention, your input method may fail to load properly after enabling the Sandbox — when users try to switch to your input method, they’ll encounter NSConnection-related failure which will have messages in </em><em>Console.app.</em></blockquote><p>Apple’s own “NumberInput” reference project provided a <a href="https://github.com/pkamb/NumberInput_IMKit_Sample/blob/6c37ea05d85d0b7b5af9378a0ce88e191ca07241/NumberInput/main.m#L53-L55"><em>poor example</em></a>, misleading macOS input method developers worldwide. When the authorities err, the misdirection is most damaging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eeIV8CUqqHydpC3E.png" /></figure><p>Apple even granted input methods that hadn’t enabled Sandbox special treatment, allowing them to continue functioning normally despite using non-standard NSConnection names. Some input method developers unfortunately misinterpreted this as “the Sandbox actually causes more problems,” which is fundamentally incorrect reasoning.</p><h3>2. Sandbox Entitlements</h3><p>Always enable the Sandbox. The instant an input method enables Sandbox on macOS, it becomes <em>theoretically</em> impossible to gain system-wide keyboard access. Because your input method is forced by the system framework to rely on NSConnection — — a fragile mechanism — failing to enable the Sandbox is turning the input method into the town bicycle; everyone’s had a ride.</p><p>Sandbox support represents an input method’s best security credential to users.</p><blockquote><em>Consequently, most remaining input methods lack Sandbox support: either they face technical challenges or they offer vague excuses.</em></blockquote><p>Define the Sandbox entitlements file as follows:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br>  &lt;key&gt;com.apple.security.app-sandbox&lt;/key&gt;<br>  &lt;true/&gt;<br>  &lt;key&gt;com.apple.security.files.bookmarks.app-scope&lt;/key&gt;<br>  &lt;true/&gt;<br>  &lt;key&gt;com.apple.security.files.user-selected.read-write&lt;/key&gt;<br>  &lt;true/&gt;<br>  &lt;key&gt;com.apple.security.network.client&lt;/key&gt;<br>  &lt;true/&gt;<br>  &lt;key&gt;com.apple.security.temporary-exception.files.home-relative-path.read-write&lt;/key&gt;<br>  &lt;array&gt;<br>    &lt;string&gt;/Library/Preferences/$(PRODUCT_BUNDLE_IDENTIFIER).plist&lt;/string&gt;<br>  &lt;/array&gt;<br>  &lt;key&gt;com.apple.security.temporary-exception.mach-register.global-name&lt;/key&gt;<br>  &lt;string&gt;$(PRODUCT_BUNDLE_IDENTIFIER)_Connection&lt;/string&gt;<br>  &lt;key&gt;com.apple.security.temporary-exception.shared-preference.read-only&lt;/key&gt;<br>  &lt;string&gt;$(PRODUCT_BUNDLE_IDENTIFIER)&lt;/string&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><p>Notice that this whitelist includes the input method’s own UserDefaults. This is essential because once an input method enables Sandbox, macOS deprives it of direct UserDefaults access.</p><h3>3. MainActor Constraints and Swift 6.2+</h3><p>All IMKInputController API interactions run on the MainActor. However, InputMethodKit’s exposed headers are incompatible with Swift Concurrency, making it impossible to properly confine IMKInputController to the MainActor.</p><p>The best approach to ensure InputMethodKit compatibility with Swift 6 Concurrency is to set the entire target’s default isolation to MainActor. While this occasionally requires awkward hacks for IMKInputController API calls, it represents the minimal-effort solution.</p><p>First, introduce these two extension APIs:</p><pre>extension IMKInputController {<br>  nonisolated fileprivate func wrap(_ object: Any?) -&gt; UInt? {<br>    guard let object = object as? AnyObject else { return nil }<br>    return UInt(bitPattern: Unmanaged.passUnretained(object).toOpaque())<br>  }<br><br>  nonisolated fileprivate func unwrap(_ addr: UInt?) -&gt; Any? {<br>    guard let addr = addr, let ptr = UnsafeMutableRawPointer(bitPattern: addr) else { return nil }<br>    return Unmanaged&lt;AnyObject&gt;.fromOpaque(ptr).takeUnretainedValue()<br>  }<br>}</pre><p>Then use this mainSync API (designed to prevent Russian doll deadlocks):</p><pre>@discardableResult<br>public func mainSync&lt;T&gt;(execute work: @MainActor () throws -&gt; T) rethrows -&gt; T {<br>  if Thread.isMainThread {<br>    return try work()<br>  }<br>  return try DispatchQueue.main.sync(execute: work)<br>}</pre><p>Here’s a template demonstrating how to translate API parameters to the MainActor:</p><pre>/// nonisolated is required by the IMKStateSetting &amp; IMKMouseHandling protocols.<br>/// Technically, Apple doesn&#39;t require it, but the header&#39;s Swift compatibility was not well-designed.<br>@objc(MyIMKInputController) // @objc is mandatory because IMK is written in Objective-C.<br>nonisolated public final class MyIMKInputController: IMKInputController, @unchecked Sendable {<br><br>  @objc(handleEvent:client:)<br>  nonisolated override public func handle(<br>    _ event: NSEvent?,<br>    client sender: Any?<br>  )<br>    -&gt; Bool {<br>    let eventRef = wrap(event)<br>    let senderRef = wrap(sender)<br>    return mainSync {<br>      let clientOnMain = unwrap(senderRef)<br>      let eventOnMain = unwrap(eventRef)<br>      // Business logic resides here.<br>    }<br>  }<br>}</pre><p>Note that I’ve declared MyIMKInputController as Sendable. Otherwise, mainSync becomes ineffective.</p><h3>4. IMKInputController Must Async-Run Tasks Appropriately</h3><p>Some input methods inevitably interact with client() during the activateServer phase, but this overhead may be unavoidable—you might need to apply a specific Ukelele layout using client.overrideKeyboard(). Since the IMKTextInput Client lacks true Async APIs, input method developers must assume all such Client operations are MainActor-blocking operations and accept the limitation.</p><p>Therefore, all Client methods <em>except</em> client()?.setMarkedText &amp; client()?.insertText can be async-run on the MainActor. By strictly confining all IMKInputController API interactions to the MainActor (as described above), you needn&#39;t worry about ordering issues from async-running.</p><blockquote><em>Note: </em><em>client()? is a MainActor-confined object. You can async-run, but the lambda expression calling Client methods must run on the MainActor.</em></blockquote><h3>5. IMKInputController Must Be MRC-Managed, and the Client Binding Must Be Re-Established per Event</h3><h3>5.1 The IMKServer Controller-Leak Flaw (Reverse‑Engineered)</h3><p>Through extensive reverse engineering of InputMethodKit across macOS 10.9 Mavericks, 10.15 Catalina, and macOS 27 GoldenGate (arm64e), the vChewing project uncovered a fundamental defect in IMKServer’s internal controller lifecycle management:</p><ol><li>IMKServer internally maintains _private._controllers — an NSMutableDictionary keyed by [NSNumber numberWithUnsignedLong:clientProxyAddr] — to track all IMKInputController instances. The key is the memory address of the client proxy object passed to each controller at init.</li><li>Every CapsLock toggle creates a brand-new DO/XPC proxy object with a different memory address. The old controller’s dictionary key can never be hit by a lookup again, because IMKServer’s built-in controller reuse logic is keyed on the proxy address that has now changed. The old controller becomes permanently orphaned.</li><li>IMKServer provides sessionFinished: to clean up accumulated controllers for a given app, but sessionFinished: is dispatched per-client-proxy. After a CapsLock toggle, the old proxy has been replaced; IMKServer no longer sends any messages to it, so sessionFinished: is never triggered for the orphaned controller. Each CapsLock toggle produces a permanently leaked controller.</li><li>The orphaned controller holds a client wrapper (IPMDServerClientWrapper on macOS ≤ 10.15; split into _IPMDServerClientWrapperModern and _IPMDServerClientWrapperLegacy on macOS 15 Sequoia and later) which in turn holds _xpcConnection (NSXPCConnection) or _clientDOProxy — these connection resources are also permanently leaked. IMK manages these wrappers via a global cache, and they can only be removed by calling private class methods (+terminateForClientXPCConn:, +terminateForClientDOProxy:).</li><li>From macOS 15 Sequoia onward, +terminateForClient: (the unsuffixed version) has been removed entirely; only the XPC and DO variants remain.</li><li>Under ARC, the retain/release churn from frequent CapsLock switching can cause perceptible stutter. Disabling ARC (-fno-objc-arc) eliminates the stutter completely, but then you must handle orphaned controller cleanup and residual XPC connection teardown manually.</li><li>The orphan is not merely leaked — it keeps the client binding it had when it was deactivated. Nothing in the framework will ever update it again, because nothing in the framework still believes the controller is in service. Any keystroke the system routes to such a controller is then answered with a retired client’s identity.</li></ol><h3>5.2 The Fix: MRC + KVC Prune + Address-Keyed Sessions + Per-Event Adoption</h3><p>a) Full MRC for the IMK interaction layer. The IMKInputSessionController target is compiled with -fno-objc-arc. All controller alloc/dealloc/retain/release happens in the ObjC MRC layer. The Swift side interacts with controllers only through raw memory addresses (uintptr_t), never performing Swift ARC operations on controller instances.</p><p>b) KVC-based orphaned controller pruning. A monotonically increasing generation number is assigned to each controller at init. On every controller creation — after the new controller has registered itself — the oldest inactive controller (lowest generation, excluding the current controller and the new one) is removed via KVC: [server valueForKeyPath:@&quot;_private._controllers&quot;] removeObjectForKey:oldKey]. This prunes orphaned controllers in MRC so they are properly deallocated.</p><p>c) A small session pool keyed by controller address. vChewing first routed sessions by generation parity (even → session A, odd → session B — the “double buffer” described in earlier revisions of this document). Generations are monotonic, so parity looks stable, and that was the trap: two controllers whose generations share a parity share one session. When the first retires, the session’s client binding is cleared; the second keeps dispatching through a session that no longer knows its client, and every key is dropped before it reaches the IME. The current design keys sessions by the controller’s own address in a pool of at most four, reaps a slot only when the lifetime tracker says the controller is gone, and never evicts by recency.</p><p>d) Delayed dealloc with XPC cleanup. After deactivateServer:, the controller is not immediately deallocated. Instead, a 3-second timer is started. When it fires, the controller: releases all blocks, invokes the private +terminateForClient* class methods on the appropriate client wrapper class (falling back through _IPMDServerClientWrapperModern → _IPMDServerClientWrapperLegacy → IPMDServerClientWrapper for forward compatibility with macOS 27), and clears the controller↔session mapping. If the controller is reactivated within 3 seconds (activateServer:), the timer is cancelled and normal service resumes. This prevents a &quot;dead controller, not-yet-ready new controller&quot; gap during rapid CapsLock toggling.</p><blockquote><em>Delayed dealloc buys the reuse window; it does not mean the controller has died. The shell may remain in </em><em>_controllers until the next prune, so never use &quot;the timer fired&quot; as a liveness test.</em></blockquote><p>e) Per-event client adoption. On every delivered event, before dispatch, the session rebinds itself to the sending controller’s address. The write is skipped when the value is unchanged, so it costs one comparison per keystroke. This single line is what makes the design self-healing: whichever copy the system routes to, the session’s client is whoever is sending <em>now</em>. IMKControllerLifetimeTracker still guards every takeUnretainedValue() on a raw address.</p><p>f) IME menu injection via ObjC runtime. The IME menu is dynamically built by IMEMenuSputnikwhich uses class_addMethod + imp_implementationWithBlock to register Swift closures directly as method IMPs on IMKInputSessionController. No @objc selector exposure is needed. The menu injects two live metrics: (1) the count of alive controller instances tracked by IMKControllerLifetimeTracker, and (2) anonymous private memory usage obtained from task_vm_info.internal. Before each menu open, purgeMallocZones() is called to flush allocator caches so the memory reading reflects actual usage.</p><h3>5.3 Architectural Summary</h3><p>The net effect is that ARC is fully removed from the IMK dispatch path, eliminating CapsLock stutter. A small address-keyed session pool replaces the parity pair and eliminates the aliasing hazard. The KVC prune path compensates for IMKServer’s inability to clean up orphaned controllers on its own. Per-event adoption makes a stale binding impossible. The delayed dealloc ensures XPC connections are properly terminated rather than leaked.</p><p>Below is a minimal sketch of the controller-side architecture:</p><pre>// IMKInputSessionController (MRC-compiled .m file):<br>// - Class-level static blocks dispatch to Swift via raw addresses.<br>// - +IMKSwift_configureWithActivatingServer: etc. set once at startup.<br><br>// Swift side — address-keyed session pool:<br>@MainActor<br>final class SessionPool {<br>  static let shared = SessionPool(capacity: 4)<br>  private var slots: [UInt: InputSession] = [:]<br><br>  func session(for ctlAddr: UInt) -&gt; InputSession { /* create or reuse this address&#39;s slot */ }<br>  func reap(using tracker: IMKControllerLifetimeTracker) { /* drop slots whose controller is gone */ }<br>}<br><br>// SessionControllerSputnik event block:<br>// 1. Resolve (or create) the session for the sending controller&#39;s address.<br>// 2. adoptClientAddr(ctlAddr) — the sender is the authority.<br>// 3. Dispatch into the session&#39;s core.</pre><blockquote><em>Note: the pool is keyed by </em>controller<em> address, not client address. The controller is the object whose lifetime the framework actually manages; the client is a proxy that can be replaced beneath it at any time. Four slots suffice because the system keeps at most one active controller plus a short tail of retiring ones.</em></blockquote><h3>5.4 Observability and Kill Switches</h3><p>You cannot breakpoint any of this. What you can do is instrument it, and make every intervention individually switchable.</p><p>Log vocabulary. The ObjC layer emits a fixed set of tokens: ControllerInit:, Prune:(controllers=, current=, self=, evicted … remaining=), ActivateServer: (with clientTerminatedBefore=), DeactivateServer:, DelayedDealloc: (scheduled / skipped / fired), EventEntry: (addr, alive, gen, session=, plus the cached client name), and guard fail: (hasHandler, hasClient, proxyNil). On macOS 26 and later they go through Logger(subsystem: &quot;vChewing&quot;, category: &quot;Log&quot;); earlier systems fall back to NSLog. A debug-mode flag gates them.</p><p>Four diagnostics-only switches, exposed in the DevZone pane and as raw UserDefaults keys:</p><p>SwitchDisablesconfigureServerControllerPruningDisabled(_:)the KVC pruneconfigureEvictedClientInvalidationDisabled(_:)invalidating the evicted controller&#39;s client entry (only the aggressive half of the eviction)configureClientWrapperTerminationDisabled(_:)+terminateForClient* on the wrapper, keeping the dealloc bookkeepingconfigureControllerDelayedDeallocationDisabled(_:)the whole deferred teardown</p><p>Each block is evaluated at the decision point and never cached; vChewing feeds them from four _IMKSwift_disable… preferences, so the switch states of a running process can be changed without a rebuild.</p><p>Sixteen raw combinations, nine distinguishable behaviours: the delayed-dealloc switch already makes the wrapper-termination and eviction switches unreachable in the same sequence, and the prune switch makes the eviction switch moot. They exist so that a report from the field can be turned into a bisection instead of a guess.</p><p>Three failure signatures the tokens let you tell apart:</p><ol><li>no EventEntry: for the dead window ⇒ the event was never delivered;</li><li>EventEntry: with alive=false, or UnresolvableController: ⇒ the address was lost;</li><li>EventEntry: with alive=true but session= naming another client, or assigned=nil ⇒ the event went to the wrong client.</li></ol><p>Installers. Capture the running PIDs <em>after</em> the payload swap, escalate SIGTERM → SIGKILL, poll for vacancy, and verify. Never killall and hope; never kill before the swap (IMK relaunches the IME from the registered bundle, so a pre-swap kill only restarts the old code under a new PID). When running as root, scope the kill to the console user via /usr/bin/stat -f%Su /dev/console.</p><h3>6. Write All Input Method Code as Swift Package Libraries</h3><p>macOS input methods cannot be debugged using breakpoints — they will indefinitely freeze any client application that has touched your input method, and consequently freeze your entire desktop. You’re left with no choice but to SSH into your machine externally and force-kill the input method process. The only viable approach is to write your own unit tests with mocked clients. Structuring all business logic as libraries greatly facilitates this debugging approach and allows developers to specify dedicated UserDefaults containers for heumetic tests. Better still, you can write a standard AppKit app simulating this unit test typing process and use Instruments to detect memory leaks. This is far more flexible than maintaining only an input method Xcode target.</p><h3>7. Self-Monitor Memory Usage; Force Termination When Necessary</h3><p>User computer memory is precious. While macOS 26’s AppKit NSWindow rendering inefficiency means an input method might consume 80–200 MB of RAM, consider this design pattern: have your input method check its own memory footprint each time activateServer switches to a new typing session. If it exceeds 1024 MB, emit an NSNotification to inform the user, then terminate gracefully. This notification warns users and prevents them from assuming the input method has crashed.</p><p>Of course, this is a fallback safeguard preventing catastrophic outcomes like memory exhaustion on user systems. Developers remain obligated to actively check their code for memory leaks.</p><blockquote><em>⚠️ If your input method uses SQLite, you need to pay extra attention to a little-known fact: after running each query with SQLite, you must use </em><em>sqlite3_finalize(StatementPointer)to release the memory, otherwise a memory leak will occur that cannot even be detected by Xcode Instruments.</em></blockquote><h3>8. Minimize NSWindow Count in Input Methods</h3><p>This guideline responds to macOS 26’s dire reality: beginning with macOS 26, memory consumed by NSWindow instances is never reclaimed by the system. The baseline overhead per NSWindow is substantial, and that overhead is amplified by the LiquidGlass rendering framework. Even if you don’t explicitly enable LiquidGlass effects, it still applies. Setting UIDesignRequiresCompatibilityin Info.plist can reduce memory footprint to macOS 15 levels, but this is a temporary measure—Apple can revoke UIDesignRequiresCompatibility support at any moment.</p><blockquote><em>I speculate that macOS 26’s massive disk footprint includes a macOS 15 AppKit environment specifically providing backward compatibility for this </em><em>Info.plist property.</em></blockquote><p>With Swift UI now mature, consider consolidating “tooltip panels” and “custom candidate windows” into a single NSPanel, reducing NSWindow baseline overhead. The input method’s “About” window can be folded into the Settings UI of the input method.</p><blockquote><em>NSPanel is a variant of NSWindow.</em></blockquote><h3>9. Avoid Using IMKCandidates</h3><p>Even the NumberInput sample didn’t dare use IMKCandidates — because IMKCandidates is ancient rubbish, still stinking to this day. Look at macOS 26’s built-in Japanese input method: it’s a victim of IMKCandidates, with text barely legible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*TGiAkQ2yq9faTT1H.png" /></figure><p>The glass background is completely transparent, exposing white behind it. The candidate window text is also white. This is clearly a result of inadequate unit testing — misuse of the LiquidGlass API.</p><p>With modern AI capabilities, it’s straightforward to ask an AI to write a custom candidate panel resembling IMKCandidates’s layout. Alternatively, you can force-expose IMKCandidates’s internal APIs (some have been stable since macOS 10.14 Mojave), though future availability is uncertain.</p><blockquote><em>In my vChewing Input Method I use my self-crafted Tadokoro Candidate Window to provide an experience hakushin-enough to IMKCandidates (dynamic grid layout).</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8EIOZTfApvksCLz2gwE3_A.png" /><figcaption>Tadokoro Candidate Window</figcaption></figure><h3>Conclusion</h3><p>InputMethodKit is a historical artifact, yet it remains the only official entry point for macOS input methods. Developers must therefore accept this framework’s baggage and establish engineering discipline atop its structural deficiencies.</p><p>The guidelines presented here aren’t mere “tricks” — they constitute a risk-containment model: transforming IMKInputController into a pure pass-through layer, modularizing all business logic completely, treating MainActor as an immutable fact, regarding memory pressure as a design constraint, and viewing the Sandbox as a non-negotiable ethical baseline.</p><p>Should Apple someday completely rewrite InputMethodKit, these guidelines may become obsolete. But until then, macOS input methods that wish to maintain engineering quality and security trustworthiness in 2026 must encode “self-discipline” into their architecture, not just into their README files.</p><p>$ EOF.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5123461fa53b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[寫在2026年的macOS輸入法開發規範]]></title>
            <link>https://shikisuen.medium.com/%E5%AF%AB%E5%9C%A82026%E5%B9%B4%E7%9A%84macos%E8%BC%B8%E5%85%A5%E6%B3%95%E9%96%8B%E7%99%BC%E8%A6%8F%E7%AF%84-cfe90dfdffc7?source=rss-747d4432e418------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfe90dfdffc7</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[appkit]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[mac]]></category>
            <dc:creator><![CDATA[Shiki Suen]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 13:47:32 GMT</pubDate>
            <atom:updated>2026-10-21T16:27:13.950Z</atom:updated>
            <content:encoded><![CDATA[<p>(本文更新於 2026–10–22)</p><p>InputMethodKit 自 macOS 10.5 Leopard 時代問世，早於 Objective-C ARC 技術、XPC 通訊技術、Sandbox 技術問世（均為 macOS 10.7）之前。自然，這也是早於 Swift 5 與 SwiftUI 流行之前。也就是說，InputMethodKit 是橫跨了兩代技術大變革的祖產級 OS Framework。當年 Apple 寫給 macOS 10.5 Leopard 的 IMK 參考手冊《<a href="https://leopard-adc.pepas.com/documentation/Cocoa/Reference/InputMethodKitFrameworkRef/InputMethodKitFrameworkRef.pdf">Input Method Kit Framework Reference</a>》（下文簡稱《IMKFR》）早已不符合這些變革所帶來的新要求（特別是 Swift 6 Concurrency）。筆者根據自己開發<a href="https://vchewing.github.io/">《唯音輸入法》(for macOS 10.09 Mavericks ~ macOS 27)</a>的經驗，將一些注意事項整理在此，留給其他想給 macOS 開發輸入法的工程師們參考。</p><blockquote><em>筆者另外製作了 </em><a href="https://github.com/vChewing/IMKSwift"><em>IMKSwift</em></a><em> 套件，允許 Swift 工程師們在寫 IMK 輸入法時更順利：IMKSwift 提供了 IMKInputSessionController 基礎型別、是在 IMKInputController 的基礎上整體換用了對 Modern Swift Concurrency 更友好的 ObjC Header 表達。該套件另已內建 §5 所述的 MRC 私有面層；下文 §5 的實作細節可以當作參考實作，而非待辦清單。</em></blockquote><h3>1. NSConnection 名稱</h3><p>《IMKFR》沒提及，但正確答案只有一個：輸入法的 Info.plist 的 InputMethodConnectionName欄位只能填寫 $(PRODUCT_BUNDLE_IDENTIFIER)_Connection。</p><blockquote><em>⚠️ 這是 macOS 10.7 Lion 開始對 NSConnection 的命名規範。</em></blockquote><blockquote><em>不按照這個規範命名的話，你的輸入法在開啟 Sandbox 之後，可能就會在使用者嘗試切換到該輸入法的時候無法正常載入。此時可以在 </em><em>Console.app 內觀測到與 NSConnection 有關的失敗訊息。</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tsynrvv9akLPSPPG.png" /></figure><p>Apple 甚至都不得不給那些沒開 Sandbox 的輸入法們開小灶、允許它們在使用非正規命名的 NSConnection 名稱的前提下繼續正常工作。但這被某些輸入法開發者們錯誤地視為「Sandbox 開了反而會壞事」。</p><h3>2. Sandbox Entitlements</h3><p>一定要開 Sandbox。macOS 輸入法只要開了 Sandbox，就在原理上絕對無法拿到系統全局鍵盤權限了。你的輸入法因為系統框架限制的原因，不得不用 NSConnection 這麼脆弱的東西，再不開 Sandbox 的話，就等於北港香爐人人插。</p><p>「Sandbox 支援」對一款 macOS 輸入法而言，堪稱對使用者的最佳的資安投名狀。</p><blockquote><em>於是剩下的幾乎都是不敢開 Sandbox 的輸入法了：或有技術難題，或支支吾吾。</em></blockquote><p>Sandbox 權能檔案的定義如下：</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br>  &lt;key&gt;com.apple.security.app-sandbox&lt;/key&gt;<br>  &lt;true/&gt;<br>  &lt;key&gt;com.apple.security.files.bookmarks.app-scope&lt;/key&gt;<br>  &lt;true/&gt;<br>  &lt;key&gt;com.apple.security.files.user-selected.read-write&lt;/key&gt;<br>  &lt;true/&gt;<br>  &lt;key&gt;com.apple.security.network.client&lt;/key&gt;<br>  &lt;true/&gt;<br>  &lt;key&gt;com.apple.security.temporary-exception.files.home-relative-path.read-write&lt;/key&gt;<br>  &lt;array&gt;<br>    &lt;string&gt;/Library/Preferences/$(PRODUCT_BUNDLE_IDENTIFIER).plist&lt;/string&gt;<br>  &lt;/array&gt;<br>  &lt;key&gt;com.apple.security.temporary-exception.mach-register.global-name&lt;/key&gt;<br>  &lt;string&gt;$(PRODUCT_BUNDLE_IDENTIFIER)_Connection&lt;/string&gt;<br>  &lt;key&gt;com.apple.security.temporary-exception.shared-preference.read-only&lt;/key&gt;<br>  &lt;string&gt;$(PRODUCT_BUNDLE_IDENTIFIER)&lt;/string&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><p>可以看到這裡將輸入法自身的 UserDefaults 拉入白名單了。這是必需的，因為 macOS 的輸入法做了 Sandbox 處理之後確實會喪失對自身 UserDefaults 的存取能力。</p><h3>3. MainActor 約束與 Swift 6.2+</h3><p>整個 IMKInputController 所有 API 交互都是走 MainActor 的。但是，InputMethodKit 曝露出來的 Header 與 Swift Concurrency 不相容，導致你在使用時反而無法將 IMKInputController 釘死在 MainActor 上。</p><p>讓 InputMethodKit 與 Swift 6 Concurrency 相容性最佳的處理方法就是將整個 target 的 default isolation 設為 MainActor。這樣雖然也難免需要對 IMKInputController 的 API 呼叫處理過程實施一些硬 Hack，但這算是相對而言工作量最小的。</p><p>你先引入這兩個 extension API：</p><pre>extension IMKInputController {<br>  nonisolated fileprivate func wrap(_ object: Any?) -&gt; UInt? {<br>    guard let object = object as? AnyObject else { return nil }<br>    return UInt(bitPattern: Unmanaged.passUnretained(object).toOpaque())<br>  }<br><br>  nonisolated fileprivate func unwrap(_ addr: UInt?) -&gt; Any? {<br>    guard let addr = addr, let ptr = UnsafeMutableRawPointer(bitPattern: addr) else { return nil }<br>    return Unmanaged&lt;AnyObject&gt;.fromOpaque(ptr).takeUnretainedValue()<br>  }<br>}</pre><p>再使用這個 MainSync API（有經過處理，防止俄羅斯套娃 DeadLock）：</p><pre>@discardableResult<br>public func mainSync&lt;T&gt;(execute work: @MainActor () throws -&gt; T) rethrows -&gt; T {<br>  if Thread.isMainThread {<br>    return try work()<br>  }<br>  return try DispatchQueue.main.sync(execute: work)<br>}</pre><p>然後，這是範本，專門示範怎樣將 API 的參數翻譯到 MainActor 上：</p><pre>/// nonisolated 是 IMKStateSetting &amp; IMKMouseHandling 協定要求的。<br>/// 或者說，官方沒要求，但是是 Swift 相容性沒做好導致的現狀。<br>@objc(MyIMKInputController) // 必須加上 ObjC，因為 IMK 是用 ObjC 寫的。<br>nonisolated public final class MyIMKInputController: IMKInputController, @unchecked Sendable {<br><br>  @objc(handleEvent:client:)<br>  nonisolated override public func handle(<br>    _ event: NSEvent?,<br>    client sender: Any?<br>  )<br>    -&gt; Bool {<br>    let eventRef = wrap(event)<br>    let senderRef = wrap(sender)<br>    return mainSync {<br>      let clientOnMain = unwrap(senderRef)<br>      let eventOnMain = unwrap(eventRef)<br>      // 此處存放業務邏輯。<br>    }<br>  }<br>}</pre><p>可能有人注意到筆者將 MyIMKInputController 定義為 Sendable 了。不然 mainSync 無效。</p><h3>4. IMKInputController 該脫手的任務一定要脫手</h3><p>有些輸入法難免會在 activateServer 階段引入與 client() 有關的交互，但這個開銷可能在所難免，因為你可能必須得對 client 使用 client.overrideKeyboard() 套用指定的 Ukelele 佈局。再加上 client() 身為 IMKTextInput Client 沒有真正意義上的 Async API，輸入法開發者只能假設所有這類 Client 的這些操作都是 MainActor 阻塞操作，然後乾瞪眼。</p><p>於是乎，除了 client()?.setMarkedText 與 client()?.insertText 以外，其餘的 client methods 應該是都可以在 MainActor 上面 Async 脫手操作的。只要你嚴格按照前文所述將 IMKInputController 所有 API 交互都釘死在 MainActor 上，你就不用擔心脫手操作所帶來的亂序的問題。</p><blockquote><em>注意：</em><em>client()? 是 MainActor 限定物件。你脫手可以，但脫手操作的 Lambda Expression 在呼叫 client() 方法時必須在 MainActor 上。</em></blockquote><h3>5. IMKInputController 必須是 MRC 管理，且客體綁定必須逐事件重建</h3><h3>5.1 IMKServer 控制器洩漏缺陷（逆向工程結論）</h3><p>筆者針對 InputMethodKit 在 macOS 10.9 Mavericks、10.15 Catalina 與 macOS 27 GoldenGate（arm64e）上做了大量逆向工程，發現 IMKServer 在控制器生命週期管理上有一個根本缺陷：</p><ol><li>IMKServer 內部以 _private._controllers 這個 NSMutableDictionary 追蹤所有 IMKInputController 實例，鍵是 [NSNumber numberWithUnsignedLong:clientProxyAddr]——也就是每枚控制器在 init 時所收到的客體代理物件之位址。</li><li>每一次 CapsLock 切換都會產生一個全新的 DO/XPC 代理物件，位址不同。舊控制器在字典裡的鍵從此再也查不到，因為 IMKServer 內建的控制器重用邏輯是以業已改變的代理位址為鍵。舊控制器就此成為永久的孤兒。</li><li>IMKServer 有 sessionFinished: 可以清理某個 App 累積下來的控制器，但 sessionFinished: 是按客體代理逐一派發的。CapsLock 一切，舊代理已被替換，IMKServer 不會再對它發任何訊息，於是孤兒控制器永遠收不到 sessionFinished:。每切一次 CapsLock，就漏掉一枚控制器。</li><li>孤兒控制器持有客體連線包裝物件（macOS ≤ 10.15 為 IPMDServerClientWrapper；macOS 15 Sequoia 起拆為 _IPMDServerClientWrapperModern 與 _IPMDServerClientWrapperLegacy），其內又持有 _xpcConnection（NSXPCConnection）或 _clientDOProxy——這些連線資源同樣永久洩漏。IMK 以全域快取管理這些包裝物件，只能透過私有的類別方法（+terminateForClientXPCConn:、+terminateForClientDOProxy:）移除。</li><li>macOS 15 Sequoia 起，無後綴的 +terminateForClient: 已被完全移除，只剩 XPC 與 DO 兩個變體。</li><li>在 ARC 之下，頻繁 CapsLock 切換造成的 retain/release churn 會導致可感知的卡頓。關閉 ARC（-fno-objc-arc）可以完全消除卡頓，但從此孤兒控制器的清理與殘餘 XPC 連線的拆除，都得自己來。</li><li>孤兒不只是被漏掉 — — 它還保留著退場當時的客體綁定。 框架裡沒有任何東西會再更新那個綁定，因為框架裡沒有任何東西還認為這枚控制器在服役。系統此後投給這枚控制器的按鍵，都會以一個已退場客體的身分被回應。</li></ol><h3>5.2 修法：MRC ＋ KVC 剔除 ＋ 位址索引的會話池 ＋ 逐事件認領</h3><p>a) IMK 互動層全面改用 MRC。 IMKInputSessionController 的 target 以 -fno-objc-arc 編譯，控制器的 alloc/dealloc/retain/release 全在 ObjC MRC 層完成。Swift 端只透過原始記憶體位址（uintptr_t）與控制器互動，絕不對控制器實例做 Swift ARC 操作。</p><p>b) 以 KVC 剔除孤兒控制器。 每枚控制器在 init 時取得一個單調遞增的世代號。每當有一枚控制器被建立、並完成自身登記之後，就以 KVC 移除最舊的閒置控制器（世代號最小者，排除當前控制器與新建的這一枚）：[server valueForKeyPath:@&quot;_private._controllers&quot;] removeObjectForKey:oldKey]。這讓孤兒控制器在 MRC 下被正常解構。</p><p>c) 以控制器位址為鍵的小型會話池。 唯音最初以世代奇偶路由會話（偶→會話 A、奇→會話 B，即本文舊版所述的「雙緩衝」）。世代單調遞增，所以奇偶看起來很穩定 — — 而那正是陷阱：兩枚世代同奇偶的控制器會共用同一份會話。第一枚退場時，該會話的客體綁定被清空；第二枚仍繼續透過一份不再認得自己客體的會話派發，於是每一個按鍵都在送達輸入法之前就被丟掉。現行設計改以控制器自身的位址為鍵，會話池至多四份，只有在生命週期追蹤器判定控制器已死時才回收該槽，且絕不做「最近最少使用」式的淘汰。</p><p>d) 延遲拆除，並清理 XPC。 deactivateServer: 之後不立即解構控制器，而是啟動一個三秒計時器。計時器觸發時，控制器會：釋放所有 block、對適當的客體包裝類別呼叫私有的 +terminateForClient* 類別方法（依 _IPMDServerClientWrapperModern → _IPMDServerClientWrapperLegacy → IPMDServerClientWrapper 的順序回退，以兼容 macOS 27），並清除控制器↔會話的對應。若控制器在三秒內被重新啟用（activateServer:），計時器即取消、正常服務。這避免了快速 CapsLock 切換時「舊控制器已死、新控制器還沒準備好」的空窗。</p><blockquote><em>延遲拆除買到的是「重用窗口」；它不代表控制器已經死了。控制器外殼可能還留在 </em><em>_controllers 裡，直到下一次剔除為止——所以千萬不要把「計時器已觸發」當成存活判據。</em></blockquote><p>e) 逐事件認領客體。 每一個送達的事件，在派發之前，會話先把自身重新綁定到「送來這枚事件之控制器」的位址。若值未變則跳過寫入，因此成本是每按一鍵一次比較。就是這一行讓整個設計能自癒：無論系統把事件路由給哪一枚副本，會話的客體永遠是當下正在送事件的那一位。IMKControllerLifetimeTracker 仍然守著每一次對原始位址的 takeUnretainedValue()。</p><p>f) 以 ObjC runtime 注入輸入法選單。 輸入法選單由 IMEMenuSputnik 動態組建：以 class_addMethod ＋ imp_implementationWithBlock 把 Swift 閉包直接註冊為 IMKInputSessionController 上的方法 IMP，無需曝露 @objc selector。選單會注入兩項即時指標：(1) IMKControllerLifetimeTracker 追蹤的存活控制器數；(2) 由 task_vm_info.internal 取得的匿名私有記憶體用量。每次選單開啟前會呼叫 purgeMallocZones() 清空配置器快取，使記憶體讀數反映實際用量。</p><h3>5.3 架構摘要</h3><p>整體效果是：ARC 徹底退出 IMK 派發路徑，CapsLock 卡頓消失；以位址為鍵的小型會話池取代了極性配對，也就消除了別名共用（aliasing）的隱患；KVC 剔除補上了 IMKServer 無力自行清理孤兒的缺口；逐事件認領讓「過期的客體綁定」不可能存在；延遲拆除則確保 XPC 連線被正常終止，而不是洩漏。</p><p>以下是控制器側架構的最小示意：</p><pre>// IMKInputSessionController（以 MRC 編譯的 .m 檔）：<br>// - 類別層級的 static block 以原始位址把呼叫派發給 Swift。<br>// - +IMKSwift_configureWithActivatingServer: 等在啟動時設定一次。<br><br>// Swift 端：以位址為鍵的會話池<br>@MainActor<br>final class SessionPool {<br>  static let shared = SessionPool(capacity: 4)<br>  private var slots: [UInt: InputSession] = [:]<br><br>  func session(for ctlAddr: UInt) -&gt; InputSession { /* 建立或重用此位址的槽位 */ }<br>  func reap(using tracker: IMKControllerLifetimeTracker) { /* 收掉控制器已死的槽位 */ }<br>}<br><br>// SessionControllerSputnik 的事件區塊：<br>// 1. 為送來事件的控制器位址取得（或建立）會話。<br>// 2. adoptClientAddr(ctlAddr)——以送事件的人為準。<br>// 3. 派發進該會話的核心。</pre><blockquote><em>註： 會話池以控制器位址為鍵，不是客體位址。控制器才是框架真正管理生命週期的物件；客體只是一個隨時可能在其腳下被替換的代理。四個槽位足夠，因為系統同時最多只會有一枚現役控制器，外加一小截正在退場的尾巴。</em></blockquote><h3>5.4 可觀測性與 kill switch</h3><p>這些東西沒法用斷點偵錯。你能做的是給它裝上觀測點，並且讓每一項干涉都能被單獨關掉。</p><p>日誌詞彙。 ObjC 層只吐一組固定的詞彙：ControllerInit:、Prune:（controllers=、current=、self=、evicted … remaining=）、ActivateServer:（含 clientTerminatedBefore=）、DeactivateServer:、DelayedDealloc:（排定／跳過／執行）、EventEntry:（addr、alive、gen、session=，以及快取下來的客體名稱）、guard fail:（hasHandler、hasClient、proxyNil）。macOS 26 起走 Logger(subsystem: &quot;vChewing&quot;, category: &quot;Log&quot;)，更早的系統回退到 NSLog；另有偵錯模式旗標可整體關閉。</p><p>四枚僅供診斷的開關，見於「開發道場」面板，亦可用原始 UserDefaults 鍵設定：</p><p>開關停用什麼configureServerControllerPruningDisabled(_:)KVC 剔除configureEvictedClientInvalidationDisabled(_:)對被剔除控制器的客體條目作失效處理（只關掉淘汰行為中較激進的那一半）configureClientWrapperTerminationDisabled(_:)對包裝物件呼叫 +terminateForClient*，但保留 dealloc 簿記configureControllerDelayedDeallocationDisabled(_:)整個延遲拆除</p><p>每一個 block 都是在「決策當下」求值、且從不快取；唯音以四個 _IMKSwift_disable… 偏好設定餵給它們，所以執行中行程的開關狀態可以即時改變，無需重編。</p><p>十六種原始組合，九種可分辨的行為：延遲拆除一關，客體終止與客體失效這兩個開關在同一序列裡就不可達；而剔除一關，客體失效的開關也就無意義了。加這些開關的理由很單純：讓現場回報可以被二分，而不是只能猜。</p><p>三種故障簽名，這些詞彙能幫你分辨：</p><ol><li>失靈時段完全沒有 EventEntry: ⇒ 事件從未送達；</li><li>有 EventEntry: 但 alive=false，或出現 UnresolvableController: ⇒ 位址弄丟了；</li><li>有 EventEntry: 且 alive=true，但 session= 指向另一個客體，或 assigned=nil ⇒ 事件送給了錯的客體。</li></ol><p>安裝器。 請在套件本體替換之後再抓取行程 PID，依序 SIGTERM → SIGKILL、輪詢確認已空、再驗證。不要 killall 了事，也不要在替換之前就殺（IMK 會從已註冊的套件按需重啟輸入法，替換前殺只是讓舊程式碼以新 PID 回來）。以 root 身分執行時，請以 /usr/bin/stat -f%Su /dev/console把終止範圍限制在當前主控使用者。</p><h3>6. 將輸入法所有程式內容寫成 Swift Package Library</h3><p>macOS 的輸入法無法用 breakpoint 等方式偵錯，因為會無限凍結任何沾過你的輸入法的 clients，進而凍結你的整個桌面，最終得依賴外部 SSH 連到你的電腦上殺掉輸入法執行緒才行。你需要自己寫單元測試搭配自己寫的 mockup client 來測試。這樣的話，將輸入法的所有業務內容寫成 Library 會更便於這種偵錯，還能允許開發者靈活地指定專用的 UserDefaults 容器來實現封閉測試。更甚者，你還可以寫個標準的 AppKit App 模擬這個單元測試打字過程，然後用 Instruments 監測是否有記憶體洩漏。這遠比僅保留一個輸入法本體 Xcode Target 要靈活得多。</p><h3>7. 記憶體佔用量自查自糾，必要時自盡以釋放記憶體</h3><p>使用者電腦的記憶體空間寸土寸金。雖然 macOS 26 的 AppKit 糟糕的 NSWindow 繪製效率導致一款輸入法平均佔用的運存可能從 80MB 暴漲到 200MB 左右。但筆者在這裡介紹的一個設計應該不壞：讓輸入法每次 activateServer 切換到新的打字會話的時候，檢查輸入法自身佔用的記憶體。如果發現佔用的記憶體的量超過 1024MB 的話，就讓輸入法拋出 NSNotification 使用者通知之後自盡。這個 NSNotification 使用者通知的內容就是告知這個情況，免得使用者以為輸入法崩潰掉。</p><p>當然，這個技巧只是兜底策略、防止在使用者的電腦上發生像是「記憶體用盡」這樣的災難性的後果。但開發者仍有義務主動檢查自己寫的東西是否有記憶體洩漏的危險。</p><blockquote><em>⚠️ 如果你的輸入法有在用 SQLite 的話，需要額外注意一個冷門常識：用 SQLite 跑完每一筆查詢之後一定要用 </em><em>sqlite3_finalize(StatementPointer) 釋放記憶體，不然會產生連 Xcode Instruments 都抓不到的記憶體洩漏。</em></blockquote><h3>8. 讓輸入法用到的 NSWindow 數量盡可能地少</h3><p>這一條是針對 macOS 26 開始的現狀而不得已的規範，因為：自 macOS 26 開始，只要是 NSWindow 用過的記憶體空間，就都不會被系統刻意回收掉 NSWindow 每個副本的基礎開銷、且這個基礎開銷因為 LiquidGlass 的原因而非常高昂。哪怕你確實沒啟用 LiquidGlass 效果，也沒差。在 Info.plist 當中啟用 UIDesignRequiresCompatibility 雖然可以讓記憶體佔用量下降到 macOS 15 的水準，但這只是緩兵之計、且 Apple 隨時都會廢掉 UIDesignRequiresCompatibility 這個 InfoPlist 屬性。</p><blockquote><em>筆者推測：macOS 26 佔用硬碟空間這麼大，很可能是系統卷宗裡面包了一個 macOS 15 AppKit 環境、專門用來對這個 InfoPlist 屬性提供 backward compatibility。</em></blockquote><p>現在 SwiftUI 這麼強了，開發者完全可以考慮將「工具提示 Panel」與「自己搓的選字窗」整合到同一個 NSPanel 裡面，這樣就少了一份 NSWindow 基礎開銷。輸入法的「關於」視窗也可以整入輸入法自身的「偏好設定」裡面。</p><blockquote><em>NSPanel 是 NSWindow 的變種。</em></blockquote><h3>9. IMKCandidates 不要用就對了</h3><p>前文提到的那個 NumberInput 範例都不敢用 IMKCandidates 選字窗，因為 IMKCandidates 就是一包陳年糞便、臭到現在。你看 macOS 26 系統內建的日語輸入法就是 IMKCandidates 的受害者，連文字都看不清：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*3CmrShurltcTLUlm.png" /></figure><p>玻璃背景居然全透明了、把白色整個透上來。偏偏選字窗的文字也是白色的。這種問題一眼看出來就是缺乏單元測試惹的禍，因為這很明顯就是 Liquid Glass API 沒正確使用所導致的。</p><p>現在 AI 技術這麼發達，你用 AI 幫你寫一個類似 IMKCandidates 那種佈局的輸入法選字窗面板應該也不難。當然，如果你用強行曝露 IMKCandidates 內部 API 的方式來使用的話，有些 API 從 macOS 10.14 Mojave 開始是固定可用的，但將來就不好說了。</p><blockquote><em>筆者給自己開發的唯音輸入法就使用了自己搓的田所選字窗，與 IMK 多行選字窗相比也算提供了比較迫真的體驗。</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8EIOZTfApvksCLz2gwE3_A.png" /><figcaption>田所選字窗</figcaption></figure><h3>結尾</h3><p>InputMethodKit 是歷史產物，但它至今仍是 macOS 輸入法唯一的官方入口。既然如此，開發者就必須接受這套框架的歷史包袱，並在其結構性缺陷之上建立自己的工程紀律。</p><p>本文所列規範，本質上並非「技巧」，而是一套風險控制模型：將 IMKInputController 變為純轉接層、將業務邏輯完全模組化、將 MainActor 當作不可違抗的事實、將記憶體壓力視為設計輸入條件、將 Sandbox 視為最低限度的道德底線。</p><p>若有一天 Apple 徹底重寫 InputMethodKit，這些規範或許會過時；但在那之前，macOS 輸入法若想在 2026 年仍保持工程品質與資安可信度，就必須把「自我約束」寫進架構，而不是寫在 README 裡。</p><p>$ EOF.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfe90dfdffc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[關於 iOS / OS X 中文螢幕字體的變遷，您必須要瞭解的幾件事情]]></title>
            <link>https://shikisuen.medium.com/%E5%85%B3%E4%BA%8E-ios-os-x-%E4%B8%AD%E6%96%87%E8%8D%A7%E5%B9%95%E5%AD%97%E4%BD%93%E7%9A%84%E5%8F%98%E8%BF%81-%E6%82%A8%E5%BF%85%E9%A1%BB%E8%A6%81%E4%BA%86%E8%A7%A3%E7%9A%84%E5%87%A0%E4%BB%B6%E4%BA%8B%E6%83%85-7b6babb3a35e?source=rss-747d4432e418------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b6babb3a35e</guid>
            <category><![CDATA[fonts]]></category>
            <category><![CDATA[os-x]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Shiki Suen]]></dc:creator>
            <pubDate>Sun, 20 Sep 2015 18:15:48 GMT</pubDate>
            <atom:updated>2015-09-20T20:14:57.412Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="http://zhuanlan.zhihu.com/ibuick/20221780">http://zhuanlan.zhihu.com/ibuick/20221780</a></p><h4>一、華文黑體標榜不了中國傳統文化</h4><p>先前 iOS 1~8 的「黑體-簡」和 iOS 3~8 「黑體-繁」都是華文黑體字體族，這一類字體談不了純正的「中國傳統設計」（請參閱《<a href="http://www.typeisbeautiful.com/psa/interview-with-xuecheng-xu/zh-hant/">徐學成的故事</a>》）</p><p>…是說，無論當時的宋一體、黑一體，都是引入了日本的秀英品牌的設計之後、將筆形修改成 GB 標準的；至於黑二體，也是承襲其設計理念而來。</p><p>於是，任何標榜華文黑體字體族（包括「華文黑體」、「華文細黑」）、「方正等線」等針對黑一體、黑二體的劣質數位復刻品「體現中華文化」的想法，都站不住腳。</p><h4>二、書法與字體排印畢竟是兩回事</h4><p>再講究彼此結合，「書法」與「字體排印」這兩個場合也是各自有各自的底線。</p><p>常州華文在針對黑一、黑二體製作其數位復刻字型產品時，只知道一個字一個字地描，並未引入數位校準的觀念、對諸如「平均字面率」等指標進行嚴格數控…而是將當年的簽字設計師請來、用肉眼校對（僅訴諸經驗、而並未結合實際衡量手段）。</p><p>這必然會無法充分照顧整個華文黑體字體族在字體排印方面的功能特徵──閱讀性（Readability）和視認性（Legibility，又稱「易識度」）…而這些恰恰就是用於正文顯示這樣的字體排印場合的黑體產品所必須要照顧到的地方，尤其是在數位螢幕顯示的場合下（這也屬於字體排印，只不過是介質變成了數位螢幕而已）。</p><h4>三、字型產品用在與其功能特性不符的場合就是濫用</h4><p>或許常州華文的黑體字體族產品一開始就不是給數位螢幕顯示專用的…畢竟當時大眾對螢幕數位字體的觀念還停滯在點陣時代。於是這黑鍋實際上還是要讓 Apple 的中文化團隊來背一部分的，是他們在 OS X 時代選擇了華文黑體字體族作為 UI 字體。</p><blockquote><em>（除了徐學成這位被請去的嘉賓不需要背以外…剩下的黑鍋，常州華文製作該數位復刻字體的所有參與者都要背，我在上文講過原因了；徐學成是黑一體、黑二體的原稿設計師）</em></blockquote><p>精確描述的話，一開始是用華文細黑（黑一體復刻品）給簡體中文介面使用，到雪豹時代更名為「黑體-簡/繁」、連繁體中文介面字體「儷黑 Pro」一併壟斷：將華文黑體（黑二體復刻品）更名為 Medium 字重來頂替需要粗體顯示的場合，同時將華文細黑做成 Light 字重。</p><p>這裡可以發現 Apple 在華分社負責 UI 字體的部門至少犯了這三個錯誤：</p><ul><li>先是拿中黑來湊合粗體、而沒有任何的仿粗措施。我承認仿粗效果很差，但、若不用的話，在小字號時難以和常規字重彼此區分開、缺乏足夠的視覺衝擊力。</li><li>再是將針對紙質印刷、且「缺乏數位校準等現代排印專用字型產品的品控手段」製作而成的華文黑體字體族用到了數位螢幕介質顯示文字的場合。而華文黑體字體族完全沒有像冬青黑體那樣同時兼顧螢幕顯示與紙質印刷效果的設計水平（偏偏兩者都是有喇叭口的黑體）。</li><li>完全沒有考慮中日文混排、中西文混排時的閱讀特徵統一性的需求。不但在中黑字重時的假名和西文分別出現了過粗和過細的毛病，且漢字以外的字符的設計態度都十分潦草…比如那毫無閱讀性可言的西文字符，等。</li></ul><p>上述三條錯誤，無一例外都是基於「湊合」的心態、完全不知道照顧自家數位產品用戶的視力衛生。</p><blockquote><em>說一個小歷史：論及上文當中的第三條當中所說的語種混排相容性問題，從 OS X Snow Leopard 開始以來，到今天，從未被修正過；偏偏 OS X Leopard 及之前系統版本的繁體中文預設介面字體「儷黑 Pro」（基於柯熾堅最開始的「蘋果儷中黑」設計而成，和蘋方同樣是威鋒數位製作的字型產品）則沒有這種問題…可惜的是、「儷黑 Pro」只有 Medium 字重。關於儷黑的介紹可以參考我之前寫的《</em><a href="http://zhuanlan.zhihu.com/ibuick/20163528"><em>關於儷黑》 </em></a><em>，請千萬不要將儷黑和冬青黑體簡體中文彼此搞混。</em></blockquote><p>咱們經常看到有人不分場合一味拿微軟雅黑（方正蘭亭黑）、康熙字典體、華文黑體字體族湊合用，然而這三款字體卻是各有其職：微軟雅黑一味強調視認性，康熙字典體是純粹追尋時代感而生的藝術字體、橫向正文排版效果並不好，華文黑體字體族則只適合用於五六十年代風格的紙面印刷、在數位螢幕顯示場合毫無視認性可言。如果說雅黑真的可以四處亂用沒問題的話，雅黑的作者齊立也就沒有理由去設計「更具有應用場合相容性」的旗黑了。畢竟微軟雅黑用於正文顯示時不具備閱讀性優勢。</p><h4>四、「對蘋方粗細不滿」並不能成為攻擊蘋方的理由</h4><p>「對蘋方粗細不滿」並不能成為攻擊蘋方產品本身的理由：因為蘋方本身還是有更細的字重的。您可以參見 iOS 9 內贈 Safari 瀏覽器當中的閱讀模式；如果您有 Mac 電腦、且安裝有 OS X El Capitan 系統的話，您可以在 Spotlight 當中鍵入「Font Book.app」開啟字體簿應用、自己親自確認蘋方有多少字重。於是您就能明白，這不是蘋方本身的問題、而是 Apple 沒能允許你為 iOS 介面選擇自己更喜歡的更細的字重。</p><h4>五、請勿訴諸「簡繁體」這種與字型設計無關的概念</h4><p>論及一款字型產品的視認性，與其顯示的文本內容「是否是簡繁體」毫無關係：簡體中文一樣會有筆劃比較多的字。</p><p>這就牽涉到一個問題：在設計一款字體時，其初稿用字當中，筆劃稀少的字不能超過三成。如果在設計字體初稿時的選字都是筆劃少的字的話，假如這時的平均字面率不夠大的話…那麼在後期設計筆劃比較多的字的時候不得不遷就字面率…於是就導致了統一字面率的問題、干擾閱讀節奏。</p><p>這是以簡體中文為書面母語的字體設計師常犯的問題，但齊立做得比較好：他主持設計的微軟雅黑、方正蘭亭黑、漢儀旗黑都沒有這種問題。</p><p>順帶一提的是，筆者之前曾指出初版方正悠黑在這方面的問題，但其團隊已經著手對悠黑的統一字面率進行了一系列修正…個人認為目前的悠黑（至少 2.00 版本）可以當做華文黑體字體族在數位螢幕顯示場合的替代品、且字重豐富。</p><h4>六、請勿訴諸「像安卓」等站不住腳的概念</h4><p>有人第一眼看到思源黑體或蘋方，就覺得「像安卓」…但這很明顯是鬼話：</p><blockquote><em>Android 前任螢幕介面顯示專用字體「Droid Sans Fallback」和現任字體「思源黑體」彼此的設計風格都不相同，「蘋方」自己也持單獨的設計風格。推薦大家讀一下這篇對蘋方設計缺陷的分析「</em><a href="http://www.zhihu.com/question/35688107/answer/64427756"><em>吐槽 iOS 9 字體的人是什麼心理？ — 知乎用戶的回答</em></a><em>」，讓大家瞭解一下蘋方與其它字體產品之間的差異。</em></blockquote><p>通過這種輿論現象，可以看出：出於「使用效率」等實用原因而購買 iOS 產品的用戶，相對於中國大陸整體 iOS 用戶群體基數而言，當真少得可憐…太多人買 iPhone 只是為了裝蒜炫酷而已。</p><p>實際上，這種設計，不應該訴諸 Android 的品牌，而應該訴諸<strong>「通用設計（Universal Design）」的觀念。這個觀念基於四項基本原則：「容易看懂（分かり易い）」、「極難誤讀（誤読し難い）」、「閱讀舒適（読み易い）」、「設計簡樸（シンプル）」</strong>，且在海外廣泛用於商品說明書包裝印刷等需要方便大眾「快速高效閱讀」的場合。想讓手機賣得更火，就得更照顧大眾需求。</p><p>Android 系統先前的 Droid Sans Fallback 字體（威鋒數位在 2006 年前後設計的作品）就是基於這種觀念設計而成的字體族，且威鋒數位將此觀念同樣用到了如今針對 iOS / watchOS / OS X 系統的全新螢幕介面字體族「蘋方」的身上。</p><p>只是，不同廠商的不同字體產品，對通用設計觀的貫徹程度與方法也不盡相同…就個人看法而言，文鼎科技的晶熙黑體對通用設計觀的貫徹程度更加深刻一些…大家可以去文鼎科技的官方網站藉由瀏覽器體驗一下顯示效果。</p><h4>七、關於螢幕文字大小粗細不一的問題</h4><p>只可能是你當前應用使用了日文介面的字體「冬青黑體 ProN」，而這套字體的設計風格與蘋方不同。於是，在遇到「冬青黑體 ProN」無法顯示的文字時，便會自動回退到蘋方身上。同時，「冬青黑體 ProN」與蘋方彼此的字重關係尚且無法逐一映射，於是就造成了文字粗細不統一的問題。</p><p># EOF.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b6babb3a35e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>