aboutsummaryrefslogtreecommitdiff
path: root/libs/bsa_ffi/src/lib.rs
blob: 2cb2f21278c44332498ee0f58b8f92931e09e7ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
mod archive;

use std::ffi::{c_char, c_int, CStr, CString};
use std::fs;
use std::path::{Path, PathBuf};
use std::ptr;

use archive::{
    extract_archive_files_batch, list_archive_files, Ba2Builder, Ba2Format, BsaBuilder,
    GameVersion,
};
use walkdir::WalkDir;

#[repr(C)]
pub struct BsaFfiStringList {
    pub items: *mut *mut c_char,
    pub count: usize,
    pub error: *mut c_char,
}

pub type BsaProgressCallback =
    Option<unsafe extern "C" fn(done: u32, total: u32, current_path: *const c_char)>;

fn to_cstring(s: &str) -> *mut c_char {
    CString::new(s).unwrap_or_default().into_raw()
}

fn error_list(msg: &str) -> BsaFfiStringList {
    BsaFfiStringList {
        items: ptr::null_mut(),
        count: 0,
        error: to_cstring(msg),
    }
}

unsafe fn from_cstr<'a>(p: *const c_char) -> Result<&'a str, &'static str> {
    if p.is_null() {
        return Err("null pointer");
    }

    CStr::from_ptr(p)
        .to_str()
        .map_err(|_| "invalid UTF-8 string")
}

fn call_progress(progress_cb: BsaProgressCallback, done: usize, total: usize, path: &str) {
    if let Some(cb) = progress_cb {
        if let Ok(c_path) = CString::new(path) {
            unsafe {
                cb(done as u32, total as u32, c_path.as_ptr());
            }
        }
    }
}

fn path_to_rel(root: &Path, child: &Path) -> anyhow::Result<String> {
    let rel = child.strip_prefix(root)?;
    Ok(rel.to_string_lossy().replace('\\', "/"))
}

fn include_file_for_mode(rel: &str, include_mode: i32) -> bool {
    let is_dds = rel.to_lowercase().ends_with(".dds");
    match include_mode {
        1 => !is_dds,
        2 => is_dds,
        _ => true,
    }
}

#[no_mangle]
pub unsafe extern "C" fn bsa_ffi_list_files(archive_path: *const c_char) -> BsaFfiStringList {
    let archive_path = match from_cstr(archive_path) {
        Ok(v) => v,
        Err(e) => return error_list(e),
    };

    let entries = match list_archive_files(Path::new(archive_path)) {
        Ok(v) => v,
        Err(e) => return error_list(&e.to_string()),
    };

    let mut items: Vec<*mut c_char> = entries.into_iter().map(|e| to_cstring(&e.path)).collect();
    let result = BsaFfiStringList {
        items: items.as_mut_ptr(),
        count: items.len(),
        error: ptr::null_mut(),
    };
    std::mem::forget(items);
    result
}

#[no_mangle]
pub unsafe extern "C" fn bsa_ffi_string_list_free(list: BsaFfiStringList) {
    if !list.items.is_null() {
        let items = Vec::from_raw_parts(list.items, list.count, list.count);
        for p in items {
            if !p.is_null() {
                let _ = CString::from_raw(p);
            }
        }
    }

    if !list.error.is_null() {
        let _ = CString::from_raw(list.error);
    }
}

#[no_mangle]
pub unsafe extern "C" fn bsa_ffi_string_free(s: *mut c_char) {
    if !s.is_null() {
        let _ = CString::from_raw(s);
    }
}

#[no_mangle]
pub unsafe extern "C" fn bsa_ffi_extract_all(
    archive_path: *const c_char,
    output_dir: *const c_char,
    progress_cb: BsaProgressCallback,
    cancel_flag: *const c_int,
) -> *mut c_char {
    let archive_path = match from_cstr(archive_path) {
        Ok(v) => v,
        Err(e) => return to_cstring(e),
    };
    let output_dir = match from_cstr(output_dir) {
        Ok(v) => v,
        Err(e) => return to_cstring(e),
    };

    let archive_path = PathBuf::from(archive_path);
    let output_dir = PathBuf::from(output_dir);

    if let Err(e) = fs::create_dir_all(&output_dir) {
        return to_cstring(&format!("failed to create output directory: {e}"));
    }

    let entries = match list_archive_files(&archive_path) {
        Ok(v) => v,
        Err(e) => return to_cstring(&e.to_string()),
    };

    let total = entries.len();
    let wanted_files: Vec<String> = entries.iter().map(|e| e.path.clone()).collect();
    let progress_count = std::sync::atomic::AtomicUsize::new(0);
    let cancel_addr = cancel_flag as usize;

    let res = extract_archive_files_batch(&archive_path, &wanted_files, |path, data| {
        let cancel_ptr = cancel_addr as *const c_int;
        if !cancel_ptr.is_null() {
            let cancelled = unsafe { *cancel_ptr } != 0;
            if cancelled {
                anyhow::bail!("cancelled");
            }
        }

        let out_path = output_dir.join(path.replace('\\', "/"));
        if let Some(parent) = out_path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(&out_path, &data)?;

        let done = progress_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
        call_progress(progress_cb, done, total, path);
        Ok(())
    });

    match res {
        Ok(_) => ptr::null_mut(),
        Err(e) => to_cstring(&e.to_string()),
    }
}

