Skip to content

Commit

Permalink
Add threshold option to is_monospace method.
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiocaccamo committed Aug 5, 2024
1 parent a061715 commit 8030ba8
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,9 @@ width = font.get_width()
"""
Determines if the font is a monospace font.
:param threshold: The threshold (0.0 <= n <= 1.0) of glyphs with the same width to consider the font as monospace.
:type threshold: float
:returns: True if monospace font, False otherwise.
:rtype: bool
"""
Expand Down
13 changes: 11 additions & 2 deletions fontbro/font.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import re
import sys
import tempfile
from collections import Counter
from curses import ascii
from io import BytesIO
from pathlib import Path
Expand Down Expand Up @@ -1396,16 +1397,24 @@ def get_width(

def is_monospace(
self,
threshold: float = 0.85,
) -> bool:
"""
Determines if the font is a monospace font.
:param threshold: The threshold (0.0 <= n <= 1.0) of glyphs with the same width to consider the font as monospace.
:type threshold: float
:returns: True if monospace font, False otherwise.
:rtype: bool
"""
font = self.get_ttfont()
widths = {metrics[0] for metrics in font["hmtx"].metrics.values()}
return len(widths) == 1
widths = [metrics[0] for metrics in font["hmtx"].metrics.values()]
widths_counter = Counter(widths)
same_width_count = widths_counter.most_common(1)[0][1]
same_width_amount = same_width_count / self.get_glyphs_count()
print(same_width_amount)
return same_width_amount >= threshold

def is_static(
self,
Expand Down
2 changes: 1 addition & 1 deletion tests/test_monospace.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def test_is_monospace(self):
with self._get_font("/Inter/static/Inter-Regular.ttf") as font:
self.assertFalse(font.is_monospace())
with self._get_font("/Noto_Sans_TC/NotoSansTC-Regular.otf") as font:
self.assertFalse(font.is_monospace())
self.assertTrue(font.is_monospace())
with self._get_font("/Open_Sans/static/OpenSans-Regular.ttf") as font:
self.assertFalse(font.is_monospace())
with self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf") as font:
Expand Down

0 comments on commit 8030ba8

Please sign in to comment.