Last active
June 23, 2021 22:04
-
-
Save zetashift/02a82e4c2e97ba3c2aa45e30e3fb2104 to your computer and use it in GitHub Desktop.
Fontim, cross platform font path finding in Nim
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, strformat, options | |
## Get the locations(paths) of a given `font` in a string | |
func getFontsDir(): seq[string] = | |
when defined(windows): | |
# TODO use winim to get Windows installation location | |
result = @[r"C:\Windows\Fonts\"] | |
elif defined(macosx): | |
result = @[r"/Library/Fonts"] | |
elif defined(linux): | |
# Might also be possible to leverage libfontconfig here | |
result = @[ | |
"/usr/share/fonts/truetype/", | |
"/usr/share/fonts/TTF/", | |
"/usr/share/fonts/" | |
] | |
proc getFontPath*(name: string, slant = "Sans", suffix = "-Regular"): Option[string] = | |
## Returns the path of a font | |
let | |
fontDir = getFontsDir() | |
fontName = fmt"{name}{slant}{suffix}.ttf" | |
for dir in fontDir: | |
# Iterate over all the files in the font directories | |
for filePath in dir.walkDirRec: | |
echo filePath.extractFilename | |
# Check if the filename matches, if so we found our font file! | |
if filePath.extractFilename == fontName: | |
echo filePath | |
return some(filePath) | |
# In case we didn't find anything | |
result = none[string]() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# To run these tests, simply execute `nimble test`. | |
import unittest, options | |
import fontim | |
test "finds Noto Regular": | |
assert getFontPath("Noto") == some("/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf") | |
test "find IBM Plex Mono Bold": | |
assert getFontPath(name = "IBMPlex", slant= "Mono", suffix="-Bold") == some("/usr/share/fonts/truetype/ibm-plex/IBMPlexMono-Bold.ttf") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment