Something went wrong. Try again.
Fork of dvui, the immediate-mode Zig GUI, with a font face index for Pipit
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542const std = @import("std");const dvui = @import("dvui.zig");const c = dvui.c;
const Rect = dvui.Rect;const Size = dvui.Size;
/// Font represents the parameters that dvui will try to satisfy when rendering/// text. If a matching font is not found, dvui will log an error and use the/// internal fallback font.////// Usually specified with `find`:/// const f: Font = .find(.{ .family = "Vera", .size = 12 });////// To source a Font from the theme, use `theme`:/// const f: Font = .theme(.mono);/// const f = Font.theme(mono).larger(2);const Font = @This();
pub const DefaultSize = 10;
pub const Error = error{FontError};pub const NAME_MAX_LEN = 50;
pub fn array(s: []const u8) [NAME_MAX_LEN:0]u8 { var v: [NAME_MAX_LEN:0]u8 = @splat(0); @memcpy(v[0..s.len], s); return v;}
pub fn string(s: *const [NAME_MAX_LEN:0]u8) [:0]const u8 { return std.mem.sliceTo(s, 0);}
pub const Weight = enum { normal, bold,};
pub const Style = enum { normal, italic,};
pub const Underline = struct { /// Percent of font size, will always be at least 1 logical pixel thick: f32 = 0.1,};
pub const Strike = struct { /// Percent of font size, will always be at least 1 logical pixel thick: f32 = 0.1,};
/// Changing any of these might query for a font.family: [NAME_MAX_LEN:0]u8 = @splat(0),
/// Height of a capital M in logical pixels. After converting to physical/// pixels, the font will have an integer M height <= size.size: f32 = DefaultSize,weight: Weight = .normal,style: Style = .normal,
/// Can be changed for any font, no query.line_height_factor: f32 = 1.2,underline: ?Underline = null,strike: ?Strike = null,
pub const FindOptions = struct { family: []const u8,
/// Height of capital M in logical pixels. size: f32 = DefaultSize, weight: Weight = .normal, style: Style = .normal, line_height_factor: f32 = 1.2,};
pub fn find(opts: FindOptions) Font { return (Font{}).withFamily(opts.family).withSize(opts.size).withWeight(opts.weight).withStyle(opts.style).withLineHeight(opts.line_height_factor);}
pub const ThemeFontName = enum { body, heading, title, mono,};
pub fn theme(which: ThemeFontName) Font { switch (which) { .body => return dvui.themeGet().font_body, .heading => return dvui.themeGet().font_heading, .title => return dvui.themeGet().font_title, .mono => return dvui.themeGet().font_mono, }}
pub fn withFamily(self: Font, n: []const u8) Font { var r: Font = self; r.family = array(n); return r;}
pub fn withSize(self: Font, s: f32) Font { var r = self; r.size = s; return r;}
pub fn larger(self: Font, ds: f32) Font { var r = self; r.size += ds; return r;}
pub fn withWeight(self: Font, w: Weight) Font { var r = self; r.weight = w; return r;}
pub fn withStyle(self: Font, s: Style) Font { var r = self; r.style = s; return r;}
pub fn withLineHeight(self: Font, factor: f32) Font { var r = self; r.line_height_factor = factor; return r;}
pub fn withUnderline(self: Font, underline: ?Underline) Font { var r = self; r.underline = underline; return r;}
pub fn withStrike(self: Font, strike: ?Strike) Font { var r = self; r.strike = strike; return r;}
pub fn familyName(self: *const Font) []const u8 { return string(&self.family);}
pub fn name(self: *const Font, allocator: std.mem.Allocator) []const u8 { const weight = switch (self.weight) { .normal => "", .bold => " Bold", }; const style = switch (self.style) { .normal => "", .italic => " Italic", }; return std.fmt.allocPrint(allocator, "{s}{s}{s}", .{ self.familyName(), weight, style }) catch "OOM";}
/// Name of underlying Font.Entry. Might be synthesized or fallback (in that/// case findSource returns null).////// Slice is invalidated if that entry is removed.////// Only valid between Window.begin/endpub fn nameEntry(self: *const Font) []const u8 { const entry = dvui.fontCacheGet(self.*) catch return "nameEntry: Error"; return entry.name;}
pub fn format(self: *const Font, writer: *std.Io.Writer) !void { const weight = switch (self.weight) { .normal => "", .bold => " Bold", }; const style = switch (self.style) { .normal => "", .italic => " Italic", }; try writer.print("{s}{s}{s} {d}", .{ self.familyName(), weight, style, self.size });}
/// Fonts that hash the same value use the same glyphs (same Font.Entry).pub fn hash(self: *const Font) u64 { var h = dvui.fnv.init(); h.update(&self.family); h.update(std.mem.asBytes(&self.size)); h.update(std.mem.asBytes(&self.weight)); h.update(std.mem.asBytes(&self.style)); return h.final();}
/// Only valid between Window.begin/endpub fn findSource(self: *const Font) ?Source { const cw = dvui.currentWindow(); return cw.fonts.findSource(self.*).@"0";}
pub const Source = struct { family: [NAME_MAX_LEN:0]u8 = @splat(0), size: f32 = 0, // zero means this source can be any size weight: Weight = .normal, style: Style = .normal,
// currently we assume that a single ttf only produces one bytes: []const u8, // points to ttf bytes /// Which face in `bytes` to use, as FreeType's `FT_Open_Face` takes it: /// the face's index in a collection in the low 16 bits, and for a /// variable font a named instance in the high 16 bits, counted from 1 -- /// so `7 << 16` is the seventh named instance, which for many variable /// fonts is Bold. Zero is the first face at its default instance. /// stb_truetype reads the collection index and ignores the instance. face_index: u32 = 0, /// If not null, this will be used to free ttf_bytes. allocator: ?std.mem.Allocator = null,
pub fn familyName(self: *const Source) []const u8 { return string(&self.family); }
pub fn name(self: *const Source, allocator: std.mem.Allocator) []const u8 { const weight = switch (self.weight) { .normal => "", .bold => " Bold", }; const style = switch (self.style) { .normal => "", .italic => " Italic", }; return std.fmt.allocPrint(allocator, "{s}{s}{s}", .{ self.familyName(), weight, style }) catch "OOM"; }
/// Return a Font that will render from this source. pub fn font(self: *const Source) Font { return .{ .family = self.family, .weight = self.weight, .style = self.style, }; }
pub fn deinit(self: *Source) void { defer self.* = undefined; if (self.allocator) |alloc| { alloc.free(self.bytes); } }
pub const fallback = Source{ .family = array("Vera"), .bytes = @embedFile("fonts/bitstream-vera/Vera.ttf"), };};
pub fn textHeight(self: Font) f32 { return self.sizeM(1, 1).h;}
pub fn lineHeight(self: Font) f32 { return self.textHeight() * self.line_height_factor;}
pub fn sizeM(self: Font, wide: f32, tall: f32) Size { const msize: Size = self.textSize("M"); return .{ .w = msize.w * wide, .h = msize.h * tall };}
/// handles multiple lines////// Only valid between `Window.begin`and `Window.end`.pub fn textSize(self: Font, text: []const u8) Size { if (text.len == 0) { // just want the normal text height return .{ .w = 0, .h = self.textHeight() }; }
var ret = Size{};
var line_height_adj: f32 = 0.0; var end: usize = 0; while (end < text.len) { if (end > 0) { ret.h += line_height_adj; }
var end_idx: usize = undefined; var s = self.textSizeEx(text[end..], .{ .end_idx = &end_idx, .end_metric = .before }); if (self.line_height_factor >= 1.0) { line_height_adj = s.h * (self.line_height_factor - 1.0); } else { s.h *= self.line_height_factor; } ret.h += s.h; ret.w = @max(ret.w, s.w);
end += end_idx; }
return ret;}
pub const EndMetric = enum { before, // end_idx stops before text goes past max_width nearest, // end_idx stops at start of character closest to max_width};
pub const TextSizeOptions = struct { max_width: ?f32 = null, end_idx: ?*usize = null, end_metric: EndMetric = .before, kerning: ?bool = null, kern_in: ?[]u32 = null, kern_out: ?[]u32 = null, ascent_out: ?*f32 = null,};
/// textSizeEx always stops at a newline, use textSize to get multiline sizes////// Only valid between `Window.begin`and `Window.end`.pub fn textSizeEx(self: Font, text: []const u8, opts: TextSizeOptions) Size { // ask for a font that matches the natural display pixels so we get a more // accurate size const ss = dvui.parentGet().screenRectScale(Rect{}).s; const ask_size = self.size * ss;
// set some reasonable defaults in case things go bad if (opts.ascent_out) |ao| ao.* = 10; if (opts.end_idx) |endout| endout.* = text.len; if (ask_size == 0.0) { // early out here so we don't try to divide by zero later if (opts.ascent_out) |ao| ao.* = 0; return Size{}; }
const sized_font = self.withSize(ask_size);
const cw = dvui.currentWindow();
// might give us a slightly smaller font const fce = dvui.fontCacheGet(sized_font) catch return .{ .w = 10, .h = 10 };
// this must be synced with dvui.renderText() const target_fraction = if (cw.snap_to_pixels) 1.0 / ss else self.size / fce.em_height;
var options = opts; if (opts.max_width) |mwidth| { // convert max_width into font units options.max_width = mwidth / target_fraction; } options.kerning = opts.kerning orelse cw.kerning;
var s = fce.textSizeRaw(cw.gpa, text, options) catch return .{ .w = 10, .h = 10 };
if (opts.ascent_out) |ao| { ao.* = fce.ascent; if (self.line_height_factor < 1.0) { ao.* = @round(ao.* * self.line_height_factor); } ao.* *= target_fraction; }
// convert size back from font units return s.scale(target_fraction, Size);}
pub const Cache = @import("FontCache.zig");
pub const FreeType = struct { pub const OpenFlags = packed struct(c_int) { memory: bool = false, stream: bool = false, path: bool = false, driver: bool = false, params: bool = false, _padding: u27 = 0, };
pub const LoadFlags = packed struct(c_int) { no_scale: bool = false, no_hinting: bool = false, render: bool = false, no_bitmap: bool = false, vertical_layout: bool = false, force_autohint: bool = false, crop_bitmap: bool = false, pedantic: bool = false, ignore_global_advance_with: bool = false, no_recurse: bool = false, ignore_transform: bool = false, monochrome: bool = false, linear_design: bool = false, no_autohint: bool = false, _padding: u1 = 0, target_normal: bool = false, target_light: bool = false, target_mono: bool = false, target_lcd: bool = false, target_lcd_v: bool = false, color: bool = false, compute_metrics: bool = false, bitmap_metrics_only: bool = false, _padding0: u9 = 0, };
pub fn intToError(err: c_int) !void { return switch (err) { c.FT_Err_Ok => {}, c.FT_Err_Cannot_Open_Resource => error.CannotOpenResource, c.FT_Err_Unknown_File_Format => error.UnknownFileFormat, c.FT_Err_Invalid_File_Format => error.InvalidFileFormat, c.FT_Err_Invalid_Version => error.InvalidVersion, c.FT_Err_Lower_Module_Version => error.LowerModuleVersion, c.FT_Err_Invalid_Argument => error.InvalidArgument, c.FT_Err_Unimplemented_Feature => error.UnimplementedFeature, c.FT_Err_Invalid_Table => error.InvalidTable, c.FT_Err_Invalid_Offset => error.InvalidOffset, c.FT_Err_Array_Too_Large => error.ArrayTooLarge, c.FT_Err_Missing_Module => error.MissingModule, c.FT_Err_Missing_Property => error.MissingProperty, c.FT_Err_Invalid_Glyph_Index => error.InvalidGlyphIndex, c.FT_Err_Invalid_Character_Code => error.InvalidCharacterCode, c.FT_Err_Invalid_Glyph_Format => error.InvalidGlyphFormat, c.FT_Err_Cannot_Render_Glyph => error.CannotRenderGlyph, c.FT_Err_Invalid_Outline => error.InvalidOutline, c.FT_Err_Invalid_Composite => error.InvalidComposite, c.FT_Err_Too_Many_Hints => error.TooManyHints, c.FT_Err_Invalid_Pixel_Size => error.InvalidPixelSize, c.FT_Err_Invalid_Handle => error.InvalidHandle, c.FT_Err_Invalid_Library_Handle => error.InvalidLibraryHandle, c.FT_Err_Invalid_Driver_Handle => error.InvalidDriverHandle, c.FT_Err_Invalid_Face_Handle => error.InvalidFaceHandle, c.FT_Err_Invalid_Size_Handle => error.InvalidSizeHandle, c.FT_Err_Invalid_Slot_Handle => error.InvalidSlotHandle, c.FT_Err_Invalid_CharMap_Handle => error.InvalidCharMapHandle, c.FT_Err_Invalid_Cache_Handle => error.InvalidCacheHandle, c.FT_Err_Invalid_Stream_Handle => error.InvalidStreamHandle, c.FT_Err_Too_Many_Drivers => error.TooManyDrivers, c.FT_Err_Too_Many_Extensions => error.TooManyExtensions, c.FT_Err_Out_Of_Memory => error.OutOfMemory, c.FT_Err_Unlisted_Object => error.UnlistedObject, c.FT_Err_Cannot_Open_Stream => error.CannotOpenStream, c.FT_Err_Invalid_Stream_Seek => error.InvalidStreamSeek, c.FT_Err_Invalid_Stream_Skip => error.InvalidStreamSkip, c.FT_Err_Invalid_Stream_Read => error.InvalidStreamRead, c.FT_Err_Invalid_Stream_Operation => error.InvalidStreamOperation, c.FT_Err_Invalid_Frame_Operation => error.InvalidFrameOperation, c.FT_Err_Nested_Frame_Access => error.NestedFrameAccess, c.FT_Err_Invalid_Frame_Read => error.InvalidFrameRead, c.FT_Err_Raster_Uninitialized => error.RasterUninitialized, c.FT_Err_Raster_Corrupted => error.RasterCorrupted, c.FT_Err_Raster_Overflow => error.RasterOverflow, c.FT_Err_Raster_Negative_Height => error.RasterNegativeHeight, c.FT_Err_Too_Many_Caches => error.TooManyCaches, c.FT_Err_Invalid_Opcode => error.InvalidOpcode, c.FT_Err_Too_Few_Arguments => error.TooFewArguments, c.FT_Err_Stack_Overflow => error.StackOverflow, c.FT_Err_Code_Overflow => error.CodeOverflow, c.FT_Err_Bad_Argument => error.BadArgument, c.FT_Err_Divide_By_Zero => error.DivideByZero, c.FT_Err_Invalid_Reference => error.InvalidReference, c.FT_Err_Debug_OpCode => error.DebugOpCode, c.FT_Err_ENDF_In_Exec_Stream => error.ENDFInExecStream, c.FT_Err_Nested_DEFS => error.NestedDEFS, c.FT_Err_Invalid_CodeRange => error.InvalidCodeRange, c.FT_Err_Execution_Too_Long => error.ExecutionTooLong, c.FT_Err_Too_Many_Function_Defs => error.TooManyFunctionDefs, c.FT_Err_Too_Many_Instruction_Defs => error.TooManyInstructionDefs, c.FT_Err_Table_Missing => error.TableMissing, c.FT_Err_Horiz_Header_Missing => error.HorizHeaderMissing, c.FT_Err_Locations_Missing => error.LocationsMissing, c.FT_Err_Name_Table_Missing => error.NameTableMissing, c.FT_Err_CMap_Table_Missing => error.CMapTableMissing, c.FT_Err_Hmtx_Table_Missing => error.HmtxTableMissing, c.FT_Err_Post_Table_Missing => error.PostTableMissing, c.FT_Err_Invalid_Horiz_Metrics => error.InvalidHorizMetrics, c.FT_Err_Invalid_CharMap_Format => error.InvalidCharMapFormat, c.FT_Err_Invalid_PPem => error.InvalidPPem, c.FT_Err_Invalid_Vert_Metrics => error.InvalidVertMetrics, c.FT_Err_Could_Not_Find_Context => error.CouldNotFindContext, c.FT_Err_Invalid_Post_Table_Format => error.InvalidPostTableFormat, c.FT_Err_Invalid_Post_Table => error.InvalidPostTable, c.FT_Err_Syntax_Error => error.Syntax, c.FT_Err_Stack_Underflow => error.StackUnderflow, c.FT_Err_Ignore => error.Ignore, c.FT_Err_No_Unicode_Glyph_Name => error.NoUnicodeGlyphName, c.FT_Err_Missing_Startfont_Field => error.MissingStartfontField, c.FT_Err_Missing_Font_Field => error.MissingFontField, c.FT_Err_Missing_Size_Field => error.MissingSizeField, c.FT_Err_Missing_Fontboundingbox_Field => error.MissingFontboundingboxField, c.FT_Err_Missing_Chars_Field => error.MissingCharsField, c.FT_Err_Missing_Startchar_Field => error.MissingStartcharField, c.FT_Err_Missing_Encoding_Field => error.MissingEncodingField, c.FT_Err_Missing_Bbx_Field => error.MissingBbxField, c.FT_Err_Bbx_Too_Big => error.BbxTooBig, c.FT_Err_Corrupted_Font_Header => error.CorruptedFontHeader, c.FT_Err_Corrupted_Font_Glyphs => error.CorruptedFontGlyphs, else => unreachable, }; }};
test { @import("std").testing.refAllDecls(@This());}
test "DOCIMG synthetic bold from a family with only a regular face" { var t = try dvui.testing.init(.{ .window_size = .{ .w = 680, .h = 150 } }); defer t.deinit();
const T = struct { const family = "SyntheticBoldTest"; const regular_font: Font = .{ .family = array("Vera Sans"), .size = 20 }; const synthetic_font: Font = .{ .family = array(family), .size = 20, .weight = .bold }; const raster = if (dvui.useFreeType) "FreeType" else "stb_truetype"; var regular: Size = .{}; var synthetic: Size = .{};
fn frame() !dvui.App.Result { if (synthetic_font.withWeight(.normal).findSource() == null) try dvui.addFont(family, @embedFile("fonts/bitstream-vera/Vera.ttf"), null); regular = regular_font.textSize("Bold"); synthetic = synthetic_font.textSize("Bold");
var box = dvui.box(@src(), .{ .dir = .vertical }, .{ .expand = .both, .background = true, .style = .window }); defer box.deinit(); dvui.label(@src(), "Hello World: Regular ({s})", .{raster}, .{ .font = regular_font }); dvui.label(@src(), "Hello World: Bold fontface ({s})", .{raster}, .{ .font = regular_font.withWeight(.bold) }); dvui.label(@src(), "Hello World: Bold synthetic ({s})", .{raster}, .{ .font = synthetic_font }); return .ok; } };
try dvui.testing.settle(T.frame); try t.saveImage(T.frame, null, "Font-synthetic-bold.png");
// synthetic bold should be wider but not taller try std.testing.expect(T.synthetic.w > T.regular.w); try std.testing.expectEqual(T.regular.h, T.synthetic.h);}