Skip to content

Commit

Permalink
feat: use subfamily as fallback of full name (#68), fixes #67
Browse files Browse the repository at this point in the history
add logs, and log-output feature to do real output
  • Loading branch information
7sDream committed Nov 18, 2023
1 parent c5f5610 commit 6220ff9
Show file tree
Hide file tree
Showing 7 changed files with 189 additions and 22 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ jobs:
- name: Build
run: |
cargo clean
cargo build --target ${{ matrix.rust-target }} --release --all-targets --all-features -vv
cargo build --target ${{ matrix.rust-target }} --release -vv
env:
RUSTFLAGS: ${{ fromJSON('["", "-C target-feature=+crt-static"]')[matrix.libc == 'msvc'] }}
- name: Move and rename binary
Expand Down
100 changes: 100 additions & 0 deletions Cargo.lock

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

8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ crossterm = "0.27"
# Alternative: output a html file into temp dir and open it
httparse = "1"

# Logger
log = { version = "0.4", features = ["release_max_level_off"] }
env_logger = { version = "0.10", optional = true }

[features]
default = []
log-output = ["dep:env_logger"]

[profile.release]
strip = true
lto = true
Expand Down
2 changes: 1 addition & 1 deletion src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use clap::Parser;

use super::one_char::OneChar;

#[derive(clap::Parser)]
#[derive(Debug, clap::Parser)]
#[command(author, version, about, arg_required_else_help(true))]
pub struct Args {
/// Verbose mode, -v show all font styles, -vv adds font file and face index
Expand Down
75 changes: 60 additions & 15 deletions src/loader/face_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,21 @@ pub struct FaceInfo {
pub gid: u16,
}

enum FontFaceFullName {
Full(String),
SubFamily(String),
None,
}

impl FaceInfo {
pub fn parse_if_contains(face: &'static fontdb::FaceInfo, c: char) -> Result<Option<Self>> {
let path = match face.source {
Source::File(ref path) => path,
_ => unreachable!("we only load font file, so source must be File variant"),
};

let index = face.index;

let Some((gid, name)) = database()
.with_face_data(face.id, |data, index| -> Result<_> {
let rf = RawFace::parse(data, index)?;
Expand All @@ -68,13 +81,34 @@ impl FaceInfo {
.map(|(s, _)| s.as_str())
.ok_or(Error::MissingFamilyName)?;
let name = name
.map(Cow::Owned)
.unwrap_or_else(|| face.post_script_name.as_str().into());
let path = match face.source {
Source::File(ref path) => path,
_ => unreachable!("we only load font file, so source must be File variant"),
let name: Cow<'static, str> = match name {
FontFaceFullName::Full(full) => full.into(),
FontFaceFullName::SubFamily(sub) => {
log::info!(
"Font face {}:{} do not have a full name, uses family({}) + subfamily({})",
path.to_string_lossy(),
index,
family,
sub,
);

if sub.is_empty() {
Cow::Borrowed(family)
} else {
format!("{} {}", family, sub).into()
}
}
FontFaceFullName::None => {
log::info!(
"Font face {}:{} do not have a full name and subfamily, uses postscript \
name({})",
path.to_string_lossy(),
index,
face.post_script_name,
);

Cow::Borrowed(&face.post_script_name)
}
};

Ok(Some(FaceInfo {
Expand All @@ -87,22 +121,33 @@ impl FaceInfo {
}))
}

fn parse_full_name(rf: RawFace<'_>) -> Result<Option<String>> {
fn parse_full_name(rf: RawFace<'_>) -> Result<FontFaceFullName> {
let name_data = rf.table(NAME_TAG).ok_or(MISSING_NAME_TABLE)?;
let name_table = NameTable::parse(name_data).ok_or(BROKEN_NAME_TABLE)?;

let mut sub_family: Option<String> = None;

for i in 0..name_table.names.len() {
let name = name_table.names.get(i).ok_or(BROKEN_NAME_TABLE)?;
if name.name_id == name_id::FULL_NAME
&& name.is_unicode()
&& name.language() == Language::English_UnitedStates
{
if let Some(name) = name.to_string() {
return Ok(Some(name));

if name.language() == Language::English_UnitedStates && name.is_unicode() {
if name.name_id == name_id::FULL_NAME {
if let Some(name) = name.to_string() {
return Ok(FontFaceFullName::Full(name));
}
}
if name.name_id == name_id::SUBFAMILY {
if let Some(name) = name.to_string() {
sub_family.replace(name);
}
}
}
}

Ok(None)
if let Some(sub) = sub_family {
Ok(FontFaceFullName::SubFamily(sub))
} else {
Ok(FontFaceFullName::None)
}
}
}
6 changes: 2 additions & 4 deletions src/loader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,8 @@ pub fn query(c: char) -> Vec<FaceInfo> {
.filter_map(|info| {
let face = FaceInfo::parse_if_contains(info, c);

if cfg!(debug_assertions) {
if let Err(ref err) = face {
eprintln!("Parse {:?}: {}", info.source, err)
}
if let Err(ref err) = face {
log::warn!("Fail to get font face name of {:?}: {}", info.source, err)
}

face.transpose()
Expand Down
18 changes: 17 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,29 @@ use std::{
net::SocketAddr,
};

use args::Args;
use family::Family;
use preview::{browser::ServerBuilder as PreviewServerBuilder, terminal::ui::UI};

fn init(arg: &Args) {
#[cfg(feature = "log-output")]
{
env_logger::Builder::from_env(
env_logger::Env::default().default_filter_or(env!("CARGO_PKG_NAME")),
)
.format_timestamp_micros()
.init();
}

log::info!("Start with argument: {:?}", arg);

loader::init(!arg.no_system, &arg.custom_font_paths);
}

fn main() {
let argument = args::get();

loader::init(!argument.no_system, &argument.custom_font_paths);
init(&argument);

let font_set = loader::query(argument.char.0);
let families = family::group_by_family_sort_by_name(&font_set);
Expand Down

0 comments on commit 6220ff9

Please sign in to comment.