require "dl/import"
require "dl/struct"

module FontList
  module FontConfig
    extend DL::Importable
    dlload "libfontconfig.so"

    FcFontSet = struct ["int nfont", "int sfont", "FcPattern** fonts"]
    FNAME = struct ["char* str"]
    
    extern "FcPattern* FcPatternCreate()"
    extern "void FcPatternDestroy(FcPattern*)"
    extern "void FcDefaultSubstitute(FcPattern*)"
    extern "FcFontSet* FcFontSort(void*, FcPattern*, int, void*, int*)"
    extern "int FcPatternGetString(FcPattern*, char*, int, void*)"
    extern "void FcFontSetDestroy(FcFontSet*)"
  end

  module_function
  def fontfiles
    ary = []
    pat = FontConfig.fcPatternCreate
    FontConfig.fcDefaultSubstitute(pat)
    fs = FontConfig::FcFontSet.new(FontConfig.fcFontSort(nil, pat, 1, nil, nil))
    FontConfig.fcPatternDestroy(pat)

    fname = DL.malloc(DL.sizeof("P"))
    FontConfig.fcPatternGetString(fs.fonts.ptr, "file", 0, fname)
    ptrsize = DL.sizeof("P")
    fs.nfont.times do |i|
      FontConfig.fcPatternGetString((fs.fonts+ptrsize*i).ptr, "file", 0, fname)
      ary <<  fname.ptr.to_s
    end
    FontConfig.fcFontSetDestroy(fs)
    return ary
  end
end

if __FILE__ == $0
  puts FontList.fontfiles
end
