Skip to content

Commit

Permalink
fix: svg
Browse files Browse the repository at this point in the history
  • Loading branch information
rsuu committed Feb 10, 2023
1 parent d8978b7 commit 412c1b3
Show file tree
Hide file tree
Showing 14 changed files with 323 additions and 420 deletions.
382 changes: 154 additions & 228 deletions Cargo.lock

Large diffs are not rendered by default.

15 changes: 8 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "rmg"
edition = "2021"
version = "0.5.0"
version = "0.5.1"
build = "build.rs"
authors = ["RSUU <[email protected]>"]
description = "Rust: Tiny And Fast Manga/Image Viewer"
Expand Down Expand Up @@ -38,11 +38,16 @@ dirs-next = "2.0.0" # config
gif = "0.12.0"
gif-dispose = "4.0.0"
image = "0.24.5"
imagesize = "0.11.0"
infer = "0.12.0" # filetype
lexopt = "0.3.0" # cli
tracing = "0.1.37" # log
walkdir = "2.3.2" # fs
log = "0.4.17"


[dependencies.env_logger]
version = "0.10.0"
features = ["color"]
default-features = false

# image
[dependencies.asefile]
Expand Down Expand Up @@ -85,10 +90,6 @@ optional = true
version = "0.8.2"
optional = true

[dependencies.tracing-subscriber]
version = "0.3.16"
features = ["env-filter"]

