Skip to content

Commit

Permalink
Add logging support if user wants it (#30)
Browse files Browse the repository at this point in the history
* add

* Update test_font_render.py

* Update CI.yaml

* Update Cargo.toml

* add

* Update CI.yaml

* Update Cargo.toml

* Reduce more size?
  • Loading branch information
baseplate-admin authored May 9, 2024
1 parent f717721 commit b143a1c
Show file tree
Hide file tree
Showing 7 changed files with 132 additions and 19 deletions.
7 changes: 3 additions & 4 deletions .github/workflows/CI.yaml
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
# This file is autogenerated by maturin v1.5.1
# To update, run
#
# maturin generate-ci github
# maturin generate-ci github
#
name: CI

on:
push:
branches:
- main
- master
- '*'
tags:
- '*'
pull_request:
Expand Down Expand Up @@ -45,7 +44,7 @@ jobs:
uses: PyO3/maturin-action@v1
with:
target: ${{ matrix.platform.target }}
args: --release --out dist --find-interpreter
args: --release --out dist --find-interpreter
sccache: 'true'
manylinux: auto
- name: Upload wheels
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,20 @@ path = "src/rust/lib.rs"
crate-type = ["cdylib"]

[dependencies]
log = "0.4.21"
pyo3 = "0.21.2"
resvg = { version = "0.41.0", features = ["raster-images","text"] }
svgtypes = "0.15.1"


[profile.release.package."*"]
opt-level = 3
codegen-units = 1
opt-level ='z'
strip = true

[profile.release]
panic = "abort"
codegen-units = 1
lto = "fat"
opt-level = 3
opt-level ='z'
strip = true
59 changes: 58 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ package-mode = false
[tool.poetry.dependencies]
python = "^3.12"


[tool.poetry.group.dev.dependencies]
pytest = "^8.1.1"
poethepoet = "^0.26.1"

[tool.poetry.group.docs.dependencies]
sphinx = "^7.2.6"
Expand Down Expand Up @@ -38,3 +40,8 @@ Documentation = "https://resvg-py.readthedocs.io/"

[tool.maturin]
features = ["pyo3/extension-module"]

[tool.poe.tasks]
test = "pytest . -rP"
"build:release" = "maturin build --release"
"dev" = "maturin build"
23 changes: 13 additions & 10 deletions resvg_py.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,22 @@ from typing import Literal
def svg_to_bytes(
svg_string: str | None = None,
svg_path: str | None = None,
background: str | None = None,
skip_system_fonts: bool | None = False,
log_information: bool = False,
width: int | None = None,
height: int | None = None,
zoom: int | None = None,
dpi: int | None = 0,
resources_dir: str | None = None,
languages: list[str] | None = None,
font_size: int | None = None,
font_family: str | None = None,
serif_family: str | None = None,
sans_serif_family: str | None = None,
cursive_family: str | None = None,
fantasy_family: str | None = None,
monospace_family: str | None = None,
languages: list[str] | None = [],
font_size: int | None = 16,
font_family: str | None = Literal["Times New Roman"],
serif_family: str | None = Literal["Times New Roman"],
sans_serif_family: str | None = Literal["Arial"],
cursive_family: str | None = Literal["Comic Sans MS"],
fantasy_family: str | None = ["Impact"],
monospace_family: str | None = Literal["Courier New"],
font_files: list[str] | None = None,
font_dirs: list[str] | None = None,
shape_rendering: Literal[
Expand All @@ -25,8 +30,6 @@ def svg_to_bytes(
image_rendering: Literal["optimize_quality", "optimize_speed"] = Literal[
"optimize_quality"
],
background: str | None = None,
skip_system_fonts: bool | None = None,
) -> list[bytes]:
"""
:param svg_str: A string containing valid svg.
Expand Down
44 changes: 42 additions & 2 deletions src/rust/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ fn load_fonts(options: &mut Opts, fontdb: &mut resvg::usvg::fontdb::Database) {
if let Some(font_files) = &options.font_files {
for path in font_files {
if let Err(e) = fontdb.load_font_file(path) {
println!("Failed to load '{}' cause {}.", path.to_string(), e);
log::warn!("Failed to load '{}' cause {}.", path.to_string(), e);
}
}
}
Expand Down Expand Up @@ -144,6 +144,8 @@ fn svg_to_bytes(
height: Option<u32>,
zoom: Option<u32>,
dpi: Option<u32>,
// Log informations
log_information: Option<bool>,
// Resource Directory
resources_dir: Option<String>,
// Fonts
Expand All @@ -166,6 +168,12 @@ fn svg_to_bytes(
// Skip System Fonts
skip_system_fonts: Option<bool>,
) -> PyResult<Vec<u8>> {
if log_information.unwrap_or(false) {
if let Ok(()) = log::set_logger(&LOGGER) {
log::set_max_level(log::LevelFilter::Warn);
}
}

let mut _svg_string = String::new();

if let Some(svg_string) = svg_string {
Expand Down Expand Up @@ -254,7 +262,7 @@ fn svg_to_bytes(
let usvg_options = resvg::usvg::Options {
resources_dir: _resources_dir,
dpi: dpi.unwrap_or(0) as f32,
font_family: font_family.unwrap_or_else(|| "Times New Roman".to_string()),
font_family: font_family.unwrap_or("Times New Roman".to_owned()),
font_size: font_size.unwrap_or(16) as f32,
languages: languages.unwrap_or(vec![]),
shape_rendering: _shape_rendering,
Expand Down Expand Up @@ -293,3 +301,35 @@ fn resvg_py(_py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(version, m)?)?;
Ok(())
}

/// A simple stderr logger.
static LOGGER: SimpleLogger = SimpleLogger;
struct SimpleLogger;
impl log::Log for SimpleLogger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() <= log::LevelFilter::Warn
}

fn log(&self, record: &log::Record) {
if self.enabled(record.metadata()) {
let target = if !record.target().is_empty() {
record.target()
} else {
record.module_path().unwrap_or_default()
};

let line = record.line().unwrap_or(0);
let args = record.args();

match record.level() {
log::Level::Error => println!("Error (in {}:{}): {}", target, line, args),
log::Level::Warn => println!("Warning (in {}:{}): {}", target, line, args),
log::Level::Info => println!("Info (in {}:{}): {}", target, line, args),
log::Level::Debug => println!("Debug (in {}:{}): {}", target, line, args),
log::Level::Trace => println!("Trace (in {}:{}): {}", target, line, args),
}
}
}

fn flush(&self) {}
}

0 comments on commit b143a1c

Please sign in to comment.