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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use std::{fmt, path::PathBuf, sync::{Arc, Mutex}};
use windows::{
    core::PCSTR,
    Win32::Foundation::{HANDLE,HINSTANCE,BOOL}, 
    Win32::System::LibraryLoader::*, 
};
use crate::utils::*;
use crate::result::*;
use crate::version::*;
use crate::id::*;

pub mod resource_type {
    //!
    //! List of resource constants representing Windows resource types
    //! expressed as [`Id`]
    //! 
    use super::Id;
    pub const UNKNOWN: Id = Id::Integer(0);
    pub const ACCELERATOR: Id = Id::Integer(9);
    pub const ANICURSOR: Id = Id::Integer(21);
    pub const ANIICON: Id = Id::Integer(22);
    pub const BITMAP: Id = Id::Integer(2);
    pub const CURSOR: Id = Id::Integer(1);
    pub const DIALOG: Id = Id::Integer(5);
    pub const DLGINCLUDE: Id = Id::Integer(17);
    pub const FONT: Id = Id::Integer(8);
    pub const FONTDIR: Id = Id::Integer(7);
    pub const HTML: Id = Id::Integer(23);
    pub const ICON: Id = Id::Integer(3);
    pub const MANIFEST: Id = Id::Integer(24);
    pub const MENU: Id = Id::Integer(4);
    pub const MESSAGETABLE: Id = Id::Integer(11);
    pub const PLUGPLAY: Id = Id::Integer(19);
    pub const VERSION: Id = Id::Integer(16);
    pub const VXD: Id = Id::Integer(20);
}


/// Placeholder for future data serialization (not implementated)
#[derive(Debug, Clone)]
pub struct ResourceDataInner {
    // ...
}

/// Placeholder for future data serialization (not implementated)
#[derive(Debug, Clone)]
pub enum ResourceData {
    Accelerator(ResourceDataInner),
    AniCursor(ResourceDataInner),
    AniIcon(ResourceDataInner),
    Bitmap(ResourceDataInner),
    Cursor(ResourceDataInner),
    Dialog(ResourceDataInner),
    DialogInclude(ResourceDataInner),
    Font(ResourceDataInner),
    FontDirectory(ResourceDataInner),
    Html(ResourceDataInner),
    Icon(ResourceDataInner),
    Manifest(ResourceDataInner),
    Menu(ResourceDataInner),
    MessageTable(ResourceDataInner),
    PlugPlay(ResourceDataInner),
    Version(VersionInfo),
    VxD(ResourceDataInner),
    Unknown(ResourceDataInner),
}

/// Structure representing a single resource
#[derive(Clone)]
pub struct Resource {
    /// resource type
    pub kind : Id,
    /// resource name
    pub name : Id,
    /// `u16` language associated with the resource
    pub lang : u16,
    /// raw resource data
    pub encoded : Arc<Mutex<Vec<u8>>>,
    /// destructured resource data (not implemented)
    pub decoded : Arc<Mutex<Option<ResourceData>>>,
    /// reference to the module handle that owns the resource
    module_handle : Arc<Mutex<Option<HANDLE>>>,
}

impl std::fmt::Debug for Resource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {

        f.debug_struct("")
            .field("kind",&self.kind)
            .field("name",&self.name)
            .field("lang",&self.lang)
            .field("data len",&self.encoded.lock().unwrap().len())
            // .field("resource",&self.decoded)
            //  .field("resource",&format!("{:?}",self.resource))
            .finish()
    }
}

impl Resource {
    pub fn new(
        rtype : PCSTR,
        rname: PCSTR,
        rlang: u16,
        data : &[u8],
        module_handle : Arc<Mutex<Option<HANDLE>>>,
    ) -> Resource {
        let typeid : Id = rtype.into();
        let info = Resource {
            kind : typeid,
            name : rname.into(),
            lang: rlang,
            encoded : Arc::new(Mutex::new(data.to_vec())),
            decoded : Arc::new(Mutex::new(None)),
            module_handle
        };

        info
    }

    /// Remove resource from the associated module (deletes the resource)
    pub fn remove(&self) -> Result<&Self> {
        if let Some(handle) = self.module_handle.lock().unwrap().as_ref() {
            let success = unsafe { UpdateResourceA(
                *handle,
                self.kind.clone(),
                self.name.clone(),
                self.lang,
                None,
                0
            ).as_bool() };

            if !success {
                return Err(format!("Resources::load(): Error removing resources: {:?}",get_last_error()).into());
            } 

        } else {
            return Err(format!("Resource::replace(): resource file is not open").into());
        };

        Ok(self)
        
    }

    /// Replace raw resource data with a user-supplied data. This only replaces
    /// the data in the resource structure. You must call [`Resource::update()`]
    /// following this call to update the resoruce data in the actual module.
    pub fn replace(&self, data : &[u8]) -> Result<&Self> {
        *self.encoded.lock().unwrap() = data.to_vec();
        Ok(self)
    }

    pub fn update(&self) -> Result<&Self> {
        
        if let Some(handle) = self.module_handle.lock().unwrap().as_ref() {
            let encoded = self.encoded.lock().unwrap();
            let success = unsafe { UpdateResourceA(
                *handle,
                self.kind.clone(),
                self.name.clone(),
                self.lang,
                Some(std::mem::transmute(encoded.as_ptr())),
                encoded.len() as u32
            ).as_bool() };

            if !success {
                return Err(format!("Resources::load(): Error removing resources: {:?}",get_last_error()).into());
            } 

        } else {
            return Err(format!("Resource::replace(): resource file is not open").into());
        };

        Ok(self)
        
    }

}

/// Data structure representing a resource file. This data structure 
/// points to a `.res` or `.exe` file and allows loading and modifying
/// resource in this file.
#[derive(Debug)]
pub struct Resources {
    file : PathBuf,
    module_handle : Arc<Mutex<Option<HANDLE>>>,
    /// resources contained in the supplied file represented by the [`Resource`] data structure.
    pub list : Arc<Mutex<Vec<Arc<Resource>>>>,
}

impl Resources {

    pub fn new(file: &PathBuf) -> Resources {
        Resources {
            file : file.clone(),
            module_handle : Arc::new(Mutex::new(None)),
            list : Arc::new(Mutex::new(Vec::new()))
        }
    }

    /// Load resources from the resource file.  This function does not need to be called
    /// explicitly as [`Resources::open`] will call it. It is useful if you want to load
    /// resources for extraction purposes only.
    pub fn load(&self) -> Result<()> {

        unsafe {
            let handle = LoadLibraryExA(
                pcstr!(self.file.to_str().unwrap()),
                None,
                // LOAD_LIBRARY_FLAGS::default()
                DONT_RESOLVE_DLL_REFERENCES | LOAD_LIBRARY_AS_DATAFILE
            )?;

            let ptr : *const Resources = std::mem::transmute(&*self);
            let success = EnumResourceTypesA(
                handle,
                Some(enum_types),
                std::mem::transmute(ptr)
            ).as_bool();

            FreeLibrary(handle);

            if !success {
                return Err(format!("Resources::load(): Error enumerating resources: {:?}",get_last_error()).into());
            } 
        }

        Ok(())
    }

    /// returns `true` if the resource file is currently open
    pub fn is_open(&self) -> bool {
        self.module_handle.lock().unwrap().is_some()
    }

    /// Open the resource file. This function opens a Windows handle to 
    /// the resource file and must be followed by [`Resources::close`].
    pub fn open(&mut self) -> Result<&Self> {
        self.open_impl(false)
    }

    /// Opens the resource file with `delete_existing_resources` set to `true`.
    /// This will result in retention in a deletion of previously existing resources.
    pub fn open_delete_existing_resources(&mut self) -> Result<&Self> {
        self.open_impl(true)
    }

    fn open_impl(&mut self, delete_existing_resources: bool) -> Result<&Self> {
        if self.is_open() {
            return Err(format!("resource '{}' is already open", self.file.to_str().unwrap()).into());
        }

        self.load()?;

        let handle = unsafe {
            BeginUpdateResourceA(
                pcstr!(self.file.to_str().unwrap()),
                delete_existing_resources)?
        };

        self.module_handle.lock().unwrap().replace(handle);
        // self.handle.lock().unwrap().replace(handle);
        
        Ok(self)
    }

    /// Remove the supplied resource from the resource file.
    pub fn remove(&self, resource: &Resource) -> Result<&Self> {
        self.remove_with_args(&resource.kind, &resource.name, resource.lang)?;
        Ok(self)
    }

    /// Remove the resource from the resource file by specifying resource type, name and lang.
    /// WARNING: If this method fails, the entire update set may fail (this is true for any API calls). 
    /// As such it is highly recommended to use [`Resources::remove`] instead and supplying and existing 
    /// [`Resource`] struct as it ensures that all supplied information is correct.
    /// This method is provided for advanced usage only.
    pub fn remove_with_args(&self, kind : &Id, name : &Id, lang : u16) -> Result<&Self> {
        // if let Some(handle) = self.handle.lock().unwrap().as_ref() {
        if let Some(handle) = self.module_handle.lock().unwrap().as_ref() {
            let success = unsafe { UpdateResourceA(
                *handle,
                kind,
                name,
                lang,
                None,
                0,
            ).as_bool() };

            if !success {
                return Err(format!("Resources::load(): Error removing resources: {:?}",get_last_error()).into());
            } 

        } else {
            return Err(format!("resource '{}' is not open", self.file.to_str().unwrap()).into());
        };

        Ok(self)
        
    }

