Skip to content

Commit 51ef2e4

Browse files
committed
add cache mechanism
1 parent b7d6d65 commit 51ef2e4

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

src/findfonts.jl

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -121,12 +121,15 @@ end
121121

122122
fontname(ft::FTFont) = "$(family_name(ft)) $(style_name(ft))"
123123

124+
const FONT_CACHE = Dict{String, Tuple{String,FTFont}}()
125+
124126
function findfont(
125127
searchstring::String;
126128
italic::Bool=false, # this is unused in the new implementation
127129
bold::Bool=false, # and this as well
128130
additional_fonts::String=""
129131
)
132+
(path_ft = get(FONT_CACHE, searchstring, nothing)) !== nothing && return path_ft
130133
font_folders = copy(fontpaths())
131134

132135
isempty(additional_fonts) || pushfirst!(font_folders, additional_fonts)
@@ -135,6 +138,7 @@ function findfont(
135138
searchparts = unique(split(lowercase(searchstring), r"\W+", keepempty=false))
136139

137140
best_score_so_far = (0, 0, false, typemin(Int))
141+
best_font_path = ""
138142
best_font = nothing
139143

140144
for folder in font_folders
@@ -144,7 +148,6 @@ function findfont(
144148
face === nothing && continue
145149

146150
score = match_font(face, searchparts)
147-
148151
# we can compare all four tuple elements of the score at once
149152
# in order of importance:
150153

@@ -156,18 +159,17 @@ function findfont(
156159
family_match_score = score[1]
157160
if family_match_score > 0 && score > best_score_so_far
158161
# finalize previous best font to close the font file
159-
if !isnothing(best_font)
160-
finalize(best_font)
161-
end
162+
isnothing(best_font) || finalize(best_font)
162163

163164
# new candidate
165+
best_font_path = fpath
164166
best_font = face
165167
best_score_so_far = score
166168
else
167169
finalize(face)
168170
end
169171
end
170172
end
171-
172-
return best_font
173+
best_font === nothing || (FONT_CACHE[searchstring] = (best_font_path, best_font))
174+
return (best_font_path, best_font)
173175
end

0 commit comments

Comments
 (0)