Skip to content

Commit

Permalink
more refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
shevernitskiy committed Nov 11, 2023
1 parent b2ebb2c commit 242d1f8
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 171 deletions.
112 changes: 41 additions & 71 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,11 @@
use anyhow::{anyhow, Context, Result};
use std::path::Path;

use crate::{encoding::Encoding, utils};

#[cfg(target_os = "windows")]
const EXE_FILE: &'static str = "./Dwarf Fortress.exe";

#[cfg(target_os = "linux")]
const EXE_FILE: &'static str = "./dwarfort";

const CONFIG_FILE: &'static str = "./dfint_data/dfint_config.toml";
const OFFSETS_DIR: &'static str = "./dfint_data/offsets/";
use crate::{
constants::{PATH_CONFIG, PATH_EXE, PATH_OFFSETS},
encoding::Encoding,
utils,
};

#[static_init::dynamic]
pub static CONFIG: Config = Config::new();
Expand Down Expand Up @@ -41,12 +36,8 @@ pub struct ConfigMetadata {
pub struct Settings {
pub log_level: usize,
pub log_file: String,
pub crash_report: bool,
pub crash_report_dir: String,
pub enable_search: bool,
pub enable_translation: bool,
pub enable_patches: bool,
pub dictionary: String,
pub watchdog: bool,
}

Expand Down Expand Up @@ -98,84 +89,63 @@ pub struct SymbolsValues {

impl Config {
pub fn new() -> Self {
let checksum = Self::checksum(Path::new(EXE_FILE)).unwrap();
let main_config = Self::parse_toml::<MainConfig>(Path::new(CONFIG_FILE)).unwrap();
let checksum = Self::checksum(PATH_EXE).unwrap_or(0);
let main_config = Self::parse_toml::<MainConfig>(PATH_CONFIG).unwrap();
let encoding = Encoding::new();
let hook_version = match option_env!("HOOK_VERSION") {
Some(version) => String::from(version),
None => String::from("not-defined"),
};

match Self::walk_offsets(Path::new(OFFSETS_DIR), checksum) {
Ok(Some(o)) => Self {
metadata: main_config.metadata,
settings: main_config.settings,
offset_metadata: o.metadata,
offset: o.offsets,
symbol: o.symbols,
hook_version,
encoding,
},
_ => Self {
metadata: main_config.metadata,
settings: main_config.settings,
offset_metadata: OffsetsMetadata {
name: String::from("not found"),
version: String::from("not found"),
checksum,
},
offset: None,
symbol: None,
hook_version,
encoding,
},
let (offset_metadata, offset, symbol) = match Self::parse_toml::<Offsets>(PATH_OFFSETS) {
Ok(o) if o.metadata.checksum == checksum => (o.metadata, o.offsets, o.symbols),
_ => {
utils::message_box(
"dfint hook error",
format!("This DF version is not supported.\nDF checksum: 0x{:x}", checksum).as_str(),
utils::MessageIconType::Error,
);
(
OffsetsMetadata {
name: String::from("not found"),
version: String::from("not found"),
checksum,
},
None,
None,
)
}
};

Self {
metadata: main_config.metadata,
settings: main_config.settings,
offset_metadata,
offset,
symbol,
hook_version,
encoding,
}
}

#[cfg(target_os = "windows")]
fn checksum(path: &Path) -> Result<u32> {
fn checksum(path: &str) -> Result<u32> {
use exe::{VecPE, PE};
let pefile = VecPE::from_disk_file(path)?;
let pefile = VecPE::from_disk_file(Path::new(path))?;
Ok(pefile.get_nt_headers_64()?.file_header.time_date_stamp)
}

#[cfg(target_os = "linux")]
fn checksum(path: &Path) -> Result<u32> {
let mut crc = checksum::crc::Crc::new(path.to_str().context("unable to read path")?);
fn checksum(path: &str) -> Result<u32> {
let mut crc = checksum::crc::Crc::new(path.context("unable to read path")?);
match crc.checksum() {
Ok(checksum) => Ok(checksum.crc32),
Err(e) => Err(anyhow!("Checksum error {:?}", e).into()),
}
}

fn walk_offsets(path: &Path, target_checksum: u32) -> Result<Option<Offsets>> {
for entry in std::fs::read_dir(path)? {
let entry = entry?;
let pentry = entry.path();
if !pentry.is_file() {
continue;
}
let offsets = Self::parse_toml::<Offsets>(&pentry)?;
if offsets.metadata.checksum == target_checksum {
return Ok(Some(offsets));
}
}

utils::message_box(
format!(
"unable to find offsets file for current version of DF\nchecksum: 0x{:x}",
target_checksum
)
.as_str(),
"dfint hook error",
utils::MessageIconType::Error,
);

Ok(None)
}

fn parse_toml<T: for<'de> serde::Deserialize<'de>>(path: &Path) -> Result<T> {
let content = std::fs::read_to_string(path)?;
fn parse_toml<T: for<'de> serde::Deserialize<'de>>(path: &str) -> Result<T> {
let content = std::fs::read_to_string(Path::new(path))?;
let data: T = toml::from_str(content.as_str())?;
Ok(data)
}
Expand Down
13 changes: 13 additions & 0 deletions src/constants.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#[cfg(target_os = "windows")]
pub const PATH_SDL2: &'static str = "SDL2.dll";
#[cfg(target_os = "linux")]
pub const PATH_SDL2: &'static str = "libSDL2-2.0.so.0";
#[cfg(target_os = "windows")]
pub const PATH_EXE: &'static str = "./Dwarf Fortress.exe";
#[cfg(target_os = "linux")]
pub const PATH_EXE: &'static str = "./dwarfort";

pub const PATH_ENCODING: &'static str = "./dfint-data/encoding.toml";
pub const PATH_CONFIG: &'static str = "./dfint-data/config.toml";
pub const PATH_OFFSETS: &'static str = "./dfint-data/offsets.toml";
pub const PATH_DICTIONARY: &'static str = "./dfint-data/dictionary.csv";
10 changes: 5 additions & 5 deletions src/dictionary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ use anyhow::Result;
use std::collections::HashMap;
use std::io::prelude::*;

use crate::config::CONFIG;
use crate::constants::PATH_DICTIONARY;
use crate::utils;

#[static_init::dynamic]
pub static DICTIONARY: Dictionary = Dictionary::new(&CONFIG.settings.dictionary);
pub static DICTIONARY: Dictionary = Dictionary::new(PATH_DICTIONARY);

#[allow(dead_code)]
pub struct Dictionary {
Expand All @@ -15,15 +15,15 @@ pub struct Dictionary {
}

impl Dictionary {
pub fn new(path: &'static String) -> Self {
pub fn new(path: &'static str) -> Self {
Self {
map: match Dictionary::load(path) {
Ok(value) => value,
Err(_) => {
log::error!("unable to load dictionary {}", path);
log::error!("unable to load dictionary {path}");
utils::message_box(
"dfint hook error",
format!("Unable to load dictionary {}", path).as_str(),
format!("Unable to load dictionary {path}").as_str(),
utils::MessageIconType::Warning,
);
HashMap::<Vec<u8>, Vec<u8>>::new()
Expand Down
4 changes: 2 additions & 2 deletions src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use anyhow::{anyhow, Result};
use std::{collections::HashMap, path::Path};
use toml::{map::Map, Table, Value};

use crate::constants::PATH_ENCODING;

pub struct Encoding {
pub capitalize: Vec<u8>,
pub lowercast: Vec<u8>,
Expand All @@ -12,8 +14,6 @@ pub struct Encoding {
pub parsed: bool,
}

const PATH_ENCODING: &'static str = "./dfint_data/encoding.toml";

impl Encoding {
pub fn new() -> Self {
match Self::parse_encodings(Path::new(PATH_ENCODING)) {
Expand Down
8 changes: 3 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ extern crate serde_derive;
extern crate toml;

mod config;
mod constants;
mod cxxstring;
mod dictionary;
mod encoding;
Expand All @@ -15,6 +16,7 @@ mod watchdog;
use log::{debug, error, info};

use crate::config::CONFIG;
use crate::constants::PATH_DICTIONARY;
use crate::dictionary::DICTIONARY;

#[static_init::constructor]
Expand All @@ -34,11 +36,7 @@ extern "C" fn attach() {
info!("pe checksum: 0x{:x}", CONFIG.offset_metadata.checksum);
info!("offsets version: {}", CONFIG.offset_metadata.version);
info!("hook version: {}", CONFIG.hook_version);
info!(
"dictionary \"{}\", items {}",
CONFIG.settings.dictionary,
DICTIONARY.size()
);
info!("dictionary \"{}\", items {}", PATH_DICTIONARY, DICTIONARY.size());
if CONFIG.offset_metadata.name != "not found" {
match unsafe { hooks::attach_all() } {
Ok(_) => debug!("hooks attached"),
Expand Down
91 changes: 3 additions & 88 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
use std::collections::HashMap;

use dlopen2::raw::Library;

#[cfg(target_os = "windows")]
const SDL2: &'static str = "SDL2.dll";
#[cfg(target_os = "linux")]
const SDL2: &'static str = "libSDL2-2.0.so.0";
use crate::constants::PATH_SDL2;

#[cfg(target_os = "windows")]
#[static_init::dynamic]
Expand All @@ -17,10 +12,10 @@ pub static MODULE: usize = 0;

#[static_init::dynamic]
static SDL_MESSAGE_BOX: fn(u32, *const i8, *const i8, *const u8) -> i32 =
unsafe { symbol_handle::<fn(u32, *const i8, *const i8, *const u8) -> i32>(SDL2, "SDL_ShowSimpleMessageBox") };
unsafe { symbol_handle::<fn(u32, *const i8, *const i8, *const u8) -> i32>(PATH_SDL2, "SDL_ShowSimpleMessageBox") };

#[static_init::dynamic]
static SDL_ERROR: fn() -> *const i8 = unsafe { symbol_handle::<fn() -> *const i8>(SDL2, "SDL_GetError") };
static SDL_ERROR: fn() -> *const i8 = unsafe { symbol_handle::<fn() -> *const i8>(PATH_SDL2, "SDL_GetError") };

pub unsafe fn symbol_handle<T>(module: &str, symbol: &str) -> T {
if module == "self" {
Expand Down Expand Up @@ -68,86 +63,6 @@ pub unsafe fn cstr<T>(src: *const T, size: usize) -> Result<&'static str, std::s
std::ffi::CStr::from_bytes_with_nul_unchecked(std::slice::from_raw_parts(src as *const u8, size)).to_str()
}

#[static_init::dynamic]
pub static UTF_TO_CP1251: std::collections::HashMap<u32, u8> = HashMap::from([
(37072, 192),
(37328, 193),
(37584, 194),
(37840, 195),
(38096, 196),
(38352, 197),
(38608, 198),
(38864, 199),
(39120, 200),
(39376, 201),
(39632, 202),
(39888, 203),
(40144, 204),
(40400, 205),
(40656, 206),
(40912, 207),
(41168, 208),
(41424, 209),
(41680, 210),
(41936, 211),
(42192, 212),
(42448, 213),
(42704, 214),
(42960, 215),
(43216, 216),
(43472, 217),
(43728, 218),
(43984, 219),
(44240, 220),
(44496, 221),
(44752, 222),
(45008, 223),
(45264, 224),
(45520, 225),
(45776, 226),
(46032, 227),
(46288, 228),
(46544, 229),
(46800, 230),
(47056, 231),
(47312, 232),
(47568, 233),
(47824, 234),
(48080, 235),
(48336, 236),
(48592, 237),
(48848, 238),
(49104, 239),
(32977, 240),
(33233, 241),
(33489, 242),
(33745, 243),
(34001, 244),
(34257, 245),
(34513, 246),
(34769, 247),
(35025, 248),
(35281, 249),
(35537, 250),
(35793, 251),
(36049, 252),
(36305, 253),
(36561, 254),
(36817, 255),
(33232, 168),
(37329, 184),
(34000, 170),
(38097, 186),
(34768, 175),
(38865, 191),
(34512, 178),
(38609, 179),
(37074, 165),
(37330, 180),
(36560, 161),
(40657, 162),
]);

pub fn log_level(level: usize) -> log::LevelFilter {
match level {
0 => log::LevelFilter::Trace,
Expand Down

0 comments on commit 242d1f8

Please sign in to comment.