#[no_mangle]
pub unsafe extern "C" fn bsa_ffi_pack_dir(
    input_dir: *const c_char,
    output_archive: *const c_char,
    game_id: *const c_char,
    progress_cb: BsaProgressCallback,
    cancel_flag: *const c_int,
) -> *mut c_char {
    bsa_ffi_pack_dir_filtered(
        input_dir,
        output_archive,
        game_id,
        0,
        progress_cb,
        cancel_flag,
    )
}

#[no_mangle]
pub unsafe extern "C" fn bsa_ffi_pack_dir_filtered(
    input_dir: *const c_char,
    output_archive: *const c_char,
    game_id: *const c_char,
    include_mode: c_int,
    progress_cb: BsaProgressCallback,
    cancel_flag: *const c_int,
) -> *mut c_char {
    let input_dir = match from_cstr(input_dir) {
        Ok(v) => v,
        Err(e) => return to_cstring(e),
    };
    let output_archive = match from_cstr(output_archive) {
        Ok(v) => v,
        Err(e) => return to_cstring(e),
    };
    let game_id = match from_cstr(game_id) {
        Ok(v) => v,
        Err(e) => return to_cstring(e),
    };

    let game = match GameVersion::from_cli_name(game_id) {
        Some(v) => v,
        None => {
            let valid = GameVersion::all()
                .iter()
                .map(GameVersion::cli_name)
                .collect::<Vec<_>>()
                .join(", ");
            return to_cstring(&format!("unknown game_id '{game_id}', valid: {valid}"));
        }
    };

    let input_dir = PathBuf::from(input_dir);
    let output_archive = PathBuf::from(output_archive);

    let mut files: Vec<(String, Vec<u8>)> = Vec::new();
    for entry in WalkDir::new(&input_dir).into_iter().filter_map(|e| e.ok()) {
        if !entry.file_type().is_file() {
            continue;
        }

        if !cancel_flag.is_null() {
            let cancelled = unsafe { *cancel_flag } != 0;
            if cancelled {
                return to_cstring("cancelled");
            }
        }

        let rel = match path_to_rel(&input_dir, entry.path()) {
            Ok(v) => v,
            Err(e) => return to_cstring(&format!("path error: {e}")),
        };

        if !include_file_for_mode(&rel, include_mode) {
            continue;
        }

        let data = match fs::read(entry.path()) {
            Ok(v) => v,
            Err(e) => return to_cstring(&format!("read error: {e}")),
        };

        files.push((rel, data));
    }

    if files.is_empty() {
        return to_cstring("no files found in input_dir");
    }

    let total = files.len();

    if game.is_ba2() {
        let ba2_version = game.ba2_version().unwrap_or_default();
        let compression = game.ba2_compression();

        let format = if output_archive
            .file_name()
            .map(|n| n.to_string_lossy().to_lowercase().contains("textures"))
            .unwrap_or(false)
        {
            Ba2Format::DX10
        } else {
            Ba2Format::General
        };

        let mut builder = Ba2Builder::new()
            .with_version(ba2_version)
            .with_compression(compression)
            .with_format(format);

        for (idx, (rel, data)) in files.into_iter().enumerate() {
            if !cancel_flag.is_null() {
                let cancelled = unsafe { *cancel_flag } != 0;
                if cancelled {
                    return to_cstring("cancelled");
                }
            }
            builder.add_file(&rel, data);
            call_progress(progress_cb, idx + 1, total, &rel);
        }

        match builder.build_with_progress(&output_archive, |_, _, _| {}) {
            Ok(_) => ptr::null_mut(),
            Err(e) => to_cstring(&e.to_string()),
        }
    } else {
        let version = match game.bsa_version() {
            Some(v) => v,
            None => return to_cstring("TES3 BSA writing is not supported yet"),
        };

        let compress = game.supports_compression();

        let mut builder = BsaBuilder::new().with_version(version).with_compression(compress);

        for (idx, (rel, data)) in files.into_iter().enumerate() {
            if !cancel_flag.is_null() {
                let cancelled = unsafe { *cancel_flag } != 0;
                if cancelled {
                    return to_cstring("cancelled");
                }
            }
            builder.add_file(&rel, data);
            call_progress(progress_cb, idx + 1, total, &rel);
        }

        match builder.build_with_progress(&output_archive, |_, _, _| {}) {
            Ok(_) => ptr::null_mut(),
            Err(e) => to_cstring(&e.to_string()),
        }
    }
}