    /// Replace (Update) the resource in the resource file. It is expected that this is the
    /// original resource with the modified raw data.
    pub fn try_replace(&self, resource: &Resource) -> Result<&Self> {
        self.replace_with_args(&resource.kind, &resource.name, resource.lang, &resource.encoded.lock().unwrap())?;
        Ok(self)
    }

    /// Replace (Update) the resource in the resource file by supplying the resource type, name and lang
    /// as well as a `u8` slice containing the raw resource data.  Please note that if this function fails
    /// the entire resoruce update set may fail.
    pub fn replace_with_args(&self, kind : &Id, name : &Id, lang : u16, data : &[u8]) -> Result<&Self> {
        if let Some(handle) = self.module_handle.lock().unwrap().as_ref() {
            let success = unsafe { UpdateResourceA(
                *handle,
                kind,
                name,
                lang,
                Some(std::mem::transmute(data.as_ptr())),
                data.len() as u32,
            ).as_bool() };

            if !success {
                return Err(format!("Resources::load(): Error removing resources: {:?}",get_last_error()).into());
            } 

        } else {
            return Err(format!("resource file '{}' is not open", self.file.to_str().unwrap()).into());
        };

        Ok(self)
        
    }

    /// Close the resource file.  This applies all the changes (updates) to the resource file.
    pub fn close(&mut self) {
        if let Some(handle) = self.module_handle.lock().unwrap().take() {
            unsafe {
                EndUpdateResourceA(handle,false);
            };
        }
    }

    /// Close the resource file discarding all changes.
    pub fn discard(&mut self) {
        if let Some(handle) = self.module_handle.lock().unwrap().take() {
            unsafe {
                EndUpdateResourceA(handle,true);
            };
        }
    }

    /// Create a new resource entry in the resource file. This function
    /// expects a valid [`Resource`] structure containing an appropriate
    /// resource type, name and raw data.
    pub fn insert(&self, r : Resource) {
        self.list.lock().unwrap().push(Arc::new(r))
    }

    /// Locate a resource entry by type and name.
    pub fn find(&self, typeid : Id, nameid: Id) -> Option<Arc<Resource>> {
        for item in self.list.lock().unwrap().iter() {
            if item.kind == typeid && item.name == nameid {
                return Some(item.clone());
            }
        }

        return None;
    }

    /// Locate and deserialize VS_VERSIONINFO structure (represented by [`VersionInfo`]).
    pub fn get_version_info(&self) -> Result<Option<VersionInfo>> {
        for item in self.list.lock().unwrap().iter() {
            if item.kind == resource_type::VERSION {
                return Ok(Some(item.clone().try_into()?));
            }
        }

        Ok(None)
    }
}

impl Drop for Resources {
    fn drop(&mut self) {
        self.close();
    }
}

unsafe extern "system" fn enum_languages(hmodule: HINSTANCE, lptype: PCSTR, lpname: PCSTR, lang: u16, lparam: isize) -> BOOL {
    let rptr : *const Resources = std::mem::transmute(lparam);
    let hresinfo = match FindResourceExA(hmodule,lptype,lpname,lang) {
        Ok(hresinfo) => hresinfo,
        Err(e) => panic!("Unable to find resource {:?} {:?} {:?} {lang}: {e}", hmodule,lptype,lpname)
    };
    let resource = LoadResource(hmodule,hresinfo);
    let len = SizeofResource(hmodule,hresinfo);
    let data_ptr = LockResource(resource);
    let data = std::slice::from_raw_parts(std::mem::transmute(data_ptr) , len as usize);
    let resources = &*rptr;
    resources.insert(Resource::new(lptype,lpname,lang,data, resources.module_handle.clone()));
    BOOL(1)
}

unsafe extern "system" fn enum_names(hmodule: HINSTANCE, lptype: PCSTR, lpname: PCSTR, lparam: isize) -> BOOL {
    EnumResourceLanguagesA(hmodule,lptype,lpname,Some(enum_languages),lparam);
    BOOL(1)
}

unsafe extern "system" fn enum_types(hmodule: HINSTANCE, lptype: PCSTR, lparam: isize) -> BOOL {
    EnumResourceNamesA(hmodule,lptype,Some(enum_names),lparam);
    BOOL(1)
}