diff --git a/kitty/core_text.m b/kitty/core_text.m index 7e2c4d6fc..12afa7833 100644 --- a/kitty/core_text.m +++ b/kitty/core_text.m @@ -1474,27 +1474,6 @@ add_font_file(PyObject UNUSED *_self, PyObject *args) { Py_RETURN_FALSE; } -static PyObject * -set_builtin_nerd_font(PyObject UNUSED *self, PyObject *pypath) { - if (!PyUnicode_Check(pypath)) { - PyErr_SetString(PyExc_TypeError, "path must be a string"); - return NULL; - } - const char *path = NULL; - Py_ssize_t sz; - path = PyUnicode_AsUTF8AndSize(pypath, &sz); - RAII_CoreFoundation(CFURLRef, url, CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const unsigned char *)path, sz, false)); - RAII_CoreFoundation(CFArrayRef, descriptors, CTFontManagerCreateFontDescriptorsFromURL(url)); - if (!descriptors || CFArrayGetCount(descriptors) == 0) { - PyErr_SetString(PyExc_OSError, "Failed to create descriptor from nerd font path"); - return NULL; - } - if (builtin_nerd_font_descriptor) CFRelease(builtin_nerd_font_descriptor); - builtin_nerd_font_descriptor = CFArrayGetValueAtIndex(descriptors, 0); - CFRetain(builtin_nerd_font_descriptor); - return font_descriptor_to_python(builtin_nerd_font_descriptor); -} - // Font selection backend, see font-select.h {{{ // This code runs in the font selection thread, so it must not use Python. // CoreText font descriptors and fonts are thread safe. @@ -1741,6 +1720,33 @@ fs_backend_font_tables(FSContext *ctx UNUSED, const FSCandidate *c, FSFontTables return true; } +void +fs_backend_prepare_builtin_nerd_font(FSContext *ctx, FSBuiltinNerdFont *nf) { + RAII_CoreFoundation(CFURLRef, url, CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8 *)nf->path, (CFIndex)strlen(nf->path), false)); + RAII_CoreFoundation(CFArrayRef, descriptors, url ? CTFontManagerCreateFontDescriptorsFromURL(url) : NULL); + if (!descriptors || CFArrayGetCount(descriptors) == 0) { + fs_add_message(ctx, "Failed to create a font descriptor for the builtin NERD font from: %s", nf->path); + return; + } + nf->handle = (void *)CFRetain(CFArrayGetValueAtIndex(descriptors, 0)); + nf->prepared = true; +} + +void +fs_backend_free_builtin_nerd_font(FSBuiltinNerdFont *nf) { + if (nf->handle) CFRelease((CTFontDescriptorRef)nf->handle); + nf->handle = NULL; +} + +PyObject * +fs_backend_install_builtin_nerd_font(const FSBuiltinNerdFont *nf) { + CTFontDescriptorRef d = (CTFontDescriptorRef)nf->handle; + if (builtin_nerd_font_descriptor) CFRelease(builtin_nerd_font_descriptor); + builtin_nerd_font_descriptor = d; + CFRetain(builtin_nerd_font_descriptor); + return font_descriptor_to_python(builtin_nerd_font_descriptor); +} + PyObject * fs_backend_descriptor(const FSFont *f) { RAII_PyObject(ans, font_descriptor_to_python((CTFontDescriptorRef)f->base->handle)); @@ -1761,7 +1767,7 @@ fs_backend_descriptor(const FSFont *f) { // }}} static PyMethodDef module_methods[] = { - METHODB(coretext_all_fonts, METH_O), METHODB(add_font_file, METH_VARARGS), METHODB(set_builtin_nerd_font, METH_O), {NULL, NULL, 0, NULL} /* Sentinel */ + METHODB(coretext_all_fonts, METH_O), METHODB(add_font_file, METH_VARARGS), {NULL, NULL, 0, NULL} /* Sentinel */ }; static PyMemberDef members[] = { diff --git a/kitty/fast_data_types.pyi b/kitty/fast_data_types.pyi index 70f82e3f4..600420071 100644 --- a/kitty/fast_data_types.pyi +++ b/kitty/fast_data_types.pyi @@ -443,7 +443,6 @@ def clear_fallback_font_cache() -> None: ... def fc_match_fallback( text: str, bold: bool = False, italic: bool = False, prefer_color: bool = False, use_candidate_cache: bool = True ) -> FontConfigPattern: ... -def set_builtin_nerd_font(path: str) -> Union[CoreTextFont, FontConfigPattern]: ... # family, style, postscript_name, full_name, system, variable_name, axes, has_features FontSelectionSpec = Tuple[Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Tuple[Tuple[str, float], ...], bool] @@ -455,9 +454,14 @@ class FontSelectionResult(TypedDict): bi: Union[CoreTextFont, FontConfigPattern] # The descriptor and whether it is bold and italic for each symbol_map family symbols: Tuple[Tuple[Union[CoreTextFont, FontConfigPattern], bool, bool], ...] + # The descriptor of the builtin NERD font, if it was requested and could be loaded + builtin_nerd_font: Optional[Union[CoreTextFont, FontConfigPattern]] def start_font_selection( - specs: Tuple[FontSelectionSpec, FontSelectionSpec, FontSelectionSpec, FontSelectionSpec], symbol_map_families: Tuple[str, ...], threaded: bool = True + specs: Tuple[FontSelectionSpec, FontSelectionSpec, FontSelectionSpec, FontSelectionSpec], + symbol_map_families: Tuple[str, ...], + threaded: bool = True, + builtin_nerd_font_path: Optional[str] = None, ) -> None: ... def finish_font_selection() -> FontSelectionResult: ... def variable_data_from_font_file(path: str, index: int = 0) -> VariableData: ... diff --git a/kitty/font-select.c b/kitty/font-select.c index b0e81f375..93ed9a893 100644 --- a/kitty/font-select.c +++ b/kitty/font-select.c @@ -492,6 +492,15 @@ read_stat(const uint8_t *table, size_t table_len, const NameTable *nt, FSVariabl } } +char * +fs_postscript_name_from_tables(const FSFontTables *t) { + NameTable nt; + parse_name_table(t->name, t->name_len, &nt); + char *ans = get_best_name(&nt, 6); + free(nt.records); + return ans; +} + bool fs_variable_data_from_tables(const FSFontTables *t, FSVariableData *vd) { memset(vd, 0, sizeof(*vd)); @@ -584,6 +593,7 @@ struct FSContext { FSFont results[4]; FSFont *symbols; bool *symbol_bold, *symbol_italic; + FSBuiltinNerdFont nerd_font; }; void ** @@ -691,6 +701,8 @@ free_context(FSContext *ctx) { free(ctx->symbols); free(ctx->symbol_bold); free(ctx->symbol_italic); + fs_backend_free_builtin_nerd_font(&ctx->nerd_font); + free(ctx->nerd_font.path); free(ctx); } @@ -1677,11 +1689,14 @@ run_selection(FSContext *ctx) { return; } if (get_font_files(ctx)) select_symbol_fonts(ctx); + if (ctx->nerd_font.path) fs_backend_prepare_builtin_nerd_font(ctx, &ctx->nerd_font); } // }}} // Python interface {{{ PyObject *fs_backend_descriptor(const FSFont *f); +// Make the prepared builtin nerd font the one used for fallback and return its descriptor, runs in the main thread +PyObject *fs_backend_install_builtin_nerd_font(const FSBuiltinNerdFont *nf); static struct { FSContext *ctx; @@ -1769,7 +1784,8 @@ static PyObject * start_font_selection(PyObject *self UNUSED, PyObject *args) { PyObject *specs, *families; int threaded = 1; - if (!PyArg_ParseTuple(args, "O!O!|p", &PyTuple_Type, &specs, &PyTuple_Type, &families, &threaded)) return NULL; + const char *builtin_nerd_font_path = NULL; + if (!PyArg_ParseTuple(args, "O!O!|pz", &PyTuple_Type, &specs, &PyTuple_Type, &families, &threaded, &builtin_nerd_font_path)) return NULL; if (PyTuple_GET_SIZE(specs) != 4) { PyErr_SetString(PyExc_ValueError, "Must specify exactly four font specifications"); return NULL; @@ -1801,6 +1817,7 @@ start_font_selection(PyObject *self UNUSED, PyObject *args) { } ctx->symbol_families[i] = xstrdup(s); } + if (builtin_nerd_font_path && builtin_nerd_font_path[0]) ctx->nerd_font.path = xstrdup(builtin_nerd_font_path); pending.ctx = ctx; if (threaded) { int ret = pthread_create(&pending.thread, NULL, selection_thread, ctx); @@ -1837,7 +1854,9 @@ selection_result(const FSContext *ctx) { if (!italic) return NULL; RAII_PyObject(bi, fs_backend_descriptor(ctx->results + 3)); if (!bi) return NULL; - return Py_BuildValue("{sO sO sO sO sO}", "medium", medium, "bold", bold, "italic", italic, "bi", bi, "symbols", symbols); + RAII_PyObject(nerd_font, ctx->nerd_font.prepared ? fs_backend_install_builtin_nerd_font(&ctx->nerd_font) : Py_NewRef(Py_None)); + if (!nerd_font) return NULL; + return Py_BuildValue("{sO sO sO sO sO sO}", "medium", medium, "bold", bold, "italic", italic, "bi", bi, "symbols", symbols, "builtin_nerd_font", nerd_font); } static PyObject * diff --git a/kitty/font-select.h b/kitty/font-select.h index fdf21123f..3dcdb2781 100644 --- a/kitty/font-select.h +++ b/kitty/font-select.h @@ -124,12 +124,23 @@ bool fs_read_font_tables_from_file(const char *path, int index, FSFontTables *t) typedef struct FSContext FSContext; +// The nerd font bundled with kitty, prepared by the selection thread +typedef struct FSBuiltinNerdFont { + char *path; // the font file, NULL if not wanted + bool prepared; // set by the backend when the font was successfully prepared + void *handle; // CoreText: CTFontDescriptorRef owned by this struct + bool hinting; // fontconfig: the hinting settings fontconfig specifies for the font + int hint_style; +} FSBuiltinNerdFont; + // Helpers for backends {{{ // The key used to compare font names: whitespace collapsed and stripped, lowercased. Caller must free. char *fs_name_to_key(const char *name); // Allocate a new candidate owned by the context FSCandidate *fs_new_candidate(FSContext *ctx); bool fs_list_append(FSCandidateList *l, const FSCandidate *c); +// The postscript name from the name table, caller must free +char *fs_postscript_name_from_tables(const FSFontTables *t); void fs_set_error(FSContext *ctx, const char *fmt, ...) __attribute__((format(printf, 2, 3))); void fs_add_message(FSContext *ctx, const char *fmt, ...) __attribute__((format(printf, 2, 3))); // Backend private data, freed with fs_backend_free_context_data() @@ -146,6 +157,9 @@ void fs_backend_free_candidate(FSCandidate *c); // CoreText the full name is the family name followed by the style name. bool fs_backend_list(FSContext *ctx, FSListKind kind, const char *name, const char *key, bool monospaced, FSCandidateList *out); bool fs_backend_font_tables(FSContext *ctx, const FSCandidate *c, FSFontTables *out); +// Prepare the builtin nerd font, called in the selection thread +void fs_backend_prepare_builtin_nerd_font(FSContext *ctx, FSBuiltinNerdFont *nf); +void fs_backend_free_builtin_nerd_font(FSBuiltinNerdFont *nf); #ifndef __APPLE__ // Equivalent to the Python fc_match(), returns NULL on failure const FSCandidate *fs_backend_fc_match(FSContext *ctx, const char *family, bool bold, bool italic, int spacing); diff --git a/kitty/fontconfig.c b/kitty/fontconfig.c index fddc3a3d1..a8c16988f 100644 --- a/kitty/fontconfig.c +++ b/kitty/fontconfig.c @@ -21,10 +21,22 @@ static bool initialized = false; static pthread_mutex_t init_lock = PTHREAD_MUTEX_INITIALIZER; static void *libfontconfig_handle = NULL; +// The face is created lazily, when it is first needed for fallback, see builtin_nerd_font_face() static struct { PyObject *face, *descriptor; + char *path; + bool face_failed; } builtin_nerd_font = {0}; +static void +clear_builtin_nerd_font(void) { + Py_CLEAR(builtin_nerd_font.face); + Py_CLEAR(builtin_nerd_font.descriptor); + free(builtin_nerd_font.path); + builtin_nerd_font.path = NULL; + builtin_nerd_font.face_failed = false; +} + #define FcInit dynamically_loaded_fc_symbol.Init #define FcFini dynamically_loaded_fc_symbol.Fini #define FcCharSetAddChar dynamically_loaded_fc_symbol.CharSetAddChar @@ -170,8 +182,7 @@ static void finalize(void) { fs_finalize_selection(); if (initialized) { - Py_CLEAR(builtin_nerd_font.face); - Py_CLEAR(builtin_nerd_font.descriptor); + clear_builtin_nerd_font(); clear_fallback_candidates(); FcFini(); dlclose(libfontconfig_handle); @@ -777,6 +788,19 @@ end: return NULL; } +static PyObject * +builtin_nerd_font_face(void) { + if (!builtin_nerd_font.face && builtin_nerd_font.path && !builtin_nerd_font.face_failed) { + builtin_nerd_font.face = face_from_path(builtin_nerd_font.path, 0, NULL); + if (!builtin_nerd_font.face) { + builtin_nerd_font.face_failed = true; + log_error("Failed to load the builtin NERD font from: %s", builtin_nerd_font.path); + if (PyErr_Occurred()) PyErr_Print(); + } + } + return builtin_nerd_font.face; +} + bool fallback_font(char_type ch, const char *family, bool bold, bool italic, bool prefer_color, FontConfigFace *ans) { ensure_initialized(); @@ -787,7 +811,7 @@ fallback_font(char_type ch, const char *family, bool bold, bool italic, bool pre ok = extract_face_from_pattern(match, ans); FcPatternDestroy(match); } - if (!ok && builtin_nerd_font.face && builtin_nerd_font.descriptor && glyph_id_for_codepoint(builtin_nerd_font.face, ch) > 0) { + if (!ok && builtin_nerd_font.descriptor && builtin_nerd_font_face() && glyph_id_for_codepoint(builtin_nerd_font.face, ch) > 0) { PyObject *pypath = PyDict_GetItemString(builtin_nerd_font.descriptor, "path"); PyObject *pyindex = PyDict_GetItemString(builtin_nerd_font.descriptor, "index"); PyObject *pyhinting = PyDict_GetItemString(builtin_nerd_font.descriptor, "hinting"); @@ -844,7 +868,7 @@ face_from_descriptor: end: Py_CLEAR(d); if (!glyph_found && !PyErr_Occurred()) { - if (builtin_nerd_font.face && has_cell_text(face_has_codepoint, builtin_nerd_font.face, false, lc)) { + if (builtin_nerd_font.descriptor && builtin_nerd_font_face() && has_cell_text(face_has_codepoint, builtin_nerd_font.face, false, lc)) { Py_CLEAR(ans); d = builtin_nerd_font.descriptor; Py_INCREF(d); @@ -861,52 +885,6 @@ end: } -static PyObject * -set_builtin_nerd_font(PyObject UNUSED *self, PyObject *pypath) { - if (!PyUnicode_Check(pypath)) { - PyErr_SetString(PyExc_TypeError, "path must be a string"); - return NULL; - } - ensure_initialized(); - const char *path = PyUnicode_AsUTF8(pypath); - FcPattern *pat = FcPatternCreate(); - if (pat == NULL) return PyErr_NoMemory(); - Py_CLEAR(builtin_nerd_font.face); - Py_CLEAR(builtin_nerd_font.descriptor); - - builtin_nerd_font.face = face_from_path(path, 0, NULL); - if (builtin_nerd_font.face) { - // Copy whatever hinting settings fontconfig returns for the nerd font postscript name - AP(FcPatternAddString, FC_POSTSCRIPT_NAME, (const unsigned char *)postscript_name_for_face(builtin_nerd_font.face), "postscript_name"); - RAII_PyObject(d, _fc_match(pat)); - if (!d) goto end; - builtin_nerd_font.descriptor = PyDict_New(); - if (!builtin_nerd_font.descriptor) goto end; -#define copy(key) \ - { \ - PyObject *t = PyDict_GetItemString(d, #key); \ - if (t) { \ - if (PyDict_SetItemString(builtin_nerd_font.descriptor, #key, t) != 0) goto end; \ - } \ - } - copy(hinting); - copy(hint_style); -#undef copy - if (PyDict_SetItemString(builtin_nerd_font.descriptor, "path", pypath) != 0) goto end; - if (PyDict_SetItemString(builtin_nerd_font.descriptor, "index", PyLong_FromLong(0)) != 0) goto end; - } -end: - if (pat) FcPatternDestroy(pat); - if (PyErr_Occurred()) { - Py_CLEAR(builtin_nerd_font.face); - Py_CLEAR(builtin_nerd_font.descriptor); - return NULL; - } - Py_INCREF(builtin_nerd_font.descriptor); - return builtin_nerd_font.descriptor; -} - - static PyObject * add_font_file(PyObject UNUSED *self, PyObject *args) { ensure_initialized(); @@ -1228,6 +1206,48 @@ fs_backend_font_tables(FSContext *ctx UNUSED, const FSCandidate *c, FSFontTables return fs_read_font_tables_from_file(c->path, c->index, out); } +void +fs_backend_prepare_builtin_nerd_font(FSContext *ctx, FSBuiltinNerdFont *nf) { + FSFontTables t = {0}; + if (!fs_read_font_tables_from_file(nf->path, 0, &t)) { + fs_add_message(ctx, "Failed to read the builtin NERD font from: %s", nf->path); + return; + } + char *psname = fs_postscript_name_from_tables(&t); + fs_free_font_tables(&t); + // Use whatever hinting settings fontconfig specifies for the nerd font postscript name + FcPattern *pat = FcPatternCreate(), *match = NULL; + if (pat && FcPatternAddString(pat, FC_POSTSCRIPT_NAME, (const FcChar8 *)psname)) { + FcResult result; + FcConfigSubstitute(NULL, pat, FcMatchPattern); + FcDefaultSubstitute(pat); + match = FcFontMatch(NULL, pat, &result); + } + if (match) { + nf->hinting = pattern_bool(match, FC_HINTING); + nf->hint_style = pattern_int(match, FC_HINT_STYLE, 0); + FcPatternDestroy(match); + } else fs_add_message(ctx, "Failed to get the hinting settings for the builtin NERD font: %s from fontconfig, using defaults", psname); + if (pat) FcPatternDestroy(pat); + free(psname); + nf->prepared = true; +} + +void +fs_backend_free_builtin_nerd_font(FSBuiltinNerdFont *nf UNUSED) {} + +PyObject * +fs_backend_install_builtin_nerd_font(const FSBuiltinNerdFont *nf) { + RAII_PyObject(d, Py_BuildValue("{sO si ss si}", "hinting", nf->hinting ? Py_True : Py_False, "hint_style", nf->hint_style, "path", nf->path, "index", 0)); + if (!d) return NULL; + char *path = strdup(nf->path); + if (!path) return PyErr_NoMemory(); + clear_builtin_nerd_font(); + builtin_nerd_font.path = path; + builtin_nerd_font.descriptor = Py_NewRef(d); + return Py_NewRef(d); +} + PyObject * fs_backend_descriptor(const FSFont *f) { RAII_PyObject(ans, pattern_as_dict((FcPattern *)f->base->handle)); @@ -1262,7 +1282,6 @@ static PyMethodDef module_methods[] = { METHODB(add_font_file, METH_VARARGS), METHODB(clear_fallback_font_cache, METH_NOARGS), {"fc_match_fallback", (PyCFunction)(void (*)(void))(fc_match_fallback), METH_VARARGS | METH_KEYWORDS, NULL}, - METHODB(set_builtin_nerd_font, METH_O), {NULL, NULL, 0, NULL} /* Sentinel */ }; diff --git a/kitty/fonts/common.py b/kitty/fonts/common.py index 1fc40aeec..738b28885 100644 --- a/kitty/fonts/common.py +++ b/kitty/fonts/common.py @@ -78,20 +78,22 @@ def spec_for_selection(spec: FontSpec) -> 'FontSelectionSpec': return spec.family, spec.style, spec.postscript_name, spec.full_name, spec.system, spec.variable_name, tuple(spec.axes), bool(spec.features) -def start_font_files_selection(opts: Options, symbol_map_families: tuple[str, ...] = (), threaded: bool = False) -> None: +def start_font_files_selection(opts: Options, symbol_map_families: tuple[str, ...] = (), threaded: bool = False, builtin_nerd_font_path: str = '') -> None: """ Start selecting the fonts specified in opts. The selection is done by C code, in a thread if threaded is True. Call finish_font_files_selection() - to get the results. + to get the results. If builtin_nerd_font_path is specified the builtin + NERD font is prepared as well and made the font used for fallback when + the selection finishes. """ specs = cast( 'tuple[FontSelectionSpec, FontSelectionSpec, FontSelectionSpec, FontSelectionSpec]', tuple(spec_for_selection(getattr(opts, attr)) for attr in attr_map.values()), ) - start_font_selection(specs, symbol_map_families, threaded) + start_font_selection(specs, symbol_map_families, threaded, builtin_nerd_font_path or None) -def finish_font_files_selection(opts: Options) -> tuple[FontFiles, tuple[SelectedSymbolFont, ...]]: +def finish_font_files_selection(opts: Options) -> tuple[FontFiles, tuple[SelectedSymbolFont, ...], Descriptor | None]: r = finish_font_selection() def with_features(font: Descriptor, spec: FontSpec) -> Descriptor: @@ -113,7 +115,7 @@ def finish_font_files_selection(opts: Options) -> tuple[FontFiles, tuple[Selecte font['features'] = medium_font['features'] ans[key] = font ff: FontFiles = {'medium': ans['medium'], 'bold': ans['bold'], 'italic': ans['italic'], 'bi': ans['bi']} - return ff, r['symbols'] + return ff, r['symbols'], r['builtin_nerd_font'] def get_font_files(opts: Options) -> FontFiles: diff --git a/kitty/fonts/render.py b/kitty/fonts/render.py index 1a62e51c4..115a60ecd 100644 --- a/kitty/fonts/render.py +++ b/kitty/fonts/render.py @@ -14,7 +14,6 @@ from kitty.fast_data_types import ( current_fonts, get_fallback_font, render_decoration, - set_builtin_nerd_font, set_font_data, set_options, set_send_sprite_to_gpu, @@ -150,15 +149,9 @@ def resolve_pending_font_selection() -> None: return opts, families, add_builtin_nerd_font = pending_selection pending_selection = None - font_map, symbol_fonts = finish_font_files_selection(opts) - if add_builtin_nerd_font: - # This is done after the selection finishes, as it uses fontconfig, - # whose initialization by the selection thread it would otherwise wait for - builtin_nerd_font_path = os.path.join(fonts_dir, 'SymbolsNerdFontMono-Regular.ttf') - if os.path.exists(builtin_nerd_font_path): - builtin_nerd_font_descriptor = set_builtin_nerd_font(builtin_nerd_font_path) - else: - log_error(f'No builtin NERD font found in {fonts_dir}') + font_map, symbol_fonts, nerd_font = finish_font_files_selection(opts) + if add_builtin_nerd_font and nerd_font is not None: + builtin_nerd_font_descriptor = nerd_font faces: list[tuple[FontObject, bool, bool]] = [ (font_map['medium'], False, False), (font_map['bold'], True, False), @@ -225,7 +218,14 @@ def set_font_family(opts: Options | None = None, override_font_size: float | Non ns = create_narrow_symbols(opts) current_faces = [] pending_selection = opts, families, add_builtin_nerd_font - start_font_files_selection(opts, families, threaded) + builtin_nerd_font_path = '' + if add_builtin_nerd_font: + # The builtin NERD font is prepared by the font selection thread too + builtin_nerd_font_path = os.path.join(fonts_dir, 'SymbolsNerdFontMono-Regular.ttf') + if not os.path.exists(builtin_nerd_font_path): + log_error(f'No builtin NERD font found in {fonts_dir}') + builtin_nerd_font_path = '' + start_font_files_selection(opts, families, threaded, builtin_nerd_font_path) # The descriptors for the bold, italic and bold-italic faces are at indices 1, 2 and 3 set_font_data(descriptor_for_idx, 1, 2, 3, len(families), sm, sz, ns) diff --git a/kitty_tests/fonts.py b/kitty_tests/fonts.py index bab94e262..e26598459 100644 --- a/kitty_tests/fonts.py +++ b/kitty_tests/fonts.py @@ -222,7 +222,8 @@ class Selection(BaseTest): self.ae(expected, keys(threaded(opts)[0])) # Fonts for symbol_map symbol_families = ('monospace', families[0]) if is_macos else ('monospace', families[0], 'NoSuchFontXYZ') - ff, symbols = threaded(opts, symbol_families) + ff, symbols, nerd_font = threaded(opts, symbol_families) + self.assertIsNone(nerd_font) self.ae(expected, keys(ff)) self.ae(len(symbols), len(symbol_families)) for d, bold, italic in symbols: @@ -235,6 +236,37 @@ class Selection(BaseTest): for x in ('medium', 'bold', 'italic', 'bi'): self.ae(ff[x].get('features'), (ParsedFontFeature('+zero'),)) + def test_builtin_nerd_font(self): + # The builtin NERD font is prepared by the font selection thread and is + # used for symbol_map entries for it and for fallback + from kitty.constants import fonts_dir + from kitty.fast_data_types import create_test_font_group, set_send_sprite_to_gpu, sprite_map_set_limits + from kitty.fonts import render + + path = os.path.join(fonts_dir, 'SymbolsNerdFontMono-Regular.ttf') + if not os.path.exists(path): + self.skipTest('The builtin NERD font is not present') + opts = self.set_options({'symbol_map': {(0xE0B0, 0xE0B0): 'Symbols Nerd Font Mono'}}) + sprite_map_set_limits(100000, 100) + set_send_sprite_to_gpu(lambda *a: None) + try: + render.set_font_family(opts, add_builtin_nerd_font=True, threaded=True) + create_test_font_group(11.0, 96.0, 96.0) # uses the results of the selection + d = render.builtin_nerd_font_descriptor + self.assertIsNotNone(d) + self.ae(d['path'], path) # type: ignore + self.ae(len(render.current_faces), 5) + self.ae(face_from_descriptor(render.current_faces[4][0]).postscript_name(), 'SymbolsNFM') # type: ignore + # The builtin NERD font is used for fallback for NERD font icons, + # unless a font installed on the system has them, which is preferred + face = get_fallback_font('\U000f0001', False, False) + if face.path != path: + self.assertIn('NerdFont', os.path.basename(face.path), f'Unexpected fallback font for a NERD font icon: {face.path}') + else: + self.ae(face.postscript_name(), 'SymbolsNFM') + finally: + set_send_sprite_to_gpu(None) + def test_variable_data_from_font_file(self): # The pure C reading of variable font data used by font selection must # match the data read via the platform font APIs