Skip to content

Instantly share code, notes, and snippets.

@phoenixenero
Last active December 7, 2015 08:23
Show Gist options
  • Save phoenixenero/c8d40a390bb1acabcf9c to your computer and use it in GitHub Desktop.
Save phoenixenero/c8d40a390bb1acabcf9c to your computer and use it in GitHub Desktop.
Get available chars
#!/usr/bin/env ruby
require 'optparse'
# Get available characters
#
# Written by Phoenix Enero.
#
# It takes a font input in OTF/TTF format and returns a text file with the
# cmap.
## Lets start!
stopwatch_start = Time.now
# Option handling
options = {:extension => '.unc', :pattern => '*.woff'}
OptionParser.new do |o|
o.banner = "Usage: get-available-chars.rb [options]"
o.on("-f", "--files [FILES]", "The file path or glob pattern") do |pattern|
options[:pattern] = pattern
end
o.on("-x", "--extension [EXTENSION]", "The extension for the output file(s).") do |ext|
options[:extension] = ext || '.unc'
# Ensure extension begins with dot `.`
options[:extension].sub!(/\A\.?(?=.)/, ".")
end
end.parse!
files = Dir.glob( options[:pattern] )
# Make a .ttx file containing only the CMAP
def make_cmap_ttx( name, source )
# puts "ttx -f -o #{name} -t cmap #{source}"
system *%W(ttx -f -o #{name} -t cmap #{source})
# Check if it worked
if ! File.file?( name )
raise "Failed to create ttx cmap `#{name}`"
exit
end
end
# Return all hexadecimal values starting with `0x` without including `0x`
def grab_hex( str )
return str.scan( /(?<=0[xX])([0-9a-fA-F]+)/ )
end
# Now we loop
files.each do |font|
font_name = File.basename( font )
font_base_name = File.basename( font, ".*" )
# Make a temporary .ttx file containing only the cmap
temp_name = "__#{Time.now.to_i.to_s}.cmap.ttx"
make_cmap_ttx( temp_name, font )
# Grab the temp file's contents
temp = File.read( temp_name )
# Get the Unicode values from the XML file
# Assumptions: UTF strings begin with '0x'
characters = grab_hex( temp )
# delete temp file
File.delete( temp_name )
# Make an output file with the same name and dir as the font file
output = File.open( File.join(File.dirname(font), File.basename(font, '.*')) + options[:extension], "w" );
# Output the unicode values line-by-line
output << characters.join( "\n" )
output.close
end
# And we're done!
stopwatch_finish = Time.now
stopwatch_delta = stopwatch_finish - stopwatch_start
puts "Finished in #{stopwatch_delta}s"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment