Skip to content

Commit

Permalink
chore(fmt): change rustfmt config, update code.
Browse files Browse the repository at this point in the history
  • Loading branch information
7sDream committed Nov 14, 2023
1 parent 9ec9e76 commit a51d05c
Show file tree
Hide file tree
Showing 15 changed files with 217 additions and 65 deletions.
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@

- Remove dependency of fontconfig and freetype lib
- Add `-vv` option to show font file location and face index
- ASCII mode render result now not narrow (Issue [#61](https://github.com/7sDream/fontfor/issues/61), fixed by PR [#63](https://github.com/7sDream/fontfor/pull/63))
- Now release contains ia32/x64/arm64 binary for Windows
- Now release contains x64/arm64 binary for macOS
- Now release contains x64/arm64/armhf binary Linux

## 0.3.1

- Display help message directly when `char` arg are missing (Issue #11, Pr #12)
- Display help message directly when `char` arg are missing (Issue [#11](https://github.com/7sDream/fontfor/issue/11), Pr [#12](https://github.com/7sDream/fontfor/pull/12))

## 0.3.0

- Browser preview page gets a new wonderful UI (Thanks [@Tiierr](https://github.com/Tiierr), PR #5)
- Browser preview page gets a new wonderful UI (Thanks [@Tiierr](https://github.com/Tiierr), PR [#5](https://github.com/7sDream/fontfor/pull/5))

## 0.2.2

Expand Down
1 change: 0 additions & 1 deletion rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,5 @@ group_imports = "StdExternalCrate"
reorder_modules = false
# short_array_element_width_threshold = 20
use_field_init_shorthand = true
use_small_heuristics = "Max"
use_try_shorthand = true
wrap_comments = true
11 changes: 9 additions & 2 deletions src/family.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ pub struct Family<'a> {

impl<'a> Family<'a> {
pub fn new(name: &'a str) -> Self {
Self { name, faces: vec![], default_name_width: name.len() }
Self {
name,
faces: vec![],
default_name_width: name.len(),
}
}

pub fn styles_count(&self) -> usize {
Expand All @@ -45,7 +49,10 @@ pub fn group_by_family_sort_by_name(faces: &[FaceInfo]) -> Vec<Family<'_>> {

faces.iter().for_each(|face| {
let family = &face.family;
families.entry(family).or_insert_with(|| Family::new(family)).add_face(face);
families
.entry(family)
.or_insert_with(|| Family::new(family))
.add_face(face);
});

let mut families: Vec<Family<'_>> = families.into_values().collect();
Expand Down
5 changes: 4 additions & 1 deletion src/loader/cmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ impl<'a> CMapTable<'a> {
}

pub fn glyph_index(&self, c: char) -> Option<GlyphId> {
self.subtables.iter().filter_map(|subtable| subtable.glyph_index(c as u32)).next()
self.subtables
.iter()
.filter_map(|subtable| subtable.glyph_index(c as u32))
.next()
}
}
20 changes: 16 additions & 4 deletions src/loader/face_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,29 @@ impl FaceInfo {
return Ok(None);
};
let family =
face.families.get(0).map(|(s, _)| s.as_str()).ok_or(Error::MissingFamilyName)?;
let family = face
.families
.get(0)
.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 name = name
.map(Cow::Owned)
.unwrap_or_else(|| face.post_script_name.as_str().into());
let path = match face.source {
fontdb::Source::File(ref path) => path,
_ => unreachable!("we only load font file, so source must be File variant"),
};

Ok(Some(FaceInfo { id: face.id, family, name, path, index: face.index, gid }))
Ok(Some(FaceInfo {
id: face.id,
family,
name,
path,
index: face.index,
gid,
}))
}

fn parse_full_name(rf: RawFace<'_>) -> Result<Option<String>> {
Expand Down
28 changes: 22 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ fn main() {
let families = family::group_by_family_sort_by_name(&font_set);

if families.is_empty() {
eprintln!("No font support this character {}.", argument.char.description());
eprintln!(
"No font support this character {}.",
argument.char.description()
);
return;
}

Expand All @@ -59,11 +62,16 @@ fn main() {
None
};

println!("Font(s) support the character {}:", argument.char.description());
println!(
"Font(s) support the character {}:",
argument.char.description()
);
show_font_list(families, argument.verbose);

if let Some(builder) = builder {
builder.build_for(argument.char.0).run_until(show_preview_addr_and_wait);
builder
.build_for(argument.char.0)
.run_until(show_preview_addr_and_wait);
}
}
}
Expand All @@ -72,17 +80,25 @@ fn show_preview_addr_and_wait(addr: SocketAddr) {
println!("{}", "-".repeat(40));
println!("Please visit http://{}/ in your browser for preview", addr);
print!("And press Enter after your finish...");
std::io::stdout().flush().expect("flush stdout should not fail");
std::io::stdout()
.flush()
.expect("flush stdout should not fail");

// Wait until user input any character before stop the server
let _ = std::io::stdin().read(&mut [0u8]).expect("read from stdout should not fail");
let _ = std::io::stdin()
.read(&mut [0u8])
.expect("read from stdout should not fail");
}

fn show_font_list(families: Vec<Family<'_>>, verbose: u8) {
let max_len = if verbose > 0 {
0
} else {
families.iter().map(|f| f.default_name_width).max().unwrap_or_default()
families
.iter()
.map(|f| f.default_name_width)
.max()
.unwrap_or_default()
};

families.into_iter().for_each(|family| {
Expand Down
5 changes: 4 additions & 1 deletion src/one_char.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ impl OneChar {
let scalar_value = u32::from(self.0);
let mut utf8 = vec![0; self.0.len_utf8()];
self.0.encode_utf8(utf8.as_mut_slice());
let bytes = utf8.iter().map(|byte| format!("0x{:X}", byte)).collect::<Vec<_>>();
let bytes = utf8
.iter()
.map(|byte| format!("0x{:X}", byte))
.collect::<Vec<_>>();
format!(
"\"{}\"(U+{:0scalar_value_length$X}, {}, {})",
self.0,
Expand Down
22 changes: 12 additions & 10 deletions src/preview/browser/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,18 @@ impl<'a> Builder<'a> {

fn build_html(self, c: char) -> String {
let font_previews =
self.families.into_iter().fold(String::new(), |mut acc: String, family| {
write!(
&mut acc,
include_str!("statics/preview_block_template.html"),
char = c,
family = family,
)
.expect("write to string should always success");
acc
});
self.families
.into_iter()
.fold(String::new(), |mut acc: String, family| {
write!(
&mut acc,
include_str!("statics/preview_block_template.html"),
char = c,
family = family,
)
.expect("write to string should always success");
acc
});

format!(
include_str!("statics/template.html"),
Expand Down
11 changes: 8 additions & 3 deletions src/preview/browser/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,11 @@ impl SingleThread {

fn response_200(content: &str) -> String {
let content_length_header = format!("Content-Length: {}\r\n", content.len());
let headers =
["Content-Type: text/html\r\n", "Content-Encoding: utf-8\r\n", &content_length_header];
let headers = [
"Content-Type: text/html\r\n",
"Content-Encoding: utf-8\r\n",
&content_length_header,
];

Self::response_common(200, "OK", &headers)
}
Expand Down Expand Up @@ -191,7 +194,9 @@ impl SingleThread {
}
};

let addr = server.local_addr().expect("tcp listener must have a local addr");
let addr = server
.local_addr()
.expect("tcp listener must have a local addr");
if addr_tx.send(addr).is_err() {
return Ok(());
}
Expand Down
12 changes: 10 additions & 2 deletions src/preview/terminal/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,17 @@ pub trait Render {
let gray = bm.pixel(row, col);

let l = if col > 0 { bm.pixel(row, col - 1) } else { 0 };
let r = if col < m.width - 1 { bm.pixel(row, col + 1) } else { 0 };
let r = if col < m.width - 1 {
bm.pixel(row, col + 1)
} else {
0
};
let u = if row > 0 { bm.pixel(row - 1, col) } else { 0 };
let d = if row < m.height - 1 { bm.pixel(row + 1, col) } else { 0 };
let d = if row < m.height - 1 {
bm.pixel(row + 1, col)
} else {
0
};

result[row][col] = self.render_pixel(u, l, gray, r, d)
}
Expand Down
15 changes: 12 additions & 3 deletions src/preview/terminal/render/moon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,13 @@

use super::Render;

static MOON_CHARS: [[char; 2]; 5] =
[['🌕', '🌕'], ['🌖', '🌔'], ['🌗', '🌓'], ['🌘', '🌒'], ['🌑', '🌑']];
static MOON_CHARS: [[char; 2]; 5] = [
['🌕', '🌕'],
['🌖', '🌔'],
['🌗', '🌓'],
['🌘', '🌒'],
['🌑', '🌑'],
];

pub struct MoonRender {
multiplier: f64,
Expand All @@ -42,6 +47,10 @@ impl Render for MoonRender {

let index = (f64::from(255 - gray) * self.multiplier).floor() as usize;

if left < right { MOON_CHARS[index][1] } else { MOON_CHARS[index][0] }
if left < right {
MOON_CHARS[index][1]
} else {
MOON_CHARS[index][0]
}
}
}
24 changes: 20 additions & 4 deletions src/preview/terminal/ui/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,14 @@ type BoxedRender<Pixel> = Box<dyn Render<Pixel = Pixel> + Send + Sync>;

pub static CHAR_RENDERS: Lazy<HashMap<RenderType, BoxedRender<char>>> = Lazy::new(|| {
let mut renders: HashMap<RenderType, BoxedRender<char>> = HashMap::new();
renders.insert(RenderType::AsciiLevel10, Box::new(AsciiRender::new(AsciiRenders::Level10)));
renders.insert(RenderType::AsciiLevel70, Box::new(AsciiRender::new(AsciiRenders::Level70)));
renders.insert(
RenderType::AsciiLevel10,
Box::new(AsciiRender::new(AsciiRenders::Level10)),
);
renders.insert(
RenderType::AsciiLevel70,
Box::new(AsciiRender::new(AsciiRenders::Level70)),
);
renders.insert(RenderType::Moon, Box::new(MoonRender::new()));
renders
});
Expand Down Expand Up @@ -71,7 +77,12 @@ impl GlyphCanvasShape {
pub fn new(bitmap: Grid<bool>, canvas_width: f64, canvas_height: f64) -> Self {
let h_pad = ((canvas_width - bitmap.cols() as f64) / 2.0).floor();
let v_pad = ((canvas_height - bitmap.rows() as f64) / 2.0).floor();
Self { h_pad, v_pad, canvas_height, bitmap }
Self {
h_pad,
v_pad,
canvas_height,
bitmap,
}
}

fn points(&self) -> GlyphCanvasShapePoints<'_> {
Expand All @@ -88,7 +99,12 @@ struct GlyphCanvasShapePoints<'a> {

impl<'a> GlyphCanvasShapePoints<'a> {
fn new(shape: &'a GlyphCanvasShape) -> Self {
Self { shape, start: false, x: 0, y: 0 }
Self {
shape,
start: false,
x: 0,
y: 0,
}
}

fn next_x_y(&mut self) -> bool {
Expand Down
Loading

0 comments on commit a51d05c

Please sign in to comment.