Class: Fontisan::SfntFont Abstract
- Inherits:
-
BinData::Record
- Object
- BinData::Record
- Fontisan::SfntFont
- Defined in:
- lib/fontisan/sfnt_font.rb
Overview
Subclasses must implement format-specific validation
Base class for SFNT font formats (TrueType and OpenType)
This class contains all shared SFNT structure and behavior. TrueType and OpenType fonts inherit from this class and add format-specific functionality.
Direct Known Subclasses
Constant Summary collapse
- TABLE_CLASS_MAP =
Map table tag to parser class (cached as constant for performance)
{ Constants::HEAD_TAG => Tables::Head, Constants::HHEA_TAG => Tables::Hhea, Constants::HMTX_TAG => Tables::Hmtx, Constants::MAXP_TAG => Tables::Maxp, Constants::NAME_TAG => Tables::Name, Constants::OS2_TAG => Tables::Os2, Constants::POST_TAG => Tables::Post, Constants::CMAP_TAG => Tables::Cmap, Constants::FVAR_TAG => Tables::Fvar, Constants::GSUB_TAG => Tables::Gsub, Constants::GPOS_TAG => Tables::Gpos, Constants::GLYF_TAG => Tables::Glyf, Constants::LOCA_TAG => Tables::Loca, "SVG " => Tables::Svg, "COLR" => Tables::Colr, "CPAL" => Tables::Cpal, "CBDT" => Tables::Cbdt, "CBLC" => Tables::Cblc, "sbix" => Tables::Sbix, }.freeze
- SFNT_TABLE_CLASS_MAP =
Map table tag to SfntTable wrapper class (cached as constant for performance)
{ Constants::HEAD_TAG => Tables::HeadTable, Constants::NAME_TAG => Tables::NameTable, Constants::OS2_TAG => Tables::Os2Table, Constants::CMAP_TAG => Tables::CmapTable, Constants::GLYF_TAG => Tables::GlyfTable, Constants::HHEA_TAG => Tables::HheaTable, Constants::MAXP_TAG => Tables::MaxpTable, Constants::POST_TAG => Tables::PostTable, Constants::HMTX_TAG => Tables::HmtxTable, Constants::LOCA_TAG => Tables::LocaTable, }.freeze
- PADDING_BYTES =
Padding bytes for table alignment (frozen to avoid reallocation)
("\x00" * 4).freeze
Instance Attribute Summary collapse
-
#io_source ⇒ Object
IO source for lazy loading.
-
#lazy_load_enabled ⇒ Object
Whether lazy loading is enabled.
-
#loading_mode ⇒ Object
Loading mode for this font (:metadata or :full).
-
#parsed_tables ⇒ Object
Parsed table instances cache.
-
#sfnt_tables ⇒ Object
OOP SfntTable instances (tag => SfntTable).
-
#table_data ⇒ Object
Table data is stored separately since it's at variable offsets.
-
#table_entry_cache ⇒ Object
Table entry lookup cache (tag => TableDirectory).
Class Method Summary collapse
-
.finalize(io) ⇒ Proc
Finalizer proc for closing IO.
-
.from_collection(io, offset, mode: LoadingModes::FULL) ⇒ SfntFont
Read SFNT Font from collection at specific offset.
-
.from_file(path, mode: LoadingModes::FULL, lazy: false) ⇒ SfntFont
Read SFNT Font from a file.
Instance Method Summary collapse
-
#all_sfnt_tables ⇒ Hash<String, SfntTable>
Get all SfntTable instances.
-
#close ⇒ void
Close the IO source (for lazy loading).
-
#collection? ⇒ Boolean
Whether this object represents a font collection rather than a single font.
-
#family_name ⇒ String?
Get font family name.
-
#find_table_entry(tag) ⇒ TableDirectory?
Find a table entry by tag (cached for performance).
-
#full_name ⇒ String?
Get full font name.
-
#has_table?(tag) ⇒ Boolean
Check if font has a specific table (optimized with cache).
-
#head_table ⇒ TableDirectory?
Get the head table entry.
-
#initialize_storage ⇒ void
Initialize storage hashes.
-
#outline_type ⇒ Symbol
Outline representation used by the font.
-
#post_script_name ⇒ String?
Get PostScript name.
-
#preferred_family_name ⇒ String?
Get preferred family name.
-
#preferred_subfamily_name ⇒ String?
Get preferred subfamily name.
-
#read_metadata_tables_batched(io) ⇒ void
Read metadata tables using page-aware batching.
-
#read_table_data(io) ⇒ void
Read table data for all tables in the font.
-
#setup_finalizer ⇒ void
Setup finalizer for cleanup.
-
#sfnt_table(tag) ⇒ SfntTable?
Get OOP SfntTable instance for a table.
-
#subfamily_name ⇒ String?
Get font subfamily name (e.g., Regular, Bold, Italic).
-
#table(tag) ⇒ Tables::*?
Get parsed table instance.
-
#table_available?(tag) ⇒ Boolean
Check if a table is available in the current loading mode.
-
#table_names ⇒ Array<String>
Get list of all table tags (cached for performance).
-
#to_file(path) ⇒ Integer
Write SFNT Font to a file.
-
#units_per_em ⇒ Integer?
Get units per em from head table.
-
#update_checksum_adjustment_in_file(path, head_offset) ⇒ void
Update checksum adjustment in head table by file path.
-
#update_checksum_adjustment_in_io(io, head_offset) ⇒ void
Update checksum adjustment in head table using IO.
-
#valid? ⇒ Boolean
Validate format correctness.
-
#variation_type ⇒ Symbol
Variation profile of the font, derived from its table set.
Instance Attribute Details
#io_source ⇒ Object
IO source for lazy loading
86 87 88 |
# File 'lib/fontisan/sfnt_font.rb', line 86 def io_source @io_source end |
#lazy_load_enabled ⇒ Object
Whether lazy loading is enabled
89 90 91 |
# File 'lib/fontisan/sfnt_font.rb', line 89 def lazy_load_enabled @lazy_load_enabled end |
#loading_mode ⇒ Object
Loading mode for this font (:metadata or :full)
83 84 85 |
# File 'lib/fontisan/sfnt_font.rb', line 83 def loading_mode @loading_mode end |
#parsed_tables ⇒ Object
Parsed table instances cache
74 75 76 |
# File 'lib/fontisan/sfnt_font.rb', line 74 def parsed_tables @parsed_tables end |
#sfnt_tables ⇒ Object
OOP SfntTable instances (tag => SfntTable)
77 78 79 |
# File 'lib/fontisan/sfnt_font.rb', line 77 def sfnt_tables @sfnt_tables end |
#table_data ⇒ Object
Table data is stored separately since it's at variable offsets. The setter normalizes all keys to UTF-8 so Hash lookups don't silently miss due to encoding mismatch — BinData-derived tag strings are ASCII-8BIT, literals callers pass are usually UTF-8, and String#eql? is encoding-sensitive.
67 68 69 |
# File 'lib/fontisan/sfnt_font.rb', line 67 def table_data @table_data end |
#table_entry_cache ⇒ Object
Table entry lookup cache (tag => TableDirectory)
80 81 82 |
# File 'lib/fontisan/sfnt_font.rb', line 80 def table_entry_cache @table_entry_cache end |
Class Method Details
.finalize(io) ⇒ Proc
Finalizer proc for closing IO
587 588 589 |
# File 'lib/fontisan/sfnt_font.rb', line 587 def self.finalize(io) proc { io&.close } end |
.from_collection(io, offset, mode: LoadingModes::FULL) ⇒ SfntFont
Read SFNT Font from collection at specific offset
202 203 204 205 206 207 208 209 210 211 |
# File 'lib/fontisan/sfnt_font.rb', line 202 def self.from_collection(io, offset, mode: LoadingModes::FULL) LoadingModes.validate_mode!(mode) io.seek(offset) font = read(io) font.initialize_storage font.loading_mode = mode font.read_table_data(io) font end |
.from_file(path, mode: LoadingModes::FULL, lazy: false) ⇒ SfntFont
Read SFNT Font from a file
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
# File 'lib/fontisan/sfnt_font.rb', line 144 def self.from_file(path, mode: LoadingModes::FULL, lazy: false) if path.nil? || path.to_s.empty? raise ArgumentError, "path cannot be nil or empty" end raise Errno::ENOENT, "File not found: #{path}" unless File.exist?(path) LoadingModes.validate_mode!(mode) font = new font.initialize_storage font.loading_mode = mode font.lazy_load_enabled = lazy lazy ? load_lazy(path, font) : load_eager(path, font) end |
Instance Method Details
#all_sfnt_tables ⇒ Hash<String, SfntTable>
Get all SfntTable instances
473 474 475 |
# File 'lib/fontisan/sfnt_font.rb', line 473 def all_sfnt_tables table_names.to_h { |tag| [tag, sfnt_table(tag)] } end |
#close ⇒ void
This method returns an undefined value.
Close the IO source (for lazy loading)
571 572 573 574 |
# File 'lib/fontisan/sfnt_font.rb', line 571 def close @io_source&.close @io_source = nil end |
#collection? ⇒ Boolean
Whether this object represents a font collection rather than a single font. Each font class is the authority on this question.
378 |
# File 'lib/fontisan/sfnt_font.rb', line 378 def collection? = false |
#family_name ⇒ String?
Get font family name
523 524 525 526 |
# File 'lib/fontisan/sfnt_font.rb', line 523 def family_name name_table = table(Constants::NAME_TAG) name_table&.english_name(Tables::Name::FAMILY) end |
#find_table_entry(tag) ⇒ TableDirectory?
Find a table entry by tag (cached for performance)
417 418 419 420 421 422 423 |
# File 'lib/fontisan/sfnt_font.rb', line 417 def find_table_entry(tag) return @table_entry_cache[tag] if @table_entry_cache.key?(tag) entry = tables.find { |entry| entry.tag == tag } @table_entry_cache[tag] = entry entry end |
#full_name ⇒ String?
Get full font name
539 540 541 542 |
# File 'lib/fontisan/sfnt_font.rb', line 539 def full_name name_table = table(Constants::NAME_TAG) name_table&.english_name(Tables::Name::FULL_NAME) end |
#has_table?(tag) ⇒ Boolean
Check if font has a specific table (optimized with cache)
370 371 372 |
# File 'lib/fontisan/sfnt_font.rb', line 370 def has_table?(tag) !find_table_entry(tag).nil? end |
#head_table ⇒ TableDirectory?
Get the head table entry
428 429 430 |
# File 'lib/fontisan/sfnt_font.rb', line 428 def head_table find_table_entry(Constants::HEAD_TAG) end |
#initialize_storage ⇒ void
This method returns an undefined value.
Initialize storage hashes
216 217 218 219 220 221 222 223 224 225 226 |
# File 'lib/fontisan/sfnt_font.rb', line 216 def initialize_storage @table_data = {} @parsed_tables = {} @sfnt_tables = {} @table_entry_cache = {} @tag_encoding_cache = {} # Cache for normalized tag encodings @table_names = nil # Cache for table names array @loading_mode = LoadingModes::FULL @lazy_load_enabled = false @io_source = nil end |
#outline_type ⇒ Symbol
Outline representation used by the font. Derived from the table set.
396 397 398 399 400 401 |
# File 'lib/fontisan/sfnt_font.rb', line 396 def outline_type return :truetype if has_table?("glyf") || has_table?("gvar") return :cff if has_table?("CFF ") || has_table?("CFF2") :unknown end |
#post_script_name ⇒ String?
Get PostScript name
547 548 549 550 |
# File 'lib/fontisan/sfnt_font.rb', line 547 def post_script_name name_table = table(Constants::NAME_TAG) name_table&.english_name(Tables::Name::POSTSCRIPT_NAME) end |
#preferred_family_name ⇒ String?
Get preferred family name
555 556 557 558 |
# File 'lib/fontisan/sfnt_font.rb', line 555 def preferred_family_name name_table = table(Constants::NAME_TAG) name_table&.english_name(Tables::Name::PREFERRED_FAMILY) end |
#preferred_subfamily_name ⇒ String?
Get preferred subfamily name
563 564 565 566 |
# File 'lib/fontisan/sfnt_font.rb', line 563 def preferred_subfamily_name name_table = table(Constants::NAME_TAG) name_table&.english_name(Tables::Name::PREFERRED_SUBFAMILY) end |
#read_metadata_tables_batched(io) ⇒ void
This method returns an undefined value.
Read metadata tables using page-aware batching
Groups adjacent tables within page boundaries and reads them together to maximize filesystem prefetching and minimize random seeks.
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 |
# File 'lib/fontisan/sfnt_font.rb', line 266 def (io) # Typical filesystem page size (4KB is common, but 8KB gives better prefetch window) page_threshold = 8192 # Get metadata tables sorted by offset for sequential access = tables.select { |entry| LoadingModes::METADATA_TABLES_SET.include?(entry.tag) } .sort_by!(&:offset) return if .empty? # Group adjacent tables within page threshold for batched reading i = 0 while i < .size batch_start = [i] batch_end = batch_start batch_entries = [batch_start] # Extend batch while next table is within page threshold j = i + 1 while j < .size next_entry = [j] gap = next_entry.offset - (batch_end.offset + batch_end.table_length) # If gap is small (within page threshold), include in batch if gap <= page_threshold batch_end = next_entry batch_entries << next_entry j += 1 else break end end # Read batch if batch_entries.size == 1 # Single table, read normally io.seek(batch_start.offset) tag_key = normalize_tag(batch_start.tag) @table_data[tag_key] = io.read(batch_start.table_length) else # Multiple tables, read contiguous segment batch_offset = batch_start.offset batch_length = (batch_end.offset + batch_end.table_length) - batch_start.offset io.seek(batch_offset) batch_data = io.read(batch_length) # Extract individual tables from batch batch_entries.each do |entry| relative_offset = entry.offset - batch_offset tag_key = normalize_tag(entry.tag) @table_data[tag_key] = batch_data[relative_offset, entry.table_length] end end i = j end end |
#read_table_data(io) ⇒ void
This method returns an undefined value.
Read table data for all tables in the font
In metadata mode, only reads metadata tables. In full mode, reads all tables. In lazy load mode, doesn't read data upfront.
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 |
# File 'lib/fontisan/sfnt_font.rb', line 235 def read_table_data(io) @table_data = {} if @lazy_load_enabled # Don't read data, just keep IO reference @io_source = io return end if @loading_mode == LoadingModes::METADATA # Only read metadata tables for performance # Use page-aware batched reading to maximize filesystem prefetching (io) else # Read all tables tables.each do |entry| io.seek(entry.offset) # Normalize tag encoding for hash key consistency tag_key = normalize_tag(entry.tag) @table_data[tag_key] = io.read(entry.table_length) end end end |
#setup_finalizer ⇒ void
This method returns an undefined value.
Setup finalizer for cleanup
579 580 581 |
# File 'lib/fontisan/sfnt_font.rb', line 579 def setup_finalizer ObjectSpace.define_finalizer(self, self.class.finalize(@io_source)) end |
#sfnt_table(tag) ⇒ SfntTable?
Get OOP SfntTable instance for a table
Returns a SfntTable (or subclass) instance that encapsulates the table's metadata, lazy loading, parsing, and validation. This provides a more object-oriented interface than the separate TableDirectory/@table_data/@parsed_tables approach.
458 459 460 461 462 463 464 465 466 467 468 |
# File 'lib/fontisan/sfnt_font.rb', line 458 def sfnt_table(tag) # Return cached instance if available (fast path) cached = @sfnt_tables[tag] return cached if cached # Only check has_table? if not cached (avoids redundant lookup) return nil unless has_table?(tag) # Create and cache (find_table_entry is already cached internally) @sfnt_tables[tag] = create_sfnt_table(tag) end |
#subfamily_name ⇒ String?
Get font subfamily name (e.g., Regular, Bold, Italic)
531 532 533 534 |
# File 'lib/fontisan/sfnt_font.rb', line 531 def subfamily_name name_table = table(Constants::NAME_TAG) name_table&.english_name(Tables::Name::SUBFAMILY) end |
#table(tag) ⇒ Tables::*?
Get parsed table instance
This method parses the raw table data into a structured table object and caches the result for subsequent calls. Enforces mode restrictions.
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 |
# File 'lib/fontisan/sfnt_font.rb', line 485 def table(tag) tag = normalize_tag(tag) # Check mode restrictions unless table_available?(tag) if has_table?(tag) raise ArgumentError, "Table '#{tag}' is not available in #{@loading_mode} mode. " \ "Available tables: #{LoadingModes.tables_for(@loading_mode).inspect}" else return nil end end # Return cached if available (fast path) return @parsed_tables[tag] if @parsed_tables.key?(tag) # Lazy load table data if enabled load_table_data(tag) if @lazy_load_enabled && !@table_data.key?(tag) # Parse and cache @parsed_tables[tag] ||= parse_table(tag) end |
#table_available?(tag) ⇒ Boolean
Check if a table is available in the current loading mode
407 408 409 410 411 |
# File 'lib/fontisan/sfnt_font.rb', line 407 def table_available?(tag) return false unless has_table?(tag) LoadingModes.table_allowed?(@loading_mode, tag) end |
#table_names ⇒ Array<String>
Get list of all table tags (cached for performance)
Returns plain UTF-8 Ruby Strings, not BinData::String instances —
callers can rely on eql?/==/Hash lookup working against literal
strings. BinData::String is encoding-sensitive and breaks Hash key
comparison silently.
440 441 442 |
# File 'lib/fontisan/sfnt_font.rb', line 440 def table_names @table_names ||= tables.map { |entry| normalize_tag(entry.tag) } end |
#to_file(path) ⇒ Integer
Write SFNT Font to a file
Writes the complete font structure to disk, including proper checksum calculation and table alignment.
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 |
# File 'lib/fontisan/sfnt_font.rb', line 334 def to_file(path) File.open(path, "w+b") do |io| # Write header and tables (directory) write_structure(io) # Write table data with updated offsets write_table_data_with_offsets(io) # Update checksum adjustment in head table BEFORE closing file # This avoids Windows file locking issues when Tempfiles are used head = head_table update_checksum_adjustment_in_io(io, head.offset) if head io.pos end File.size(path) end |
#units_per_em ⇒ Integer?
Get units per em from head table
512 513 514 515 |
# File 'lib/fontisan/sfnt_font.rb', line 512 def units_per_em head = table(Constants::HEAD_TAG) head&.units_per_em end |
#update_checksum_adjustment_in_file(path, head_offset) ⇒ void
This method returns an undefined value.
Update checksum adjustment in head table by file path
Opens the file, calculates the checksum, and updates the adjustment.
614 615 616 617 618 |
# File 'lib/fontisan/sfnt_font.rb', line 614 def update_checksum_adjustment_in_file(path, head_offset) File.open(path, "r+b") do |io| update_checksum_adjustment_in_io(io, head_offset) end end |
#update_checksum_adjustment_in_io(io, head_offset) ⇒ void
This method returns an undefined value.
Update checksum adjustment in head table using IO
Calculates the checksum of the entire file and writes the adjustment value to the head table's checksumAdjustment field.
599 600 601 602 603 604 605 |
# File 'lib/fontisan/sfnt_font.rb', line 599 def update_checksum_adjustment_in_io(io, head_offset) io.rewind checksum = Utilities::ChecksumCalculator.calculate_checksum_from_io(io) adjustment = Utilities::ChecksumCalculator.calculate_adjustment(checksum) io.seek(head_offset + 8) io.write([adjustment].pack("N")) end |
#valid? ⇒ Boolean
Validate format correctness
356 357 358 359 360 361 362 363 364 |
# File 'lib/fontisan/sfnt_font.rb', line 356 def valid? return false unless header return false unless tables.respond_to?(:length) return false unless @table_data.is_a?(Hash) return false if tables.length != header.num_tables return false unless head_table true end |
#variation_type ⇒ Symbol
Variation profile of the font, derived from its table set. Used by the conversion pipeline to choose between preserving variation tables and generating a static instance.
385 386 387 388 389 390 391 |
# File 'lib/fontisan/sfnt_font.rb', line 385 def variation_type return :static unless has_table?("fvar") return :gvar if has_table?("gvar") return :cff2 if has_table?("CFF2") :static end |