basic bdf parsing

This commit is contained in:
Hamcha 2024-05-06 00:23:06 +02:00
commit 31141ebfb7
Signed by: hamcha
GPG key ID: 1669C533B8CF6D89
5 changed files with 293 additions and 0 deletions

5
.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
zig-cache
zig-out
*.bdf
out
*.font.zon

36
build.zig Normal file
View file

@ -0,0 +1,36 @@
const std = @import("std");
// Although this function looks imperative, note that its job is to
// declaratively construct a build graph that will be executed by an external
// runner.
pub fn build(b: *std.Build) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard optimization options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "binfon",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}

67
build.zig.zon Normal file
View file

@ -0,0 +1,67 @@
.{
.name = "binfon",
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",
// This field is optional.
// This is currently advisory only; Zig does not yet do anything
// with this value.
//.minimum_zig_version = "0.11.0",
// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
//.example = .{
// // When updating this field to a new URL, be sure to delete the corresponding
// // `hash`, otherwise you are communicating that you expect to find the old hash at
// // the new URL.
// .url = "https://example.com/foo.tar.gz",
//
// // This is computed from the file contents of the directory of files that is
// // obtained after fetching `url` and applying the inclusion rules given by
// // `paths`.
// //
// // This field is the source of truth; packages do not come from a `url`; they
// // come from a `hash`. `url` is just one of many possible mirrors for how to
// // obtain a package matching this `hash`.
// //
// // Uses the [multihash](https://multiformats.io/multihash/) format.
// .hash = "...",
//
// // When this is provided, the package is found in a directory relative to the
// // build root. In this case the package's hash is irrelevant and therefore not
// // computed. This field and `url` are mutually exclusive.
// .path = "foo",
// // When this is set to `true`, a package is declared to be lazily
// // fetched. This makes the dependency only get fetched if it is
// // actually used.
// .lazy = false,
//},
},
// Specifies the set of files and directories that are included in this package.
// Only files and directories listed here are included in the `hash` that
// is computed for this package.
// Paths are relative to the build root. Use the empty string (`""`) to refer to
// the build root itself.
// A directory listed here means that all files within, recursively, are included.
.paths = .{
// This makes *all* files, recursively, included in this package. It is generally
// better to explicitly list the files and directories instead, to insure that
// fetching from tarballs, file system paths, and version control all result
// in the same contents hash.
"",
// For example...
//"build.zig",
//"build.zig.zon",
//"src",
//"LICENSE",
//"README.md",
},
}

156
src/bdf.zig Normal file
View file

@ -0,0 +1,156 @@
const std = @import("std");
const Bitmap = [][]u8;
const Character = struct {
name: []u8,
bitmap: Bitmap,
pub fn deinit(self: *Character, allocator: std.mem.Allocator) void {
for (self.bitmap) |line| {
allocator.free(line);
}
allocator.free(self.bitmap);
allocator.free(self.name);
}
};
const CharacterMap = std.AutoHashMap(u16, Character);
const Font = struct {
name: []const u8,
height: u8,
width: u8,
characters: CharacterMap,
pub fn deinit(self: *Font, allocator: std.mem.Allocator) void {
var iterator = self.characters.valueIterator();
while (iterator.next()) |char| {
char.deinit(allocator);
}
self.characters.deinit();
}
};
const Command = enum {
FONT,
FONTBOUNDINGBOX,
ENCODING,
BITMAP,
STARTCHAR,
_IGNORED,
};
const Line = struct {
command: Command,
params: []const u8,
};
pub fn parse(allocator: std.mem.Allocator, bdf: anytype) !Font {
var font: Font = .{
.name = undefined,
.height = 0,
.width = 0,
.characters = CharacterMap.init(allocator),
};
var bufferedReader = std.io.bufferedReader(bdf);
var reader = bufferedReader.reader();
var currentName: []const u8 = undefined;
var currentCharacter: u16 = 0;
while (true) {
var lineBuffer: [1024]u8 = undefined;
const nextLine = try reader.readUntilDelimiterOrEof(&lineBuffer, '\n') orelse break;
// Parse line
const line = try parseLine(nextLine);
switch (line.command) {
.FONT => {
font.name = line.params;
std.log.debug("Font: {s}", .{font.name});
},
.FONTBOUNDINGBOX => {
var boundingBox = std.mem.splitScalar(u8, line.params, ' ');
font.width = try std.fmt.parseInt(u8, boundingBox.next().?, 10);
font.height = try std.fmt.parseInt(u8, boundingBox.next().?, 10);
std.log.debug("Bounding box: {d}x{d}", .{ font.width, font.height });
},
.BITMAP => {
const bitmap = try readBitmap(allocator, font.width, font.height, reader);
try font.characters.put(currentCharacter, .{
.name = try allocator.dupe(u8, currentName),
.bitmap = bitmap,
});
},
.STARTCHAR => {
currentName = line.params;
},
.ENCODING => {
// This probably breaks with custom encodings, not doing anything for now
currentCharacter = try std.fmt.parseInt(u16, line.params, 10);
},
else => {},
}
}
return font;
}
fn parseLine(line: []const u8) !Line {
const firstSpace = std.mem.indexOfScalar(u8, line, ' ') orelse line.len;
const command = line[0..firstSpace];
return .{
.command = std.meta.stringToEnum(Command, command) orelse Command._IGNORED,
.params = if (firstSpace == line.len) "" else line[firstSpace + 1 ..],
};
}
fn readBitmap(
allocator: std.mem.Allocator,
width: u8,
height: u8,
reader: anytype,
) !Bitmap {
var lineIndex: u8 = 0;
var char = try allocator.alloc([]u8, height);
errdefer {
for (0..lineIndex) |i| {
allocator.free(char[i]);
}
allocator.free(char);
}
// Allocate memory for the parsed bitmap
var line: []u8 = try allocator.alloc(u8, width / 8);
defer allocator.free(line);
// Read lines until ENDCHAR
while (true) {
std.debug.assert(lineIndex < height + 1);
// Read the next line
var lineBuffer: [128]u8 = undefined;
const nextLine = try reader.readUntilDelimiterOrEof(&lineBuffer, '\n') orelse break;
// If we encounter the magic string, we're done
if (std.mem.eql(u8, nextLine, "ENDCHAR")) {
break;
}
// Parse every 2 char as a hexadecimal number
var i: usize = 0;
while (i < nextLine.len) : (i += 2) {
const hex = try std.fmt.parseInt(u8, nextLine[i .. i + 2], 16);
line[i / 2] = hex;
}
// Copy over to the array (this memory must be freed later)
char[lineIndex] = try allocator.dupe(u8, line);
lineIndex += 1;
}
return char;
}

29
src/main.zig Normal file
View file

@ -0,0 +1,29 @@
const std = @import("std");
const bdf = @import("bdf.zig");
pub fn main() !void {
// Get allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
defer _ = gpa.deinit();
// Get args
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
if (args.len < 3) {
std.log.err("Usage: {s} <input.bdf> <input.zon> <output-dir>", .{args[0]});
std.process.exit(1);
}
const inputFile = args[1];
const outputPath = args[2];
_ = outputPath; // autofix
// Read font
const input = try std.fs.cwd().openFile(inputFile, .{});
defer input.close();
var font = try bdf.parse(allocator, input.reader());
defer font.deinit(allocator);
}