Created
April 25, 2019 10:35
Revisions
-
NyxCode created this gist
Apr 25, 2019 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal 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" }