First Commit
[orfont.git] / font.rb
blob3d8608dd22a6204f2b52d9892a6e2d64aeaa8a60
1 #!/usr/bin/ruby
3 # == Synopsis
4 # Handles finding and reading font files.
6 # == Usage
7 # No commandline usage.
9 # ==Author
10 # Tim Dresser
13 require 'ttf'
15 #Handles finding and reading font files.
17 class Font
18   #Recursively searches through a directory for fonts.
19   #
20   def Font.find_in_dir(directory, extensions)
21     paths = []
22     if File.directory?(directory) then
23       Dir.glob("#{directory}/*") do |file|
24         next if file[0] == ?. 
25         if File.directory? file 
26           paths.push(*Font.find_in_dir(file, extensions))
27         elsif font?(file, extensions)
28           paths.push(file)
29         end
30       end
31     end
32     return paths
33   end
34   
35   #Recursively searches through an array of directories for fonts.
36   #
37   def Font.find(directories, extensions)
38     paths = []
39     directories.each do |directory|
40       paths.push(Font.find_in_dir(directory, extensions))
41     end
42     return paths.flatten
43   end
45   #Get metadata from a TTF file.
46   #Indexes used are:
47   #
48   # * 0 Copyright 
49   # * 1 Family 
50   # * 2 Subfamily 
51   # * 4 Full Name 
52   # * 8 Foundry 
53   # * 10 Description 
54   # * 14 License URL 
55   # * 19 Default Text 
56   #
57   def Font.meta(path)
58         #FIXME 
59         #Stop using this library, its slow and bulky for what needs to be done.
60         font = FontTTF::TTF::File.new(path)
61         meta = font.get_table(:name).name_records.values_at(0,1,2,4,8,10,14,19)
62         meta.collect!{|meta_item|
63           #Clean up metadata
64           
65           #Escape nasty characters, get rid of quotation marks around data,
66           #replace ' with '', remove trailing and leading whitespace,
67           #get rid of successive spaces
68           meta_item.to_s.dump.gsub("\\000","")[1..-2].gsub("'","''") \
69             .gsub(/^\s+/, "").gsub(/\s+$/, $/).gsub(/ +/," ")
70         }
71         return meta
72   end
73   
74   private
76     #Returns true if a path has one of the given extensions.
77     #
78     def Font.font?(path, extensions)
79       extensions.each do |extension|
80         if path[-extension.length..-1] == extension then
81           return true
82         end
83       end
84       return false
85     end
86 end