MacOS:如何在系统范围内以编程方式激活字体?

MacOS: How can I activate fonts programmatically, systemwide?

我正在尝试做一些与字体管理器行为非常相似的东西,但我根本找不到任何关于如何将 OpenType 字体添加到 NSFontManager 提供的列表的文档。我什至看到 Font Book 显示通过字体管理器应用程序激活的字体,所以我想了解引擎盖下发生的事情。正在调用哪些库?

谢谢!

Apple 有一篇名为 Mac OS X: Font locations and their purposes 的旧存档文章,其中有一节是关于手动管理字体的:

[...] You may install fonts by double-clicking them and following the on screen prompts in the Font Book application, or by manually copying or dragging font files to any of the standard Fonts folders in Mac OS X.

The folder in which a font is located determines who can access and use the font. For example: If a user manually installs a new font at ~/Library/Fonts/, the font is available only to that user. If a root or admin user installs the same font at /Network/Library/Fonts/, all network users can use the fonts (assuming that the network administrator has set up computers for this type of sharing).

Changes to fonts take effect when an application is opened or a user logs in to the account or computer on which the changes occurred. Duplicate fonts are resolved based on the order of precedence defined for the standard Fonts folders and are described from highest to lowest priority below.

我使用我创建的空字体 (Awfulcode-Regular.otf) 和 TextEdit 对此进行了测试,发现更改是即时的。因此我推测任何延迟实际上是由特定应用程序而不是 macOS 本身引入的。

我花了一些时间,但是 here's the way to go

CTFontManagerRegisterFontURLs 完全符合我在 macOS 上寻找的功能。此外,来自 2019 年 WWDC 的 session 227 有更多关于它的信息,尽管主要集中在 iOS.

函数

CTFontManagerRegisterFontURLs(::::)

  • 声明 *
func CTFontManagerRegisterFontURLs(_ fontURLs: CFArray, 
                                 _ scope: CTFontManagerScope, 
                                 _ enabled: Bool, 
                                 _ registrationHandler: ((CFArray, Bool) -> Bool)?)