freetype: move to github.com/hexops/mach-freetype

Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
This commit is contained in:
Stephen Gutekanst 2023-07-08 14:39:48 -07:00
parent 7d89a0f07b
commit 3a45c41141
39 changed files with 0 additions and 3983 deletions

View file

@ -1,2 +0,0 @@
* text=auto eol=lf
upstream/** linguist-vendored

View file

@ -1 +0,0 @@
github: slimsag

View file

@ -1,5 +0,0 @@
Please send your change to [the main repository](https://github.com/hexops/mach/tree/main/libs/freetype) instead, sorry for the trouble!
This helps us avoid some complex merge conflicts we run into when changes are made to both repositories and history needs to be reconciled. Keeping PRs in just that repository enables us to use `git subtree` to trivially keep the two repositories in sync.
Once your PR is merged over there, it'll automatically sync to this repository.

View file

@ -1,43 +0,0 @@
name: CI
on:
- push
- pull_request
jobs:
x86_64-linux:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup Zig
run: |
sudo apt install xz-utils
sudo sh -c 'wget -c https://ziglang.org/builds/zig-linux-x86_64-0.11.0-dev.3883+7166407d8.tar.xz -O - | tar -xJ --strip-components=1 -C /usr/local/bin'
- name: x86_64-linux -> aarch64-macos
run: zig build -Dtarget=aarch64-macos
- name: test
run: zig build test
x86_64-windows:
runs-on: windows-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup Zig
run: |
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri "https://ziglang.org/builds/zig-windows-x86_64-0.11.0-dev.3883+7166407d8.zip" -OutFile "C:\zig.zip"
cd C:\
7z x zig.zip
Add-Content $env:GITHUB_PATH "C:\zig-windows-x86_64-0.11.0-dev.3883+7166407d8\"
- name: test
run: zig build test
x86_64-macos:
runs-on: macos-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup Zig
run: |
brew install xz
sudo sh -c 'wget -c https://ziglang.org/builds/zig-macos-x86_64-0.11.0-dev.3883+7166407d8.tar.xz -O - | tar -xJ --strip-components=1 -C /usr/local/bin'
- name: test
run: zig build test

View file

@ -1,20 +0,0 @@
# This file is for zig-specific build artifacts.
# If you have OS-specific or editor-specific files to ignore,
# such as *.swp or .DS_Store, put those in your global
# ~/.gitignore and put this in your ~/.gitconfig:
#
# [core]
# excludesfile = ~/.gitignore
#
# Cheers!
# -andrewrk
zig-cache/
zig-out/
/release/
/debug/
/build/
/build-*/
/docgen_tmp/
/out.svg

View file

@ -1,3 +0,0 @@
[submodule "upstream"]
path = upstream
url = https://github.com/hexops-graveyard/freetype

View file

@ -1,13 +0,0 @@
Copyright 2021, Hexops Contributors (given via the Git commit history).
All documentation, image, sound, font, and 2D/3D model files are CC-BY-4.0 licensed unless
otherwise noted. You may get a copy of this license at https://creativecommons.org/licenses/by/4.0
Files in a directory with a separate LICENSE file may contain files under different license terms,
described within that LICENSE file.
All other files are licensed under the Apache License, Version 2.0 (see LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
or the MIT license (see LICENSE-MIT or http://opensource.org/licenses/MIT), at your option.
All files in the project without exclusions may not be copied, modified, or distributed except
according to the terms above.

View file

@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -1,25 +0,0 @@
Copyright (c) 2021 Hexops Contributors (given via the Git commit history).
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View file

@ -1,42 +0,0 @@
FREETYPE LICENSES
-----------------
The FreeType 2 font engine is copyrighted work and cannot be used
legally without a software license. In order to make this project
usable to a vast majority of developers, we distribute it under two
mutually exclusive open-source licenses.
This means that *you* must choose *one* of the two licenses described
below, then obey all its terms and conditions when using FreeType 2 in
any of your projects or products.
- The FreeType License, found in the file `docs/FTL.TXT`, which is
similar to the original BSD license *with* an advertising clause
that forces you to explicitly cite the FreeType project in your
product's documentation. All details are in the license file.
This license is suited to products which don't use the GNU General
Public License.
Note that this license is compatible to the GNU General Public
License version 3, but not version 2.
- The GNU General Public License version 2, found in
`docs/GPLv2.TXT` (any later version can be used also), for
programs which already use the GPL. Note that the FTL is
incompatible with GPLv2 due to its advertisement clause.
The contributed BDF and PCF drivers come with a license similar to
that of the X Window System. It is compatible to the above two
licenses (see files `src/bdf/README` and `src/pcf/README`). The same
holds for the source code files `src/base/fthash.c` and
`include/freetype/internal/fthash.h`; they wer part of the BDF driver
in earlier FreeType versions.
The gzip module uses the zlib license (see `src/gzip/zlib.h`) which
too is compatible to the above two licenses.
The MD5 checksum support (only used for debugging in development
builds) is in the public domain.
--- end of LICENSE.TXT ---

View file

@ -1,108 +0,0 @@
# mach/freetype - Ziggified FreeType 2 bindings [![CI](https://github.com/hexops/mach-freetype/workflows/CI/badge.svg)](https://github.com/hexops/mach-freetype/actions) <a href="https://hexops.com"><img align="right" alt="Hexops logo" src="https://raw.githubusercontent.com/hexops/media/main/readme.svg"></img></a>
Ziggified FreeType 2 bindings that [Mach engine](https://github.com/hexops/mach) uses, with zero-fuss installation, cross compilation, and more.
This repository is a separate copy of the same library in the [main Mach repository](https://github.com/hexops/mach), and is automatically kept in sync, so that anyone can use this library in their own project / engine if they like!
## Zero fuss installation, cross compilation, and more
[Just as with Mach](https://github.com/hexops/mach#zero-fuss-installation--cross-compilation), you get zero fuss installation & cross compilation using these Freetype bindings. **only `zig` and `git` are needed to build from any OS and produce binaries for every OS.** No system dependencies at all.
## Usage
## Getting started
### Adding dependency (using Git)
In a `libs` subdirectory of the root of your project:
```sh
git clone https://github.com/hexops/mach-freetype
```
Then in your `build.zig` add:
```zig
...
const freetype = @import("libs/mach-freetype/build.zig");
pub fn build(b: *Build) void {
...
exe.addModule("freetype", freetype.module(b));
freetype.link(b, exe, .{});
// use this option if you are including zlib separately
//freetype.link(b, exe, .{ .freetype = .{ .use_system_zlib = true } });
}
```
and optionaly add harfbuzz:
```zig
exe.addModule("harfbuzz", freetype.harfbuzzModule(b));
freetype.link(b, exe, .{ .harfbuzz = .{} });
```
You can also optionally build brotli compression (for WOFF2 font support):
```zig
exe.addModule("freetype", freetype.module(b));
freetype.link(b, exe, .{ .freetype = .{ .brotli = true } });
```
<details>
<description>Optional: Using Gyro dependency manager</description>
```sh
gyro add --src github hexops/mach-freetype --root src/main.zig --alias freetype
gyro add --build-dep --src github hexops/mach-freetype --root build.zig --alias build-freetype
```
Then in your `build.zig` add:
```zig
...
const pkgs = @import("deps.zig").pkgs;
const freetype = @import("build-freetype");
pub fn build(b: *Build) void {
...
exe.addModule("freetype", pkgs.freetype);
freetype.link(b, exe, .{});
}
```
**WARNING: You should use `gyro build` instead of `zig build` now!**
</details>
Now you can import in code:
```zig
const freetype = @import("freetype");
```
## Examples
See the `examples/` directory. for running each example do:
```sh
zig build run-example-<name> # e.g run-example-single-glyph
```
## Join the community
Join the Mach engine community [on Discord](https://discord.gg/XNG3NZgCqp) to discuss this project, ask questions, get help, etc.
## Issues
Issues are tracked in the [main Mach repository](https://github.com/hexops/mach/issues?q=is%3Aissue+is%3Aopen+label%3Afreetype).
## Contributing
Contributions are very welcome. Pull requests must be sent to [the main repository](https://github.com/hexops/mach/tree/main/libs/freetype) to avoid some complex merge conflicts we'd get by accepting contributions in both repositories. Once the changes are merged there, they'll get sync'd to this repository automatically.
# Thanks
Special thanks to [@alichraghi](https://github.com/alichraghi), original author of these bindings who contributed them to Mach!

View file

@ -1,318 +0,0 @@
const std = @import("std");
const Build = std.Build;
const ft_root = sdkPath("/upstream/freetype");
const ft_include_path = ft_root ++ "/include";
const hb_root = sdkPath("/upstream/harfbuzz");
const hb_include_path = hb_root ++ "/src";
const brotli_root = sdkPath("/upstream/brotli");
var _module: ?*std.build.Module = null;
pub fn module(b: *std.Build) *std.build.Module {
if (_module) |m| return m;
_module = b.createModule(.{
.source_file = .{ .path = sdkPath("/src/main.zig") },
});
return _module.?;
}
var _harfbuzz_module: ?*std.build.Module = null;
pub fn harfbuzzModule(b: *std.Build) *std.build.Module {
if (_harfbuzz_module) |m| return m;
_harfbuzz_module = b.createModule(.{
.source_file = .{ .path = sdkPath("/src/harfbuzz/main.zig") },
.dependencies = &.{
.{ .name = "freetype", .module = module(b) },
},
});
return _harfbuzz_module.?;
}
pub const Options = struct {
freetype: FreetypeOptions = .{},
harfbuzz: ?HarfbuzzOptions = null,
};
pub const FreetypeOptions = struct {
/// the path you specify freetype options
/// via `ftoptions.h` and `ftmodule.h`
config_path: ?[]const u8 = null,
install_libs: bool = false,
brotli: bool = false,
use_system_zlib: bool = false,
};
pub const HarfbuzzOptions = struct {
install_libs: bool = false,
};
pub fn build(b: *std.Build) !void {
const optimize = b.standardOptimizeOption(.{});
const target = b.standardTargetOptions(.{});
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&testStep(b, optimize, target).step);
inline for ([_][]const u8{
"single-glyph",
"glyph-to-svg",
}) |example| {
const example_exe = b.addExecutable(.{
.name = "example-" ++ example,
.root_source_file = .{ .path = "examples/" ++ example ++ ".zig" },
.target = target,
.optimize = optimize,
});
example_exe.addModule("freetype", module(b));
link(b, example_exe, .{});
const example_install = b.addInstallArtifact(example_exe);
var example_compile_step = b.step("example-" ++ example, "Compile '" ++ example ++ "' example");
example_compile_step.dependOn(&example_install.step);
const example_run_cmd = b.addRunArtifact(example_exe);
if (b.args) |args| {
example_run_cmd.addArgs(args);
}
const example_run_step = b.step("run-example-" ++ example, "Run '" ++ example ++ "' example");
example_run_step.dependOn(&example_run_cmd.step);
}
}
pub fn testStep(b: *Build, optimize: std.builtin.OptimizeMode, target: std.zig.CrossTarget) *std.build.RunStep {
const main_tests = b.addTest(.{
.name = "freetype-tests",
.root_source_file = .{ .path = sdkPath("/src/main.zig") },
.target = target,
.optimize = optimize,
});
main_tests.addModule("freetype", module(b));
link(b, main_tests, .{
.freetype = .{
.brotli = true,
},
.harfbuzz = .{},
});
main_tests.main_pkg_path = sdkPath("/");
b.installArtifact(main_tests);
const harfbuzz_tests = b.addTest(.{
.name = "harfbuzz-tests",
.root_source_file = .{ .path = sdkPath("/src/harfbuzz/main.zig") },
.target = target,
.optimize = optimize,
});
harfbuzz_tests.addModule("freetype", module(b));
link(b, harfbuzz_tests, .{
.freetype = .{
.brotli = true,
},
.harfbuzz = .{},
});
harfbuzz_tests.main_pkg_path = sdkPath("/");
b.installArtifact(harfbuzz_tests);
const main_tests_run = b.addRunArtifact(main_tests);
main_tests_run.step.dependOn(&b.addRunArtifact(harfbuzz_tests).step);
return main_tests_run;
}
pub fn link(b: *Build, step: *std.build.CompileStep, options: Options) void {
linkFreetype(b, step, options.freetype);
if (options.harfbuzz) |harfbuzz_options|
linkHarfbuzz(b, step, harfbuzz_options);
}
pub fn linkFreetype(b: *Build, step: *std.build.CompileStep, options: FreetypeOptions) void {
const ft_lib = buildFreetype(b, step.optimize, step.target, options);
step.linkLibrary(ft_lib);
step.addIncludePath(ft_include_path);
if (options.brotli) {
const brotli_lib = buildBrotli(b, step.optimize, step.target);
if (options.install_libs)
b.installArtifact(brotli_lib);
step.linkLibrary(brotli_lib);
}
}
pub fn linkHarfbuzz(b: *Build, step: *std.build.CompileStep, options: HarfbuzzOptions) void {
const hb_lib = buildHarfbuzz(b, step.optimize, step.target, options);
step.linkLibrary(hb_lib);
step.addIncludePath(hb_include_path);
}
pub fn buildFreetype(b: *Build, optimize: std.builtin.OptimizeMode, target: std.zig.CrossTarget, options: FreetypeOptions) *std.build.CompileStep {
// TODO(build-system): https://github.com/hexops/mach/issues/229#issuecomment-1100958939
ensureDependencySubmodule(b.allocator, "upstream") catch unreachable;
const lib = b.addStaticLibrary(.{
.name = "freetype",
.target = target,
.optimize = optimize,
});
lib.defineCMacro("FT2_BUILD_LIBRARY", "1");
if (options.use_system_zlib) {
lib.defineCMacro("FT_CONFIG_OPTION_SYSTEM_ZLIB", "1");
}
lib.linkLibC();
lib.addIncludePath(ft_include_path);
if (options.config_path) |path|
lib.addIncludePath(path);
if (options.brotli)
lib.defineCMacro("FT_REQUIRE_BROTLI", "1");
const target_info = (std.zig.system.NativeTargetInfo.detect(target) catch unreachable).target;
if (target_info.os.tag == .windows) {
lib.addCSourceFile(ft_root ++ "/builds/windows/ftsystem.c", &.{});
lib.addCSourceFile(ft_root ++ "/builds/windows/ftdebug.c", &.{});
} else {
lib.addCSourceFile(ft_root ++ "/src/base/ftsystem.c", &.{});
lib.addCSourceFile(ft_root ++ "/src/base/ftdebug.c", &.{});
}
if (target_info.os.tag.isBSD() or target_info.os.tag == .linux) {
lib.defineCMacro("HAVE_UNISTD_H", "1");
lib.defineCMacro("HAVE_FCNTL_H", "1");
lib.addCSourceFile(ft_root ++ "/builds/unix/ftsystem.c", &.{});
if (target_info.os.tag == .macos)
lib.addCSourceFile(ft_root ++ "/src/base/ftmac.c", &.{});
}
lib.addCSourceFiles(freetype_base_sources, &.{});
if (options.install_libs)
b.installArtifact(lib);
return lib;
}
pub fn buildHarfbuzz(b: *Build, optimize: std.builtin.OptimizeMode, target: std.zig.CrossTarget, options: HarfbuzzOptions) *std.build.CompileStep {
const lib = b.addStaticLibrary(.{
.name = "harfbuzz",
.target = target,
.optimize = optimize,
});
lib.addCSourceFile(hb_root ++ "/src/harfbuzz.cc", &.{});
lib.linkLibCpp();
lib.addIncludePath(hb_include_path);
lib.addIncludePath(ft_include_path);
lib.defineCMacro("HAVE_FREETYPE", "1");
lib.defineCMacro("HB_NO_PRAGMA_GCC_DIAGNOSTIC_ERROR", "1");
if (options.install_libs)
b.installArtifact(lib);
return lib;
}
fn buildBrotli(b: *Build, optimize: std.builtin.OptimizeMode, target: std.zig.CrossTarget) *std.build.CompileStep {
const lib = b.addStaticLibrary(.{
.name = "brotli",
.target = target,
.optimize = optimize,
});
lib.linkLibC();
lib.addIncludePath(brotli_root ++ "/include");
lib.addCSourceFiles(brotli_base_sources, &.{});
return lib;
}
fn ensureDependencySubmodule(allocator: std.mem.Allocator, path: []const u8) !void {
if (std.process.getEnvVarOwned(allocator, "NO_ENSURE_SUBMODULES")) |no_ensure_submodules| {
defer allocator.free(no_ensure_submodules);
if (std.mem.eql(u8, no_ensure_submodules, "true")) return;
} else |_| {}
var child = std.ChildProcess.init(&.{ "git", "submodule", "update", "--init", path }, allocator);
child.cwd = sdkPath("/");
child.stderr = std.io.getStdErr();
child.stdout = std.io.getStdOut();
_ = try child.spawnAndWait();
}
fn sdkPath(comptime suffix: []const u8) []const u8 {
if (suffix[0] != '/') @compileError("suffix must be an absolute path");
return comptime blk: {
const root_dir = std.fs.path.dirname(@src().file) orelse ".";
break :blk root_dir ++ suffix;
};
}
const freetype_base_sources = &[_][]const u8{
ft_root ++ "/src/autofit/autofit.c",
ft_root ++ "/src/base/ftbase.c",
ft_root ++ "/src/base/ftbbox.c",
ft_root ++ "/src/base/ftbdf.c",
ft_root ++ "/src/base/ftbitmap.c",
ft_root ++ "/src/base/ftcid.c",
ft_root ++ "/src/base/ftfstype.c",
ft_root ++ "/src/base/ftgasp.c",
ft_root ++ "/src/base/ftglyph.c",
ft_root ++ "/src/base/ftgxval.c",
ft_root ++ "/src/base/ftinit.c",
ft_root ++ "/src/base/ftmm.c",
ft_root ++ "/src/base/ftotval.c",
ft_root ++ "/src/base/ftpatent.c",
ft_root ++ "/src/base/ftpfr.c",
ft_root ++ "/src/base/ftstroke.c",
ft_root ++ "/src/base/ftsynth.c",
ft_root ++ "/src/base/fttype1.c",
ft_root ++ "/src/base/ftwinfnt.c",
ft_root ++ "/src/bdf/bdf.c",
ft_root ++ "/src/bzip2/ftbzip2.c",
ft_root ++ "/src/cache/ftcache.c",
ft_root ++ "/src/cff/cff.c",
ft_root ++ "/src/cid/type1cid.c",
ft_root ++ "/src/gzip/ftgzip.c",
ft_root ++ "/src/lzw/ftlzw.c",
ft_root ++ "/src/pcf/pcf.c",
ft_root ++ "/src/pfr/pfr.c",
ft_root ++ "/src/psaux/psaux.c",
ft_root ++ "/src/pshinter/pshinter.c",
ft_root ++ "/src/psnames/psnames.c",
ft_root ++ "/src/raster/raster.c",
ft_root ++ "/src/sdf/sdf.c",
ft_root ++ "/src/sfnt/sfnt.c",
ft_root ++ "/src/smooth/smooth.c",
ft_root ++ "/src/svg/svg.c",
ft_root ++ "/src/truetype/truetype.c",
ft_root ++ "/src/type1/type1.c",
ft_root ++ "/src/type42/type42.c",
ft_root ++ "/src/winfonts/winfnt.c",
};
const brotli_base_sources = &[_][]const u8{
brotli_root ++ "/enc/backward_references.c",
brotli_root ++ "/enc/fast_log.c",
brotli_root ++ "/enc/histogram.c",
brotli_root ++ "/enc/cluster.c",
brotli_root ++ "/enc/command.c",
brotli_root ++ "/enc/compress_fragment_two_pass.c",
brotli_root ++ "/enc/entropy_encode.c",
brotli_root ++ "/enc/bit_cost.c",
brotli_root ++ "/enc/memory.c",
brotli_root ++ "/enc/backward_references_hq.c",
brotli_root ++ "/enc/dictionary_hash.c",
brotli_root ++ "/enc/encoder_dict.c",
brotli_root ++ "/enc/block_splitter.c",
brotli_root ++ "/enc/compress_fragment.c",
brotli_root ++ "/enc/literal_cost.c",
brotli_root ++ "/enc/brotli_bit_stream.c",
brotli_root ++ "/enc/encode.c",
brotli_root ++ "/enc/static_dict.c",
brotli_root ++ "/enc/utf8_util.c",
brotli_root ++ "/enc/metablock.c",
brotli_root ++ "/dec/decode.c",
brotli_root ++ "/dec/bit_reader.c",
brotli_root ++ "/dec/huffman.c",
brotli_root ++ "/dec/state.c",
brotli_root ++ "/common/constants.c",
brotli_root ++ "/common/context.c",
brotli_root ++ "/common/dictionary.c",
brotli_root ++ "/common/transform.c",
brotli_root ++ "/common/platform.c",
};

View file

@ -1,123 +0,0 @@
const std = @import("std");
const freetype = @import("freetype");
const OutlinePrinter = struct {
library: freetype.Library,
face: freetype.Face,
output_file: std.fs.File,
path_stream: std.io.FixedBufferStream([]u8),
xMin: isize,
yMin: isize,
width: isize,
height: isize,
const Self = @This();
var buf = [_]u8{0} ** (1024 * 10);
pub fn init(file: std.fs.File) freetype.Error!Self {
var lib = try freetype.Library.init();
return Self{
.library = lib,
.face = try lib.createFace("upstream/assets/FiraSans-Regular.ttf", 0),
.output_file = file,
.path_stream = std.io.fixedBufferStream(&buf),
.xMin = 0,
.yMin = 0,
.width = 0,
.height = 0,
};
}
pub fn deinit(self: Self) void {
self.library.deinit();
}
pub fn outlineExists(self: Self) bool {
const outline = self.face.glyph().outline() orelse return false;
if (outline.numContours() <= 0 or outline.numPoints() <= 0)
return false;
outline.check() catch return false;
return true;
}
pub fn flipOutline(self: Self) void {
const multiplier = 65536;
const matrix = freetype.Matrix{
.xx = 1 * multiplier,
.xy = 0 * multiplier,
.yx = 0 * multiplier,
.yy = -1 * multiplier,
};
self.face.glyph().outline().?.transform(matrix);
}
pub fn extractOutline(self: *Self) !void {
try self.path_stream.writer().writeAll("<path d='");
var callbacks = freetype.Outline.Funcs(*Self){
.move_to = moveToFunction,
.line_to = lineToFunction,
.conic_to = conicToFunction,
.cubic_to = cubicToFunction,
.shift = 0,
.delta = 0,
};
try self.face.glyph().outline().?.decompose(self, callbacks);
try self.path_stream.writer().writeAll("' fill='#000'/>");
}
pub fn computeViewBox(self: *Self) !void {
const boundingBox = try self.face.glyph().outline().?.bbox();
self.xMin = boundingBox.xMin;
self.yMin = boundingBox.yMin;
self.width = boundingBox.xMax - boundingBox.xMin;
self.height = boundingBox.yMax - boundingBox.yMin;
}
pub fn printSVG(self: Self) !void {
try self.output_file.writer().print(
\\<svg xmlns='http://www.w3.org/2000/svg'
\\ xmlns:xlink='http://www.w3.org/1999/xlink'
\\ viewBox='{d} {d} {d} {d}'>
\\ {s}
\\</svg>
, .{ self.xMin, self.yMin, self.width, self.height, self.path_stream.getWritten() });
}
pub fn moveToFunction(self: *Self, to: freetype.Vector) freetype.Error!void {
self.path_stream.writer().print("M {d} {d}\t", .{ to.x, to.y }) catch unreachable;
}
pub fn lineToFunction(self: *Self, to: freetype.Vector) freetype.Error!void {
self.path_stream.writer().print("L {d} {d}\t", .{ to.x, to.y }) catch unreachable;
}
pub fn conicToFunction(self: *Self, control: freetype.Vector, to: freetype.Vector) freetype.Error!void {
self.path_stream.writer().print("Q {d} {d}, {d} {d}\t", .{ control.x, control.y, to.x, to.y }) catch unreachable;
}
pub fn cubicToFunction(self: *Self, control_0: freetype.Vector, control_1: freetype.Vector, to: freetype.Vector) freetype.Error!void {
self.path_stream.writer().print("C {d} {d}, {d} {d}, {d} {d}\t", .{ control_0.x, control_0.y, control_1.x, control_1.y, to.x, to.y }) catch unreachable;
}
pub fn run(self: *Self, symbol: u32) !void {
try self.face.loadChar(symbol, .{ .no_scale = true, .no_bitmap = true });
if (!self.outlineExists())
return error.OutlineDoesntExists;
self.flipOutline();
try self.extractOutline();
try self.computeViewBox();
try self.printSVG();
}
};
pub fn main() !void {
var file = try std.fs.cwd().createFile("out.svg", .{});
defer file.close();
var outline_printer = try OutlinePrinter.init(file);
defer outline_printer.deinit();
try outline_printer.run(@as(u32, 'ë'));
}

View file

@ -1,37 +0,0 @@
// zig build run-example-single-glyph -- B
const std = @import("std");
const freetype = @import("freetype");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
const lib = try freetype.Library.init();
defer lib.deinit();
const face = try lib.createFace("upstream/assets/FiraSans-Regular.ttf", 0);
try face.setCharSize(60 * 48, 0, 50, 0);
if (args.len < 2) {
std.debug.print("usage: single-glyph 'a'\n", .{});
std.process.exit(1);
}
try face.loadChar(args[1][0], .{ .render = true });
const bitmap = face.glyph().bitmap();
var i: usize = 0;
while (i < bitmap.rows()) : (i += 1) {
var j: usize = 0;
while (j < bitmap.width()) : (j += 1) {
const char: u8 = switch (bitmap.buffer().?[i * bitmap.width() + j]) {
0 => ' ',
1...128 => ';',
else => '#',
};
std.debug.print("{c}", .{char});
}
std.debug.print("\n", .{});
}
}

View file

@ -1,418 +0,0 @@
const std = @import("std");
const c = @import("c.zig");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const GlyphSlot = @import("freetype.zig").GlyphSlot;
const LoadFlags = @import("freetype.zig").LoadFlags;
const FaceFlags = @import("freetype.zig").FaceFlags;
const StyleFlags = @import("freetype.zig").StyleFlags;
const FSType = @import("freetype.zig").FSType;
const OpenArgs = @import("freetype.zig").OpenArgs;
const KerningMode = @import("freetype.zig").KerningMode;
const Encoding = @import("freetype.zig").Encoding;
const CharMap = @import("freetype.zig").CharMap;
const Size = @import("freetype.zig").Size;
const SizeRequest = @import("freetype.zig").SizeRequest;
const BitmapSize = @import("freetype.zig").BitmapSize;
const Matrix = @import("types.zig").Matrix;
const BBox = @import("types.zig").BBox;
const Vector = @import("image.zig").Vector;
const RootTransform = @import("color.zig").RootTransform;
const PaintFormat = @import("color.zig").PaintFormat;
const Color = @import("color.zig").Color;
const ClipBox = @import("color.zig").ClipBox;
const OpaquePaint = @import("color.zig").OpaquePaint;
const Paint = @import("color.zig").Paint;
const PaletteData = @import("color.zig").PaletteData;
const GlyphLayersIterator = @import("color.zig").GlyphLayersIterator;
pub const CharmapIterator = struct {
face: Face,
index: u32,
charcode: u32,
pub fn init(face: Face) CharmapIterator {
var i: u32 = 0;
const cc = c.FT_Get_First_Char(face.handle, &i);
return .{
.face = face,
.index = i,
.charcode = @as(u32, @intCast(cc)),
};
}
pub fn next(self: *CharmapIterator) ?u32 {
self.charcode = @as(u32, @intCast(c.FT_Get_Next_Char(self.face.handle, self.charcode, &self.index)));
return if (self.index != 0)
self.charcode
else
null;
}
};
const Face = @This();
handle: c.FT_Face,
pub fn deinit(self: Face) void {
_ = c.FT_Done_Face(self.handle);
}
pub fn attachFile(self: Face, path: [*:0]const u8) Error!void {
return self.attachStream(.{
.flags = .{ .path = true },
.data = .{ .path = path },
});
}
pub fn attachMemory(self: Face, bytes: []const u8) Error!void {
return self.attachStream(.{
.flags = .{ .memory = true },
.data = .{ .memory = bytes },
});
}
pub fn attachStream(self: Face, args: OpenArgs) Error!void {
return intToError(c.FT_Attach_Stream(self.handle, &args.cast()));
}
pub fn loadGlyph(self: Face, index: u32, flags: LoadFlags) Error!void {
return intToError(c.FT_Load_Glyph(self.handle, index, @as(i32, @bitCast(flags))));
}
pub fn loadChar(self: Face, char: u32, flags: LoadFlags) Error!void {
return intToError(c.FT_Load_Char(self.handle, char, @as(i32, @bitCast(flags))));
}
pub fn setCharSize(self: Face, pt_width: i32, pt_height: i32, horz_resolution: u16, vert_resolution: u16) Error!void {
return intToError(c.FT_Set_Char_Size(self.handle, pt_width, pt_height, horz_resolution, vert_resolution));
}
pub fn setPixelSizes(self: Face, pixel_width: u32, pixel_height: u32) Error!void {
return intToError(c.FT_Set_Pixel_Sizes(self.handle, pixel_width, pixel_height));
}
pub fn requestSize(self: Face, req: SizeRequest) Error!void {
var req_mut = req;
return intToError(c.FT_Request_Size(self.handle, &req_mut));
}
pub fn selectSize(self: Face, strike_index: i32) Error!void {
return intToError(c.FT_Select_Size(self.handle, strike_index));
}
pub fn setTransform(self: Face, matrix: ?Matrix, delta: ?Vector) Error!void {
var matrix_mut = matrix;
var delta_mut = delta;
return c.FT_Set_Transform(self.handle, if (matrix_mut) |*m| m else null, if (delta_mut) |*d| d else null);
}
pub fn getTransform(self: Face) std.meta.Tuple(&.{ Matrix, Vector }) {
var matrix: Matrix = undefined;
var delta: Vector = undefined;
c.FT_Get_Transform(self.handle, &matrix, &delta);
return .{ matrix, delta };
}
pub fn getCharIndex(self: Face, char: u32) ?u32 {
const i = c.FT_Get_Char_Index(self.handle, char);
return if (i == 0) null else i;
}
pub fn getNameIndex(self: Face, name: [:0]const u8) ?u32 {
const i = c.FT_Get_Name_Index(self.handle, name.ptr);
return if (i == 0) null else i;
}
pub fn getKerning(self: Face, left_char_index: u32, right_char_index: u32, mode: KerningMode) Error!Vector {
var kerning: Vector = undefined;
try intToError(c.FT_Get_Kerning(self.handle, left_char_index, right_char_index, @intFromEnum(mode), &kerning));
return kerning;
}
pub fn getTrackKerning(self: Face, point_size: i32, degree: i32) Error!i32 {
var kerning: c_long = 0;
try intToError(c.FT_Get_Track_Kerning(self.handle, point_size, degree, kerning));
return @as(i32, @intCast(kerning));
}
pub fn getGlyphName(self: Face, index: u32, buf: []u8) Error!void {
try intToError(c.FT_Get_Glyph_Name(self.handle, index, buf.ptr, @as(c_uint, @intCast(buf.len))));
}
pub fn getPostscriptName(self: Face) ?[:0]const u8 {
return if (c.FT_Get_Postscript_Name(self.handle)) |face_name|
std.mem.span(@as([*:0]const u8, @ptrCast(face_name)))
else
null;
}
pub fn iterateCharmap(self: Face) CharmapIterator {
return CharmapIterator.init(self);
}
pub fn selectCharmap(self: Face, encoding: Encoding) Error!void {
return intToError(c.FT_Select_Charmap(self.handle, @intFromEnum(encoding)));
}
pub fn setCharmap(self: Face, char_map: *CharMap) Error!void {
return intToError(c.FT_Set_Charmap(self.handle, char_map));
}
pub fn getFSTypeFlags(self: Face) FSType {
return @as(FSType, @bitCast(c.FT_Get_FSType_Flags(self.handle)));
}
pub fn getCharVariantIndex(self: Face, char: u32, variant_selector: u32) ?u32 {
return switch (c.FT_Face_GetCharVariantIndex(self.handle, char, variant_selector)) {
0 => null,
else => |i| i,
};
}
pub fn getCharVariantIsDefault(self: Face, char: u32, variant_selector: u32) ?bool {
return switch (c.FT_Face_GetCharVariantIsDefault(self.handle, char, variant_selector)) {
-1 => null,
0 => false,
1 => true,
else => unreachable,
};
}
pub fn getVariantSelectors(self: Face) ?[]u32 {
return if (c.FT_Face_GetVariantSelectors(self.handle)) |chars|
@as([]u32, @ptrCast(std.mem.sliceTo(@as([*:0]u32, @ptrCast(chars)), 0)))
else
null;
}
pub fn getVariantsOfChar(self: Face, char: u32) ?[]u32 {
return if (c.FT_Face_GetVariantsOfChar(self.handle, char)) |variants|
@as([]u32, @ptrCast(std.mem.sliceTo(@as([*:0]u32, @ptrCast(variants)), 0)))
else
null;
}
pub fn getCharsOfVariant(self: Face, variant_selector: u32) ?[]u32 {
return if (c.FT_Face_GetCharsOfVariant(self.handle, variant_selector)) |chars|
@as([]u32, @ptrCast(std.mem.sliceTo(@as([*:0]u32, @ptrCast(chars)), 0)))
else
null;
}
pub fn getPaletteData(self: Face) Error!PaletteData {
var p: c.FT_Palette_Data = undefined;
try intToError(c.FT_Palette_Data_Get(self.handle, &p));
return PaletteData{ .handle = p };
}
fn selectPalette(self: Face, index: u16) Error!?[]const Color {
var color: [*:0]Color = undefined;
try intToError(c.FT_Palette_Select(self.handle, index, &color));
const pd = try getPaletteData();
return self.color[0..pd.numPaletteEntries()];
}
pub fn setPaletteForegroundColor(self: Face, color: Color) Error!void {
try intToError(c.FT_Palette_Set_Foreground_Color(self.handle, color));
}
pub fn getGlyphLayersIterator(self: Face, glyph_index: u32) GlyphLayersIterator {
return GlyphLayersIterator.init(self, glyph_index);
}
pub fn getColorGlyphPaint(self: Face, base_glyph: u32, root_transform: RootTransform) ?Paint {
var opaque_paint: OpaquePaint = undefined;
if (c.FT_Get_Color_Glyph_Paint(self.handle, base_glyph, @intFromEnum(root_transform), &opaque_paint) == 0)
return null;
return self.getPaint(opaque_paint);
}
pub fn getColorGlyphClibBox(self: Face, base_glyph: u32) ?ClipBox {
var clib_box: ClipBox = undefined;
if (c.FT_Get_Color_Glyph_ClipBox(self.handle, base_glyph, &clib_box) == 0)
return null;
return clib_box;
}
pub fn getPaint(self: Face, opaque_paint: OpaquePaint) ?Paint {
var p: c.FT_COLR_Paint = undefined;
if (c.FT_Get_Paint(self.handle, opaque_paint, &p) == 0)
return null;
return switch (@as(PaintFormat, @enumFromInt(p.format))) {
.color_layers => Paint{ .color_layers = p.u.colr_layers },
.glyph => Paint{ .glyph = p.u.glyph },
.solid => Paint{ .solid = p.u.solid },
.linear_gradient => Paint{ .linear_gradient = p.u.linear_gradient },
.radial_gradient => Paint{ .radial_gradient = p.u.radial_gradient },
.sweep_gradient => Paint{ .sweep_gradient = p.u.sweep_gradient },
.transform => Paint{ .transform = p.u.transform },
.translate => Paint{ .translate = p.u.translate },
.scale => Paint{ .scale = p.u.scale },
.rotate => Paint{ .rotate = p.u.rotate },
.skew => Paint{ .skew = p.u.skew },
.composite => Paint{ .composite = p.u.composite },
.color_glyph => Paint{ .color_glyph = p.u.colr_glyph },
};
}
pub fn newSize(self: Face) Error!Size {
var s: c.FT_Size = undefined;
try intToError(c.FT_New_Size(self.handle, &s));
return Size{ .handle = s };
}
pub fn numFaces(self: Face) u32 {
return @as(u32, @intCast(self.handle.*.num_faces));
}
pub fn faceIndex(self: Face) u32 {
return @as(u32, @intCast(self.handle.*.face_index));
}
pub fn faceFlags(self: Face) FaceFlags {
return @as(FaceFlags, @bitCast(self.handle.*.face_flags));
}
pub fn styleFlags(self: Face) StyleFlags {
return @as(StyleFlags, @bitCast(self.handle.*.style_flags));
}
pub fn numGlyphs(self: Face) u32 {
return @as(u32, @intCast(self.handle.*.num_glyphs));
}
pub fn familyName(self: Face) ?[:0]const u8 {
return if (self.handle.*.family_name) |family|
std.mem.span(@as([*:0]const u8, @ptrCast(family)))
else
null;
}
pub fn styleName(self: Face) ?[:0]const u8 {
return if (self.handle.*.style_name) |style_name|
std.mem.span(@as([*:0]const u8, @ptrCast(style_name)))
else
null;
}
pub fn numFixedSizes(self: Face) u32 {
return @as(u32, @intCast(self.handle.*.num_fixed_sizes));
}
pub fn availableSizes(self: Face) []BitmapSize {
return if (self.handle.*.available_sizes != null)
self.handle.*.available_sizes[0..self.numFixedSizes()]
else
&.{};
}
pub fn getAdvance(self: Face, glyph_index: u32, load_flags: LoadFlags) Error!i32 {
var a: c_long = 0;
try intToError(c.FT_Get_Advance(self.handle, glyph_index, @as(i32, @bitCast(load_flags)), &a));
return @as(i32, @intCast(a));
}
pub fn getAdvances(self: Face, start: u32, advances_out: []c_long, load_flags: LoadFlags) Error!void {
try intToError(c.FT_Get_Advances(self.handle, start, @as(u32, @intCast(advances_out.len)), @as(i32, @bitCast(load_flags)), advances_out.ptr));
}
pub fn numCharmaps(self: Face) u32 {
return @as(u32, @intCast(self.handle.*.num_charmaps));
}
pub fn charmaps(self: Face) []const CharMap {
return @as([*]const CharMap, @ptrCast(self.handle.*.charmaps))[0..self.numCharmaps()];
}
pub fn bbox(self: Face) BBox {
return self.handle.*.bbox;
}
pub fn unitsPerEM(self: Face) u16 {
return self.handle.*.units_per_EM;
}
pub fn ascender(self: Face) i16 {
return self.handle.*.ascender;
}
pub fn descender(self: Face) i16 {
return self.handle.*.descender;
}
pub fn height(self: Face) i16 {
return self.handle.*.height;
}
pub fn maxAdvanceWidth(self: Face) i16 {
return self.handle.*.max_advance_width;
}
pub fn maxAdvanceHeight(self: Face) i16 {
return self.handle.*.max_advance_height;
}
pub fn underlinePosition(self: Face) i16 {
return self.handle.*.underline_position;
}
pub fn underlineThickness(self: Face) i16 {
return self.handle.*.underline_thickness;
}
pub fn glyph(self: Face) GlyphSlot {
return .{ .handle = self.handle.*.glyph };
}
pub fn size(self: Face) Size {
return Size{ .handle = self.handle.*.size };
}
pub fn charmap(self: Face) CharMap {
return self.handle.*.charmap.*;
}
pub fn hasHorizontal(self: Face) bool {
return c.FT_HAS_HORIZONTAL(self.handle);
}
pub fn hasVertical(self: Face) bool {
return c.FT_HAS_VERTICAL(self.handle);
}
pub fn hasKerning(self: Face) bool {
return c.FT_HAS_KERNING(self.handle);
}
pub fn hasFixedSizes(self: Face) bool {
return c.FT_HAS_FIXED_SIZES(self.handle);
}
pub fn hasGlyphNames(self: Face) bool {
return c.FT_HAS_GLYPH_NAMES(self.handle);
}
pub fn hasColor(self: Face) bool {
return c.FT_HAS_COLOR(self.handle);
}
pub fn isScalable(self: Face) bool {
return c.FT_IS_SCALABLE(self.handle);
}
pub fn isSfnt(self: Face) bool {
return c.FT_IS_SFNT(self.handle);
}
pub fn isFixedWidth(self: Face) bool {
return c.FT_IS_FIXED_WIDTH(self.handle);
}
pub fn isCidKeyed(self: Face) bool {
return c.FT_IS_CID_KEYED(self.handle);
}
pub fn isTricky(self: Face) bool {
return c.FT_IS_TRICKY(self.handle);
}

View file

@ -1,105 +0,0 @@
const c = @import("c.zig");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const Glyph = @import("glyph.zig").Glyph;
const Library = @import("freetype.zig").Library;
const Face = @import("freetype.zig").Face;
const RenderMode = @import("freetype.zig").RenderMode;
const Matrix = @import("types.zig").Matrix;
const Outline = @import("image.zig").Outline;
const GlyphFormat = @import("image.zig").GlyphFormat;
const Vector = @import("image.zig").Vector;
const GlyphMetrics = @import("image.zig").GlyphMetrics;
const Bitmap = @import("image.zig").Bitmap;
const GlyphSlot = @This();
pub const SubGlyphInfo = struct {
index: i32,
flags: c_uint,
arg1: i32,
arg2: i32,
transform: Matrix,
};
handle: c.FT_GlyphSlot,
pub fn library(self: GlyphSlot) Library {
return .{ .handle = self.handle.*.library };
}
pub fn face(self: GlyphSlot) Face {
return .{ .handle = self.handle.*.face };
}
pub fn next(self: GlyphSlot) GlyphSlot {
return .{ .handle = self.handle.*.next };
}
pub fn glyphIndex(self: GlyphSlot) u32 {
return self.handle.*.glyph_index;
}
pub fn metrics(self: GlyphSlot) GlyphMetrics {
return self.handle.*.metrics;
}
pub fn linearHoriAdvance(self: GlyphSlot) i32 {
return @as(i32, @intCast(self.handle.*.linearHoriAdvance));
}
pub fn linearVertAdvance(self: GlyphSlot) i32 {
return @as(i32, @intCast(self.handle.*.linearVertAdvance));
}
pub fn advance(self: GlyphSlot) Vector {
return self.handle.*.advance;
}
pub fn format(self: GlyphSlot) GlyphFormat {
return @as(GlyphFormat, @enumFromInt(self.handle.*.format));
}
pub fn ownBitmap(self: GlyphSlot) Error!void {
try intToError(c.FT_GlyphSlot_Own_Bitmap(self.handle));
}
pub fn bitmap(self: GlyphSlot) Bitmap {
return .{ .handle = self.handle.*.bitmap };
}
pub fn bitmapLeft(self: GlyphSlot) i32 {
return self.handle.*.bitmap_left;
}
pub fn bitmapTop(self: GlyphSlot) i32 {
return self.handle.*.bitmap_top;
}
pub fn outline(self: GlyphSlot) ?Outline {
return if (self.format() == .outline) .{ .handle = &self.handle.*.outline } else null;
}
pub fn lsbDelta(self: GlyphSlot) i32 {
return @as(i32, @intCast(self.handle.*.lsb_delta));
}
pub fn rsbDelta(self: GlyphSlot) i32 {
return @as(i32, @intCast(self.handle.*.rsb_delta));
}
pub fn render(self: GlyphSlot, render_mode: RenderMode) Error!void {
return intToError(c.FT_Render_Glyph(self.handle, @intFromEnum(render_mode)));
}
pub fn getSubGlyphInfo(self: GlyphSlot, sub_index: u32) Error!SubGlyphInfo {
var info: SubGlyphInfo = undefined;
try intToError(c.FT_Get_SubGlyph_Info(self.handle, sub_index, &info.index, &info.flags, &info.arg1, &info.arg2, &info.transform));
return info;
}
pub fn getGlyph(self: GlyphSlot) Error!Glyph {
var res: c.FT_Glyph = undefined;
try intToError(c.FT_Get_Glyph(self.handle, &res));
return Glyph{ .handle = res };
}

View file

@ -1,84 +0,0 @@
const std = @import("std");
const c = @import("c.zig");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const Face = @import("freetype.zig").Face;
const Stroker = @import("stroke.zig").Stroker;
const OpenArgs = @import("freetype.zig").OpenArgs;
const Bitmap = @import("image.zig").Bitmap;
const Outline = @import("image.zig").Outline;
const RasterParams = @import("image.zig").Raster.Params;
const LcdFilter = @import("lcdfilter.zig").LcdFilter;
const Library = @This();
pub const Version = struct {
major: i32,
minor: i32,
patch: i32,
};
handle: c.FT_Library,
pub fn init() Error!Library {
var lib = Library{ .handle = undefined };
try intToError(c.FT_Init_FreeType(&lib.handle));
return lib;
}
pub fn deinit(self: Library) void {
_ = c.FT_Done_FreeType(self.handle);
}
pub fn createFace(self: Library, path: [*:0]const u8, face_index: i32) Error!Face {
return self.openFace(.{
.flags = .{ .path = true },
.data = .{ .path = path },
}, face_index);
}
pub fn createFaceMemory(self: Library, bytes: []const u8, face_index: i32) Error!Face {
return self.openFace(.{
.flags = .{ .memory = true },
.data = .{ .memory = bytes },
}, face_index);
}
pub fn openFace(self: Library, args: OpenArgs, face_index: i32) Error!Face {
var f: c.FT_Face = undefined;
try intToError(c.FT_Open_Face(self.handle, &args.cast(), face_index, &f));
return Face{ .handle = f };
}
pub fn version(self: Library) Version {
var v: Version = undefined;
c.FT_Library_Version(
self.handle,
&v.major,
&v.minor,
&v.patch,
);
return v;
}
pub fn createStroker(self: Library) Error!Stroker {
var s: c.FT_Stroker = undefined;
try intToError(c.FT_Stroker_New(self.handle, &s));
return Stroker{ .handle = s };
}
pub fn createOutlineFromBitmap(self: Library, bitmap: Bitmap) Error!Outline {
var o: Outline = undefined;
try intToError(c.FT_Outline_Get_Bitmap(self.handle, o.handle, &bitmap.handle));
return o;
}
pub fn renderOutline(self: Library, outline: Outline, params: *RasterParams) Error!void {
try intToError(FT_Outline_Render(self.handle, outline.handle, params));
}
pub fn setLcdFilter(self: Library, lcd_filter: LcdFilter) Error!void {
return intToError(c.FT_Library_SetLcdFilter(self.handle, @intFromEnum(lcd_filter)));
}
pub extern fn FT_Outline_Render(library: c.FT_Library, outline: [*c]c.FT_Outline, params: [*c]RasterParams) c_int;

View file

@ -1,10 +0,0 @@
pub usingnamespace @cImport({
@cInclude("freetype/ftadvanc.h");
@cInclude("freetype/ftbbox.h");
@cInclude("freetype/ftbitmap.h");
@cInclude("freetype/ftcolor.h");
@cInclude("freetype/ftlcdfil.h");
@cInclude("freetype/ftsizes.h");
@cInclude("freetype/ftstroke.h");
@cInclude("freetype/fttrigon.h");
});

View file

@ -1,165 +0,0 @@
const std = @import("std");
const testing = std.testing;
const c = @import("c.zig");
const Face = @import("freetype.zig").Face;
pub const Color = c.FT_Color;
pub const LayerIterator = c.FT_LayerIterator;
pub const ColorStopIterator = c.FT_ColorStopIterator;
pub const ColorIndex = c.FT_ColorIndex;
pub const ColorStop = c.FT_ColorStop;
pub const ColorLine = c.FT_ColorLine;
pub const Affine23 = c.FT_Affine23;
pub const OpaquePaint = c.FT_OpaquePaint;
pub const PaintColrLayers = c.FT_PaintColrLayers;
pub const PaintSolid = c.FT_PaintSolid;
pub const PaintLinearGradient = c.FT_PaintLinearGradient;
pub const PaintRadialGradient = c.FT_PaintRadialGradient;
pub const PaintSweepGradient = c.FT_PaintSweepGradient;
pub const PaintGlyph = c.FT_PaintGlyph;
pub const PaintColrGlyph = c.FT_PaintColrGlyph;
pub const PaintTransform = c.FT_PaintTransform;
pub const PaintTranslate = c.FT_PaintTranslate;
pub const PaintScale = c.FT_PaintScale;
pub const PaintRotate = c.FT_PaintRotate;
pub const PaintSkew = c.FT_PaintSkew;
pub const PaintComposite = c.FT_PaintComposite;
pub const ClipBox = c.FT_ClipBox;
pub const RootTransform = enum(u1) {
include_root_transform = c.FT_COLOR_INCLUDE_ROOT_TRANSFORM,
no_root_transform = c.FT_COLOR_NO_ROOT_TRANSFORM,
};
pub const PaintExtend = enum(u2) {
pad = c.FT_COLR_PAINT_EXTEND_PAD,
repeat = c.FT_COLR_PAINT_EXTEND_REPEAT,
reflect = c.FT_COLR_PAINT_EXTEND_REFLECT,
};
pub const PaintFormat = enum(u8) {
color_layers = c.FT_COLR_PAINTFORMAT_COLR_LAYERS,
solid = c.FT_COLR_PAINTFORMAT_SOLID,
linear_gradient = c.FT_COLR_PAINTFORMAT_LINEAR_GRADIENT,
radial_gradient = c.FT_COLR_PAINTFORMAT_RADIAL_GRADIENT,
sweep_gradient = c.FT_COLR_PAINTFORMAT_SWEEP_GRADIENT,
glyph = c.FT_COLR_PAINTFORMAT_GLYPH,
color_glyph = c.FT_COLR_PAINTFORMAT_COLR_GLYPH,
transform = c.FT_COLR_PAINTFORMAT_TRANSFORM,
translate = c.FT_COLR_PAINTFORMAT_TRANSLATE,
scale = c.FT_COLR_PAINTFORMAT_SCALE,
rotate = c.FT_COLR_PAINTFORMAT_ROTATE,
skew = c.FT_COLR_PAINTFORMAT_SKEW,
composite = c.FT_COLR_PAINTFORMAT_COMPOSITE,
};
pub const CompositeMode = enum(u5) {
clear = c.FT_COLR_COMPOSITE_CLEAR,
src = c.FT_COLR_COMPOSITE_SRC,
dest = c.FT_COLR_COMPOSITE_DEST,
src_over = c.FT_COLR_COMPOSITE_SRC_OVER,
dest_over = c.FT_COLR_COMPOSITE_DEST_OVER,
src_in = c.FT_COLR_COMPOSITE_SRC_IN,
dest_in = c.FT_COLR_COMPOSITE_DEST_IN,
src_out = c.FT_COLR_COMPOSITE_SRC_OUT,
dest_out = c.FT_COLR_COMPOSITE_DEST_OUT,
src_atop = c.FT_COLR_COMPOSITE_SRC_ATOP,
dest_atop = c.FT_COLR_COMPOSITE_DEST_ATOP,
xor = c.FT_COLR_COMPOSITE_XOR,
plus = c.FT_COLR_COMPOSITE_PLUS,
screen = c.FT_COLR_COMPOSITE_SCREEN,
overlay = c.FT_COLR_COMPOSITE_OVERLAY,
darken = c.FT_COLR_COMPOSITE_DARKEN,
lighten = c.FT_COLR_COMPOSITE_LIGHTEN,
color_dodge = c.FT_COLR_COMPOSITE_COLOR_DODGE,
color_burn = c.FT_COLR_COMPOSITE_COLOR_BURN,
hard_light = c.FT_COLR_COMPOSITE_HARD_LIGHT,
soft_light = c.FT_COLR_COMPOSITE_SOFT_LIGHT,
difference = c.FT_COLR_COMPOSITE_DIFFERENCE,
exclusion = c.FT_COLR_COMPOSITE_EXCLUSION,
multiply = c.FT_COLR_COMPOSITE_MULTIPLY,
hsl_hue = c.FT_COLR_COMPOSITE_HSL_HUE,
hsl_saturation = c.FT_COLR_COMPOSITE_HSL_SATURATION,
hsl_color = c.FT_COLR_COMPOSITE_HSL_COLOR,
hsl_luminosity = c.FT_COLR_COMPOSITE_HSL_LUMINOSITY,
};
pub const Paint = union(PaintFormat) {
color_layers: PaintColrLayers,
glyph: PaintGlyph,
solid: PaintSolid,
linear_gradient: PaintLinearGradient,
radial_gradient: PaintRadialGradient,
sweep_gradient: PaintSweepGradient,
transform: PaintTransform,
translate: PaintTranslate,
scale: PaintScale,
rotate: PaintRotate,
skew: PaintSkew,
composite: PaintComposite,
color_glyph: PaintColrGlyph,
};
pub const PaletteData = struct {
handle: c.FT_Palette_Data,
pub fn numPalettes(self: PaletteData) u16 {
return self.handle.num_palettes;
}
pub fn paletteNameIDs(self: PaletteData) ?[]const u16 {
return self.handle.palette_name_ids[0..self.numPalettes()];
}
pub fn paletteFlags(self: PaletteData) ?[]const u16 {
return self.handle.palette_flags[0..self.numPalettes()];
}
pub fn paletteFlag(self: PaletteData, index: u32) PaletteFlags {
return @as(PaletteFlags, @bitCast(self.handle.palette_flags[index]));
}
pub fn numPaletteEntries(self: PaletteData) u16 {
return self.handle.num_palette_entries;
}
pub fn paletteEntryNameIDs(self: PaletteData) ?[]const u16 {
return self.handle.palette_entry_name_ids[0..self.numPaletteEntries()];
}
};
pub const PaletteFlags = packed struct(c_ushort) {
for_light_background: bool = false,
for_dark_background: bool = false,
_padding: u14 = 0,
};
pub const GlyphLayersIterator = struct {
face: Face,
glyph_index: u32,
layer_glyph_index: u32,
layer_color_index: u32,
iterator: LayerIterator,
pub fn init(face: Face, glyph_index: u32) GlyphLayersIterator {
var iterator: LayerIterator = undefined;
iterator.p = null;
return .{
.face = face,
.glyph_index = glyph_index,
.layer_glyph_index = 0,
.layer_color_index = 0,
.iterator = iterator,
};
}
pub fn next(self: *GlyphLayersIterator) bool {
return if (c.FT_Get_Color_Glyph_Layer(
self.face.handle,
self.glyph_index,
&self.layer_glyph_index,
&self.layer_color_index,
&self.iterator,
) == 0) false else true;
}
};

View file

@ -1,71 +0,0 @@
const _c = @import("c.zig");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const Vector = @import("image.zig").Vector;
const Matrix = @import("types.zig").Matrix;
pub const angel_pi = _c.FT_ANGLE_PI;
pub const angel_2pi = _c.FT_ANGLE_2PI;
pub const angel_pi2 = _c.FT_ANGLE_PI2;
pub const angel_pi4 = _c.FT_ANGLE_PI4;
pub fn mulDiv(a: i32, b: i32, c: i32) i32 {
return @as(i32, @intCast(_c.FT_MulDiv(a, b, c)));
}
pub fn mulFix(a: i32, b: i32) i32 {
return @as(i32, @intCast(_c.FT_MulFix(a, b)));
}
pub fn divFix(a: i32, b: i32) i32 {
return @as(i32, @intCast(_c.FT_DivFix(a, b)));
}
pub fn roundFix(a: i32) i32 {
return @as(i32, @intCast(_c.FT_RoundFix(a)));
}
pub fn ceilFix(a: i32) i32 {
return @as(i32, @intCast(_c.FT_CeilFix(a)));
}
pub fn floorFix(a: i32) i32 {
return @as(i32, @intCast(_c.FT_FloorFix(a)));
}
pub fn vectorTransform(vec: *Vector, matrix: Matrix) void {
_c.FT_Vector_Transform(vec, &matrix);
}
pub fn matrixMul(a: Matrix, b: *Matrix) void {
_c.FT_Matrix_Multiply(&a, b);
}
pub fn matrixInvert(m: *Matrix) Error!void {
try intToError(_c.FT_Matrix_Invert(m));
}
pub fn angleDiff(a: i32, b: i32) i32 {
return @as(i32, @intCast(_c.FT_Angle_Diff(a, b)));
}
pub fn vectorUnit(vec: *Vector, angle: i32) void {
_c.FT_Vector_Unit(vec, angle);
}
pub fn vectorRotate(vec: *Vector, angle: i32) void {
_c.FT_Vector_Rotate(vec, angle);
}
pub fn vectorLength(vec: *Vector) i32 {
return @as(i32, @intCast(_c.FT_Vector_Length(vec)));
}
pub fn vectorPolarize(vec: *Vector, length: *c_long, angle: *c_long) void {
_c.FT_Vector_Polarize(vec, length, angle);
}
pub fn vectorFromPolar(vec: *Vector, length: i32, angle: i32) void {
_c.FT_Vector_From_Polar(vec, length, angle);
}

View file

@ -1,290 +0,0 @@
const c = @import("c.zig");
pub const Error = error{
CannotOpenResource,
UnknownFileFormat,
InvalidFileFormat,
InvalidVersion,
LowerModuleVersion,
InvalidArgument,
UnimplementedFeature,
InvalidTable,
InvalidOffset,
ArrayTooLarge,
MissingModule,
MissingProperty,
InvalidGlyphIndex,
InvalidCharacterCode,
InvalidGlyphFormat,
CannotRenderGlyph,
InvalidOutline,
InvalidComposite,
TooManyHints,
InvalidPixelSize,
InvalidHandle,
InvalidLibraryHandle,
InvalidDriverHandle,
InvalidFaceHandle,
InvalidSizeHandle,
InvalidSlotHandle,
InvalidCharMapHandle,
InvalidCacheHandle,
InvalidStreamHandle,
TooManyDrivers,
TooManyExtensions,
OutOfMemory,
UnlistedObject,
CannotOpenStream,
InvalidStreamSeek,
InvalidStreamSkip,
InvalidStreamRead,
InvalidStreamOperation,
InvalidFrameOperation,
NestedFrameAccess,
InvalidFrameRead,
RasterUninitialized,
RasterCorrupted,
RasterOverflow,
RasterNegativeHeight,
TooManyCaches,
InvalidOpcode,
TooFewArguments,
StackOverflow,
CodeOverflow,
BadArgument,
DivideByZero,
InvalidReference,
DebugOpCode,
ENDFInExecStream,
NestedDEFS,
InvalidCodeRange,
ExecutionTooLong,
TooManyFunctionDefs,
TooManyInstructionDefs,
TableMissing,
HorizHeaderMissing,
LocationsMissing,
NameTableMissing,
CMapTableMissing,
HmtxTableMissing,
PostTableMissing,
InvalidHorizMetrics,
InvalidCharMapFormat,
InvalidPPem,
InvalidVertMetrics,
CouldNotFindContext,
InvalidPostTableFormat,
InvalidPostTable,
Syntax,
StackUnderflow,
Ignore,
NoUnicodeGlyphName,
MissingStartfontField,
MissingFontField,
MissingSizeField,
MissingFontboundingboxField,
MissingCharsField,
MissingStartcharField,
MissingEncodingField,
MissingBbxField,
BbxTooBig,
CorruptedFontHeader,
CorruptedFontGlyphs,
};
pub fn intToError(err: c_int) Error!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,
};
}
pub fn errorToInt(err: Error) c_int {
return switch (err) {
Error.CannotOpenResource => c.FT_Err_Cannot_Open_Resource,
Error.UnknownFileFormat => c.FT_Err_Unknown_File_Format,
Error.InvalidFileFormat => c.FT_Err_Invalid_File_Format,
Error.InvalidVersion => c.FT_Err_Invalid_Version,
Error.LowerModuleVersion => c.FT_Err_Lower_Module_Version,
Error.InvalidArgument => c.FT_Err_Invalid_Argument,
Error.UnimplementedFeature => c.FT_Err_Unimplemented_Feature,
Error.InvalidTable => c.FT_Err_Invalid_Table,
Error.InvalidOffset => c.FT_Err_Invalid_Offset,
Error.ArrayTooLarge => c.FT_Err_Array_Too_Large,
Error.MissingModule => c.FT_Err_Missing_Module,
Error.MissingProperty => c.FT_Err_Missing_Property,
Error.InvalidGlyphIndex => c.FT_Err_Invalid_Glyph_Index,
Error.InvalidCharacterCode => c.FT_Err_Invalid_Character_Code,
Error.InvalidGlyphFormat => c.FT_Err_Invalid_Glyph_Format,
Error.CannotRenderGlyph => c.FT_Err_Cannot_Render_Glyph,
Error.InvalidOutline => c.FT_Err_Invalid_Outline,
Error.InvalidComposite => c.FT_Err_Invalid_Composite,
Error.TooManyHints => c.FT_Err_Too_Many_Hints,
Error.InvalidPixelSize => c.FT_Err_Invalid_Pixel_Size,
Error.InvalidHandle => c.FT_Err_Invalid_Handle,
Error.InvalidLibraryHandle => c.FT_Err_Invalid_Library_Handle,
Error.InvalidDriverHandle => c.FT_Err_Invalid_Driver_Handle,
Error.InvalidFaceHandle => c.FT_Err_Invalid_Face_Handle,
Error.InvalidSizeHandle => c.FT_Err_Invalid_Size_Handle,
Error.InvalidSlotHandle => c.FT_Err_Invalid_Slot_Handle,
Error.InvalidCharMapHandle => c.FT_Err_Invalid_CharMap_Handle,
Error.InvalidCacheHandle => c.FT_Err_Invalid_Cache_Handle,
Error.InvalidStreamHandle => c.FT_Err_Invalid_Stream_Handle,
Error.TooManyDrivers => c.FT_Err_Too_Many_Drivers,
Error.TooManyExtensions => c.FT_Err_Too_Many_Extensions,
Error.OutOfMemory => c.FT_Err_Out_Of_Memory,
Error.UnlistedObject => c.FT_Err_Unlisted_Object,
Error.CannotOpenStream => c.FT_Err_Cannot_Open_Stream,
Error.InvalidStreamSeek => c.FT_Err_Invalid_Stream_Seek,
Error.InvalidStreamSkip => c.FT_Err_Invalid_Stream_Skip,
Error.InvalidStreamRead => c.FT_Err_Invalid_Stream_Read,
Error.InvalidStreamOperation => c.FT_Err_Invalid_Stream_Operation,
Error.InvalidFrameOperation => c.FT_Err_Invalid_Frame_Operation,
Error.NestedFrameAccess => c.FT_Err_Nested_Frame_Access,
Error.InvalidFrameRead => c.FT_Err_Invalid_Frame_Read,
Error.RasterUninitialized => c.FT_Err_Raster_Uninitialized,
Error.RasterCorrupted => c.FT_Err_Raster_Corrupted,
Error.RasterOverflow => c.FT_Err_Raster_Overflow,
Error.RasterNegativeHeight => c.FT_Err_Raster_Negative_Height,
Error.TooManyCaches => c.FT_Err_Too_Many_Caches,
Error.InvalidOpcode => c.FT_Err_Invalid_Opcode,
Error.TooFewArguments => c.FT_Err_Too_Few_Arguments,
Error.StackOverflow => c.FT_Err_Stack_Overflow,
Error.CodeOverflow => c.FT_Err_Code_Overflow,
Error.BadArgument => c.FT_Err_Bad_Argument,
Error.DivideByZero => c.FT_Err_Divide_By_Zero,
Error.InvalidReference => c.FT_Err_Invalid_Reference,
Error.DebugOpCode => c.FT_Err_Debug_OpCode,
Error.ENDFInExecStream => c.FT_Err_ENDF_In_Exec_Stream,
Error.NestedDEFS => c.FT_Err_Nested_DEFS,
Error.InvalidCodeRange => c.FT_Err_Invalid_CodeRange,
Error.ExecutionTooLong => c.FT_Err_Execution_Too_Long,
Error.TooManyFunctionDefs => c.FT_Err_Too_Many_Function_Defs,
Error.TooManyInstructionDefs => c.FT_Err_Too_Many_Instruction_Defs,
Error.TableMissing => c.FT_Err_Table_Missing,
Error.HorizHeaderMissing => c.FT_Err_Horiz_Header_Missing,
Error.LocationsMissing => c.FT_Err_Locations_Missing,
Error.NameTableMissing => c.FT_Err_Name_Table_Missing,
Error.CMapTableMissing => c.FT_Err_CMap_Table_Missing,
Error.HmtxTableMissing => c.FT_Err_Hmtx_Table_Missing,
Error.PostTableMissing => c.FT_Err_Post_Table_Missing,
Error.InvalidHorizMetrics => c.FT_Err_Invalid_Horiz_Metrics,
Error.InvalidCharMapFormat => c.FT_Err_Invalid_CharMap_Format,
Error.InvalidPPem => c.FT_Err_Invalid_PPem,
Error.InvalidVertMetrics => c.FT_Err_Invalid_Vert_Metrics,
Error.CouldNotFindContext => c.FT_Err_Could_Not_Find_Context,
Error.InvalidPostTableFormat => c.FT_Err_Invalid_Post_Table_Format,
Error.InvalidPostTable => c.FT_Err_Invalid_Post_Table,
Error.Syntax => c.FT_Err_Syntax_Error,
Error.StackUnderflow => c.FT_Err_Stack_Underflow,
Error.Ignore => c.FT_Err_Ignore,
Error.NoUnicodeGlyphName => c.FT_Err_No_Unicode_Glyph_Name,
Error.MissingStartfontField => c.FT_Err_Missing_Startfont_Field,
Error.MissingFontField => c.FT_Err_Missing_Font_Field,
Error.MissingSizeField => c.FT_Err_Missing_Size_Field,
Error.MissingFontboundingboxField => c.FT_Err_Missing_Fontboundingbox_Field,
Error.MissingCharsField => c.FT_Err_Missing_Chars_Field,
Error.MissingStartcharField => c.FT_Err_Missing_Startchar_Field,
Error.MissingEncodingField => c.FT_Err_Missing_Encoding_Field,
Error.MissingBbxField => c.FT_Err_Missing_Bbx_Field,
Error.BbxTooBig => c.FT_Err_Bbx_Too_Big,
Error.CorruptedFontHeader => c.FT_Err_Corrupted_Font_Header,
Error.CorruptedFontGlyphs => c.FT_Err_Corrupted_Font_Glyphs,
};
}
test "error convertion" {
const expectError = @import("std").testing.expectError;
try intToError(c.FT_Err_Ok);
try expectError(Error.OutOfMemory, intToError(c.FT_Err_Out_Of_Memory));
}

View file

@ -1,193 +0,0 @@
const std = @import("std");
const testing = std.testing;
const c = @import("c.zig");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const Generic = @import("types.zig").Generic;
pub const Library = @import("Library.zig");
pub const Face = @import("Face.zig");
pub const GlyphSlot = @import("GlyphSlot.zig");
pub const SizeRequest = c.FT_Size_RequestRec;
pub const BitmapSize = c.FT_Bitmap_Size;
pub const CharMap = c.FT_CharMapRec;
pub const SizeMetrics = c.FT_Size_Metrics;
pub const KerningMode = enum(u2) {
default = c.FT_KERNING_DEFAULT,
unfitted = c.FT_KERNING_UNFITTED,
unscaled = c.FT_KERNING_UNSCALED,
};
pub const RenderMode = enum(u3) {
normal = c.FT_RENDER_MODE_NORMAL,
light = c.FT_RENDER_MODE_LIGHT,
mono = c.FT_RENDER_MODE_MONO,
lcd = c.FT_RENDER_MODE_LCD,
lcd_v = c.FT_RENDER_MODE_LCD_V,
sdf = c.FT_RENDER_MODE_SDF,
};
pub const SizeRequestType = enum(u3) {
nominal = c.FT_SIZE_REQUEST_TYPE_NOMINAL,
real_dim = c.FT_SIZE_REQUEST_TYPE_REAL_DIM,
bbox = c.FT_SIZE_REQUEST_TYPE_BBOX,
cell = c.FT_SIZE_REQUEST_TYPE_CELL,
scales = c.FT_SIZE_REQUEST_TYPE_SCALES,
max = c.FT_SIZE_REQUEST_TYPE_MAX,
};
pub const Encoding = enum(u31) {
none = c.FT_ENCODING_NONE,
ms_symbol = c.FT_ENCODING_MS_SYMBOL,
unicode = c.FT_ENCODING_UNICODE,
sjis = c.FT_ENCODING_SJIS,
prc = c.FT_ENCODING_PRC,
big5 = c.FT_ENCODING_BIG5,
wansung = c.FT_ENCODING_WANSUNG,
johab = c.FT_ENCODING_JOHAB,
adobe_standard = c.FT_ENCODING_ADOBE_STANDARD,
adobe_expert = c.FT_ENCODING_ADOBE_EXPERT,
adobe_custom = c.FT_ENCODING_ADOBE_CUSTOM,
adobe_latin_1 = c.FT_ENCODING_ADOBE_LATIN_1,
old_latin_2 = c.FT_ENCODING_OLD_LATIN_2,
apple_roman = c.FT_ENCODING_APPLE_ROMAN,
};
pub const Size = struct {
handle: c.FT_Size,
pub fn face(self: Size) Face {
return Face{ .handle = self.handle.*.face };
}
pub fn generic(self: Size) Generic {
return self.handle.*.generic;
}
pub fn metrics(self: Size) SizeMetrics {
return self.handle.*.metrics;
}
pub fn activate(self: Size) Error!void {
try intToError(c.FT_Activate_Size(self.handle));
}
pub fn deinit(self: Size) void {
intToError(c.FT_Done_Size(self.handle)) catch |err| {
std.log.err("mach/freetype: Failed to destroy Size: {}", .{err});
};
}
};
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 const FaceFlags = packed struct(c_long) {
scalable: bool = false,
fixed_sizes: bool = false,
fixed_width: bool = false,
sfnt: bool = false,
horizontal: bool = false,
vertical: bool = false,
kerning: bool = false,
fast_glyphs: bool = false,
multiple_masters: bool = false,
glyph_names: bool = false,
external_stream: bool = false,
hinter: bool = false,
cid_keyed: bool = false,
tricky: bool = false,
color: bool = false,
variation: bool = false,
svg: bool = false,
sbix: bool = false,
sbix_overlay: bool = false,
_padding: if (@sizeOf(c_long) == 4) u13 else u45 = 0,
};
pub const FSType = packed struct(c_ushort) {
installable_embedding: bool = false,
restriced_license_embedding: bool = false,
preview_and_print_embedding: bool = false,
editable_embedding: bool = false,
_padding: u4 = 0,
no_subsetting: bool = false,
bitmap_embedding_only: bool = false,
_padding0: u6 = 0,
};
pub const StyleFlags = packed struct(c_long) {
italic: bool = false,
bold: bool = false,
_padding: if (@sizeOf(c_long) == 4) u30 else u62 = 0,
};
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 OpenArgs = struct {
flags: OpenFlags,
data: union(enum) {
memory: []const u8,
path: [*:0]const u8,
stream: c.FT_Stream,
driver: c.FT_Module,
params: []const c.FT_Parameter,
},
pub fn cast(self: OpenArgs) c.FT_Open_Args {
var oa: c.FT_Open_Args = undefined;
oa.flags = @as(u32, @bitCast(self.flags));
switch (self.data) {
.memory => |d| {
oa.memory_base = d.ptr;
oa.memory_size = @as(u31, @intCast(d.len));
},
// The Freetype API requires a mutable string.
// This is an oversight, Freetype actually never writes to this string.
.path => |d| oa.pathname = @constCast(d),
.stream => |d| oa.stream = d,
.driver => |d| oa.driver = d,
.params => |*d| {
oa.params = @as(*c.FT_Parameter, @ptrFromInt(@intFromPtr(d.ptr)));
oa.num_params = @as(u31, @intCast(d.len));
},
}
return oa;
}
};
pub fn getCharmapIndex(self: [*c]CharMap) ?u32 {
const i = c.FT_Get_Charmap_Index(self);
return if (i == -1) null else @as(u32, @intCast(i));
}

View file

@ -1,172 +0,0 @@
const std = @import("std");
const c = @import("c.zig");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const Stroker = @import("stroke.zig").Stroker;
const Library = @import("freetype.zig").Library;
const RenderMode = @import("freetype.zig").RenderMode;
const SizeMetrics = @import("freetype.zig").SizeMetrics;
const Matrix = @import("types.zig").Matrix;
const BBox = @import("types.zig").BBox;
const Outline = @import("image.zig").Outline;
const GlyphFormat = @import("image.zig").GlyphFormat;
const Vector = @import("image.zig").Vector;
const Bitmap = @import("image.zig").Bitmap;
pub const BBoxMode = enum(u2) {
// https://freetype.org/freetype2/docs/reference/ft2-glyph_management.html#ft_glyph_bbox_mode
// both `unscaled` and `subpixel` are set to 0
unscaled_or_subpixels = c.FT_GLYPH_BBOX_UNSCALED,
gridfit = c.FT_GLYPH_BBOX_GRIDFIT,
truncate = c.FT_GLYPH_BBOX_TRUNCATE,
pixels = c.FT_GLYPH_BBOX_PIXELS,
};
pub const Glyph = struct {
handle: c.FT_Glyph,
pub fn deinit(self: Glyph) void {
c.FT_Done_Glyph(self.handle);
}
pub fn newGlyph(library: Library, glyph_format: GlyphFormat) Glyph {
var g: c.FT_Glyph = undefined;
return .{
.handle = c.FT_New_Glyph(library.handle, @intFromEnum(glyph_format), &g),
};
}
pub fn copy(self: Glyph) Error!Glyph {
var g: c.FT_Glyph = undefined;
try intToError(c.FT_Glyph_Copy(self.handle, &g));
return Glyph{ .handle = g };
}
pub fn transform(self: Glyph, matrix: ?Matrix, delta: ?Vector) Error!void {
try intToError(c.FT_Glyph_Transform(self.handle, if (matrix) |m| &m else null, if (delta) |d| &d else null));
}
pub fn getCBox(self: Glyph, bbox_mode: BBoxMode) BBox {
var b: BBox = undefined;
c.FT_Glyph_Get_CBox(self.handle, @intFromEnum(bbox_mode), &b);
return b;
}
pub fn toBitmapGlyph(self: *Glyph, render_mode: RenderMode, origin: ?Vector) Error!BitmapGlyph {
try intToError(c.FT_Glyph_To_Bitmap(&self.handle, @intFromEnum(render_mode), if (origin) |o| &o else null, 1));
return BitmapGlyph{ .handle = @as(c.FT_BitmapGlyph, @ptrCast(self.handle)) };
}
pub fn copyBitmapGlyph(self: *Glyph, render_mode: RenderMode, origin: ?Vector) Error!BitmapGlyph {
try intToError(c.FT_Glyph_To_Bitmap(&self.handle, @intFromEnum(render_mode), if (origin) |o| &o else null, 0));
return BitmapGlyph{ .handle = @as(c.FT_BitmapGlyph, @ptrCast(self.handle)) };
}
pub fn castBitmapGlyph(self: Glyph) Error!BitmapGlyph {
return BitmapGlyph{ .handle = @as(c.FT_BitmapGlyph, @ptrCast(self.handle)) };
}
pub fn castOutlineGlyph(self: Glyph) Error!OutlineGlyph {
return OutlineGlyph{ .handle = @as(c.FT_OutlineGlyph, @ptrCast(self.handle)) };
}
pub fn castSvgGlyph(self: Glyph) Error!SvgGlyph {
return SvgGlyph{ .handle = @as(c.FT_SvgGlyph, @ptrCast(self.handle)) };
}
pub fn stroke(self: *Glyph, stroker: Stroker) Error!void {
try intToError(c.FT_Glyph_Stroke(&self.handle, stroker.handle, 0));
}
pub fn strokeBorder(self: *Glyph, stroker: Stroker, inside: bool) Error!void {
try intToError(c.FT_Glyph_StrokeBorder(&self.handle, stroker.handle, if (inside) 1 else 0, 0));
}
pub fn format(self: Glyph) GlyphFormat {
return @as(GlyphFormat, @enumFromInt(self.handle.*.format));
}
pub fn advanceX(self: Glyph) isize {
return self.handle.*.advance.x;
}
pub fn advanceY(self: Glyph) isize {
return self.handle.*.advance.y;
}
};
const SvgGlyph = struct {
handle: c.FT_SvgGlyph,
pub fn deinit(self: SvgGlyph) void {
c.FT_Done_Glyph(@as(c.FT_Glyph, @ptrCast(self.handle)));
}
pub fn svgBuffer(self: SvgGlyph) []const u8 {
return self.handle.*.svg_document[0..self.svgBufferLen()];
}
pub fn svgBufferLen(self: SvgGlyph) u32 {
return self.handle.*.svg_document_length;
}
pub fn glyphIndex(self: SvgGlyph) u32 {
return self.handle.*.glyph_index;
}
pub fn metrics(self: SvgGlyph) SizeMetrics {
return self.handle.*.metrics;
}
pub fn unitsPerEM(self: SvgGlyph) u16 {
return self.handle.*.units_per_EM;
}
pub fn startGlyphID(self: SvgGlyph) u16 {
return self.handle.*.start_glyph_id;
}
pub fn endGlyphID(self: SvgGlyph) u16 {
return self.handle.*.end_glyph_id;
}
pub fn transform(self: SvgGlyph) Matrix {
return self.handle.*.transform;
}
pub fn delta(self: SvgGlyph) Vector {
return self.handle.*.delta;
}
};
pub const BitmapGlyph = struct {
handle: c.FT_BitmapGlyph,
pub fn deinit(self: BitmapGlyph) void {
c.FT_Done_Glyph(@as(c.FT_Glyph, @ptrCast(self.handle)));
}
pub fn left(self: BitmapGlyph) i32 {
return self.handle.*.left;
}
pub fn top(self: BitmapGlyph) i32 {
return self.handle.*.top;
}
pub fn bitmap(self: BitmapGlyph) Bitmap {
return .{ .handle = self.handle.*.bitmap };
}
};
pub const OutlineGlyph = struct {
handle: c.FT_OutlineGlyph,
pub fn deinit(self: OutlineGlyph) void {
c.FT_Done_Glyph(@as(c.FT_Glyph, @ptrCast(self.handle)));
}
pub fn outline(self: OutlineGlyph) Outline {
return .{ .handle = &self.handle.*.outline };
}
};

View file

@ -1,95 +0,0 @@
const std = @import("std");
const c = @import("c.zig");
pub const MemoryMode = enum(u2) {
duplicate = c.HB_MEMORY_MODE_DUPLICATE,
readonly = c.HB_MEMORY_MODE_READONLY,
writable = c.HB_MEMORY_MODE_WRITABLE,
readonly_may_make_writable = c.HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE,
};
pub const Blob = struct {
handle: *c.hb_blob_t,
pub fn init(data: []u8, mode: MemoryMode) ?Blob {
return Blob{
.handle = c.hb_blob_create_or_fail(&data[0], @as(c_uint, @intCast(data.len)), @intFromEnum(mode), null, null) orelse return null,
};
}
pub fn initOrEmpty(data: []u8, mode: MemoryMode) Blob {
return .{
.handle = c.hb_blob_create(&data[0], @as(c_uint, @intCast(data.len)), @intFromEnum(mode), null, null).?,
};
}
pub fn initFromFile(path: [*:0]const u8) ?Blob {
return Blob{
.handle = c.hb_blob_create_from_file_or_fail(path) orelse return null,
};
}
pub fn initFromFileOrEmpty(path: [*:0]const u8) Blob {
return .{
.handle = c.hb_blob_create_from_file(path).?,
};
}
pub fn initEmpty() Blob {
return .{ .handle = c.hb_blob_get_empty().? };
}
pub fn createSubBlobOrEmpty(self: Blob, offset: u32, len: u32) Blob {
return .{
.handle = c.hb_blob_create_sub_blob(self.handle, offset, len).?,
};
}
pub fn copyWritable(self: Blob) ?Blob {
return Blob{
.handle = c.hb_blob_copy_writable_or_fail(self.handle) orelse return null,
};
}
pub fn deinit(self: Blob) void {
c.hb_blob_destroy(self.handle);
}
pub fn getData(self: Blob, len: ?u32) []const u8 {
var l = len;
const data = c.hb_blob_get_data(self.handle, if (l) |_| &l.? else null);
return if (l) |_|
data[0..l.?]
else
std.mem.sliceTo(data, 0);
}
pub fn getDataWritable(self: Blob, len: ?u32) ?[]const u8 {
var l = len;
const data = c.hb_blob_get_data(self.handle, if (l) |_| &l.? else null);
return if (data == null)
null
else if (l) |_|
data[0..l.?]
else
std.mem.sliceTo(data, 0);
}
pub fn getLength(self: Blob) u32 {
return c.hb_blob_get_length(self.handle);
}
pub fn isImmutable(self: Blob) bool {
return c.hb_blob_is_immutable(self.handle) > 0;
}
pub fn makeImmutable(self: Blob) void {
c.hb_blob_make_immutable(self.handle);
}
pub fn reference(self: Blob) Blob {
return .{
.handle = c.hb_blob_reference(self.handle).?,
};
}
};

View file

@ -1,334 +0,0 @@
const std = @import("std");
const c = @import("c.zig");
const Direction = @import("common.zig").Direction;
const Script = @import("common.zig").Script;
const Language = @import("common.zig").Language;
const Font = @import("font.zig").Font;
pub const ContentType = enum(u2) {
invalid = c.HB_BUFFER_CONTENT_TYPE_INVALID,
unicode = c.HB_BUFFER_CONTENT_TYPE_UNICODE,
glyphs = c.HB_BUFFER_CONTENT_TYPE_GLYPHS,
};
pub const ClusterLevel = enum(u2) {
monotone_graphemes = c.HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES,
monotone_characters = c.HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS,
characters = c.HB_BUFFER_CLUSTER_LEVEL_CHARACTERS,
};
pub const SerializeFormat = enum(u31) {
text = c.HB_BUFFER_SERIALIZE_FORMAT_TEXT,
json = c.HB_BUFFER_SERIALIZE_FORMAT_JSON,
invalid = c.HB_BUFFER_SERIALIZE_FORMAT_INVALID,
};
pub const GlyphInfo = extern struct {
codepoint: u32,
mask: u32,
cluster: u32,
var1: u32,
var2: u32,
pub fn getFlags(self: GlyphInfo) GlyphFlags {
return @as(GlyphFlags, @bitCast(hb_glyph_info_get_glyph_flags(&self)));
}
};
pub const Position = extern struct {
x_advance: i32,
y_advance: i32,
x_offset: i32,
y_offset: i32,
_padding: u32, // private
};
pub const GlyphFlags = packed struct(c_int) {
unsafe_to_break: bool = false,
unsafe_to_concat: bool = false,
_padding: u30 = 0,
};
pub const SegmentProps = struct {
direction: Direction,
script: Script,
language: Language,
pub fn from(c_struct: c.hb_segment_properties_t) SegmentProps {
return .{
.direction = @as(Direction, @enumFromInt(c_struct.direction)),
.script = @as(Script, @enumFromInt(c_struct.script)),
.language = Language{ .handle = c_struct.language },
};
}
pub fn cast(self: SegmentProps) c.hb_segment_properties_t {
return .{
.reserved1 = undefined,
.reserved2 = undefined,
.direction = @intFromEnum(self.direction),
.script = @intFromEnum(self.script),
.language = self.language.handle,
};
}
pub fn compare(a: SegmentProps, b: SegmentProps) bool {
return c.hb_segment_properties_equal(&a.cast(), &b.cast()) > 0;
}
pub fn hash(self: SegmentProps) u32 {
return c.hb_segment_properties_hash(&self.cast());
}
pub fn overlay(self: *SegmentProps, src: SegmentProps) void {
var seg_props = self.cast();
c.hb_segment_properties_overlay(&seg_props, &src.cast());
self.* = SegmentProps.from(seg_props);
}
};
pub const SerializeFlags = packed struct(c_int) {
no_clusters: bool = false,
no_positions: bool = false,
no_glyph_names: bool = false,
glyph_extents: bool = false,
glyph_flags: bool = false,
no_advances: bool = false,
_padding: u26 = 0,
};
pub const DiffFlags = packed struct(c_int) {
content_type_mismatch: bool = false,
length_mismatch: bool = false,
notdef_present: bool = false,
dotted_circle_present: bool = false,
codepoint_mismatch: bool = false,
cluster_mismatch: bool = false,
glyph_flags_mismatch: bool = false,
position_mismatch: bool = false,
_padding: u24 = 0,
};
pub const Buffer = struct {
pub const Flags = packed struct(c_int) {
bot: bool = false,
eot: bool = false,
preserve_default_ignorables: bool = false,
remove_default_ignorables: bool = false,
do_not_insert_dotted_circle: bool = false,
verify: bool = false,
produce_unsafe_to_concat: bool = false,
_padding: u25 = 0,
};
handle: *c.hb_buffer_t,
pub fn init() ?Buffer {
var b = c.hb_buffer_create();
if (c.hb_buffer_allocation_successful(b) < 1)
return null;
return Buffer{ .handle = b.? };
}
pub fn initEmpty() Buffer {
return .{ .handle = c.hb_buffer_get_empty().? };
}
pub fn initSimilar(self: Buffer) ?Buffer {
var b = c.hb_buffer_create_similar(self.handle);
if (c.hb_buffer_allocation_successful(b) < 1)
return null;
return Buffer{ .handle = b.? };
}
pub fn reference(self: Buffer) Buffer {
return .{
.handle = c.hb_buffer_reference(self.handle).?,
};
}
pub fn deinit(self: Buffer) void {
c.hb_buffer_destroy(self.handle);
}
pub fn reset(self: Buffer) void {
c.hb_buffer_reset(self.handle);
}
pub fn clearContents(self: Buffer) void {
c.hb_buffer_clear_contents(self.handle);
}
pub fn preAllocate(self: Buffer, size: u32) error{OutOfMemory}!void {
if (c.hb_buffer_pre_allocate(self.handle, size) < 1)
return error.OutOfMemory;
}
pub fn allocationSuccessful(self: Buffer) bool {
return c.hb_buffer_allocation_successful(self.handle) > 0;
}
pub fn add(self: Buffer, codepoint: u32, cluster: u32) void {
c.hb_buffer_add(self.handle, codepoint, cluster);
}
pub fn addCodepoints(self: Buffer, text: []const u32, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_codepoints(self.handle, &text[0], @as(c_int, @intCast(text.len)), item_offset, if (item_length) |l| l else @as(c_int, @intCast(text.len)));
}
pub fn addUTF32(self: Buffer, text: []const u32, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_utf32(self.handle, &text[0], @as(c_int, @intCast(text.len)), item_offset, if (item_length) |l| l else @as(c_int, @intCast(text.len)));
}
pub fn addUTF16(self: Buffer, text: []const u16, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_utf16(self.handle, &text[0], @as(c_int, @intCast(text.len)), item_offset, if (item_length) |l| l else @as(c_int, @intCast(text.len)));
}
pub fn addUTF8(self: Buffer, text: []const u8, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_utf8(self.handle, &text[0], @as(c_int, @intCast(text.len)), item_offset, if (item_length) |l| l else @as(c_int, @intCast(text.len)));
}
pub fn addLatin1(self: Buffer, text: []const u8, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_latin1(self.handle, &text[0], @as(c_int, @intCast(text.len)), item_offset, if (item_length) |l| l else @as(c_int, @intCast(text.len)));
}
pub fn append(self: Buffer, source: Buffer, start: u32, end: u32) void {
c.hb_buffer_append(self.handle, source.handle, start, end);
}
pub fn getContentType(self: Buffer) ContentType {
return @as(ContentType, @enumFromInt(c.hb_buffer_get_content_type(self.handle)));
}
pub fn setContentType(self: Buffer, content_type: ContentType) void {
c.hb_buffer_set_content_type(self.handle, @intFromEnum(content_type));
}
pub fn getDirection(self: Buffer) Direction {
return @as(Direction, @enumFromInt(c.hb_buffer_get_direction(self.handle)));
}
pub fn setDirection(self: Buffer, direction: Direction) void {
c.hb_buffer_set_direction(self.handle, @intFromEnum(direction));
}
pub fn getScript(self: Buffer) Script {
return @as(Script, @enumFromInt(c.hb_buffer_get_script(self.handle)));
}
pub fn setScript(self: Buffer, script: Script) void {
c.hb_buffer_set_script(self.handle, @intFromEnum(script));
}
pub fn getLanguage(self: Buffer) Language {
return Language{ .handle = c.hb_buffer_get_language(self.handle) };
}
pub fn setLanguage(self: Buffer, lang: Language) void {
c.hb_buffer_set_language(self.handle, lang.handle);
}
pub fn getFlags(self: Buffer) Flags {
return @as(Flags, @bitCast(c.hb_buffer_get_flags(self.handle)));
}
pub fn setFlags(self: Buffer, flags: Flags) void {
c.hb_buffer_set_flags(self.handle, @as(u32, @bitCast(flags)));
}
pub fn getClusterLevel(self: Buffer) ClusterLevel {
return @as(ClusterLevel, @enumFromInt(c.hb_buffer_get_cluster_level(self.handle)));
}
pub fn setClusterLevel(self: Buffer, level: ClusterLevel) void {
c.hb_buffer_set_cluster_level(self.handle, @intFromEnum(level));
}
pub fn getLength(self: Buffer) u32 {
return c.hb_buffer_get_length(self.handle);
}
pub fn setLength(self: Buffer, new_len: u32) error{OutOfMemory}!void {
if (c.hb_buffer_set_length(self.handle, new_len) < 1)
return error.OutOfMemory;
}
pub fn getSegmentProps(self: Buffer) SegmentProps {
var props: c.hb_segment_properties_t = undefined;
c.hb_buffer_get_segment_properties(self.handle, &props);
return SegmentProps.from(props);
}
pub fn setSegmentProps(self: Buffer, props: SegmentProps) void {
c.hb_buffer_set_segment_properties(self.handle, &props.cast());
}
pub fn guessSegmentProps(self: Buffer) void {
c.hb_buffer_guess_segment_properties(self.handle);
}
pub fn getGlyphInfos(self: Buffer) []GlyphInfo {
var length: u32 = 0;
return hb_buffer_get_glyph_infos(self.handle, &length)[0..length];
}
pub fn getGlyphPositions(self: Buffer) ?[]Position {
var length: u32 = 0;
return if (hb_buffer_get_glyph_positions(self.handle, &length)) |positions|
@as([*]Position, @ptrCast(positions))[0..length]
else
null;
}
pub fn hasPositions(self: Buffer) bool {
return c.hb_buffer_has_positions(self.handle) > 0;
}
pub fn getInvisibleGlyph(self: Buffer) u32 {
return c.hb_buffer_get_invisible_glyph(self.handle);
}
pub fn setInvisibleGlyph(self: Buffer, codepoint: u32) void {
c.hb_buffer_set_invisible_glyph(self.handle, codepoint);
}
pub fn getGlyphNotFound(self: Buffer) u32 {
return c.hb_buffer_get_not_found_glyph(self.handle);
}
pub fn setGlyphNotFound(self: Buffer, codepoint: u32) void {
c.hb_buffer_set_not_found_glyph(self.handle, codepoint);
}
pub fn getReplacementCodepoint(self: Buffer) u32 {
return c.hb_buffer_get_replacement_codepoint(self.handle);
}
pub fn setReplacementCodepoint(self: Buffer, codepoint: u32) void {
c.hb_buffer_set_replacement_codepoint(self.handle, codepoint);
}
pub fn normalizeGlyphs(self: Buffer) void {
c.hb_buffer_normalize_glyphs(self.handle);
}
pub fn reverse(self: Buffer) void {
c.hb_buffer_reverse(self.handle);
}
pub fn reverseRange(self: Buffer, start: u32, end: u32) void {
c.hb_buffer_reverse_range(self.handle, start, end);
}
pub fn reverseClusters(self: Buffer) void {
c.hb_buffer_reverse_clusters(self.handle);
}
pub fn diff(self: Buffer, ref: Buffer, dottedcircle_glyph: u32, position_fuzz: u32) DiffFlags {
return @as(DiffFlags, @bitCast(c.hb_buffer_diff(self.handle, ref.handle, dottedcircle_glyph, position_fuzz)));
}
};
pub extern fn hb_glyph_info_get_glyph_flags(info: [*c]const GlyphInfo) c.hb_glyph_flags_t;
pub extern fn hb_buffer_get_glyph_infos(buffer: ?*c.hb_buffer_t, length: [*c]c_uint) [*c]GlyphInfo;
pub extern fn hb_buffer_get_glyph_positions(buffer: ?*c.hb_buffer_t, length: [*c]c_uint) [*c]Position;

View file

@ -1 +0,0 @@
pub usingnamespace @cImport(@cInclude("hb-ft.h"));

View file

@ -1,284 +0,0 @@
const std = @import("std");
const c = @import("c.zig");
pub const Direction = enum(u3) {
invalid = c.HB_DIRECTION_INVALID,
ltr = c.HB_DIRECTION_LTR,
rtl = c.HB_DIRECTION_RTL,
ttb = c.HB_DIRECTION_TTB,
bit = c.HB_DIRECTION_BTT,
pub fn fromString(str: []const u8) Direction {
return @as(Direction, @enumFromInt(c.hb_direction_from_string(str.ptr, @as(c_int, @intCast(str.len)))));
}
pub fn toString(self: Direction) [:0]const u8 {
return std.mem.span(@as([*:0]const u8, @ptrCast(c.hb_direction_to_string(@intFromEnum(self)))));
}
};
pub const Script = enum(u31) {
common = c.HB_SCRIPT_COMMON,
inherited = c.HB_SCRIPT_INHERITED,
unknown = c.HB_SCRIPT_UNKNOWN,
arabic = c.HB_SCRIPT_ARABIC,
armenian = c.HB_SCRIPT_ARMENIAN,
bengali = c.HB_SCRIPT_BENGALI,
cyrillic = c.HB_SCRIPT_CYRILLIC,
devanagari = c.HB_SCRIPT_DEVANAGARI,
georgian = c.HB_SCRIPT_GEORGIAN,
greek = c.HB_SCRIPT_GREEK,
gujarati = c.HB_SCRIPT_GUJARATI,
gurmukhi = c.HB_SCRIPT_GURMUKHI,
hangul = c.HB_SCRIPT_HANGUL,
han = c.HB_SCRIPT_HAN,
hebrew = c.HB_SCRIPT_HEBREW,
hiragana = c.HB_SCRIPT_HIRAGANA,
kannada = c.HB_SCRIPT_KANNADA,
katakana = c.HB_SCRIPT_KATAKANA,
lao = c.HB_SCRIPT_LAO,
latin = c.HB_SCRIPT_LATIN,
malayalam = c.HB_SCRIPT_MALAYALAM,
oriya = c.HB_SCRIPT_ORIYA,
tamil = c.HB_SCRIPT_TAMIL,
telugu = c.HB_SCRIPT_TELUGU,
thai = c.HB_SCRIPT_THAI,
tibetan = c.HB_SCRIPT_TIBETAN,
bopomofo = c.HB_SCRIPT_BOPOMOFO,
braille = c.HB_SCRIPT_BRAILLE,
canadian_syllabics = c.HB_SCRIPT_CANADIAN_SYLLABICS,
cherokee = c.HB_SCRIPT_CHEROKEE,
ethiopic = c.HB_SCRIPT_ETHIOPIC,
khmer = c.HB_SCRIPT_KHMER,
mongolian = c.HB_SCRIPT_MONGOLIAN,
myanmar = c.HB_SCRIPT_MYANMAR,
ogham = c.HB_SCRIPT_OGHAM,
runic = c.HB_SCRIPT_RUNIC,
sinhala = c.HB_SCRIPT_SINHALA,
syriac = c.HB_SCRIPT_SYRIAC,
thaana = c.HB_SCRIPT_THAANA,
yi = c.HB_SCRIPT_YI,
deseret = c.HB_SCRIPT_DESERET,
gothic = c.HB_SCRIPT_GOTHIC,
old_italic = c.HB_SCRIPT_OLD_ITALIC,
buhid = c.HB_SCRIPT_BUHID,
hanunoo = c.HB_SCRIPT_HANUNOO,
tagalog = c.HB_SCRIPT_TAGALOG,
tagbanwa = c.HB_SCRIPT_TAGBANWA,
cypriot = c.HB_SCRIPT_CYPRIOT,
limbu = c.HB_SCRIPT_LIMBU,
linear_b = c.HB_SCRIPT_LINEAR_B,
osmanya = c.HB_SCRIPT_OSMANYA,
shavian = c.HB_SCRIPT_SHAVIAN,
tai_le = c.HB_SCRIPT_TAI_LE,
ugaritic = c.HB_SCRIPT_UGARITIC,
buginese = c.HB_SCRIPT_BUGINESE,
coptic = c.HB_SCRIPT_COPTIC,
glagolitic = c.HB_SCRIPT_GLAGOLITIC,
kharoshthi = c.HB_SCRIPT_KHAROSHTHI,
new_tai_lue = c.HB_SCRIPT_NEW_TAI_LUE,
old_persian = c.HB_SCRIPT_OLD_PERSIAN,
syloti_nagri = c.HB_SCRIPT_SYLOTI_NAGRI,
tifinagh = c.HB_SCRIPT_TIFINAGH,
balinese = c.HB_SCRIPT_BALINESE,
cuneiform = c.HB_SCRIPT_CUNEIFORM,
nko = c.HB_SCRIPT_NKO,
phags_pa = c.HB_SCRIPT_PHAGS_PA,
phoenician = c.HB_SCRIPT_PHOENICIAN,
carian = c.HB_SCRIPT_CARIAN,
cham = c.HB_SCRIPT_CHAM,
kayah_li = c.HB_SCRIPT_KAYAH_LI,
lepcha = c.HB_SCRIPT_LEPCHA,
lycian = c.HB_SCRIPT_LYCIAN,
lydian = c.HB_SCRIPT_LYDIAN,
ol_chiki = c.HB_SCRIPT_OL_CHIKI,
rejang = c.HB_SCRIPT_REJANG,
saurashtra = c.HB_SCRIPT_SAURASHTRA,
sundanese = c.HB_SCRIPT_SUNDANESE,
vai = c.HB_SCRIPT_VAI,
avestan = c.HB_SCRIPT_AVESTAN,
bamum = c.HB_SCRIPT_BAMUM,
egyptian_hieroglyphs = c.HB_SCRIPT_EGYPTIAN_HIEROGLYPHS,
imperial_aramaic = c.HB_SCRIPT_IMPERIAL_ARAMAIC,
inscriptional_pahlavi = c.HB_SCRIPT_INSCRIPTIONAL_PAHLAVI,
inscriptional_parthian = c.HB_SCRIPT_INSCRIPTIONAL_PARTHIAN,
javanese = c.HB_SCRIPT_JAVANESE,
kaithi = c.HB_SCRIPT_KAITHI,
lisu = c.HB_SCRIPT_LISU,
meetei_mayek = c.HB_SCRIPT_MEETEI_MAYEK,
old_south_arabian = c.HB_SCRIPT_OLD_SOUTH_ARABIAN,
old_turkic = c.HB_SCRIPT_OLD_TURKIC,
samaritan = c.HB_SCRIPT_SAMARITAN,
tai_tham = c.HB_SCRIPT_TAI_THAM,
tai_viet = c.HB_SCRIPT_TAI_VIET,
batak = c.HB_SCRIPT_BATAK,
brahmi = c.HB_SCRIPT_BRAHMI,
mandaic = c.HB_SCRIPT_MANDAIC,
chakma = c.HB_SCRIPT_CHAKMA,
meroitic_cursive = c.HB_SCRIPT_MEROITIC_CURSIVE,
meroitic_hieroglyphs = c.HB_SCRIPT_MEROITIC_HIEROGLYPHS,
miao = c.HB_SCRIPT_MIAO,
sharada = c.HB_SCRIPT_SHARADA,
sora_sompeng = c.HB_SCRIPT_SORA_SOMPENG,
takri = c.HB_SCRIPT_TAKRI,
bassa_vah = c.HB_SCRIPT_BASSA_VAH,
caucasian_albanian = c.HB_SCRIPT_CAUCASIAN_ALBANIAN,
duployan = c.HB_SCRIPT_DUPLOYAN,
elbasan = c.HB_SCRIPT_ELBASAN,
grantha = c.HB_SCRIPT_GRANTHA,
khojki = c.HB_SCRIPT_KHOJKI,
khudawadi = c.HB_SCRIPT_KHUDAWADI,
linear_a = c.HB_SCRIPT_LINEAR_A,
mahajani = c.HB_SCRIPT_MAHAJANI,
manichaean = c.HB_SCRIPT_MANICHAEAN,
mende_kikakui = c.HB_SCRIPT_MENDE_KIKAKUI,
modi = c.HB_SCRIPT_MODI,
mro = c.HB_SCRIPT_MRO,
nabataean = c.HB_SCRIPT_NABATAEAN,
old_north_arabian = c.HB_SCRIPT_OLD_NORTH_ARABIAN,
old_permic = c.HB_SCRIPT_OLD_PERMIC,
pahawh_hmong = c.HB_SCRIPT_PAHAWH_HMONG,
palmyrene = c.HB_SCRIPT_PALMYRENE,
pau_cin_hau = c.HB_SCRIPT_PAU_CIN_HAU,
psalter_pahlavi = c.HB_SCRIPT_PSALTER_PAHLAVI,
siddham = c.HB_SCRIPT_SIDDHAM,
tirhuta = c.HB_SCRIPT_TIRHUTA,
warang_citi = c.HB_SCRIPT_WARANG_CITI,
ahom = c.HB_SCRIPT_AHOM,
anatolian_hieroglyphs = c.HB_SCRIPT_ANATOLIAN_HIEROGLYPHS,
hatran = c.HB_SCRIPT_HATRAN,
multani = c.HB_SCRIPT_MULTANI,
old_hungarian = c.HB_SCRIPT_OLD_HUNGARIAN,
signwriting = c.HB_SCRIPT_SIGNWRITING,
adlam = c.HB_SCRIPT_ADLAM,
bhaiksuki = c.HB_SCRIPT_BHAIKSUKI,
marchen = c.HB_SCRIPT_MARCHEN,
osage = c.HB_SCRIPT_OSAGE,
tangut = c.HB_SCRIPT_TANGUT,
newa = c.HB_SCRIPT_NEWA,
masaram_gondi = c.HB_SCRIPT_MASARAM_GONDI,
nushu = c.HB_SCRIPT_NUSHU,
soyombo = c.HB_SCRIPT_SOYOMBO,
zanabazar_square = c.HB_SCRIPT_ZANABAZAR_SQUARE,
dogra = c.HB_SCRIPT_DOGRA,
gunjala_gondi = c.HB_SCRIPT_GUNJALA_GONDI,
hanifi_rohingya = c.HB_SCRIPT_HANIFI_ROHINGYA,
makasar = c.HB_SCRIPT_MAKASAR,
medefaidrin = c.HB_SCRIPT_MEDEFAIDRIN,
old_sogdian = c.HB_SCRIPT_OLD_SOGDIAN,
sogdian = c.HB_SCRIPT_SOGDIAN,
elymaic = c.HB_SCRIPT_ELYMAIC,
nandinagari = c.HB_SCRIPT_NANDINAGARI,
nyiakeng_puachue_hmong = c.HB_SCRIPT_NYIAKENG_PUACHUE_HMONG,
wancho = c.HB_SCRIPT_WANCHO,
chorasmian = c.HB_SCRIPT_CHORASMIAN,
dives_akuru = c.HB_SCRIPT_DIVES_AKURU,
khitan_small_script = c.HB_SCRIPT_KHITAN_SMALL_SCRIPT,
yezidi = c.HB_SCRIPT_YEZIDI,
cypro_minoan = c.HB_SCRIPT_CYPRO_MINOAN,
old_uyghur = c.HB_SCRIPT_OLD_UYGHUR,
tangsa = c.HB_SCRIPT_TANGSA,
toto = c.HB_SCRIPT_TOTO,
vithkuqi = c.HB_SCRIPT_VITHKUQI,
math = c.HB_SCRIPT_MATH,
invalid = c.HB_SCRIPT_INVALID,
pub fn fromISO15924Tag(tag: Tag) Script {
return @as(Script, @enumFromInt(c.hb_script_from_iso15924_tag(tag.handle)));
}
pub fn fromString(str: []const u8) Script {
return @as(Script, @enumFromInt(c.hb_script_from_string(str.ptr, @as(c_int, @intCast(str.len)))));
}
pub fn toISO15924Tag(self: Script) Tag {
return .{ .handle = c.hb_script_to_iso15924_tag(@intFromEnum(self)) };
}
pub fn getHorizontalDirection(self: Script) Direction {
return @as(Direction, @enumFromInt(c.hb_script_get_horizontal_direction(@intFromEnum(self))));
}
};
pub const Language = struct {
handle: c.hb_language_t,
pub fn fromString(name: []const u8) Language {
return .{
.handle = c.hb_language_from_string(name.ptr, @as(c_int, @intCast(name.len))),
};
}
pub fn toString(self: Language) [:0]const u8 {
return std.mem.span(@as([*:0]const u8, @ptrCast(c.hb_language_to_string(self.handle))));
}
pub fn getDefault() Language {
return .{ .handle = c.hb_language_get_default() };
}
};
pub const Feature = extern struct {
tag: c.hb_tag_t,
value: u32,
start: c_uint,
end: c_uint,
pub fn fromString(str: []const u8) ?Feature {
var f: Feature = undefined;
return if (hb_feature_from_string(str.ptr, @as(c_int, @intCast(str.len)), &f) > 1)
f
else
null;
}
pub fn toString(self: *Feature, buf: []u8) void {
hb_feature_to_string(self, buf.ptr, @as(c_uint, @intCast(buf.len)));
}
};
pub const Variation = extern struct {
tag: u32,
value: f32,
pub fn fromString(str: []const u8) ?Variation {
var v: Variation = undefined;
return if (hb_variation_from_string(str.ptr, @as(c_int, @intCast(str.len)), &v) > 1)
v
else
null;
}
pub fn toString(self: *Variation, buf: []u8) void {
hb_variation_to_string(self, buf.ptr, @as(c_uint, @intCast(buf.len)));
}
pub fn tag(self: Variation) Tag {
return .{ .handle = self.tag };
}
pub fn value(self: Variation) f32 {
return self.value;
}
};
pub const Tag = struct {
handle: u32,
pub fn fromString(str: []const u8) Tag {
return .{ .handle = c.hb_tag_from_string(str.ptr, @as(c_int, @intCast(str.len))) };
}
pub fn toString(self: Tag) []const u8 {
var str: [4]u8 = undefined;
c.hb_tag_to_string(self.handle, &str[0]);
return &str;
}
};
pub const Shapers = ?[*:null]const ?[*:0]const u8;
pub extern fn hb_feature_from_string(str: [*c]const u8, len: c_int, feature: [*c]Feature) u8;
pub extern fn hb_feature_to_string(feature: [*c]Feature, buf: [*c]u8, size: c_uint) void;
pub extern fn hb_variation_from_string(str: [*c]const u8, len: c_int, variation: [*c]Variation) u8;
pub extern fn hb_variation_to_string(variation: [*c]Variation, buf: [*c]u8, size: c_uint) void;

View file

@ -1,81 +0,0 @@
const freetype = @import("freetype");
const c = @import("c.zig");
const private = @import("private.zig");
const Blob = @import("blob.zig").Blob;
pub const UnicodeIterator = struct {
set: *c.hb_set_t,
prev_codepoint: u32 = 0,
pub fn next(self: *UnicodeIterator) ?u32 {
var codepoint: u32 = c.HB_SET_VALUE_INVALID;
return if (c.hb_set_next(self.set, &codepoint) > 1) b: {
self.prev_codepoint = codepoint;
break :b codepoint;
} else null;
}
};
pub const Face = struct {
handle: *c.hb_face_t,
pub fn init(blob: Blob, index: u16) Face {
return .{ .handle = c.hb_face_create(blob.handle, index).? };
}
pub fn fromFreetypeFace(face: freetype.Face) Face {
return .{ .handle = private.hb_ft_face_create_referenced(face.handle).? };
}
pub fn initEmpty() Face {
return .{ .handle = c.hb_face_get_empty().? };
}
pub fn getCount(blob: Blob) u32 {
return c.hb_face_count(blob.handle);
}
pub fn deinit(self: Face) void {
c.hb_face_destroy(self.handle);
}
pub fn getGlyphcount(self: Face) u32 {
return c.hb_face_get_glyph_count(self.handle);
}
pub fn setGlyphcount(self: Face, count: u32) void {
return c.hb_face_set_glyph_count(self.handle, count);
}
pub fn getUnitsPerEM(self: Face) u32 {
return c.hb_face_get_upem(self.handle);
}
pub fn setUnitsPerEM(self: Face, upem: u32) void {
return c.hb_face_set_upem(self.handle, upem);
}
pub fn setIndex(self: Face, index: u32) void {
return c.hb_face_set_index(self.handle, index);
}
pub fn isImmutable(self: Face) bool {
return c.hb_face_is_immutable(self.handle) > 0;
}
pub fn makeImmutable(self: Face) void {
c.hb_face_make_immutable(self.handle);
}
pub fn reference(self: Face) Face {
return .{
.handle = c.hb_face_reference(self.handle).?,
};
}
pub fn collectUnicodes(self: Face) UnicodeIterator {
var set: *c.hb_set_t = undefined;
c.hb_face_collect_unicodes(self.handle, set);
return .{ .set = set };
}
};

View file

@ -1,102 +0,0 @@
const freetype = @import("freetype");
const c = @import("c.zig");
const private = @import("private.zig");
const Face = @import("face.zig").Face;
const Buffer = @import("buffer.zig").Buffer;
const Feature = @import("common.zig").Feature;
const SegmentProps = @import("buffer.zig").SegmentProps;
const Shapers = @import("common.zig").Shapers;
pub const Font = struct {
handle: *c.hb_font_t,
pub fn init(face: Face) Font {
return .{ .handle = c.hb_font_create(face.handle).? };
}
pub fn fromFreetypeFace(face: freetype.Face) Font {
return .{ .handle = private.hb_ft_font_create_referenced(face.handle).? };
}
pub fn createSubFont(self: Font) Font {
return .{
.handle = c.hb_font_create_sub_font(self.handle).?,
};
}
pub fn deinit(self: Font) void {
c.hb_font_destroy(self.handle);
}
pub fn freetypeFaceChanged(self: Font) void {
c.hb_ft_font_changed(self.handle);
}
pub fn setFreetypeLoadFlags(self: Font, flags: freetype.LoadFlags) void {
c.hb_ft_font_set_load_flags(self.handle, @as(i32, @bitCast(flags)));
}
pub fn getFace(self: Font) Face {
return .{ .handle = c.hb_font_get_face(self.handle).? };
}
pub fn getFreetypeFace(self: Font) freetype.Face {
return .{ .handle = private.hb_ft_font_get_face(self.handle) };
}
pub fn getGlyph(self: Font, unicode: u32, variation_selector: u32) ?u32 {
var g: u32 = 0;
return if (c.hb_font_get_glyph(self.handle, unicode, variation_selector, &g) > 0)
g
else
null;
}
pub fn getParent(self: Font) ?Font {
return Font{ .handle = c.hb_font_get_parent(self.handle) orelse return null };
}
pub fn getPPEM(self: Font) @Vector(2, u32) {
var x: c_uint = 0;
var y: c_uint = 0;
c.hb_font_get_ppem(self.handle, &x, &y);
return @Vector(2, u32){ @as(u32, @intCast(x)), @as(u32, @intCast(y)) };
}
pub fn getPTEM(self: Font) f32 {
return c.hb_font_get_ptem(self.handle);
}
pub fn getScale(self: Font) @Vector(2, i32) {
var x: c_int = 0;
var y: c_int = 0;
c.hb_font_get_scale(self.handle, &x, &y);
return @Vector(2, i32){ @as(i32, @intCast(x)), @as(i32, @intCast(y)) };
}
pub fn setFace(self: Font, face: Face) void {
return c.hb_font_set_face(self.handle, face.handle);
}
pub fn shape(self: Font, buf: Buffer, features: ?[]const Feature) void {
hb_shape(
self.handle,
buf.handle,
if (features) |f| f.ptr else null,
if (features) |f| @as(c_uint, @intCast(f.len)) else 0,
);
}
pub fn shapeFull(self: Font, buf: Buffer, features: ?[]const Feature, shapers: Shapers) error{ShapingFailed}!void {
if (hb_shape_full(
self.handle,
buf.handle,
if (features) |f| f.ptr else null,
if (features) |f| @as(c_uint, @intCast(f.len)) else 0,
shapers,
) < 1) return error.ShapingFailed;
}
};
pub extern fn hb_shape(font: ?*c.hb_font_t, buffer: ?*c.hb_buffer_t, features: [*c]const Feature, num_features: c_uint) void;
pub extern fn hb_shape_full(font: ?*c.hb_font_t, buffer: ?*c.hb_buffer_t, features: [*c]const Feature, num_features: c_uint, shaper_list: [*c]const [*c]const u8) u8;

View file

@ -1,19 +0,0 @@
pub usingnamespace @import("blob.zig");
pub usingnamespace @import("buffer.zig");
pub usingnamespace @import("common.zig");
pub usingnamespace @import("face.zig");
pub usingnamespace @import("font.zig");
pub usingnamespace @import("shape.zig");
pub usingnamespace @import("shape_plan.zig");
pub const c = @import("c.zig");
const std = @import("std");
test {
std.testing.refAllDeclsRecursive(@import("blob.zig"));
std.testing.refAllDeclsRecursive(@import("buffer.zig"));
std.testing.refAllDeclsRecursive(@import("common.zig"));
std.testing.refAllDeclsRecursive(@import("face.zig"));
std.testing.refAllDeclsRecursive(@import("font.zig"));
std.testing.refAllDeclsRecursive(@import("shape.zig"));
std.testing.refAllDeclsRecursive(@import("shape_plan.zig"));
}

View file

@ -1,5 +0,0 @@
const freetype = @import("freetype");
const c = @import("c.zig");
pub extern fn hb_ft_face_create_referenced(ft_face: freetype.c.FT_Face) ?*c.hb_face_t;
pub extern fn hb_ft_font_create_referenced(ft_face: freetype.c.FT_Face) ?*c.hb_font_t;
pub extern fn hb_ft_font_get_face(font: ?*c.hb_font_t) freetype.c.FT_Face;

View file

@ -1,18 +0,0 @@
const std = @import("std");
const c = @import("c.zig");
pub const ListShapers = struct {
index: usize,
list: [*:null]const ?[*:0]const u8,
pub fn init() ListShapers {
return .{ .index = 0, .list = c.hb_shape_list_shapers() };
}
pub fn next(self: *ListShapers) ?[:0]const u8 {
self.index += 1;
return std.mem.span(
self.list[self.index - 1] orelse return null,
);
}
};

View file

@ -1,80 +0,0 @@
const std = @import("std");
const c = @import("c.zig");
const Buffer = @import("buffer.zig").Buffer;
const Font = @import("font.zig").Font;
const Face = @import("face.zig").Face;
const SegmentProps = @import("buffer.zig").SegmentProps;
const Feature = @import("common.zig").Feature;
const Shapers = @import("common.zig").Shapers;
pub const ShapePlan = struct {
handle: *c.hb_shape_plan_t,
pub fn init(face: Face, props: SegmentProps, features: ?[]const Feature, shapers: Shapers) ShapePlan {
return .{ .handle = hb_shape_plan_create(
face.handle,
&props.cast(),
if (features) |f| f.ptr else null,
if (features) |f| @as(c_uint, @intCast(f.len)) else 0,
shapers,
).? };
}
pub fn initCached(face: Face, props: SegmentProps, features: ?[]const Feature, shapers: Shapers) ShapePlan {
return .{ .handle = hb_shape_plan_create_cached(
face.handle,
&props.cast(),
if (features) |f| f.ptr else null,
if (features) |f| @as(c_uint, @intCast(f.len)) else 0,
shapers,
).? };
}
pub fn init2(face: Face, props: SegmentProps, features: ?[]const Feature, cords: []const i32, shapers: Shapers) ShapePlan {
return .{ .handle = hb_shape_plan_create2(
face.handle,
&props.cast(),
if (features) |f| f.ptr else null,
if (features) |f| @as(c_uint, @intCast(f.len)) else 0,
cords.ptr,
@as(c_uint, @intCast(cords.len)),
shapers,
).? };
}
pub fn initCached2(face: Face, props: SegmentProps, features: ?[]const Feature, cords: []const i32, shapers: Shapers) ShapePlan {
return .{ .handle = hb_shape_plan_create_cached2(
face.handle,
&props.cast(),
if (features) |f| f.ptr else null,
if (features) |f| @as(c_uint, @intCast(f.len)) else 0,
cords.ptr,
@as(c_uint, @intCast(cords.len)),
shapers,
).? };
}
pub fn deinit(self: ShapePlan) void {
c.hb_shape_plan_destroy(self.handle);
}
pub fn execute(self: ShapePlan, font: Font, buffer: Buffer, features: ?[]Feature) error{ShapingFailed}!void {
if (hb_shape_plan_execute(
self.handle,
font.handle,
buffer.handle,
if (features) |f| f.ptr else null,
if (features) |f| @as(c_uint, @intCast(f.len)) else 0,
) < 1) return error.ShapingFailed;
}
pub fn getShaper(self: ShapePlan) [:0]const u8 {
return std.mem.span(@as([*:0]const u8, @ptrCast(c.hb_shape_plan_get_shaper(self.handle))));
}
};
pub extern fn hb_shape_plan_create(face: ?*c.hb_face_t, props: [*c]const c.hb_segment_properties_t, user_features: [*c]const Feature, num_user_features: c_uint, shaper_list: [*c]const [*c]const u8) ?*c.hb_shape_plan_t;
pub extern fn hb_shape_plan_create_cached(face: ?*c.hb_face_t, props: [*c]const c.hb_segment_properties_t, user_features: [*c]const Feature, num_user_features: c_uint, shaper_list: [*c]const [*c]const u8) ?*c.hb_shape_plan_t;
pub extern fn hb_shape_plan_create2(face: ?*c.hb_face_t, props: [*c]const c.hb_segment_properties_t, user_features: [*c]const Feature, num_user_features: c_uint, coords: [*c]const c_int, num_coords: c_uint, shaper_list: [*c]const [*c]const u8) ?*c.hb_shape_plan_t;
pub extern fn hb_shape_plan_create_cached2(face: ?*c.hb_face_t, props: [*c]const c.hb_segment_properties_t, user_features: [*c]const Feature, num_user_features: c_uint, coords: [*c]const c_int, num_coords: c_uint, shaper_list: [*c]const [*c]const u8) ?*c.hb_shape_plan_t;
pub extern fn hb_shape_plan_execute(shape_plan: ?*c.hb_shape_plan_t, font: ?*c.hb_font_t, buffer: ?*c.hb_buffer_t, features: [*c]const Feature, num_features: c_uint) u8;

View file

@ -1,322 +0,0 @@
const builtin = @import("builtin");
const std = @import("std");
const testing = std.testing;
const c = @import("c.zig");
const intToError = @import("error.zig").intToError;
const errorToInt = @import("error.zig").errorToInt;
const Error = @import("error.zig").Error;
const Library = @import("freetype.zig").Library;
const Color = @import("color.zig").Color;
const Stroker = @import("stroke.zig").Stroker;
const Matrix = @import("types.zig").Matrix;
const BBox = @import("types.zig").BBox;
pub const Vector = c.FT_Vector;
pub const GlyphMetrics = c.FT_Glyph_Metrics;
pub const Span = c.FT_Span;
pub const SpanFunc = *const fn (y: c_int, count: c_int, spans: [*]const Span, user: *anyopaque) callconv(.C) void;
pub const PixelMode = enum(u3) {
none = c.FT_PIXEL_MODE_NONE,
mono = c.FT_PIXEL_MODE_MONO,
gray = c.FT_PIXEL_MODE_GRAY,
gray2 = c.FT_PIXEL_MODE_GRAY2,
gray4 = c.FT_PIXEL_MODE_GRAY4,
lcd = c.FT_PIXEL_MODE_LCD,
lcd_v = c.FT_PIXEL_MODE_LCD_V,
bgra = c.FT_PIXEL_MODE_BGRA,
};
pub const GlyphFormat = enum(u32) {
none = c.FT_GLYPH_FORMAT_NONE,
composite = c.FT_GLYPH_FORMAT_COMPOSITE,
bitmap = c.FT_GLYPH_FORMAT_BITMAP,
outline = c.FT_GLYPH_FORMAT_OUTLINE,
plotter = c.FT_GLYPH_FORMAT_PLOTTER,
svg = c.FT_GLYPH_FORMAT_SVG,
};
pub const Bitmap = struct {
handle: c.FT_Bitmap,
pub fn init() Bitmap {
var b: c.FT_Bitmap = undefined;
c.FT_Bitmap_Init(&b);
return .{ .handle = b };
}
pub fn deinit(self: *Bitmap, lib: Library) void {
_ = c.FT_Bitmap_Done(lib.handle, &self.handle);
}
pub fn copy(self: Bitmap, lib: Library) Error!Bitmap {
var b: c.FT_Bitmap = undefined;
try intToError(c.FT_Bitmap_Copy(lib.handle, &self.handle, &b));
return Bitmap{ .handle = b };
}
pub fn embolden(self: *Bitmap, lib: Library, x_strength: i32, y_strength: i32) Error!void {
try intToError(c.FT_Bitmap_Embolden(lib.handle, &self.handle, x_strength, y_strength));
}
pub fn convert(self: Bitmap, lib: Library, alignment: u29) Error!Bitmap {
var b: c.FT_Bitmap = undefined;
try intToError(c.FT_Bitmap_Convert(lib.handle, &self.handle, &b, alignment));
return Bitmap{ .handle = b };
}
pub fn blend(self: *Bitmap, lib: Library, source_offset: Vector, target_offset: *Vector, color: Color) Error!void {
var b: c.FT_Bitmap = undefined;
c.FT_Bitmap_Init(&b);
try intToError(c.FT_Bitmap_Blend(lib.handle, &self.handle, source_offset, &b, target_offset, color));
}
pub fn width(self: Bitmap) u32 {
return self.handle.width;
}
pub fn pitch(self: Bitmap) i32 {
return self.handle.pitch;
}
pub fn rows(self: Bitmap) u32 {
return self.handle.rows;
}
pub fn pixelMode(self: Bitmap) PixelMode {
return @as(PixelMode, @enumFromInt(self.handle.pixel_mode));
}
pub fn buffer(self: Bitmap) ?[]const u8 {
const buffer_size = std.math.absCast(self.pitch()) * self.rows();
return if (self.handle.buffer == null)
// freetype returns a null pointer for zero-length allocations
// https://github.com/hexops-graveyard/freetype/blob/bbd80a52b7b749140ec87d24b6c767c5063be356/freetype/src/base/ftutil.c#L135
null
else
self.handle.buffer[0..buffer_size];
}
};
pub const Outline = struct {
pub const Orientation = enum(u2) {
truetype = c.FT_ORIENTATION_TRUETYPE,
postscript = c.FT_ORIENTATION_POSTSCRIPT,
none = c.FT_ORIENTATION_NONE,
};
pub const Flags = packed struct(c_int) {
owner: bool = false,
even_odd_fill: bool = false,
reverse_fill: bool = false,
ignore_dropouts: bool = false,
smart_dropouts: bool = false,
include_stubs: bool = false,
overlap: bool = false,
_padding: u1 = 0,
high_precision: bool = false,
single_pass: bool = false,
_padding0: u22 = 0,
};
handle: *c.FT_Outline,
pub fn numPoints(self: Outline) u15 {
return @as(u15, @intCast(self.handle.*.n_points));
}
pub fn numContours(self: Outline) u15 {
return @as(u15, @intCast(self.handle.*.n_contours));
}
pub fn points(self: Outline) []const Vector {
return self.handle.*.points[0..self.numPoints()];
}
pub fn tags(self: Outline) []const u8 {
return self.handle.tags[0..@as(u15, @intCast(self.handle.n_points))];
}
pub fn contours(self: Outline) []const i16 {
return self.handle.*.contours[0..self.numContours()];
}
pub fn flags(self: Outline) Flags {
return @as(Flags, @bitCast(self.handle.*.flags));
}
pub fn copy(self: Outline) Error!Outline {
var o: c.FT_Outline = undefined;
try intToError(c.FT_Outline_Copy(self.handle, &o));
return Outline{ .handle = &o };
}
pub fn translate(self: Outline, x_offset: i32, y_offset: i32) void {
c.FT_Outline_Translate(self.handle, x_offset, y_offset);
}
pub fn transform(self: Outline, matrix: ?Matrix) void {
c.FT_Outline_Transform(self.handle, if (matrix) |m| &m else null);
}
pub fn embolden(self: Outline, strength: i32) Error!void {
try intToError(c.FT_Outline_Embolden(self.handle, strength));
}
pub fn emboldenXY(self: Outline, x_strength: i32, y_strength: i32) Error!void {
try intToError(c.FT_Outline_EmboldenXY(self.handle, x_strength, y_strength));
}
pub fn reverse(self: Outline) void {
c.FT_Outline_Reverse(self.handle);
}
pub fn check(self: Outline) Error!void {
try intToError(c.FT_Outline_Check(self.handle));
}
pub fn cbox(self: Outline) BBox {
var b: BBox = undefined;
c.FT_Outline_Get_CBox(self.handle, &b);
return b;
}
pub fn bbox(self: Outline) Error!BBox {
var b: BBox = undefined;
try intToError(c.FT_Outline_Get_BBox(self.handle, &b));
return b;
}
pub fn orientation(self: Outline) Orientation {
return @as(Orientation, @enumFromInt(c.FT_Outline_Get_Orientation(self.handle)));
}
pub fn getInsideBorder(self: Outline) Stroker.Border {
return @as(Stroker.Border, @enumFromInt(c.FT_Outline_GetInsideBorder(self.handle)));
}
pub fn getOutsideBorder(self: Outline) Stroker.Border {
return @as(Stroker.Border, @enumFromInt(c.FT_Outline_GetOutsideBorder(self.handle)));
}
pub fn Funcs(comptime Context: type) type {
return struct {
move_to: *const fn (ctx: Context, to: Vector) Error!void,
line_to: *const fn (ctx: Context, to: Vector) Error!void,
conic_to: *const fn (ctx: Context, control: Vector, to: Vector) Error!void,
cubic_to: *const fn (ctx: Context, control_0: Vector, control_1: Vector, to: Vector) Error!void,
shift: i32,
delta: i32,
};
}
fn FuncsWrapper(comptime Context: type) type {
return struct {
const Self = @This();
ctx: Context,
callbacks: Funcs(Context),
fn getSelf(ptr: ?*anyopaque) *Self {
return @as(*Self, @ptrCast(@alignCast(ptr)));
}
pub fn move_to(to: [*c]const c.FT_Vector, ctx: ?*anyopaque) callconv(.C) c_int {
const self = getSelf(ctx);
return if (self.callbacks.move_to(self.ctx, to.*)) |_|
0
else |err|
errorToInt(err);
}
pub fn line_to(to: [*c]const c.FT_Vector, ctx: ?*anyopaque) callconv(.C) c_int {
const self = getSelf(ctx);
return if (self.callbacks.line_to(self.ctx, to.*)) |_|
0
else |err|
errorToInt(err);
}
pub fn conic_to(
control: [*c]const c.FT_Vector,
to: [*c]const c.FT_Vector,
ctx: ?*anyopaque,
) callconv(.C) c_int {
const self = getSelf(ctx);
return if (self.callbacks.conic_to(
self.ctx,
control.*,
to.*,
)) |_|
0
else |err|
errorToInt(err);
}
pub fn cubic_to(
control_0: [*c]const c.FT_Vector,
control_1: [*c]const c.FT_Vector,
to: [*c]const c.FT_Vector,
ctx: ?*anyopaque,
) callconv(.C) c_int {
const self = getSelf(ctx);
return if (self.callbacks.cubic_to(
self.ctx,
control_0.*,
control_1.*,
to.*,
)) |_|
0
else |err|
errorToInt(err);
}
};
}
pub fn decompose(self: Outline, ctx: anytype, callbacks: Funcs(@TypeOf(ctx))) Error!void {
var wrapper = FuncsWrapper(@TypeOf(ctx)){ .ctx = ctx, .callbacks = callbacks };
try intToError(c.FT_Outline_Decompose(
self.handle,
&c.FT_Outline_Funcs{
.move_to = @TypeOf(wrapper).move_to,
.line_to = @TypeOf(wrapper).line_to,
.conic_to = @TypeOf(wrapper).conic_to,
.cubic_to = @TypeOf(wrapper).cubic_to,
.shift = callbacks.shift,
.delta = callbacks.delta,
},
&wrapper,
));
}
};
pub const Raster = struct {
handle: c.FT_Raster,
pub const NewFunc = *const fn (memory: ?*anyopaque, raster: [*c]c.FT_Raster) callconv(.C) c_int;
pub const DoneFunc = *const fn (raster: [*c]c.FT_Raster) callconv(.C) void;
pub const ResetFunc = *const fn (raster: c.FT_Raster, pool_base: [*c]u8, pool_size: c_ulong) callconv(.C) void;
pub const SetModeFunc = *const fn (raster: c.FT_Raster, mode: c_ulong, args: ?*anyopaque) callconv(.C) c_int;
pub const RenderFunc = *const fn (raster: c.FT_Raster, params: Params) callconv(.C) c_int;
pub const BitTestFunc = *const fn (y: c_int, x: c_int, user: ?*anyopaque) callconv(.C) c_int;
pub const BitSetFunc = *const fn (y: c_int, x: c_int, user: ?*anyopaque) callconv(.C) void;
pub const Params = extern struct {
target: [*c]const c.FT_Bitmap,
source: [*]const u8,
flags: c_int,
gray_spans: SpanFunc,
black_spans: ?SpanFunc = null, // unused
bit_test: ?BitTestFunc = null, // unused
bit_set: ?BitSetFunc = null, // unused
user: ?*anyopaque = null,
clip_box: BBox,
};
pub const Flags = packed struct(c_int) {
aa: bool = false,
direct: bool = false,
clip: bool = false,
sdf: bool = false,
_padding: u28 = 0,
};
};

View file

@ -1,8 +0,0 @@
const c = @import("c.zig");
pub const LcdFilter = enum(u5) {
none = c.FT_LCD_FILTER_NONE,
default = c.FT_LCD_FILTER_DEFAULT,
light = c.FT_LCD_FILTER_LIGHT,
legacy = c.FT_LCD_FILTER_LEGACY,
};

View file

@ -1,90 +0,0 @@
pub usingnamespace @import("color.zig");
pub usingnamespace @import("computations.zig");
pub usingnamespace @import("error.zig");
pub usingnamespace @import("freetype.zig");
pub usingnamespace @import("glyph.zig");
pub usingnamespace @import("image.zig");
pub usingnamespace @import("lcdfilter.zig");
pub usingnamespace @import("stroke.zig");
pub usingnamespace @import("types.zig");
pub const c = @import("c.zig");
const std = @import("std");
const testing = std.testing;
const ft = @import("freetype.zig");
fn sdkPath(comptime suffix: [*:0]const u8) [*:0]const u8 {
if (suffix[0] != '/') @compileError("suffix must be an absolute path");
return comptime blk: {
const root_dir = std.fs.path.dirname(@src().file) orelse ".";
break :blk root_dir ++ suffix;
};
}
test {
std.testing.refAllDeclsRecursive(@import("color.zig"));
std.testing.refAllDeclsRecursive(@import("computations.zig"));
std.testing.refAllDeclsRecursive(@import("error.zig"));
std.testing.refAllDeclsRecursive(@import("freetype.zig"));
std.testing.refAllDeclsRecursive(@import("glyph.zig"));
std.testing.refAllDeclsRecursive(@import("image.zig"));
std.testing.refAllDeclsRecursive(@import("lcdfilter.zig"));
std.testing.refAllDeclsRecursive(@import("stroke.zig"));
std.testing.refAllDeclsRecursive(@import("types.zig"));
}
const firasans_font_path = sdkPath("/../upstream/assets/FiraSans-Regular.ttf");
const firasans_font_data = @embedFile("../upstream/assets/FiraSans-Regular.ttf");
test "create face from file" {
const lib = try ft.Library.init();
_ = try lib.createFace(firasans_font_path, 0);
}
test "create face from memory" {
const lib = try ft.Library.init();
_ = try lib.createFaceMemory(firasans_font_data, 0);
}
test "create stroker" {
const lib = try ft.Library.init();
_ = try lib.createStroker();
}
test "load glyph" {
const lib = try ft.Library.init();
const face = try lib.createFace(firasans_font_path, 0);
try face.setPixelSizes(100, 100);
try face.setCharSize(10 * 10, 0, 72, 0);
try face.loadGlyph(205, .{});
try face.loadChar('A', .{});
face.deinit();
}
test "charmap iterator" {
const lib = try ft.Library.init();
const face = try lib.createFace(firasans_font_path, 0);
var iterator = face.iterateCharmap();
var old_char: u32 = 0;
while (iterator.next()) |char| {
try testing.expect(old_char != char);
old_char = char;
}
}
test "get name index" {
const lib = try ft.Library.init();
const face = try lib.createFace(firasans_font_path, 0);
try testing.expectEqual(@as(u32, 1120), face.getNameIndex("summation").?);
}
test "get index name" {
const lib = try ft.Library.init();
const face = try lib.createFace(firasans_font_path, 0);
var buf: [32]u8 = undefined;
try face.getGlyphName(1120, &buf);
try testing.expectEqualStrings(std.mem.sliceTo(&buf, 0), "summation");
}

View file

@ -1,88 +0,0 @@
const c = @import("c.zig");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const Outline = @import("image.zig").Outline;
const Vector = @import("image.zig").Vector;
pub const LineCap = enum(u2) {
butt = c.FT_STROKER_LINECAP_BUTT,
round = c.FT_STROKER_LINECAP_ROUND,
square = c.FT_STROKER_LINECAP_SQUARE,
};
pub const LineJoin = enum(u2) {
round = c.FT_STROKER_LINEJOIN_ROUND,
bevel = c.FT_STROKER_LINEJOIN_BEVEL,
miter_variable = c.FT_STROKER_LINEJOIN_MITER_VARIABLE,
miter_fixed = c.FT_STROKER_LINEJOIN_MITER_FIXED,
};
pub const Stroker = struct {
pub const Border = enum(u1) {
left,
right,
};
pub const BorderCounts = struct {
points: u32,
contours: u32,
};
handle: c.FT_Stroker,
pub fn set(self: Stroker, radius: i32, line_cap: LineCap, line_join: LineJoin, miter_limit: i32) void {
c.FT_Stroker_Set(self.handle, radius, @intFromEnum(line_cap), @intFromEnum(line_join), miter_limit);
}
pub fn rewind(self: Stroker) void {
c.FT_Stroker_Rewind(self.handle);
}
pub fn parseOutline(self: Stroker, outline: Outline, opened: bool) Error!void {
try intToError(c.FT_Stroker_ParseOutline(self.handle, outline.handle, if (opened) 1 else 0));
}
pub fn beginSubPath(self: Stroker, to: *Vector, open: bool) Error!void {
try intToError(c.FT_Stroker_BeginSubPath(self.handle, to, if (open) 1 else 0));
}
pub fn endSubPath(self: Stroker) Error!void {
try intToError(c.FT_Stroker_EndSubPath(self.handle));
}
pub fn lineTo(self: Stroker, to: *Vector) Error!void {
try intToError(c.FT_Stroker_LineTo(self.handle, to));
}
pub fn conicTo(self: Stroker, control: *Vector, to: *Vector) Error!void {
try intToError(c.FT_Stroker_ConicTo(self.handle, control, to));
}
pub fn cubicTo(self: Stroker, control_0: *Vector, control_1: *Vector, to: *Vector) Error!void {
try intToError(c.FT_Stroker_CubicTo(self.handle, control_0, control_1, to));
}
pub fn getBorderCounts(self: Stroker, border: Border) Error!BorderCounts {
var counts: BorderCounts = undefined;
try intToError(c.FT_Stroker_GetBorderCounts(self.handle, @intFromEnum(border), &counts.points, &counts.contours));
return counts;
}
pub fn exportBorder(self: Stroker, border: Border, outline: *Outline) void {
c.FT_Stroker_ExportBorder(self.handle, @intFromEnum(border), outline.handle);
}
pub fn getCounts(self: Stroker) Error!BorderCounts {
var counts: BorderCounts = undefined;
try intToError(c.FT_Stroker_GetCounts(self.handle, &counts.points, &counts.contours));
return counts;
}
pub fn exportAll(self: Stroker, outline: *Outline) void {
c.FT_Stroker_Export(self.handle, outline.handle);
}
pub fn deinit(self: Stroker) void {
c.FT_Stroker_Done(self.handle);
}
};

View file

@ -1,5 +0,0 @@
const c = @import("c.zig");
pub const Matrix = c.FT_Matrix;
pub const Generic = c.FT_Generic;
pub const BBox = c.FT_BBox;

@ -1 +0,0 @@
Subproject commit d2eb35016c56cc3e2ef4076e8d61e3fd035071ab