Skip to content

Instantly share code, notes, and snippets.

@NyxCode
Created April 25, 2019 10:35

Revisions

  1. NyxCode created this gist Apr 25, 2019.
    69 changes: 69 additions & 0 deletions AutoFont.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    import org.apache.commons.io.FileUtils
    import java.awt.Font
    import java.awt.GraphicsEnvironment
    import java.io.File
    import java.io.FileNotFoundException
    import java.net.URL

    private const val FONTS_REPOSITORY = "https://github.com/google/fonts/raw/master"
    private val LICENSES = arrayOf("apache", "ofl", "ufl")
    private val SANITIZE_EXPR = Regex("\\W+")

    enum class Emphasis {
    Regular,
    Bold,
    Italic,
    Light,
    Medium,
    Thin,
    Black
    }

    fun installFont(name: String, vararg emphasis: Emphasis) {
    print("Downloading Font..")
    val file = downloadFont(_fontName = name, emphasis = *emphasis)
    print("Installing Font..")
    GraphicsEnvironment
    .getLocalGraphicsEnvironment()
    .registerFont(Font.createFont(Font.TRUETYPE_FONT, file))
    print("Done!")
    }

    fun downloadFont(directory: File = createTempDir(), _fontName: String, vararg emphasis: Emphasis): File {
    assert(directory.isDirectory) { "$directory is not a directory" }

    val fontName = _fontName.replace(SANITIZE_EXPR, "")

    val fileName = constructFilename(fontName, *emphasis)

    val targetFile = File(directory, fileName)
    if (targetFile.isFile) {
    println("$targetFile already exists, skipping download")
    return targetFile
    }

    for (license in LICENSES) {
    try {
    val url = URL("$FONTS_REPOSITORY/$license/${fontName.toLowerCase()}/$fileName")
    FileUtils.copyURLToFile(url, targetFile)
    return targetFile
    } catch (_: FileNotFoundException) {
    // Ignore
    }
    }

    throw FileNotFoundException()
    }

    private fun constructFilename(sanitizedName: String, vararg emphasis: Emphasis): String {
    val emphasisStr = if (emphasis.isEmpty()) {
    "Regular"
    } else {
    emphasis
    .distinct()
    .map(Emphasis::name)
    .joinToString(separator = "")
    }

    return "$sanitizedName-$emphasisStr.ttf"
    }