# svg
[dependencies.usvg]
version = "0.28.0"
Expand Down
2 changes: 1 addition & 1 deletion src/archive/dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub fn get_file(path: &Path, index: usize) -> anyhow::Result<Vec<u8>> {
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;

tracing::debug!("{}, {}", pos, index);
log::debug!("{}, {}", pos, index);

return Ok(buffer);
}
Expand Down
142 changes: 68 additions & 74 deletions src/archive/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,29 @@ use crate::{
use infer;
use std::path::{Path, PathBuf};

#[derive(Debug, Copy, Clone)]
pub enum ArchiveType {
Tar,
Zip,
Dir,
File,
}

#[derive(Debug)]
pub struct FileList {
inner: Vec<FileInfo>,
}

#[derive(Debug)]
pub struct FileInfo {
pub path: String,
pub index: usize,
// pub fmt: ImgFormat,
// pub ty: ImgType,
// pub size: Size<u32>,
// pub resize: Size<u32>,
}

pub trait ForExtract {
fn get_list(&self, path: &Path) -> anyhow::Result<FileList>;
fn get_file(&self, path: &Path, index: usize) -> anyhow::Result<Vec<u8>>;
Expand Down Expand Up @@ -61,48 +84,6 @@ impl ArchiveType {
}
}

pub fn get_img_type(path: impl AsRef<Path>) -> ImgFormat {
let ty = infer::get_from_path(path.as_ref()).unwrap();

match ty {
Some(v) => ImgFormat::from(v.extension().to_string().as_str()),
None => ImgFormat::from(path.as_ref().extension().unwrap().to_str().unwrap()),
}
}

// e.g. width = 6
// '01.jpg' -> '000001.jpg' (pad "0000")
// '000001.jpg' -> '000001.jpg' (do nothing)
// '000000001.jpg' -> '0000000001.jpg' (do nothing)
pub fn pad_name(width: usize, name: &str) -> String {
let full = Path::new(name);

let mut path = full.parent().unwrap().to_str().unwrap().to_string();
let suffix = full.extension().unwrap().to_str().unwrap();
let filename = full.file_stem().unwrap().to_str().unwrap();

path.push('/');

if filename.len() < width {
path.extend(vec!['0'; (width - filename.len())]);
}

path.push_str(format!("{filename}.{suffix}").as_ref());

tracing::debug!("path = {:?}", path);

path
}

#[inline(always)]
pub fn is_same_slice(foo: &[u8], bar: &[u8], start: usize, len: usize) -> anyhow::Result<bool> {
if foo.len() > start + len && &foo[start..start + len] == bar {
Ok(true)
} else {
Err(anyhow::anyhow!(""))
}
}

impl FileList {
pub fn to_page_list(&self, rename_pad: usize) -> Vec<Page> {
let mut res = Vec::new();
Expand All @@ -126,29 +107,6 @@ impl FileList {
}
}

#[derive(Debug, Copy, Clone)]
pub enum ArchiveType {
Tar,
Zip,
Dir,
File,
}

#[derive(Debug)]
pub struct FileList {
inner: Vec<FileInfo>,
}

#[derive(Debug)]
pub struct FileInfo {
pub path: String,
pub index: usize,
// pub fmt: ImgFormat,
// pub ty: ImgType,
// pub size: Size<u32>,
// pub resize: Size<u32>,
}

impl FileList {
pub fn new() -> Self {
Self { inner: vec![] }
Expand Down Expand Up @@ -191,13 +149,49 @@ impl FileInfo {
}
}

pub fn get_filetype<T>(path: &T) -> String
where
T: AsRef<Path> + ?Sized,
{
infer::get_from_path(path.as_ref())
.expect("file read successfully")
.expect("file type is known")
.extension()
.to_string()
// e.g. width = 6
// '01.jpg' -> '000001.jpg' (pad "0000")
// '000001.jpg' -> '000001.jpg' (do nothing)
// '000000001.jpg' -> '0000000001.jpg' (do nothing)
pub fn pad_name(width: usize, name: &str) -> String {
let full = Path::new(name);

let mut path = full.parent().unwrap().to_str().unwrap().to_string();
let suffix = full.extension().unwrap().to_str().unwrap();
let filename = full.file_stem().unwrap().to_str().unwrap();

path.push('/');

if filename.len() < width {
path.extend(vec!['0'; (width - filename.len())]);
}

path.push_str(format!("{filename}.{suffix}").as_ref());

log::debug!("path = {:?}", path);

path
}

pub fn is_same_slice(foo: &[u8], bar: &[u8], start: usize, len: usize) -> anyhow::Result<bool> {
if foo.len() > start + len && &foo[start..start + len] == bar {
Ok(true)
} else {
anyhow::bail!("")
}
}

pub fn get_img_format(file: &[u8]) -> ImgFormat {
let ty = infer::get(file);

match ty {
Some(v) => ImgFormat::from(v.extension().to_string().as_str()),
None => {
if is_same_slice(file, &[0xe0, 0xa5], 4, 2).is_ok() {
ImgFormat::Aseprite
} else {
panic!("Unknown Format")
}
}
}
}
2 changes: 1 addition & 1 deletion src/config/rsconf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use dirs_next;
use fir;
use lexopt::{self, prelude::*};
use std::{fs::File, io::Read, path::Path, path::PathBuf, process::exit};
use tracing::debug;
use log::debug;

#[derive(Debug)]
pub struct Config {
Expand Down
8 changes: 4 additions & 4 deletions src/img/heic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ mod feat {
#[inline]
pub fn load_heic(bytes: &[u8]) -> anyhow::Result<(u32, u32, Vec<Vec<u8>>)> {
if let Ok(ctx) = libheif_rs::HeifContext::read_from_bytes(bytes) {
tracing::debug!("{}", bytes.len());
log::debug!("{}", bytes.len());

let handle = ctx.primary_image_handle().unwrap();

Expand All @@ -32,9 +32,9 @@ mod feat {
let width = src_img.planes().interleaved.unwrap().width;
let height = src_img.planes().interleaved.unwrap().height;

tracing::debug!("w: {} -- h: {}", width, height);
tracing::debug!("{}", width * height * 3);
tracing::debug!(
log::debug!("w: {} -- h: {}", width, height);
log::debug!("{}", width * height * 3);
log::debug!(
"{} -- {}",
bytes.len(),
src_img.planes().interleaved.unwrap().stride,
Expand Down
8 changes: 4 additions & 4 deletions src/img/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,8 @@ pub fn resize_rgba8(
to: &Size<u32>,
filter: &fir::FilterType,
) -> anyhow::Result<()> {
tracing::debug!("{:?}", from);
tracing::debug!("{:?}", to);
log::debug!("{:?}", from);
log::debug!("{:?}", to);

let mut src_image = fir::Image::from_vec_u8(
NonZeroU32::new(from.width).unwrap(),
Expand Down Expand Up @@ -208,8 +208,8 @@ pub fn center_img(
fg_size: &Size<u32>,
offset: usize,
) {
tracing::info!("{}, {}", bg.len(), fg.len());
tracing::info!("{:?}, {:?}", bg_size, fg_size);
log::info!("{}, {}", bg.len(), fg.len());
log::info!("{:?}, {:?}", bg_size, fg_size);

let bg_w = bg_size.width as usize;
let fg_w = fg_size.width as usize;
Expand Down
7 changes: 1 addition & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,13 @@

// ==========================================
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const FPS: u64 = 1000 / 25;
pub const FPS: u32 = 1000 / 25;
pub const EXT_LIST: &[&str] = &[
"jpg", "jpeg", "png", "heic", "heif", "avif", "ase", "aseprite", "gif", "svg",
];

// ==========================================
pub mod utils {
// ==========================================
pub fn sleep(ms: u64) {
std::thread::sleep(std::time::Duration::from_millis(ms));
}

// ==========================================
impl<AnyType: ?Sized> AutoTrait for AnyType {}

Expand Down
38 changes: 20 additions & 18 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,21 @@ use rmg::{
use std::path::PathBuf;

fn main() {
fn init_log() {
use tracing_subscriber::{fmt, prelude::*, registry, EnvFilter};

// e.g. RUST_LOG="rmg::render::scroll=debug"
let env_filter = EnvFilter::builder().with_regex(true).from_env_lossy();
let log_fmt = fmt::layer().without_time().with_thread_names(true);

registry().with(log_fmt).with(env_filter).init();

tracing::info!("init_log()");
}

init_log();
// fn init_log() {
// use log_subscriber::{fmt, prelude::*, registry, EnvFilter};
//
// // e.g. RUST_LOG="rmg::render::scroll=debug"
// let env_filter = EnvFilter::builder().with_regex(true).from_env_lossy();
// let log_fmt = fmt::layer().without_time().with_thread_names(true);
//
// registry().with(log_fmt).with(env_filter).init();
//
// log::info!("init_log()");
// }
//
// init_log();

env_logger::init();

let config = {
let mut res = Config::new();
Expand All @@ -32,8 +34,8 @@ fn main() {

let meta_size = MetaSize::new(0, 0, config.base.size.width, config.base.size.height, 0, 0);

tracing::trace!("{:#?}", config);
tracing::trace!("meta_size: {:#?}", &meta_size);
log::trace!("{:#?}", config);
log::trace!("meta_size: {:#?}", &meta_size);

let path = {
let Some(tmp)=&config.cli.file_path else { print_help() };
Expand All @@ -44,11 +46,11 @@ fn main() {
let file_list = archive_type.get_list(path.as_path()).unwrap();
let mut page_list = file_list.to_page_list(config.base.rename_pad as usize);

tracing::trace!("file_list: {:#?}", file_list);
tracing::trace!("page_list: {:#?}", page_list);
log::trace!("file_list: {:#?}", file_list);
log::trace!("page_list: {:#?}", page_list);
println!("Open: {}", path.as_path().display());

if let Err(_) = display::cat_img(&config, &mut page_list, meta_size, path, archive_type) {
tracing::debug!("err");
log::debug!("err");
}
}
2 changes: 1 addition & 1 deletion src/render/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ pub fn cat_img(
}
}

tracing::info!("*** EXIT ***");
log::info!("*** EXIT ***");

Ok(())
}
Expand Down
Loading

0 comments on commit 412c1b3

Please sign in to comment.