diff --git a/Cargo.lock b/Cargo.lock index b8e6c8b6..cc40ad25 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -286,6 +286,7 @@ name = "canvas_nanovg" version = "0.1.0" dependencies = [ "arrayvec 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", + "font-kit 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", "gl 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)", "image 0.23.0 (registry+https://github.com/rust-lang/crates.io-index)", "pathfinder_canvas 0.1.0", diff --git a/canvas/src/text.rs b/canvas/src/text.rs index 2e5b4f14..236dcf06 100644 --- a/canvas/src/text.rs +++ b/canvas/src/text.rs @@ -21,8 +21,7 @@ use pathfinder_geometry::transform2d::Transform2F; use pathfinder_geometry::vector::Vector2F; use pathfinder_renderer::paint::PaintId; use pathfinder_text::{SceneExt, TextRenderMode}; -use skribo::{FontCollection, FontFamily, Layout, TextStyle}; -use std::iter; +use skribo::{FontCollection, FontFamily, FontRef, Layout, TextStyle}; use std::sync::Arc; impl CanvasRenderingContext2D { @@ -95,37 +94,14 @@ impl CanvasRenderingContext2D { // Text styles #[inline] - pub fn set_font_collection(&mut self, font_collection: Arc) { - self.current_state.font_collection = font_collection; + pub fn font(&self) -> Arc { + self.current_state.font_collection.clone() } #[inline] - pub fn set_font_families(&mut self, font_families: I) where I: Iterator { - let mut font_collection = FontCollection::new(); - for font_family in font_families { - font_collection.add_family(font_family); - } - self.current_state.font_collection = Arc::new(font_collection); - } - - /// A convenience method to set a single font family. - #[inline] - pub fn set_font_family(&mut self, font_family: FontFamily) { - self.set_font_families(iter::once(font_family)) - } - - /// A convenience method to set a single font family consisting of a single font. - #[inline] - pub fn set_font(&mut self, font: Font) { - self.set_font_family(FontFamily::new_from_font(font)) - } - - /// A convenience method to set a single font family consisting of a font - /// described by a PostScript name. - #[inline] - pub fn set_font_by_postscript_name(&mut self, postscript_name: &str) { - let font = self.font_context.font_source.select_by_postscript_name(postscript_name); - self.set_font(font.expect("Didn't find the font!").load().unwrap()); + pub fn set_font(&mut self, font_collection: FC) where FC: IntoFontCollection { + let font_collection = font_collection.into_font_collection(&self.font_context); + self.current_state.font_collection = font_collection; } #[inline] @@ -263,3 +239,99 @@ impl LayoutExt for Layout { 0.0 } } + +/// Various things that can be conveniently converted into font collections for use with +/// `CanvasRenderingContext2D::set_font()`. +pub trait IntoFontCollection { + fn into_font_collection(self, font_context: &CanvasFontContext) -> Arc; +} + +impl IntoFontCollection for Arc { + #[inline] + fn into_font_collection(self, _: &CanvasFontContext) -> Arc { + self + } +} + +impl IntoFontCollection for FontFamily { + #[inline] + fn into_font_collection(self, _: &CanvasFontContext) -> Arc { + let mut font_collection = FontCollection::new(); + font_collection.add_family(self); + Arc::new(font_collection) + } +} + +impl IntoFontCollection for Vec { + #[inline] + fn into_font_collection(self, _: &CanvasFontContext) -> Arc { + let mut font_collection = FontCollection::new(); + for family in self { + font_collection.add_family(family); + } + Arc::new(font_collection) + } +} + +impl IntoFontCollection for Handle { + #[inline] + fn into_font_collection(self, context: &CanvasFontContext) -> Arc { + self.load().expect("Failed to load the font!").into_font_collection(context) + } +} + +impl<'a> IntoFontCollection for &'a [Handle] { + #[inline] + fn into_font_collection(self, _: &CanvasFontContext) -> Arc { + let mut font_collection = FontCollection::new(); + for handle in self { + let font = handle.load().expect("Failed to load the font!"); + font_collection.add_family(FontFamily::new_from_font(font)); + } + Arc::new(font_collection) + } +} + +impl IntoFontCollection for Font { + #[inline] + fn into_font_collection(self, context: &CanvasFontContext) -> Arc { + FontFamily::new_from_font(self).into_font_collection(context) + } +} + +impl<'a> IntoFontCollection for &'a [Font] { + #[inline] + fn into_font_collection(self, context: &CanvasFontContext) -> Arc { + let mut family = FontFamily::new(); + for font in self { + family.add_font(FontRef::new((*font).clone())) + } + family.into_font_collection(context) + } +} + +impl<'a> IntoFontCollection for &'a str { + #[inline] + fn into_font_collection(self, context: &CanvasFontContext) -> Arc { + context.font_source + .select_by_postscript_name(self) + .expect("Couldn't find a font with that PostScript name!") + .into_font_collection(context) + } +} + +impl<'a, 'b> IntoFontCollection for &'a [&'b str] { + #[inline] + fn into_font_collection(self, context: &CanvasFontContext) -> Arc { + let mut font_collection = FontCollection::new(); + for postscript_name in self { + let font = context.font_source + .select_by_postscript_name(postscript_name) + .expect("Failed to find a font with that PostScript name!") + .load() + .expect("Failed to load the font!"); + font_collection.add_family(FontFamily::new_from_font(font)); + } + Arc::new(font_collection) + } +} diff --git a/examples/canvas_nanovg/Cargo.toml b/examples/canvas_nanovg/Cargo.toml index b1b02e93..e934d632 100644 --- a/examples/canvas_nanovg/Cargo.toml +++ b/examples/canvas_nanovg/Cargo.toml @@ -6,6 +6,7 @@ edition = "2018" [dependencies] arrayvec = "0.5" +font-kit = "0.5" gl = "0.14" sdl2 = "0.33" sdl2-sys = "0.33" diff --git a/examples/canvas_nanovg/src/main.rs b/examples/canvas_nanovg/src/main.rs index 344a18e4..69880e3f 100644 --- a/examples/canvas_nanovg/src/main.rs +++ b/examples/canvas_nanovg/src/main.rs @@ -9,6 +9,8 @@ // except according to those terms. use arrayvec::ArrayVec; +use font_kit::handle::Handle; +use font_kit::sources::mem::MemSource; use image; use pathfinder_canvas::{CanvasFontContext, CanvasRenderingContext2D, LineJoin, Path2D}; use pathfinder_canvas::{TextAlign, TextBaseline}; @@ -37,6 +39,7 @@ use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::video::GLProfile; use std::f32::consts::PI; +use std::sync::Arc; use std::time::Instant; // TODO(pcwalton): See if we can reduce the amount of code by using the canvas shadow feature. @@ -50,7 +53,7 @@ const WINDOW_HEIGHT: i32 = 768; static PARAGRAPH_TEXT: &'static str = "This is a longer chunk of text. I would have used lorem ipsum, but she was busy jumping over the lazy dog with the fox and all \ -the men who came to the aid of the party."; +the men who came to the aid of the party. 🎉"; fn render_demo(canvas: &mut CanvasRenderingContext2D, mouse_position: Vector2F, @@ -205,6 +208,7 @@ fn draw_paragraph(canvas: &mut CanvasRenderingContext2D, rect: RectF) { canvas.save(); + canvas.set_font(&["Roboto-Regular", "NotoEmoji"][..]); canvas.set_font_size(18.0); let mut cursor = rect.origin(); @@ -553,7 +557,7 @@ fn draw_window(canvas: &mut CanvasRenderingContext2D, title: &str, rect: RectF) canvas.set_stroke_style(ColorU::new(0, 0, 0, 32)); canvas.stroke_path(path); - // TODO(pcwalton): Bold text. + canvas.set_font("Roboto-Bold"); canvas.set_font_size(15.0); canvas.set_text_align(TextAlign::Center); canvas.set_text_baseline(TextBaseline::Middle); @@ -578,6 +582,7 @@ fn draw_search_box(canvas: &mut CanvasRenderingContext2D, text: &str, rect: Rect ColorU::new(0, 0, 0, 16), ColorU::new(0, 0, 0, 92)); + canvas.set_font("Roboto-Bold"); canvas.set_font_size(17.0); canvas.set_fill_style(ColorU::new(255, 255, 255, 64)); canvas.set_text_align(TextAlign::Left); @@ -599,6 +604,7 @@ fn draw_dropdown(canvas: &mut CanvasRenderingContext2D, text: &str, rect: RectF) canvas.stroke_path(create_rounded_rect_path(rect.contract(vec2f(0.5, 0.5)), CORNER_RADIUS - 0.5)); + canvas.set_font("Roboto-Regular"); canvas.set_font_size(17.0); canvas.set_fill_style(ColorU::new(255, 255, 255, 160)); canvas.set_text_align(TextAlign::Left); @@ -607,6 +613,7 @@ fn draw_dropdown(canvas: &mut CanvasRenderingContext2D, text: &str, rect: RectF) } fn draw_label(canvas: &mut CanvasRenderingContext2D, text: &str, rect: RectF) { + canvas.set_font("Roboto-Regular"); canvas.set_font_size(15.0); canvas.set_fill_style(ColorU::new(255, 255, 255, 128)); canvas.set_text_align(TextAlign::Left); @@ -635,6 +642,7 @@ fn draw_edit_box(canvas: &mut CanvasRenderingContext2D, rect: RectF) { fn draw_text_edit_box(canvas: &mut CanvasRenderingContext2D, text: &str, rect: RectF) { draw_edit_box(canvas, rect); + canvas.set_font("Roboto-Regular"); canvas.set_font_size(17.0); canvas.set_fill_style(ColorU::new(255, 255, 255, 64)); canvas.set_text_align(TextAlign::Left); @@ -648,6 +656,7 @@ fn draw_numeric_edit_box(canvas: &mut CanvasRenderingContext2D, rect: RectF) { draw_edit_box(canvas, rect); + canvas.set_font("Roboto-Regular"); canvas.set_font_size(15.0); let unit_width = canvas.measure_text(unit).width; @@ -667,6 +676,7 @@ fn draw_numeric_edit_box(canvas: &mut CanvasRenderingContext2D, fn draw_check_box(canvas: &mut CanvasRenderingContext2D, text: &str, rect: RectF) { const CORNER_RADIUS: f32 = 3.0; + canvas.set_font("Roboto-Regular"); canvas.set_font_size(15.0); canvas.set_fill_style(ColorU::new(255, 255, 255, 160)); canvas.set_text_align(TextAlign::Left); @@ -706,8 +716,8 @@ fn draw_button(canvas: &mut CanvasRenderingContext2D, text: &str, rect: RectF, c canvas.stroke_path(create_rounded_rect_path(rect.contract(vec2f(0.5, 0.5)), CORNER_RADIUS - 0.5)); - // TODO(pcwalton): Bold font. // TODO(pcwalton): Icon. + canvas.set_font("Roboto-Bold"); canvas.set_font_size(17.0); let text_width = canvas.measure_text(text).width; let icon_width = 0.0; @@ -1103,6 +1113,11 @@ fn main() { // Load demo data. let resources = FilesystemResourceLoader::locate(); + let font_data = vec![ + Handle::from_memory(Arc::new(resources.slurp("fonts/Roboto-Regular.ttf").unwrap()), 0), + Handle::from_memory(Arc::new(resources.slurp("fonts/Roboto-Bold.ttf").unwrap()), 0), + Handle::from_memory(Arc::new(resources.slurp("fonts/NotoEmoji-Regular.ttf").unwrap()), 0), + ]; let demo_data = DemoData::load(&resources); // Create a Pathfinder renderer. @@ -1113,11 +1128,14 @@ fn main() { background_color: Some(ColorF::new(0.3, 0.3, 0.32, 1.0)), }); - // Initialize state. + // Initialize font state. + let font_source = Arc::new(MemSource::from_fonts(font_data.into_iter()).unwrap()); + let font_context = CanvasFontContext::new(font_source.clone()); + + // Initialize general state. let mut event_pump = sdl_context.event_pump().unwrap(); let mut mouse_position = Vector2F::zero(); let start_time = Instant::now(); - let font_context = CanvasFontContext::from_system_source(); // Enter the main loop. loop { diff --git a/examples/canvas_text/src/main.rs b/examples/canvas_text/src/main.rs index 7b8230a1..428d7814 100644 --- a/examples/canvas_text/src/main.rs +++ b/examples/canvas_text/src/main.rs @@ -11,7 +11,7 @@ use font_kit::handle::Handle; use pathfinder_canvas::{CanvasFontContext, CanvasRenderingContext2D, TextAlign}; use pathfinder_color::ColorF; -use pathfinder_geometry::vector::{Vector2F, Vector2I, vec2f, vec2i}; +use pathfinder_geometry::vector::{vec2f, vec2i}; use pathfinder_gl::{GLDevice, GLVersion}; use pathfinder_renderer::concurrent::rayon::RayonExecutor; use pathfinder_renderer::concurrent::scene_proxy::SceneProxy; @@ -64,7 +64,7 @@ fn main() { let mut canvas = CanvasRenderingContext2D::new(font_context, window_size.to_f32()); // Draw the text. - canvas.set_font_by_postscript_name("Overpass-Regular"); + canvas.set_font("Overpass-Regular"); canvas.set_font_size(32.0); canvas.fill_text("Hello Pathfinder!", vec2f(32.0, 48.0)); canvas.set_text_align(TextAlign::Right); diff --git a/resources/fonts/LICENSE-APACHE b/resources/fonts/LICENSE-APACHE new file mode 100644 index 00000000..75b52484 --- /dev/null +++ b/resources/fonts/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/resources/fonts/NotoEmoji-Regular.ttf b/resources/fonts/NotoEmoji-Regular.ttf new file mode 100644 index 00000000..19b7badf Binary files /dev/null and b/resources/fonts/NotoEmoji-Regular.ttf differ diff --git a/resources/fonts/Overpass-Regular.otf b/resources/fonts/Overpass-Regular.otf old mode 100755 new mode 100644 diff --git a/resources/fonts/Roboto-Bold.ttf b/resources/fonts/Roboto-Bold.ttf new file mode 100644 index 00000000..d998cf5b Binary files /dev/null and b/resources/fonts/Roboto-Bold.ttf differ diff --git a/resources/fonts/Roboto-Regular.ttf b/resources/fonts/Roboto-Regular.ttf new file mode 100644 index 00000000..2b6392ff Binary files /dev/null and b/resources/fonts/Roboto-Regular.ttf differ