Created
April 25, 2019 10:35
-
-
Save NyxCode/f26abcda8e888346d6d1ff418b40d3a1 to your computer and use it in GitHub Desktop.
use all fonts available on fonts.google.com in Kotlin JVM applications
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 characters
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" | |
} |
Author
NyxCode
commented
Apr 25, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment