├── .gitignore ├── fonts ├── kosugi_maru │ ├── kosugi_maru_enc_4.bin │ ├── README │ └── LICENSE.txt └── notomono-hinted │ ├── NotoMono-Regular.ttf │ ├── README │ └── LICENSE_OFL.txt ├── src ├── macros.rs ├── lib.rs ├── geom.rs ├── raster.rs ├── accumulate.rs └── font.rs ├── Cargo.toml ├── .travis.yml ├── tests └── raster_issues.rs ├── CONTRIBUTING.md ├── benches ├── glyph.rs └── raster.rs ├── examples ├── draw_shape.rs └── render.rs ├── rustfmt.toml ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | target 3 | 4 | -------------------------------------------------------------------------------- /fonts/kosugi_maru/kosugi_maru_enc_4.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/raphlinus/font-rs/HEAD/fonts/kosugi_maru/kosugi_maru_enc_4.bin -------------------------------------------------------------------------------- /fonts/notomono-hinted/NotoMono-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/raphlinus/font-rs/HEAD/fonts/notomono-hinted/NotoMono-Regular.ttf -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | #[macro_export] 2 | macro_rules! gen_new { 3 | ($r:ident, $($field:ident : $field_type:ty),*) => { 4 | impl $r { 5 | pub fn new($($field: $field_type),*) -> Self { 6 | $r { 7 | $($field: $field),* 8 | } 9 | } 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "font-rs" 3 | version = "0.1.3" 4 | license = "Apache-2.0" 5 | authors = [ "Raph Levien " ] 6 | keywords = ["font", "truetype", "ttf"] 7 | description = "A font renderer written (mostly) in pure, safe Rust" 8 | repository = "https://github.com/google/font-rs" 9 | 10 | [features] 11 | sse = [] 12 | -------------------------------------------------------------------------------- /fonts/notomono-hinted/README: -------------------------------------------------------------------------------- 1 | This package is part of the noto project. Visit 2 | google.com/get/noto for more information. 3 | 4 | Built on 2017-10-24 from the following noto repository: 5 | ----- 6 | Repo: noto-fonts 7 | Tag: v2017-10-24-phase3-second-cleanup 8 | Date: 2017-10-24 12:10:34 GMT 9 | Commit: 8ef14e6c606a7a0ef3943b9ca01fd49445620d79 10 | 11 | Remove some files that aren't for release. 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta 5 | - nightly 6 | cache: 7 | - apt 8 | - cargo 9 | 10 | os: 11 | - linux 12 | 13 | script: 14 | - cargo build --verbose --features "" 15 | - cargo test --verbose --features "" 16 | - cargo build --verbose --features sse 17 | - cargo test --verbose --features sse 18 | - | 19 | if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then 20 | cargo bench --features "" 21 | cargo bench --features "sse" 22 | fi 23 | -------------------------------------------------------------------------------- /tests/raster_issues.rs: -------------------------------------------------------------------------------- 1 | extern crate font_rs; 2 | 3 | use font_rs::{raster::Raster, geom::Point}; 4 | 5 | /// Index oob panic found rasterizing "Gauntl" using Bitter-Regular.otf. 6 | #[test] 7 | fn draw_line_index_panic() { 8 | let mut r = Raster::new(6, 16); 9 | r.draw_line(&Point::new(5.54, 14.299999), &Point::new(3.7399998, 13.799999)); 10 | r.draw_line(&Point::new(3.7399998, 13.799999), &Point::new(3.7399998, 0.0)); 11 | r.draw_line(&Point::new(3.7399998, 0.0), &Point::new(0.0, 0.10000038)); 12 | } 13 | -------------------------------------------------------------------------------- /fonts/kosugi_maru/README: -------------------------------------------------------------------------------- 1 | Kosugi Maru 2 | 3 | Designer 4 | MOTOYA 5 | Principal design 6 | 7 | About 8 | Kosugi Maru is a Gothic Rounded design, with low stroke contrast and monospaced metrics, and rounded terminals. Initially developed by MOTOYA and released for the Android platform under the Apache license, the typeface is based on a design from the 1950s. It aims for beauty and readability, and evokes the Japanese cedar trees that have straight and thick trunks and branches. Originally available as "MotoyaLMaru W3 mono", it is now available under the name Kosugi Maru. A regular gothic version is available as Kosugi. 9 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //! A very high performance font renderer. 16 | 17 | #[macro_use] 18 | pub mod macros; 19 | pub mod accumulate; 20 | pub mod font; 21 | pub mod geom; 22 | pub mod raster; 23 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Want to contribute? Great! First, read this page (including the small print at the end). 2 | 3 | ### Before you contribute 4 | Before we can use your code, you must sign the 5 | [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1) 6 | (CLA), which you can do online. The CLA is necessary mainly because you own the 7 | copyright to your changes, even after your contribution becomes part of our 8 | codebase, so we need your permission to use and distribute your code. We also 9 | need to be sure of various other things—for instance that you'll tell us if you 10 | know that your code infringes on other people's patents. You don't have to sign 11 | the CLA until after you've submitted your code for review and a member has 12 | approved it, but you must do it before we can put your code into our codebase. 13 | Before you start working on a larger contribution, you should get in touch with 14 | us first through the issue tracker with your idea so that we can help out and 15 | possibly guide you. Coordinating up front makes it much easier to avoid 16 | frustration later on. 17 | 18 | ### Code reviews 19 | All submissions, including submissions by project members, require review. We 20 | use Github pull requests for this purpose. 21 | 22 | ### The small print 23 | Contributions made by corporations are covered by a different agreement than 24 | the one above, the Software Grant and Corporate Contributor License Agreement. 25 | -------------------------------------------------------------------------------- /benches/glyph.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Google Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #![feature(test)] 16 | extern crate font_rs; 17 | extern crate test; 18 | 19 | use font_rs::font; 20 | use test::Bencher; 21 | 22 | static FONT_DATA: &'static [u8] = 23 | include_bytes!("../fonts/notomono-hinted/NotoMono-Regular.ttf"); 24 | 25 | fn glyphbench(b: &mut Bencher, size: u32) { 26 | let font = font::parse(&FONT_DATA).unwrap(); 27 | b.iter(|| font.render_glyph(200, size)); 28 | } 29 | 30 | #[bench] 31 | fn glyph400(b: &mut Bencher) { 32 | glyphbench(b, 400) 33 | } 34 | 35 | #[bench] 36 | fn glyph100(b: &mut Bencher) { 37 | glyphbench(b, 100) 38 | } 39 | 40 | #[bench] 41 | fn glyph040(b: &mut Bencher) { 42 | glyphbench(b, 40) 43 | } 44 | 45 | #[bench] 46 | fn glyph020(b: &mut Bencher) { 47 | glyphbench(b, 20) 48 | } 49 | 50 | #[bench] 51 | fn glyph010(b: &mut Bencher) { 52 | glyphbench(b, 10) 53 | } 54 | -------------------------------------------------------------------------------- /examples/draw_shape.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //! A simple test program for exercising the rasterizer. 16 | 17 | extern crate font_rs; 18 | 19 | use std::io::{stdout, Write}; 20 | 21 | use font_rs::geom::Point; 22 | use font_rs::raster::Raster; 23 | 24 | fn draw_shape(r: &mut Raster, s: f32) { 25 | r.draw_line( 26 | &Point { 27 | x: s * 10.0, 28 | y: s * 10.5, 29 | }, 30 | &Point { 31 | x: s * 20.0, 32 | y: s * 150.0, 33 | }, 34 | ); 35 | r.draw_line( 36 | &Point { 37 | x: s * 20.0, 38 | y: s * 150.0, 39 | }, 40 | &Point { 41 | x: s * 50.0, 42 | y: s * 139.0, 43 | }, 44 | ); 45 | r.draw_quad( 46 | &Point { 47 | x: s * 50.0, 48 | y: s * 139.0, 49 | }, 50 | &Point { 51 | x: s * 100.0, 52 | y: s * 60.0, 53 | }, 54 | &Point { 55 | x: s * 10.0, 56 | y: s * 10.5, 57 | }, 58 | ); 59 | } 60 | 61 | fn main() { 62 | let w = 400; 63 | let h = 400; 64 | let mut r = Raster::new(w, h); 65 | draw_shape(&mut r, 4.0); 66 | let mut o = stdout(); 67 | let _ = o.write(format!("P5\n{} {}\n255\n", w, h).as_bytes()); 68 | let _ = o.write(&r.get_bitmap()); 69 | } 70 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | # This file was originally created by running the command 2 | # rustfmt --dump-default-config rustfmt.toml && sort -u rustfmt.toml -o rustfmt.toml. 3 | # Changes from the defaults are marked with comments. 4 | binop_separator = "Front" 5 | blank_lines_lower_bound = 0 6 | blank_lines_upper_bound = 1 7 | brace_style = "SameLineWhere" 8 | color = "Auto" 9 | combine_control_expr = true 10 | comment_width = 100 # Fuchsia uses 100 11 | condense_wildcard_suffixes = false 12 | control_brace_style = "AlwaysSameLine" 13 | disable_all_formatting = false 14 | empty_item_single_line = true 15 | error_on_line_overflow = false 16 | error_on_unformatted = false 17 | fn_args_density = "Compressed" # Fuchsia prefers compressed 18 | fn_single_line = false 19 | force_explicit_abi = true 20 | force_multiline_blocks = false 21 | format_strings = true # otherwise strings will violate max_width 22 | hard_tabs = false 23 | hide_parse_errors = false 24 | imports_indent = "Visual" 25 | imports_layout = "Mixed" 26 | indent_style = "Block" 27 | match_arm_blocks = true 28 | match_block_trailing_comma = false 29 | max_width = 100 30 | merge_derives = true 31 | merge_imports = false 32 | newline_style = "Unix" 33 | normalize_comments = false 34 | remove_blank_lines_at_start_or_end_of_block = true 35 | reorder_impl_items = false 36 | reorder_imports = true 37 | reorder_modules = true 38 | report_fixme = "Never" 39 | report_todo = "Never" 40 | skip_children = false 41 | space_after_colon = true 42 | space_before_colon = false 43 | spaces_around_ranges = false 44 | spaces_within_parens_and_brackets = false 45 | struct_field_align_threshold = 0 46 | struct_lit_single_line = true 47 | tab_spaces = 4 48 | trailing_comma = "Vertical" 49 | trailing_semicolon = true 50 | type_punctuation_density = "Wide" 51 | unstable_features = false 52 | use_field_init_shorthand = false 53 | use_small_heuristics = true 54 | use_try_shorthand = true # Fuchsia prefers the shortcut 55 | where_single_line = false 56 | wrap_comments = true # otherwise comments will violate max_width 57 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # font-rs 2 | 3 | This is a font renderer written (mostly) in pure, safe Rust. There is an optional 4 | SIMD module for cumulative sum, currently written in C SSE3 intrinsics. 5 | 6 | The current state of the code is quite rough. The code isn't well organized, 7 | and it's basically not ready for prime time. However, it runs well enough to 8 | run benchmarks, and those benchmarks suggest extremely promising performance 9 | compared with Freetype and freetype-go (the loose port of Freetype to Go). 10 | 11 | The rasterizer is basically very similar in design to 12 | [libart](https://people.gnome.org/~mathieu/libart/internals.html), except that 13 | vectors are drawn immediately into the buffer, rather than sorted and stored 14 | in intermediate form, and that the buffer for rasterization is a dense array 15 | rather than a sparse data structure. The main motivation for the latter is to 16 | avoid branch misprediction and to better exploit data parallelism, both valid 17 | trends in optimization since libart was originally written. 18 | 19 | It's worth comparing the algorithm with that in 20 | [Anti-Grain Geometry](http://projects.tuxee.net/cl-vectors/section-the-cl-aa-algorithm). 21 | The original libart algorithm was also inspiration for the current antialiased 22 | renderer in Freetype. All these renderers share many common features, 23 | particularly computation of exact subpixel areas and an integration step 24 | to determine winding number (and convert to pixel value), but differ in details 25 | such as data structures to represent the vectors and the buffer. 26 | 27 | The parsing of TrueType glyph data is done in pull-parser style, as iterators 28 | over the lower-level data. This technique basically avoids allocating any 29 | memory for representation of points and quadratic Beziers. 30 | 31 | ## Authors 32 | 33 | The main author is Raph Levien. 34 | 35 | ## Contributions 36 | 37 | We gladly accept contributions via GitHub pull requests, as long as the author 38 | has signed the Google Contributor License. Please see CONTRIBUTIONS.md for 39 | more details. 40 | 41 | ### Disclaimer 42 | 43 | This is not an official Google product (experimental or otherwise), it 44 | is just code that happens to be owned by Google. 45 | -------------------------------------------------------------------------------- /src/geom.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //! Geometry primitive data structures and manipulations 16 | 17 | use std::fmt::{Debug, Formatter, Result}; 18 | 19 | #[derive(Copy, Clone)] 20 | pub struct Point { 21 | pub x: f32, 22 | pub y: f32, 23 | } 24 | 25 | impl Point { 26 | pub fn new(x: T, y: T) -> Point 27 | where 28 | T: Into, 29 | { 30 | Point { 31 | x: x.into(), 32 | y: y.into(), 33 | } 34 | } 35 | 36 | pub fn lerp(t: f32, p0: &Self, p1: &Self) -> Self { 37 | Point { 38 | x: p0.x + t * (p1.x - p0.x), 39 | y: p0.y + t * (p1.y - p0.y), 40 | } 41 | } 42 | } 43 | 44 | impl Debug for Point { 45 | fn fmt(&self, f: &mut Formatter) -> Result { 46 | write!(f, "({}, {})", self.x, self.y) 47 | } 48 | } 49 | 50 | #[derive(Debug)] 51 | pub struct Affine { 52 | a: f32, 53 | b: f32, 54 | c: f32, 55 | d: f32, 56 | e: f32, 57 | f: f32, 58 | } 59 | 60 | impl Affine { 61 | /// Concatenate two affine transforms. 62 | pub fn concat(t1: &Affine, t2: &Affine) -> Affine { 63 | Affine { 64 | a: t1.a * t2.a + t1.c * t2.b, 65 | b: t1.b * t2.a + t1.d * t2.b, 66 | c: t1.a * t2.c + t1.c * t2.d, 67 | d: t1.b * t2.c + t1.d * t2.d, 68 | e: t1.a * t2.e + t1.c * t2.f + t1.e, 69 | f: t1.b * t2.e + t1.d * t2.f + t1.f, 70 | } 71 | } 72 | } 73 | 74 | pub fn affine_pt(z: &Affine, p: &Point) -> Point { 75 | Point { 76 | x: z.a * p.x + z.c * p.y + z.e, 77 | y: z.b * p.x + z.d * p.y + z.f, 78 | } 79 | } 80 | 81 | gen_new!(Affine, a: f32, b: f32, c: f32, d: f32, e: f32, f: f32); 82 | -------------------------------------------------------------------------------- /examples/render.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | extern crate font_rs; 16 | 17 | use std::fs::File; 18 | use std::io::{Read, Write}; 19 | use std::time::SystemTime; 20 | 21 | use font_rs::font::{parse, GlyphBitmap}; 22 | 23 | fn dump_pgm(glyph: &GlyphBitmap, out_filename: &str) { 24 | let mut o = File::create(&out_filename).unwrap(); 25 | let _ = o.write(format!("P5\n{} {}\n255\n", glyph.width, glyph.height).as_bytes()); 26 | println!("data len = {}", glyph.data.len()); 27 | let _ = o.write(&glyph.data); 28 | } 29 | 30 | fn main() { 31 | let mut args = std::env::args(); 32 | let _ = args.next(); 33 | let filename = args.next().unwrap(); 34 | let glyph_id: u16 = args.next().unwrap().parse().unwrap(); 35 | let out_filename = args.next().unwrap(); 36 | let mut f = File::open(&filename).unwrap(); 37 | let mut data = Vec::new(); 38 | match f.read_to_end(&mut data) { 39 | Err(e) => println!("failed to read {}, {}", filename, e), 40 | Ok(_) => match parse(&data) { 41 | Ok(font) => { 42 | if out_filename == "__bench__" { 43 | for size in 1..201 { 44 | let start = SystemTime::now(); 45 | let n_iter = 1000; 46 | for _ in 0..n_iter { 47 | match font.render_glyph(glyph_id, size) { 48 | Some(_glyph) => (), 49 | None => (), 50 | } 51 | } 52 | let elapsed = start.elapsed().unwrap(); 53 | let elapsed = 54 | elapsed.as_secs() as f64 + 1e-9 * (elapsed.subsec_nanos() as f64); 55 | println!("{} {}", size, elapsed * (1e6 / n_iter as f64)); 56 | } 57 | } else { 58 | match font.render_glyph(glyph_id, 400) { 59 | Some(glyph) => dump_pgm(&glyph, &out_filename), 60 | None => println!("failed to render {} {}", filename, glyph_id), 61 | } 62 | } 63 | } 64 | Err(_) => println!("failed to parse {}", filename), 65 | }, 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /benches/raster.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Google Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #![feature(test)] 16 | extern crate font_rs; 17 | extern crate test; 18 | 19 | use font_rs::geom::Point; 20 | use font_rs::raster::*; 21 | use test::Bencher; 22 | 23 | fn draw_shape(r: &mut Raster, s: f32) { 24 | r.draw_line( 25 | &Point::new(s * 10.0, s * 10.5), 26 | &Point::new(s * 20.0, s * 150.0), 27 | ); 28 | r.draw_line( 29 | &Point::new(s * 20.0, s * 150.0), 30 | &Point::new(s * 50.0, s * 139.0), 31 | ); 32 | r.draw_quad( 33 | &Point::new(s * 50.0, s * 139.0), 34 | &Point::new(s * 100.0, s * 60.0), 35 | &Point::new(s * 10.0, s * 10.5), 36 | ); 37 | } 38 | 39 | #[bench] 40 | fn empty200(b: &mut Bencher) { 41 | b.iter(|| { 42 | let w = 200; 43 | let h = 200; 44 | let r = Raster::new(w, h); 45 | r.get_bitmap() 46 | }) 47 | } 48 | 49 | #[bench] 50 | fn render200(b: &mut Bencher) { 51 | b.iter(|| { 52 | let w = 200; 53 | let h = 200; 54 | let mut r = Raster::new(w, h); 55 | draw_shape(&mut r, 1.0); 56 | r.get_bitmap() 57 | }) 58 | } 59 | 60 | #[bench] 61 | fn prep200(b: &mut Bencher) { 62 | b.iter(|| { 63 | let w = 200; 64 | let h = 200; 65 | let mut r = Raster::new(w, h); 66 | draw_shape(&mut r, 1.0); 67 | }) 68 | } 69 | 70 | #[bench] 71 | fn prep400(b: &mut Bencher) { 72 | b.iter(|| { 73 | let w = 400; 74 | let h = 400; 75 | let mut r = Raster::new(w, h); 76 | draw_shape(&mut r, 2.0); 77 | }) 78 | } 79 | 80 | #[bench] 81 | fn render400(b: &mut Bencher) { 82 | b.iter(|| { 83 | let w = 400; 84 | let h = 400; 85 | let mut r = Raster::new(w, h); 86 | draw_shape(&mut r, 2.0); 87 | r.get_bitmap() 88 | }) 89 | } 90 | 91 | #[bench] 92 | fn empty400(b: &mut Bencher) { 93 | b.iter(|| { 94 | let w = 400; 95 | let h = 400; 96 | let r = Raster::new(w, h); 97 | r.get_bitmap() 98 | }) 99 | } 100 | 101 | #[bench] 102 | fn alloc400(b: &mut Bencher) { 103 | b.iter(|| vec![0.0; 400 * 400 + 1]) 104 | } 105 | 106 | #[bench] 107 | fn alloc200(b: &mut Bencher) { 108 | b.iter(|| vec![0.0; 200 * 200 + 1]) 109 | } 110 | -------------------------------------------------------------------------------- /fonts/notomono-hinted/LICENSE_OFL.txt: -------------------------------------------------------------------------------- 1 | This Font Software is licensed under the SIL Open Font License, 2 | Version 1.1. 3 | 4 | This license is copied below, and is also available with a FAQ at: 5 | http://scripts.sil.org/OFL 6 | 7 | ----------------------------------------------------------- 8 | SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 9 | ----------------------------------------------------------- 10 | 11 | PREAMBLE 12 | The goals of the Open Font License (OFL) are to stimulate worldwide 13 | development of collaborative font projects, to support the font 14 | creation efforts of academic and linguistic communities, and to 15 | provide a free and open framework in which fonts may be shared and 16 | improved in partnership with others. 17 | 18 | The OFL allows the licensed fonts to be used, studied, modified and 19 | redistributed freely as long as they are not sold by themselves. The 20 | fonts, including any derivative works, can be bundled, embedded, 21 | redistributed and/or sold with any software provided that any reserved 22 | names are not used by derivative works. The fonts and derivatives, 23 | however, cannot be released under any other type of license. The 24 | requirement for fonts to remain under this license does not apply to 25 | any document created using the fonts or their derivatives. 26 | 27 | DEFINITIONS 28 | "Font Software" refers to the set of files released by the Copyright 29 | Holder(s) under this license and clearly marked as such. This may 30 | include source files, build scripts and documentation. 31 | 32 | "Reserved Font Name" refers to any names specified as such after the 33 | copyright statement(s). 34 | 35 | "Original Version" refers to the collection of Font Software 36 | components as distributed by the Copyright Holder(s). 37 | 38 | "Modified Version" refers to any derivative made by adding to, 39 | deleting, or substituting -- in part or in whole -- any of the 40 | components of the Original Version, by changing formats or by porting 41 | the Font Software to a new environment. 42 | 43 | "Author" refers to any designer, engineer, programmer, technical 44 | writer or other person who contributed to the Font Software. 45 | 46 | PERMISSION & CONDITIONS 47 | Permission is hereby granted, free of charge, to any person obtaining 48 | a copy of the Font Software, to use, study, copy, merge, embed, 49 | modify, redistribute, and sell modified and unmodified copies of the 50 | Font Software, subject to the following conditions: 51 | 52 | 1) Neither the Font Software nor any of its individual components, in 53 | Original or Modified Versions, may be sold by itself. 54 | 55 | 2) Original or Modified Versions of the Font Software may be bundled, 56 | redistributed and/or sold with any software, provided that each copy 57 | contains the above copyright notice and this license. These can be 58 | included either as stand-alone text files, human-readable headers or 59 | in the appropriate machine-readable metadata fields within text or 60 | binary files as long as those fields can be easily viewed by the user. 61 | 62 | 3) No Modified Version of the Font Software may use the Reserved Font 63 | Name(s) unless explicit written permission is granted by the 64 | corresponding Copyright Holder. This restriction only applies to the 65 | primary font name as presented to the users. 66 | 67 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font 68 | Software shall not be used to promote, endorse or advertise any 69 | Modified Version, except to acknowledge the contribution(s) of the 70 | Copyright Holder(s) and the Author(s) or with their explicit written 71 | permission. 72 | 73 | 5) The Font Software, modified or unmodified, in part or in whole, 74 | must be distributed entirely under this license, and must not be 75 | distributed under any other license. The requirement for fonts to 76 | remain under this license does not apply to any document created using 77 | the Font Software. 78 | 79 | TERMINATION 80 | This license becomes null and void if any of the above conditions are 81 | not met. 82 | 83 | DISCLAIMER 84 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 85 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 86 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 87 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 88 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 89 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 90 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 91 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM 92 | OTHER DEALINGS IN THE FONT SOFTWARE. 93 | -------------------------------------------------------------------------------- /src/raster.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //! An antialiased rasterizer for quadratic Beziers 16 | 17 | use accumulate::accumulate; 18 | use geom::Point; 19 | 20 | // TODO: sort out crate structure. Right now we want this when compiling raster as a binary, 21 | // but need it commented out when compiling showttf 22 | //mod geom; 23 | 24 | pub struct Raster { 25 | w: usize, 26 | h: usize, 27 | a: Vec, 28 | } 29 | 30 | // TODO: is there a faster way? (investigate whether approx recip is good enough) 31 | fn recip(x: f32) -> f32 { 32 | x.recip() 33 | } 34 | 35 | impl Raster { 36 | pub fn new(w: usize, h: usize) -> Raster { 37 | Raster { 38 | w: w, 39 | h: h, 40 | a: vec![0.0; w * h + 4], 41 | } 42 | } 43 | 44 | pub fn draw_line(&mut self, p0: &Point, p1: &Point) { 45 | //println!("draw_line {} {}", p0, p1); 46 | if (p0.y - p1.y).abs() <= core::f32::EPSILON { 47 | return; 48 | } 49 | let (dir, p0, p1) = if p0.y < p1.y { 50 | (1.0, p0, p1) 51 | } else { 52 | (-1.0, p1, p0) 53 | }; 54 | let dxdy = (p1.x - p0.x) / (p1.y - p0.y); 55 | let mut x = p0.x; 56 | let y0 = p0.y as usize; // note: implicit max of 0 because usize (TODO: really true?) 57 | if p0.y < 0.0 { 58 | x -= p0.y * dxdy; 59 | } 60 | for y in y0..self.h.min(p1.y.ceil() as usize) { 61 | let linestart = y * self.w; 62 | let dy = ((y + 1) as f32).min(p1.y) - (y as f32).max(p0.y); 63 | let xnext = x + dxdy * dy; 64 | let d = dy * dir; 65 | let (x0, x1) = if x < xnext { (x, xnext) } else { (xnext, x) }; 66 | let x0floor = x0.floor(); 67 | let x0i = x0floor as i32; 68 | let x1ceil = x1.ceil(); 69 | let x1i = x1ceil as i32; 70 | if x1i <= x0i + 1 { 71 | let xmf = 0.5 * (x + xnext) - x0floor; 72 | let linestart_x0i = linestart as isize + x0i as isize; 73 | if linestart_x0i < 0 { 74 | continue; // oob index 75 | } 76 | self.a[linestart_x0i as usize] += d - d * xmf; 77 | self.a[linestart_x0i as usize + 1] += d * xmf; 78 | } else { 79 | let s = (x1 - x0).recip(); 80 | let x0f = x0 - x0floor; 81 | let a0 = 0.5 * s * (1.0 - x0f) * (1.0 - x0f); 82 | let x1f = x1 - x1ceil + 1.0; 83 | let am = 0.5 * s * x1f * x1f; 84 | let linestart_x0i = linestart as isize + x0i as isize; 85 | if linestart_x0i < 0 { 86 | continue; // oob index 87 | } 88 | self.a[linestart_x0i as usize] += d * a0; 89 | if x1i == x0i + 2 { 90 | self.a[linestart_x0i as usize + 1] += d * (1.0 - a0 - am); 91 | } else { 92 | let a1 = s * (1.5 - x0f); 93 | self.a[linestart_x0i as usize + 1] += d * (a1 - a0); 94 | for xi in x0i + 2..x1i - 1 { 95 | self.a[linestart + xi as usize] += d * s; 96 | } 97 | let a2 = a1 + (x1i - x0i - 3) as f32 * s; 98 | self.a[linestart + (x1i - 1) as usize] += d * (1.0 - a2 - am); 99 | } 100 | self.a[linestart + x1i as usize] += d * am; 101 | } 102 | x = xnext; 103 | } 104 | } 105 | 106 | pub fn draw_quad(&mut self, p0: &Point, p1: &Point, p2: &Point) { 107 | //println!("draw_quad {} {} {}", p0, p1, p2); 108 | let devx = p0.x - 2.0 * p1.x + p2.x; 109 | let devy = p0.y - 2.0 * p1.y + p2.y; 110 | let devsq = devx * devx + devy * devy; 111 | if devsq < 0.333 { 112 | self.draw_line(p0, p2); 113 | return; 114 | } 115 | let tol = 3.0; 116 | let n = 1 + (tol * (devx * devx + devy * devy)).sqrt().sqrt().floor() as usize; 117 | //println!("n = {}", n); 118 | let mut p = *p0; 119 | let nrecip = recip(n as f32); 120 | let mut t = 0.0; 121 | for _i in 0..n - 1 { 122 | t += nrecip; 123 | let pn = Point::lerp(t, &Point::lerp(t, p0, p1), &Point::lerp(t, p1, p2)); 124 | self.draw_line(&p, &pn); 125 | p = pn; 126 | } 127 | self.draw_line(&p, p2); 128 | } 129 | 130 | /* 131 | fn get_bitmap_fancy(&self) -> Vec { 132 | let mut acc = 0.0; 133 | // This would translate really well to SIMD 134 | self.a[0..self.w * self.h].iter().map(|&a| { 135 | acc += a; 136 | (255.0 * acc.abs().min(1.0)) as u8 137 | //(255.5 * (0.5 + 0.4 * acc)) as u8 138 | }).collect() 139 | } 140 | */ 141 | 142 | pub fn get_bitmap(&self) -> Vec { 143 | accumulate(&self.a[0..self.w * self.h]) 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/accumulate.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Google Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::mem; 16 | 17 | #[cfg(target_arch = "x86_64")] 18 | use std::arch::x86_64::*; 19 | 20 | #[cfg(target_arch = "x86")] 21 | use std::arch::x86::*; 22 | 23 | macro_rules! _mm_shuffle { 24 | ($z:expr, $y:expr, $x:expr, $w:expr) => { 25 | ($z << 6) | ($y << 4) | ($x << 2) | $w 26 | }; 27 | } 28 | 29 | #[cfg(feature = "sse")] 30 | pub fn accumulate(src: &[f32]) -> Vec { 31 | // SIMD instructions force us to align data since we iterate each 4 elements 32 | // So: 33 | // n (0) => 0 34 | // n (1 or 2 or 3 or 4) => 4, 35 | // n (5) => 8 36 | // and so on 37 | let len = src.len(); 38 | let n = (len + 3) & !3; // align data 39 | let mut dst: Vec = vec![0; n]; 40 | 41 | unsafe { 42 | let mut offset = _mm_setzero_ps(); 43 | let sign_mask = _mm_set1_ps(-0.); 44 | let mask = _mm_set1_epi32(0x0c080400); 45 | 46 | for i in (0..n).step_by(4) { 47 | let mut x = _mm_loadu_ps(&src[i]); 48 | x = _mm_add_ps(x, _mm_castsi128_ps(_mm_slli_si128(_mm_castps_si128(x), 4))); 49 | x = _mm_add_ps(x, _mm_shuffle_ps(_mm_setzero_ps(), x, 0x40)); 50 | x = _mm_add_ps(x, offset); 51 | 52 | let mut y = _mm_andnot_ps(sign_mask, x); // fabs(x) 53 | y = _mm_min_ps(y, _mm_set1_ps(1.0)); 54 | y = _mm_mul_ps(y, _mm_set1_ps(255.0)); 55 | 56 | let mut z = _mm_cvttps_epi32(y); 57 | z = _mm_shuffle_epi8(z, mask); 58 | 59 | _mm_store_ss(mem::transmute(&dst[i]), _mm_castsi128_ps(z)); 60 | offset = _mm_shuffle_ps(x, x, _mm_shuffle!(3, 3, 3, 3)); 61 | } 62 | 63 | dst.set_len(len); // we must return vec of the same length as src.len() 64 | } 65 | 66 | dst 67 | } 68 | 69 | #[cfg(not(feature = "sse"))] 70 | pub fn accumulate(src: &[f32]) -> Vec { 71 | let mut acc = 0.0; 72 | src.iter() 73 | .map(|c| { 74 | // This would translate really well to SIMD 75 | acc += c; 76 | let y = acc.abs(); 77 | let y = if y < 1.0 { y } else { 1.0 }; 78 | (255.0 * y) as u8 79 | }) 80 | .collect() 81 | } 82 | 83 | #[cfg(test)] 84 | mod tests { 85 | use super::*; 86 | 87 | // The most simple and straightforward implementation of 88 | // accumulate fn 89 | fn accumulate_simple_impl(src: &[f32]) -> Vec { 90 | let mut acc = 0.0; 91 | src.iter() 92 | .map(|c| { 93 | acc += c; 94 | let y = acc.abs(); 95 | let y = if y < 1.0 { y } else { 1.0 }; 96 | (255.0 * y) as u8 97 | }) 98 | .collect() 99 | } 100 | fn test_accumulate(src: Vec) { 101 | assert_eq!(accumulate_simple_impl(&src), accumulate(&src)); 102 | } 103 | 104 | #[test] 105 | fn max_255_from_1_0() { 106 | // 1.0 * 255.0 = 255.0 (max value) 107 | test_accumulate(vec![1.0]); 108 | } 109 | #[test] 110 | fn max_255_from_0_5() { 111 | // 0.5 * 2 = 1.0 112 | // 1.0 * 255.0 = 255.0 (max value) 113 | test_accumulate(vec![0.5; 2]); 114 | } 115 | #[test] 116 | fn max_255_from_0_25() { 117 | // 0.25 * 4 = 1.0 118 | // 1.0 * 255.0 = 255.0 (max value) 119 | test_accumulate(vec![0.25; 4]); 120 | } 121 | #[test] 122 | fn max_255_from_0_125() { 123 | // 0.125 * 8 = 1.0 124 | // 1.0 * 255.0 = 255.0 (max value) 125 | test_accumulate(vec![0.125; 8]); 126 | } 127 | #[test] 128 | fn max_255_from_0_0625() { 129 | // 0.0625 * 16 = 1.0 130 | // 1.0 * 255.0 = 255.0 (max value) 131 | test_accumulate(vec![0.0625; 16]); 132 | } 133 | #[test] 134 | fn max_255_from_0_03125() { 135 | // 0.03125 * 32 = 1.0 136 | // 1.0 * 255.0 = 255.0 (max value) 137 | test_accumulate(vec![0.03125; 32]); 138 | } 139 | #[test] 140 | fn max_255_from_0_015625() { 141 | // 0.015625 * 64 = 1.0 142 | // 1.0 * 255.0 = 255.0 (max value) 143 | test_accumulate(vec![0.015625; 64]); 144 | } 145 | #[test] 146 | fn max_255_from_0_0078125() { 147 | // 0.0078125 * 128 = 1.0 148 | // 1.0 * 255.0 = 255.0 (max value) 149 | test_accumulate(vec![0.0078125; 128]); 150 | } 151 | 152 | #[test] 153 | fn simple_0() { 154 | test_accumulate(vec![]); 155 | } 156 | #[test] 157 | fn simple_1() { 158 | test_accumulate(vec![0.1]); 159 | } 160 | #[test] 161 | fn simple_2() { 162 | test_accumulate(vec![0.1, 0.2]); 163 | } 164 | #[test] 165 | fn simple_3() { 166 | test_accumulate(vec![0.1, 0.2, 0.3]); 167 | } 168 | #[test] 169 | fn simple_4() { 170 | test_accumulate(vec![0.1, 0.2, 0.3, 0.4]); 171 | } 172 | #[test] 173 | fn simple_5() { 174 | test_accumulate(vec![0.1, 0.2, 0.3, 0.4, 0.5]); 175 | } 176 | #[test] 177 | fn simple_6() { 178 | test_accumulate(vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6]); 179 | } 180 | #[test] 181 | fn simple_7() { 182 | test_accumulate(vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]); 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /fonts/kosugi_maru/LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /src/font.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //! A simple renderer for TrueType fonts 16 | 17 | use std::collections::HashMap; 18 | use std::fmt; 19 | use std::fmt::{Debug, Display, Formatter}; 20 | use std::result::Result; 21 | 22 | use geom::{affine_pt, Affine, Point}; 23 | use raster::Raster; 24 | 25 | #[derive(PartialEq, Eq, Hash)] 26 | struct Tag(u32); 27 | 28 | impl Tag { 29 | fn from_str(s: &str) -> Tag { 30 | Tag(get_u32(s.as_bytes(), 0).unwrap()) 31 | } 32 | } 33 | 34 | impl Display for Tag { 35 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 36 | let &Tag(tag) = self; 37 | let buf = vec![ 38 | ((tag >> 24) & 0xff) as u8, 39 | ((tag >> 16) & 0xff) as u8, 40 | ((tag >> 8) & 0xff) as u8, 41 | (tag & 0xff) as u8, 42 | ]; 43 | f.write_str(&String::from_utf8(buf).unwrap()) 44 | } 45 | } 46 | 47 | fn get_u16(data: &[u8], off: usize) -> Option { 48 | if off + 1 > data.len() { 49 | None 50 | } else { 51 | Some(((data[off] as u16) << 8) | data[off + 1] as u16) 52 | } 53 | } 54 | 55 | fn get_i16(data: &[u8], off: usize) -> Option { 56 | get_u16(data, off).map(|x| x as i16) 57 | } 58 | 59 | fn get_f2_14(data: &[u8], off: usize) -> Option { 60 | get_i16(data, off).map(|x| x as f32 * (1.0 / (1 << 14) as f32)) 61 | } 62 | 63 | fn get_u32(data: &[u8], off: usize) -> Option { 64 | if off + 3 > data.len() { 65 | None 66 | } else { 67 | Some( 68 | ((data[off] as u32) << 24) 69 | | ((data[off + 1] as u32) << 16) 70 | | ((data[off + 2] as u32) << 8) 71 | | data[off + 3] as u32, 72 | ) 73 | } 74 | } 75 | 76 | // TODO: be consistent, use newtype or one-field struct everywhere 77 | struct Head<'a>(&'a [u8]); 78 | 79 | impl<'a> Head<'a> { 80 | fn index_to_loc_format(&self) -> i16 { 81 | get_i16(self.0, 50).unwrap() 82 | } 83 | 84 | fn units_per_em(&self) -> u16 { 85 | get_u16(self.0, 18).unwrap() 86 | } 87 | } 88 | 89 | struct Maxp<'a> { 90 | data: &'a [u8], 91 | } 92 | 93 | impl<'a> Maxp<'a> { 94 | fn num_glyphs(&self) -> u16 { 95 | get_u16(self.data, 4).unwrap() 96 | } 97 | } 98 | 99 | struct Loca<'a>(&'a [u8]); 100 | 101 | impl<'a> Loca<'a> { 102 | fn get_off(&self, glyph_ix: u16, fmt: i16) -> Option { 103 | if fmt != 0 { 104 | get_u32(self.0, glyph_ix as usize * 4) 105 | } else { 106 | get_u16(self.0, glyph_ix as usize * 2).map(|raw| raw as u32 * 2) 107 | } 108 | } 109 | } 110 | 111 | struct Hhea<'a>(&'a [u8]); 112 | 113 | impl<'a> Hhea<'a> { 114 | fn ascent(&self) -> Option { 115 | get_i16(self.0, 4) 116 | } 117 | 118 | fn descent(&self) -> Option { 119 | get_i16(self.0, 6) 120 | } 121 | 122 | fn line_gap(&self) -> Option { 123 | get_i16(self.0, 8) 124 | } 125 | 126 | fn num_of_long_hor_metrics(&self) -> Option { 127 | get_u16(self.0, 34) 128 | } 129 | } 130 | 131 | struct Hmtx<'a>(&'a [u8]); 132 | 133 | impl<'a> Hmtx<'a> { 134 | fn get_h_metrics(&self, glyph_id: u16, num_of_long_hor_metrics: u16) -> (Option, Option) { 135 | if glyph_id < num_of_long_hor_metrics { 136 | let advance_width = get_u16(self.0, 4 * glyph_id as usize); 137 | let left_side_bearing = get_i16(self.0, 4 * glyph_id as usize + 2); 138 | (advance_width, left_side_bearing) 139 | } else { 140 | let advance_width = get_u16(self.0, 4 * (num_of_long_hor_metrics as usize - 1)); 141 | let left_side_bearing = get_i16(self.0, 142 | 4 * num_of_long_hor_metrics as usize + 143 | 2 * (glyph_id as usize - num_of_long_hor_metrics as usize)); 144 | (advance_width, left_side_bearing) 145 | } 146 | } 147 | } 148 | 149 | struct EncodingRecord<'a>(&'a [u8]); 150 | 151 | impl<'a> EncodingRecord<'a> { 152 | fn get_platform_id(&self) -> u16 { 153 | get_u16(self.0, 0).unwrap() 154 | } 155 | 156 | fn get_encoding_id(&self) -> u16 { 157 | get_u16(self.0, 2).unwrap() 158 | } 159 | 160 | fn get_offset(&self) -> u32 { 161 | get_u32(self.0, 4).unwrap() 162 | } 163 | } 164 | 165 | impl<'a> Debug for EncodingRecord<'a> { 166 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 167 | f.debug_struct("EncodingRecord") 168 | .field("platformID", &self.get_platform_id()) 169 | .field("encodingID", &self.get_encoding_id()) 170 | .field("offset", &self.get_offset()) 171 | .finish() 172 | } 173 | } 174 | 175 | struct Encoding<'a>(&'a [u8]); 176 | 177 | impl<'a> Encoding<'a> { 178 | fn get_format(&self) -> u16 { 179 | get_u16(self.0, 0).unwrap() 180 | } 181 | 182 | fn get_length(&self) -> u16 { 183 | get_u16(self.0, 2).unwrap() 184 | } 185 | 186 | fn get_language(&self) -> u16 { 187 | get_u16(self.0, 4).unwrap() 188 | } 189 | } 190 | 191 | impl<'a> Debug for Encoding<'a> { 192 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 193 | f.debug_struct("Encoding") 194 | .field("format", &self.get_format()) 195 | .field("length", &self.get_length()) 196 | .field("language", &self.get_language()) 197 | .finish() 198 | } 199 | } 200 | 201 | struct EncodingFormat4<'a>(&'a [u8]); 202 | 203 | impl<'a> EncodingFormat4<'a> { 204 | fn get_format(&self) -> u16 { 205 | get_u16(self.0, 0).unwrap() 206 | } 207 | 208 | fn get_length(&self) -> u16 { 209 | get_u16(self.0, 2).unwrap() 210 | } 211 | 212 | fn get_language(&self) -> u16 { 213 | get_u16(self.0, 4).unwrap() 214 | } 215 | 216 | fn get_seg_count_x_2(&self) -> u16 { 217 | get_u16(self.0, 6).unwrap() 218 | } 219 | 220 | fn get_seg_count(&self) -> u16 { 221 | self.get_seg_count_x_2() / 2 222 | } 223 | 224 | fn get_search_range(&self) -> u16 { 225 | get_u16(self.0, 8).unwrap() 226 | } 227 | 228 | fn get_entry_selector(&self) -> u16 { 229 | get_u16(self.0, 10).unwrap() 230 | } 231 | 232 | fn get_range_shift(&self) -> u16 { 233 | get_u16(self.0, 12).unwrap() 234 | } 235 | 236 | fn get_u16_vec(&self, start_position: u16, count: u16) -> Vec { 237 | let mut result = vec![]; 238 | let mut vec_position = start_position; 239 | let limit = vec_position + 2 * count; 240 | while vec_position < limit { 241 | result.push(get_u16(self.0, vec_position as usize).unwrap()); 242 | vec_position += 2; 243 | } 244 | result 245 | } 246 | 247 | fn get_i16_vec(&self, start_position: u16, count: u16) -> Vec { 248 | let mut result = vec![]; 249 | let mut vec_position = start_position; 250 | let limit = vec_position + 2 * count; 251 | while vec_position < limit { 252 | result.push(get_i16(self.0, vec_position as usize).unwrap()); 253 | vec_position += 2; 254 | } 255 | result 256 | } 257 | 258 | fn get_end_counts_position() -> u16 { 259 | 14 260 | } 261 | 262 | fn get_end_counts(&self) -> Vec { 263 | let seg_count = self.get_seg_count(); 264 | self.get_u16_vec(Self::get_end_counts_position(), seg_count) 265 | } 266 | 267 | fn get_start_counts_position(seg_count: u16) -> u16 { 268 | Self::get_end_counts_position() + 2 + 2 * seg_count 269 | } 270 | 271 | fn get_start_counts(&self) -> Vec { 272 | let seg_count = self.get_seg_count(); 273 | self.get_u16_vec(Self::get_start_counts_position(seg_count), seg_count) 274 | } 275 | 276 | fn get_id_deltas_position(seg_count: u16) -> u16 { 277 | Self::get_start_counts_position(seg_count) + 2 * seg_count 278 | } 279 | 280 | fn get_id_deltas(&self) -> Vec { 281 | let seg_count = self.get_seg_count(); 282 | self.get_i16_vec(Self::get_id_deltas_position(seg_count), seg_count) 283 | } 284 | 285 | fn get_id_range_offset_position(seg_count: u16) -> u16 { 286 | Self::get_id_deltas_position(seg_count) + 2 * seg_count 287 | } 288 | 289 | fn get_id_range_offsets(&self) -> Vec { 290 | let seg_count = self.get_seg_count(); 291 | self.get_u16_vec(Self::get_id_range_offset_position(seg_count), seg_count) 292 | } 293 | 294 | fn extract_glyph_id( 295 | &self, code_point: u16, start_value: u16, seg_count: u16, seg_index: u16, 296 | ) -> Option { 297 | let data = self.0; 298 | let seg_index_pos = 2 * seg_index; 299 | let id_range_offset_pos = Self::get_id_range_offset_position(seg_count) + seg_index_pos; 300 | let id_range_offset_value = get_u16(data, id_range_offset_pos as usize).unwrap(); 301 | let id_delta_pos = Self::get_id_deltas_position(seg_count) + seg_index_pos; 302 | let id_delta = get_i16(data, id_delta_pos as usize).unwrap(); 303 | if id_range_offset_value == 0 { 304 | Some(code_point.wrapping_add(id_delta as u16)) 305 | } else { 306 | let delta = (code_point - start_value) * 2; 307 | let pos = id_range_offset_pos.wrapping_add(delta) + id_range_offset_value; 308 | let glyph_array_value = get_u16(data, pos as usize).unwrap(); 309 | if glyph_array_value == 0 { 310 | return None; 311 | } 312 | let glyph_index = (glyph_array_value as i16).wrapping_add(id_delta); 313 | Some(glyph_index as u16) 314 | } 315 | } 316 | 317 | pub fn lookup_glyph_id(&self, code_point: u16) -> Option { 318 | let end_counts_position = Self::get_end_counts_position(); 319 | let seg_count = self.get_seg_count(); 320 | let mut start = 0; 321 | let mut end = seg_count; 322 | while end > start { 323 | // Note: this is overflow-safe because seg_count < 0x8000 324 | let index = (start + end) / 2; 325 | let search = end_counts_position + index * 2; 326 | let end_value = get_u16(self.0, search as usize).unwrap(); 327 | if end_value >= code_point { 328 | let start_pos = Self::get_start_counts_position(seg_count) + 2 * index; 329 | let start_value = get_u16(self.0, start_pos as usize).unwrap(); 330 | if start_value > code_point { 331 | end = index; 332 | } else { 333 | return self.extract_glyph_id(code_point, start_value, seg_count, index); 334 | } 335 | } else { 336 | start = index + 1; 337 | } 338 | } 339 | None 340 | } 341 | } 342 | 343 | impl<'a> Debug for EncodingFormat4<'a> { 344 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 345 | f.debug_struct("EncodingFormat4") 346 | .field("format", &self.get_format()) 347 | .field("length", &self.get_length()) 348 | .field("language", &self.get_language()) 349 | .field("segCountX2", &self.get_seg_count_x_2()) 350 | .field("searchRange", &self.get_search_range()) 351 | .field("entrySelector", &self.get_entry_selector()) 352 | .field("rangeShift", &self.get_range_shift()) 353 | .field("endCounts", &self.get_end_counts()) 354 | .field("startCounts", &self.get_start_counts()) 355 | .field("idDeltas", &self.get_id_deltas()) 356 | .field("idRangeOffsets", &self.get_id_range_offsets()) 357 | .finish() 358 | } 359 | } 360 | 361 | struct Cmap<'a>(&'a [u8]); 362 | 363 | impl<'a> Cmap<'a> { 364 | fn get_version(&self) -> u16 { 365 | get_u16(self.0, 0).unwrap() 366 | } 367 | 368 | fn get_num_tables(&self) -> u16 { 369 | get_u16(self.0, 2).unwrap() 370 | } 371 | 372 | fn get_encoding_record(&self, index: u16) -> Option> { 373 | if index >= self.get_num_tables() { 374 | return None; 375 | } 376 | let enc_offset = (index * 8 + 4) as usize; 377 | let encoding_data = &self.0[enc_offset as usize..(enc_offset + 12) as usize]; 378 | Some(EncodingRecord(encoding_data)) 379 | } 380 | 381 | fn get_encoding_records(&self) -> Vec { 382 | let mut encodings = vec![]; 383 | for i in 0..self.get_num_tables() { 384 | encodings.push(self.get_encoding_record(i).unwrap()); 385 | } 386 | encodings 387 | } 388 | 389 | fn get_encoding(&self, index: u16) -> Option> { 390 | if index >= self.get_num_tables() { 391 | return None; 392 | } 393 | let record = self.get_encoding_record(index).unwrap(); 394 | let subtable_len = get_u16(self.0, (record.get_offset() + 2) as usize).unwrap() as u32; 395 | let encoding_data = 396 | &self.0[record.get_offset() as usize..(record.get_offset() + subtable_len) as usize]; 397 | Some(Encoding(encoding_data)) 398 | } 399 | 400 | fn get_encoding_format_4_at(&self, index: u16) -> Option> { 401 | let encoding = self.get_encoding(index); 402 | if encoding.is_none() || encoding.unwrap().get_format() != 4 { 403 | return None; 404 | } 405 | let record = self.get_encoding_record(index).unwrap(); 406 | let subtable_len = get_u16(self.0, (record.get_offset() + 2) as usize).unwrap() as u32; 407 | let encoding_data = 408 | &self.0[record.get_offset() as usize..(record.get_offset() + subtable_len) as usize]; 409 | Some(EncodingFormat4(encoding_data)) 410 | } 411 | 412 | fn get_encodings(&self) -> Vec { 413 | let mut encodings = vec![]; 414 | for i in 0..self.get_num_tables() { 415 | encodings.push(self.get_encoding(i).unwrap()); 416 | } 417 | encodings 418 | } 419 | 420 | pub fn find_format_4_encoding(&self) -> Option { 421 | for index in 0..self.get_num_tables() { 422 | let encoding = self.get_encoding(index); 423 | if let Some(encoding) = encoding { 424 | if encoding.get_format() == 4 { 425 | return Some(index); 426 | } 427 | } 428 | } 429 | None 430 | } 431 | } 432 | 433 | impl<'a> Debug for Cmap<'a> { 434 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 435 | f.debug_struct("Cmap") 436 | .field("version", &self.get_version()) 437 | .field("numTables", &self.get_num_tables()) 438 | .field("encodingRecords", &self.get_encoding_records()) 439 | .field("encodings", &self.get_encodings()) 440 | .finish() 441 | } 442 | } 443 | 444 | fn get_bbox_raw(data: &[u8]) -> (i16, i16, i16, i16) { 445 | ( 446 | get_i16(data, 2).unwrap(), 447 | get_i16(data, 4).unwrap(), 448 | get_i16(data, 6).unwrap(), 449 | get_i16(data, 8).unwrap(), 450 | ) 451 | } 452 | 453 | enum Glyph<'a> { 454 | Empty, 455 | Simple(SimpleGlyph<'a>), 456 | Compound(CompoundGlyph<'a>), 457 | } 458 | 459 | struct SimpleGlyph<'a> { 460 | data: &'a [u8], 461 | } 462 | 463 | impl<'a> SimpleGlyph<'a> { 464 | fn number_of_contours(&self) -> i16 { 465 | get_i16(self.data, 0).unwrap() 466 | } 467 | 468 | fn bbox(&self) -> (i16, i16, i16, i16) { 469 | get_bbox_raw(self.data) 470 | } 471 | 472 | fn points(&self) -> GlyphPoints<'a> { 473 | let data = self.data; 474 | let n_contours = self.number_of_contours(); 475 | let insn_len_off = 10 + 2 * n_contours as usize; 476 | let n_points = get_u16(data, insn_len_off - 2).unwrap() as usize + 1; 477 | let insn_len = get_u16(data, insn_len_off).unwrap(); // insn_len 478 | let flags_ix = insn_len_off + insn_len as usize + 2; 479 | let mut flags_size = 0; 480 | let mut x_size = 0; 481 | let mut points_remaining = n_points; 482 | while points_remaining > 0 { 483 | let flag = data[flags_ix as usize + flags_size]; 484 | let repeat_count = if (flag & 8) == 0 { 485 | 1 486 | } else { 487 | flags_size += 1; 488 | data[flags_ix as usize + flags_size] as usize + 1 489 | }; 490 | flags_size += 1; 491 | match flag & 0x12 { 492 | 0x02 | 0x12 => x_size += repeat_count, 493 | 0x00 => x_size += 2 * repeat_count, 494 | _ => (), 495 | } 496 | points_remaining -= repeat_count; 497 | } 498 | let x_ix = flags_ix + flags_size; 499 | let y_ix = x_ix + x_size; 500 | GlyphPoints { 501 | data: data, 502 | x: 0, 503 | y: 0, 504 | points_remaining: n_points, 505 | last_flag: 0, 506 | flag_repeats_remaining: 0, 507 | flags_ix: flags_ix, 508 | x_ix: x_ix, 509 | y_ix: y_ix, 510 | } 511 | } 512 | 513 | fn contour_sizes(&self) -> ContourSizes { 514 | let n_contours = self.number_of_contours(); 515 | ContourSizes { 516 | data: self.data, 517 | contours_remaining: n_contours as usize, 518 | ix: 10, 519 | offset: -1, 520 | } 521 | } 522 | } 523 | 524 | struct GlyphPoints<'a> { 525 | data: &'a [u8], 526 | x: i16, 527 | y: i16, 528 | points_remaining: usize, 529 | last_flag: u8, 530 | flag_repeats_remaining: u8, 531 | flags_ix: usize, 532 | x_ix: usize, 533 | y_ix: usize, 534 | } 535 | 536 | impl<'a> Iterator for GlyphPoints<'a> { 537 | type Item = (bool, i16, i16); 538 | fn next(&mut self) -> Option<(bool, i16, i16)> { 539 | if self.points_remaining == 0 { 540 | None 541 | } else { 542 | if self.flag_repeats_remaining == 0 { 543 | self.last_flag = self.data[self.flags_ix]; 544 | if (self.last_flag & 8) == 0 { 545 | self.flags_ix += 1; 546 | } else { 547 | self.flag_repeats_remaining = self.data[self.flags_ix + 1]; 548 | self.flags_ix += 2; 549 | } 550 | } else { 551 | self.flag_repeats_remaining -= 1; 552 | } 553 | let flag = self.last_flag; 554 | //println!("flag={:02x}, flags_ix={}, x_ix={}, ({}) y_ix={} ({})", 555 | // flag, self.flags_ix, self.x_ix, self.data.get(self.x_ix), self.y_ix, 556 | // self.data.get(self.y_ix)); 557 | match flag & 0x12 { 558 | 0x02 => { 559 | self.x -= self.data[self.x_ix] as i16; 560 | self.x_ix += 1; 561 | } 562 | 0x00 => { 563 | self.x += get_i16(self.data, self.x_ix).unwrap(); 564 | self.x_ix += 2; 565 | } 566 | 0x12 => { 567 | self.x += self.data[self.x_ix] as i16; 568 | self.x_ix += 1; 569 | } 570 | _ => (), 571 | } 572 | match flag & 0x24 { 573 | 0x04 => { 574 | self.y -= self.data[self.y_ix] as i16; 575 | self.y_ix += 1; 576 | } 577 | 0x00 => { 578 | self.y += get_i16(self.data, self.y_ix).unwrap(); 579 | self.y_ix += 2; 580 | } 581 | 0x24 => { 582 | self.y += self.data[self.y_ix] as i16; 583 | self.y_ix += 1; 584 | } 585 | _ => (), 586 | } 587 | self.points_remaining -= 1; 588 | Some(((self.last_flag & 1) != 0, self.x, self.y)) 589 | } 590 | } 591 | 592 | fn size_hint(&self) -> (usize, Option) { 593 | ( 594 | self.points_remaining as usize, 595 | Some(self.points_remaining as usize), 596 | ) 597 | } 598 | } 599 | 600 | struct ContourSizes<'a> { 601 | data: &'a [u8], 602 | contours_remaining: usize, 603 | ix: usize, 604 | offset: i32, 605 | } 606 | 607 | impl<'a> Iterator for ContourSizes<'a> { 608 | type Item = usize; 609 | fn next(&mut self) -> Option<(usize)> { 610 | if self.contours_remaining == 0 { 611 | None 612 | } else { 613 | let ret = get_u16(self.data, self.ix).unwrap() as i32 - self.offset; 614 | self.offset += ret; 615 | self.ix += 2; 616 | self.contours_remaining -= 1; 617 | Some(ret as usize) 618 | } 619 | } 620 | 621 | fn size_hint(&self) -> (usize, Option) { 622 | (self.contours_remaining, Some(self.contours_remaining)) 623 | } 624 | } 625 | 626 | struct CompoundGlyph<'a> { 627 | data: &'a [u8], 628 | } 629 | 630 | struct Components<'a> { 631 | data: &'a [u8], 632 | more: bool, 633 | ix: usize, 634 | } 635 | 636 | const ARG_1_AND_2_ARE_WORDS: u16 = 1; 637 | const WE_HAVE_A_SCALE: u16 = 1 << 3; 638 | const MORE_COMPONENTS: u16 = 1 << 5; 639 | const WE_HAVE_AN_X_AND_Y_SCALE: u16 = 1 << 6; 640 | const WE_HAVE_A_TWO_BY_TWO: u16 = 1 << 7; 641 | 642 | impl<'a> Iterator for Components<'a> { 643 | type Item = (u16, Affine); 644 | fn next(&mut self) -> Option<(u16, Affine)> { 645 | if !self.more { 646 | return None; 647 | } 648 | let flags = get_u16(self.data, self.ix).unwrap(); 649 | self.ix += 2; 650 | let glyph_index = get_u16(self.data, self.ix).unwrap(); 651 | self.ix += 2; 652 | let arg1; 653 | let arg2; 654 | if (flags & ARG_1_AND_2_ARE_WORDS) != 0 { 655 | arg1 = get_i16(self.data, self.ix).unwrap(); 656 | self.ix += 2; 657 | arg2 = get_i16(self.data, self.ix).unwrap(); 658 | self.ix += 2; 659 | } else { 660 | arg1 = self.data[self.ix] as i16; 661 | self.ix += 1; 662 | arg2 = self.data[self.ix] as i16; 663 | self.ix += 1; 664 | } 665 | let mut a = 1.0; 666 | let mut b = 0.0; 667 | let mut c = 0.0; 668 | let mut d = 1.0; 669 | if (flags & WE_HAVE_A_TWO_BY_TWO) != 0 { 670 | a = get_f2_14(self.data, self.ix).unwrap(); 671 | self.ix += 2; 672 | b = get_f2_14(self.data, self.ix).unwrap(); 673 | self.ix += 2; 674 | c = get_f2_14(self.data, self.ix).unwrap(); 675 | self.ix += 2; 676 | d = get_f2_14(self.data, self.ix).unwrap(); 677 | self.ix += 2; 678 | } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) != 0 { 679 | a = get_f2_14(self.data, self.ix).unwrap(); 680 | self.ix += 2; 681 | d = get_f2_14(self.data, self.ix).unwrap(); 682 | self.ix += 2; 683 | } else if (flags & WE_HAVE_A_SCALE) != 0 { 684 | a = get_f2_14(self.data, self.ix).unwrap(); 685 | self.ix += 2; 686 | d = a; 687 | } 688 | // TODO: handle non-ARGS_ARE_XY_VALUES case 689 | let x = arg1 as f32; 690 | let y = arg2 as f32; 691 | let z = Affine::new(a, b, c, d, x, y); 692 | self.more = (flags & MORE_COMPONENTS) != 0; 693 | Some((glyph_index, z)) 694 | } 695 | } 696 | 697 | impl<'a> CompoundGlyph<'a> { 698 | fn bbox(&self) -> (i16, i16, i16, i16) { 699 | get_bbox_raw(self.data) 700 | } 701 | 702 | fn components(&self) -> Components { 703 | Components { 704 | data: self.data, 705 | ix: 10, 706 | more: true, 707 | } 708 | } 709 | } 710 | 711 | pub struct Font<'a> { 712 | _version: u32, 713 | _tables: HashMap, 714 | head: Head<'a>, 715 | maxp: Maxp<'a>, 716 | cmap: Option>, 717 | loca: Option>, 718 | glyf: Option<&'a [u8]>, 719 | encoding_index: Option, 720 | hhea: Option>, 721 | hmtx: Option>, 722 | } 723 | 724 | struct Metrics { 725 | l: i32, 726 | t: i32, 727 | r: i32, 728 | b: i32, 729 | } 730 | 731 | impl Metrics { 732 | fn width(&self) -> usize { 733 | (self.r - self.l) as usize 734 | } 735 | 736 | fn height(&self) -> usize { 737 | (self.b - self.t) as usize 738 | } 739 | } 740 | 741 | pub struct VMetrics { 742 | pub ascent: f32, 743 | pub descent: f32, 744 | pub line_gap: f32, 745 | } 746 | 747 | pub struct HMetrics { 748 | pub advance_width: f32, 749 | pub left_side_bearing: f32, 750 | } 751 | 752 | impl<'a> Font<'a> { 753 | fn scale(&self, size: u32) -> f32 { 754 | let ppem = self.head.units_per_em(); 755 | (size as f32) / (ppem as f32) 756 | } 757 | 758 | fn metrics_and_affine( 759 | &self, xmin: i16, ymin: i16, xmax: i16, ymax: i16, size: u32, 760 | ) -> (Metrics, Affine) { 761 | let scale = self.scale(size); 762 | let l = (xmin as f32 * scale).floor() as i32; 763 | let t = (ymax as f32 * -scale).floor() as i32; 764 | let r = (xmax as f32 * scale).ceil() as i32; 765 | let b = (ymin as f32 * -scale).ceil() as i32; 766 | let metrics = Metrics { 767 | l: l, 768 | t: t, 769 | r: r, 770 | b: b, 771 | }; 772 | let z = Affine::new(scale, 0.0, 0.0, -scale, -l as f32, -t as f32); 773 | (metrics, z) 774 | } 775 | 776 | fn render_glyph_inner(&self, raster: &mut Raster, z: &Affine, glyph: &Glyph) { 777 | match *glyph { 778 | Glyph::Simple(ref s) => { 779 | let mut p = s.points(); 780 | for n in s.contour_sizes() { 781 | //println!("n = {}", n); 782 | //let v = path_from_pts(p.by_ref().take(n)).collect::>(); 783 | //println!("size = {}", v.len()); 784 | draw_path(raster, z, &mut path_from_pts(p.by_ref().take(n))); 785 | } 786 | } 787 | Glyph::Compound(ref c) => { 788 | for (glyph_index, affine) in c.components() { 789 | //println!("component {} {:?}", glyph_index, affine); 790 | let concat = Affine::concat(z, &affine); 791 | if let Some(component_glyph) = self.get_glyph(glyph_index) { 792 | self.render_glyph_inner(raster, &concat, &component_glyph); 793 | } 794 | } 795 | } 796 | _ => { 797 | println!("unhandled glyph case"); 798 | } 799 | } 800 | } 801 | 802 | pub fn render_glyph(&self, glyph_id: u16, size: u32) -> Option { 803 | let glyph = self.get_glyph(glyph_id); 804 | match glyph { 805 | Some(Glyph::Simple(ref s)) => { 806 | let (xmin, ymin, xmax, ymax) = s.bbox(); 807 | let (metrics, z) = self.metrics_and_affine(xmin, ymin, xmax, ymax, size); 808 | let mut raster = Raster::new(metrics.width(), metrics.height()); 809 | //dump_glyph(SimpleGlyph(s)); 810 | self.render_glyph_inner(&mut raster, &z, glyph.as_ref().unwrap()); 811 | //None 812 | Some(GlyphBitmap { 813 | width: metrics.width(), 814 | height: metrics.height(), 815 | left: metrics.l, 816 | top: metrics.t, 817 | data: raster.get_bitmap(), 818 | }) 819 | } 820 | Some(Glyph::Compound(ref c)) => { 821 | let (xmin, ymin, xmax, ymax) = c.bbox(); 822 | let (metrics, z) = self.metrics_and_affine(xmin, ymin, xmax, ymax, size); 823 | let mut raster = Raster::new(metrics.width(), metrics.height()); 824 | self.render_glyph_inner(&mut raster, &z, glyph.as_ref().unwrap()); 825 | Some(GlyphBitmap { 826 | width: metrics.width(), 827 | height: metrics.height(), 828 | left: metrics.l, 829 | top: metrics.t, 830 | data: raster.get_bitmap(), 831 | }) 832 | } 833 | _ => { 834 | println!("glyph {} error", glyph_id); 835 | None 836 | } 837 | } 838 | } 839 | 840 | fn get_glyph(&self, glyph_ix: u16) -> Option { 841 | if glyph_ix >= self.maxp.num_glyphs() { 842 | return None; 843 | } 844 | let fmt = self.head.index_to_loc_format(); 845 | match self.loca { 846 | Some(ref loca) => match ( 847 | loca.get_off(glyph_ix, fmt), 848 | loca.get_off(glyph_ix + 1, fmt), 849 | self.glyf, 850 | ) { 851 | (Some(off0), Some(off1), Some(glyf)) => if off0 == off1 { 852 | Some(Glyph::Empty) 853 | } else { 854 | let glyph_data = &glyf[off0 as usize..off1 as usize]; 855 | if get_i16(glyph_data, 0) == Some(-1) { 856 | Some(Glyph::Compound(CompoundGlyph { data: glyph_data })) 857 | } else { 858 | Some(Glyph::Simple(SimpleGlyph { data: glyph_data })) 859 | } 860 | }, 861 | (_, _, _) => None, 862 | }, 863 | None => None, 864 | } 865 | } 866 | 867 | pub fn lookup_glyph_id(&self, code_point: u32) -> Option { 868 | match self.encoding_index { 869 | Some(encoding_index) => { 870 | if code_point > u16::max_value() as u32 { 871 | return None; 872 | } 873 | 874 | self.cmap 875 | .as_ref() 876 | .unwrap() 877 | .get_encoding_format_4_at(encoding_index) 878 | .unwrap() 879 | .lookup_glyph_id(code_point as u16) 880 | } 881 | None => None, 882 | } 883 | } 884 | 885 | pub fn get_v_metrics(&self, size: u32) -> Option { 886 | if let Some(ref hhea) = self.hhea { 887 | match ( 888 | hhea.ascent(), 889 | hhea.descent(), 890 | hhea.line_gap(), 891 | ) { 892 | (Some(ascent), Some(descent), Some(line_gap)) => { 893 | let scale = self.scale(size); 894 | Some(VMetrics { 895 | ascent: ascent as f32 * scale, 896 | descent: descent as f32 * scale, 897 | line_gap: line_gap as f32 * scale, 898 | }) 899 | }, 900 | (_, _, _) => None, 901 | } 902 | } else { 903 | None 904 | } 905 | } 906 | 907 | pub fn get_h_metrics(&self, glyph_id: u16, size: u32) -> Option { 908 | if let (Some(ref hhea), Some(ref hmtx)) = (&self.hhea, &self.hmtx) { 909 | if let Some(num_of_long_hor_metrics) = hhea.num_of_long_hor_metrics() { 910 | match hmtx.get_h_metrics(glyph_id, num_of_long_hor_metrics) { 911 | (Some(advance_width), Some(left_side_bearing)) => { 912 | let scale = self.scale(size); 913 | Some(HMetrics { 914 | advance_width: advance_width as f32 * scale, 915 | left_side_bearing: left_side_bearing as f32 * scale, 916 | }) 917 | }, 918 | (_, _) => None, 919 | } 920 | } else { 921 | None 922 | } 923 | } else { 924 | None 925 | } 926 | } 927 | } 928 | 929 | #[derive(Debug)] 930 | enum PathOp { 931 | MoveTo(Point), 932 | LineTo(Point), 933 | QuadTo(Point, Point), 934 | } 935 | 936 | use self::PathOp::{LineTo, MoveTo, QuadTo}; 937 | 938 | struct BezPathOps { 939 | inner: T, 940 | first_oncurve: Option, 941 | first_offcurve: Option, 942 | last_offcurve: Option, 943 | alldone: bool, 944 | closing: bool, 945 | } 946 | 947 | fn path_from_pts(inner: T) -> BezPathOps { 948 | BezPathOps { 949 | inner: inner, 950 | first_oncurve: None, 951 | first_offcurve: None, 952 | last_offcurve: None, 953 | alldone: false, 954 | closing: false, 955 | } 956 | } 957 | 958 | impl Iterator for BezPathOps 959 | where 960 | I: Iterator, 961 | { 962 | type Item = PathOp; 963 | fn next(&mut self) -> Option { 964 | loop { 965 | if self.closing { 966 | if self.alldone { 967 | return None; 968 | } else { 969 | match (self.first_offcurve, self.last_offcurve) { 970 | (None, None) => { 971 | self.alldone = true; 972 | return Some(LineTo(self.first_oncurve.unwrap())); 973 | } 974 | (None, Some(last_offcurve)) => { 975 | self.alldone = true; 976 | return Some(QuadTo(last_offcurve, self.first_oncurve.unwrap())); 977 | } 978 | (Some(first_offcurve), None) => { 979 | self.alldone = true; 980 | return self.first_oncurve 981 | .map(|oncurve| QuadTo(first_offcurve, oncurve)); 982 | } 983 | (Some(first_offcurve), Some(last_offcurve)) => { 984 | self.last_offcurve = None; 985 | return Some(QuadTo( 986 | last_offcurve, 987 | Point::lerp(0.5, &last_offcurve, &first_offcurve), 988 | )); 989 | } 990 | } 991 | } 992 | } else { 993 | match self.inner.next() { 994 | None => { 995 | self.closing = true; 996 | } 997 | Some((oncurve, x, y)) => { 998 | let p = Point::new(x, y); 999 | if self.first_oncurve.is_none() { 1000 | if oncurve { 1001 | self.first_oncurve = Some(p); 1002 | return Some(MoveTo(p)); 1003 | } else { 1004 | match self.first_offcurve { 1005 | None => self.first_offcurve = Some(p), 1006 | Some(first_offcurve) => { 1007 | let midp = Point::lerp(0.5, &first_offcurve, &p); 1008 | self.first_oncurve = Some(midp); 1009 | self.last_offcurve = Some(p); 1010 | return Some(MoveTo(midp)); 1011 | } 1012 | } 1013 | } 1014 | } else { 1015 | match (self.last_offcurve, oncurve) { 1016 | (None, false) => self.last_offcurve = Some(p), 1017 | (None, true) => return Some(LineTo(p)), 1018 | (Some(last_offcurve), false) => { 1019 | self.last_offcurve = Some(p); 1020 | return Some(QuadTo( 1021 | last_offcurve, 1022 | Point::lerp(0.5, &last_offcurve, &p), 1023 | )); 1024 | } 1025 | (Some(last_offcurve), true) => { 1026 | self.last_offcurve = None; 1027 | return Some(QuadTo(last_offcurve, p)); 1028 | } 1029 | } 1030 | } 1031 | } 1032 | } 1033 | } 1034 | } 1035 | } 1036 | } 1037 | 1038 | #[derive(Debug)] 1039 | pub enum FontError { 1040 | Invalid, 1041 | } 1042 | 1043 | pub fn parse(data: &[u8]) -> Result { 1044 | if data.len() < 12 { 1045 | return Err(FontError::Invalid); 1046 | } 1047 | let version = get_u32(data, 0).unwrap(); 1048 | let num_tables = get_u16(data, 4).unwrap() as usize; 1049 | let _search_range = get_u16(data, 6).unwrap(); 1050 | let _entry_selector = get_u16(data, 8).unwrap(); 1051 | let _range_shift = get_u16(data, 10).unwrap(); 1052 | let mut tables = HashMap::new(); 1053 | for i in 0..num_tables { 1054 | let header = &data[12 + i * 16..12 + (i + 1) * 16]; 1055 | let tag = get_u32(header, 0).unwrap(); 1056 | let _check_sum = get_u32(header, 4).unwrap(); 1057 | let offset = get_u32(header, 8).unwrap(); 1058 | let length = get_u32(header, 12).unwrap(); 1059 | let table_data = &data[offset as usize..(offset + length) as usize]; 1060 | //println!("{}: {}", Tag(tag), table_data.len()); 1061 | tables.insert(Tag(tag), table_data); 1062 | } 1063 | let head = Head(*tables.get(&Tag::from_str("head")).unwrap()); // todo: don't fail 1064 | let maxp = Maxp { 1065 | data: *tables.get(&Tag::from_str("maxp")).unwrap(), 1066 | }; 1067 | let loca = tables.get(&Tag::from_str("loca")).map(|&data| Loca(data)); 1068 | let glyf = tables.get(&Tag::from_str("glyf")).map(|&data| data); 1069 | let cmap = tables.get(&Tag::from_str("cmap")).map(|&data| Cmap(data)); 1070 | let encoding_index = cmap.as_ref().and_then(|cmap| cmap.find_format_4_encoding()); 1071 | let hhea = tables.get(&Tag::from_str("hhea")).map(|&data| Hhea(data)); 1072 | let hmtx = tables.get(&Tag::from_str("hmtx")).map(|&data| Hmtx(data)); 1073 | let f = Font { 1074 | _version: version, 1075 | _tables: tables, 1076 | head: head, 1077 | maxp: maxp, 1078 | loca: loca, 1079 | cmap: cmap, 1080 | glyf: glyf, 1081 | encoding_index: encoding_index, 1082 | hhea: hhea, 1083 | hmtx: hmtx, 1084 | }; 1085 | //println!("version = {:x}", version); 1086 | Ok(f) 1087 | } 1088 | 1089 | /* 1090 | fn dump_glyph(g: Glyph) { 1091 | match g { 1092 | Glyph::Empty => println!("empty"), 1093 | Glyph::Simple(s) => { 1094 | //println!("{} contours", s.number_of_contours()) 1095 | let mut p = s.points(); 1096 | for n in s.contour_sizes() { 1097 | for _ in 0..n { 1098 | println!("{:?}", p.next().unwrap()); 1099 | } 1100 | println!("z"); 1101 | } 1102 | let mut p = s.points(); 1103 | for n in s.contour_sizes() { 1104 | for pathop in path_from_pts(p.by_ref().take(n)) { 1105 | println!("{:?}", pathop); 1106 | } 1107 | } 1108 | }, 1109 | _ => println!("other") 1110 | } 1111 | } 1112 | */ 1113 | 1114 | /* 1115 | fn dump(data: Vec) { 1116 | println!("length is {}", data.len()); 1117 | match parse(&data) { 1118 | Ok(font) => { 1119 | println!("numGlyphs = {}", font.maxp.num_glyphs()); 1120 | for i in 0.. font.maxp.num_glyphs() { 1121 | println!("glyph {}", i); 1122 | match font.get_glyph(i) { 1123 | Some(g) => dump_glyph(g), 1124 | None => println!("glyph {} error", i) 1125 | } 1126 | } 1127 | }, 1128 | _ => () 1129 | } 1130 | } 1131 | */ 1132 | 1133 | fn draw_path>(r: &mut Raster, z: &Affine, path: &mut I) { 1134 | let mut lastp = Point::new(0i16, 0i16); 1135 | for op in path { 1136 | match op { 1137 | MoveTo(p) => lastp = p, 1138 | LineTo(p) => { 1139 | r.draw_line(&affine_pt(z, &lastp), &affine_pt(z, &p)); 1140 | lastp = p 1141 | } 1142 | QuadTo(p1, p2) => { 1143 | r.draw_quad( 1144 | &affine_pt(z, &lastp), 1145 | &affine_pt(z, &p1), 1146 | &affine_pt(z, &p2), 1147 | ); 1148 | lastp = p2; 1149 | } 1150 | } 1151 | } 1152 | } 1153 | 1154 | pub struct GlyphBitmap { 1155 | pub width: usize, 1156 | pub height: usize, 1157 | pub left: i32, 1158 | pub top: i32, 1159 | pub data: Vec, 1160 | } 1161 | 1162 | #[cfg(test)] 1163 | mod tests { 1164 | 1165 | use font::parse; 1166 | 1167 | static FONT_DATA: &'static [u8] = 1168 | include_bytes!("../fonts/notomono-hinted/NotoMono-Regular.ttf"); 1169 | 1170 | #[test] 1171 | fn test_cmap_format_4() { 1172 | let font = parse(&FONT_DATA).unwrap(); 1173 | let cmap = font.cmap.as_ref().unwrap(); 1174 | assert!(cmap.get_encoding_record(cmap.get_num_tables()).is_none()); 1175 | assert!(cmap.get_encoding(cmap.get_num_tables()).is_none()); 1176 | assert_eq!(font.lookup_glyph_id('A' as u32).unwrap(), 36); 1177 | assert_eq!(font.lookup_glyph_id(0x3c8).unwrap(), 405); 1178 | assert_eq!(font.lookup_glyph_id(0xfffd).unwrap(), 589); 1179 | assert_eq!(font.lookup_glyph_id(0x232B).is_none(), true); 1180 | assert_eq!(font.lookup_glyph_id(0x1000232B).is_none(), true); 1181 | // test for panics 1182 | for i in 0..0x1ffff { 1183 | font.lookup_glyph_id(i); 1184 | } 1185 | } 1186 | 1187 | static KOSUGI_MARU_ENCODING_4: &'static [u8] = 1188 | include_bytes!("../fonts/kosugi_maru/kosugi_maru_enc_4.bin"); 1189 | 1190 | static KANJI: &'static str = "\ 1191 | 一九七二人入八力十下三千上口土夕大女子小山川五天中六円手文日月木水火犬王正出本右四左\ 1192 | 玉生田白目石立百年休先名字早気竹糸耳虫村男町花見貝赤足車学林空金雨青草音校森刀万丸才\ 1193 | 工弓内午少元今公分切友太引心戸方止毛父牛半市北古台兄冬外広母用矢交会合同回寺地多光当\ 1194 | 毎池米羽考肉自色行西来何作体弟図声売形汽社角言谷走近里麦画東京夜直国姉妹岩店明歩知長\ 1195 | 門昼前南点室後春星海活思科秋茶計風食首夏弱原家帰時紙書記通馬高強教理細組船週野雪魚鳥\ 1196 | 黄黒場晴答絵買朝道番間雲園数新楽話遠電鳴歌算語読聞線親頭曜顔丁予化区反央平申世由氷主\ 1197 | 仕他代写号去打皮皿礼両曲向州全次安守式死列羊有血住助医君坂局役投対決究豆身返表事育使\ 1198 | 命味幸始実定岸所放昔板泳注波油受物具委和者取服苦重乗係品客県屋炭度待急指持拾昭相柱"; 1199 | 1200 | #[test] 1201 | fn test_glyph_lookup_format_4() { 1202 | use font::EncodingFormat4; 1203 | let encoding4 = EncodingFormat4(KOSUGI_MARU_ENCODING_4); 1204 | for kanji in KANJI.chars() { 1205 | assert!(encoding4.lookup_glyph_id(kanji as u16).is_some()); 1206 | } 1207 | assert!(encoding4.lookup_glyph_id('\n' as u16).is_none()); 1208 | } 1209 | } 1210 | --------------------------------------------------------------------------------