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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
#![allow(non_snake_case)]

use crate::aliases::{DLGPROC, WinResult};
use crate::co;
use crate::enums::{IdIdcStr, IdIdiStr, IdStr, RtStr};
use crate::ffi::{BOOL, kernel32, user32};
use crate::funcs::GetLastError;
use crate::handles::{
	HACCEL,
	HBITMAP,
	HCURSOR,
	HICON,
	HMENU,
	HRSRC,
	HRSRCMEM,
	HWND,
};
use crate::privs::{bool_to_winresult, MAX_PATH, str_to_iso88591};
use crate::structs::{ATOM, LANGID, SIZE, WNDCLASSEX};
use crate::various::WString;

pub_struct_handle! {
	/// Handle to an
	/// [instance](https://docs.microsoft.com/en-us/windows/win32/winprog/windows-data-types#hinstance),
	/// same as `HMODULE`.
	HINSTANCE
}

impl HINSTANCE {
	/// [`CreateDialogParam`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createdialogparamw)
	/// method.
	pub fn CreateDialogParam(
		self,
		resource_id: IdStr,
		hwnd_parent: Option<HWND>,
		dialog_proc: DLGPROC,
		init_param: Option<isize>) -> WinResult<HWND>
	{
		unsafe {
			user32::CreateDialogParamW(
				self.ptr,
				resource_id.as_ptr(),
				hwnd_parent.map_or(std::ptr::null_mut(), |h| h.ptr),
				dialog_proc as _,
				init_param.unwrap_or_default(),
			).as_mut()
		}.map(|ptr| HWND { ptr })
			.ok_or_else(|| GetLastError())
	}

	/// [`DialogBoxParam`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-dialogboxparamw)
	/// method.
	pub fn DialogBoxParam(
		self,
		resource_id: IdStr,
		hwnd_parent: Option<HWND>,
		dialog_proc: DLGPROC,
		init_param: Option<isize>) -> WinResult<isize>
	{
		match unsafe {
			user32::DialogBoxParamW(
				self.ptr,
				resource_id.as_ptr(),
				hwnd_parent.map_or(std::ptr::null_mut(), |h| h.ptr),
				dialog_proc as _,
				init_param.unwrap_or_default(),
			)
		} {
			-1 => Err(GetLastError()),
			res => Ok(res), // assumes hWndParent as valid, so no check for zero
		}
	}

	/// [`EnumResourceLanguages`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-enumresourcelanguagesw)
	/// method.
	pub fn EnumResourceLanguages<F>(self,
		resource_type: RtStr, resource_id: IdStr, func: F) -> WinResult<()>
		where F: Fn(LANGID) -> bool,
	{
		bool_to_winresult(
			unsafe {
				kernel32::EnumResourceLanguagesW(
					self.ptr,
					resource_type.as_ptr(),
					resource_id.as_ptr(),
					Self::enum_resource_languages_proc::<F> as _,
					&func as *const _ as _,
				)
			},
		)
	}
	extern "system" fn enum_resource_languages_proc<F>(
		_: HINSTANCE, _: *const u16, _: *const u16,
		language_id: u16, lparam: isize) -> BOOL
		where F: Fn(LANGID) -> bool,
	{
		let func = unsafe { &*(lparam as *const F) };
		func(LANGID(language_id)) as _
	}

	/// [`EnumResourceNames`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-enumresourcenamesw)
	/// method.
	pub fn EnumResourceNames<F>(self,
		resource_type: RtStr, func: F) -> WinResult<()>
		where F: Fn(IdStr) -> bool,
	{
		bool_to_winresult(
			unsafe {
				kernel32::EnumResourceNamesW(
					self.ptr,
					resource_type.as_ptr(),
					Self::enum_resource_names_proc::<F> as _,
					&func as *const _ as _,
				)
			},
		)
	}
	extern "system" fn enum_resource_names_proc<F>(
		_: HINSTANCE, _: *const u16, resource_id: *mut u16, lparam: isize) -> BOOL
		where F: Fn(IdStr) -> bool,
	{
		let func = unsafe { &*(lparam as *const F) };
		func(IdStr::from_ptr(resource_id)) as _
	}

	/// [`EnumResourceTypes`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-enumresourcetypesw)
	/// method.
	pub fn EnumResourceTypes<F>(self, func: F) -> WinResult<()>
		where F: Fn(RtStr) -> bool,
	{
		bool_to_winresult(
			unsafe {
				kernel32::EnumResourceTypesW(
					self.ptr,
					Self::enum_resource_types_proc::<F> as _,
					&func as *const _ as _,
				)
			},
		)
	}
	extern "system" fn enum_resource_types_proc<F>(
		_: HINSTANCE, resource_type: *const u16, lparam: isize) -> BOOL
		where F: Fn(RtStr) -> bool,
	{
		let func = unsafe { &*(lparam as *const F) };
		func(RtStr::from_ptr(resource_type)) as _
	}

	/// [`FindResource`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-findresourcew)
	/// method.
	///
	/// For an example, see
	/// [`HINSTANCE::LockResource`](crate::HINSTANCE::LockResource).
	pub fn FindResource(self,
		resource_id: IdStr, resource_type: RtStr) -> WinResult<HRSRC>
	{
		unsafe {
			kernel32::FindResourceW(
				self.ptr,
				resource_id.as_ptr(),
				resource_type.as_ptr(),
			).as_mut()
		}.map(|ptr| HRSRC { ptr })
			.ok_or_else(|| GetLastError())
	}

	/// [`FindResourceEx`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-findresourceexw)
	/// method.
	///
	/// For an example, see
	/// [`HINSTANCE::LockResource`](crate::HINSTANCE::LockResource).
	pub fn FindResourceEx(self,
		resource_id: IdStr, resource_type: RtStr,
		language: Option<LANGID>) -> WinResult<HRSRC>
	{
		unsafe {
			kernel32::FindResourceExW(
				self.ptr,
				resource_id.as_ptr(),
				resource_type.as_ptr(),
				language.unwrap_or(LANGID::new(co::LANG::NEUTRAL, co::SUBLANG::NEUTRAL)).0,
			).as_mut()
		}.map(|ptr| HRSRC { ptr })
			.ok_or_else(|| GetLastError())
	}

	/// [`FreeLibrary`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-freelibrary)
	/// method.
	pub fn FreeLibrary(self) -> WinResult<()> {
		bool_to_winresult(unsafe { kernel32::FreeLibrary(self.ptr) })
	}

	/// [`GetClassInfoEx`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclassinfoexw)
	/// method.
	///
	/// # Examples
	///
	/// Retrieving information of a window class created in our application:
	/// ```rust,ignore
	/// use winsafe::{HINSTANCE, WNDCLASSEX};
	///
	/// let mut wcx = WNDCLASSEX::default();
	/// HINSTANCE::GetModuleHandle(None)?
	///     .GetClassInfoEx("SOME_CLASS_NAME", &mut wcx)?;
	/// ```
	pub fn GetClassInfoEx(self,
		class_name: &str, wcx: &mut WNDCLASSEX) -> WinResult<ATOM>
	{
		match unsafe {
			user32::GetClassInfoExW(
				self.ptr,
				WString::from_str(class_name).as_ptr(),
				wcx as *mut _ as _,
			)
		} {
			0 => Err(GetLastError()),
			atom => Ok(ATOM(atom as _)),
		}
	}

	/// [`GetModuleFileName`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamew)
	/// method.
	///
	/// # Examples
	///
	/// Retrieving the full path of currently running .exe file:
	///
	/// ```rust,ignore
	/// use winsafe::HINSTANCE;
	///
	/// let exe_name = HINSTANCE::NULL.GetModuleFileName()?;
	///
	/// println!("EXE: {}", exe_name);
	/// ```
	pub fn GetModuleFileName(self) -> WinResult<String> {
		let mut buf = [0; MAX_PATH];
		match unsafe {
			kernel32::GetModuleFileNameW(
				self.ptr,
				buf.as_mut_ptr(),
				buf.len() as _,
			)
		} {
			0 => Err(GetLastError()),
			_ => Ok(WString::from_wchars_slice(&buf).to_string()),
		}
	}

	/// [`GetModuleHandle`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlew)
	/// static method.
	///
	/// # Examples
	///
	/// Retrieving current module instance:
	/// ```rust,ignore
	/// use winsafe::HINSTANCE;
	///
	/// let hinstance = HINSTANCE::GetModuleHandle(None)?;
	/// ```
	pub fn GetModuleHandle(module_name: Option<&str>) -> WinResult<HINSTANCE> {
		unsafe {
			kernel32::GetModuleHandleW(
				WString::from_opt_str(module_name).as_ptr()
			).as_mut()
		}.map(|ptr| Self { ptr })
			.ok_or_else(|| GetLastError())
	}

	/// [`GetProcAddress`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress)
	/// method.
	pub fn GetProcAddress(self,
		proc_name: &str) -> WinResult<*const std::ffi::c_void>
	{
		unsafe {
			kernel32::GetProcAddress(
				self.ptr,
				str_to_iso88591(proc_name).as_ptr(),
			).as_ref()
		}.map(|ptr| ptr as _)
			.ok_or_else(|| GetLastError())
	}

	/// [`LoadAccelerators`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadacceleratorsw)
	/// method.
	pub fn LoadAccelerators(self, table_name: IdStr) -> WinResult<HACCEL> {
		unsafe {
			user32::LoadAcceleratorsW(
				self.ptr,
				table_name.as_ptr(),
			).as_mut()
		}.map(|ptr| HACCEL { ptr })
			.ok_or_else(|| GetLastError())
	}

	/// [`LoadCursor`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadcursorw)
	/// method.
	///
	/// # Examples
	///
	/// Loading a system cursor:
	/// ```rust,ignore
	/// use winsafe::{co, HINSTANCE, IdIdc};
	///
	/// let sys_cursor = HINSTANCE::default()
	///     .LoadCursor(IdIdc::Idc(co::IDC::ARROW))?;
	/// ```
	pub fn LoadCursor(self, resource_id: IdIdcStr) -> WinResult<HCURSOR> {
		unsafe {
				user32::LoadCursorW(
				self.ptr,
				resource_id.as_ptr(),
			).as_mut()
		}.map(|ptr| HCURSOR { ptr })
			.ok_or_else(|| GetLastError())
	}

	/// [`LoadIcon`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadiconw)
	/// method.
	///
	/// # Examples
	///
	/// Loading a system icon:
	/// ```rust,ignore
	/// use winsafe::{co, IdIdi, HINSTANCE};
	///
	/// let sys_icon = HINSTANCE::default()
	///     .LoadIcon(IdIdi::Idi(co::IDI::INFORMATION))?;
	/// ```
	pub fn LoadIcon(self, icon_id: IdIdiStr) -> WinResult<HICON> {
		unsafe {
			user32::LoadIconW(
				self.ptr,
				icon_id.as_ptr(),
			).as_mut()
		}.map(|ptr| HICON { ptr })
			.ok_or_else(|| GetLastError())
	}

	/// [`LoadImage`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadimagew)
	/// method for [`HBITMAP`](crate::HBITMAP).
	pub fn LoadImageBitmap(self,
		name: u16, sz: SIZE, load: co::LR) -> WinResult<HBITMAP>
	{
		unsafe {
			user32::LoadImageW(self.ptr, name as _, 0, sz.cx, sz.cy, load.0)
				.as_mut()
		}.map(|ptr| HBITMAP { ptr })
			.ok_or_else(|| GetLastError())
	}

	/// [`LoadImage`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadimagew)
	/// method for [`HCURSOR`](crate::HCURSOR).
	pub fn LoadImageCursor(self,
		name: u16, cx: i32, cy: i32, load: co::LR) -> WinResult<HCURSOR>
	{
		unsafe {
			user32::LoadImageW(self.ptr, name as _, 2, cx, cy, load.0)
				.as_mut()
		}.map(|ptr| HCURSOR { ptr })
			.ok_or_else(|| GetLastError())
	}

	/// [`LoadImage`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadimagew)
	/// method for [`HICON`](crate::HICON).
	pub fn LoadImageIcon(self,
		name: u16, cx: i32, cy: i32, load: co::LR) -> WinResult<HICON>
	{
		unsafe {
			user32::LoadImageW(self.ptr, name as _, 1, cx, cy, load.0)
				.as_mut()
		}.map(|ptr| HICON { ptr })
			.ok_or_else(|| GetLastError())
	}

	/// [`LoadLibrary`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryw)
	/// static method.
	///
	/// **Note:** Must be paired with an
	/// [`HINSTANCE::FreeLibrary`](crate::HINSTANCE::FreeLibrary) call.
	pub fn LoadLibrary(lib_file_name: &str) -> WinResult<HINSTANCE> {
		unsafe {
			kernel32::LoadLibraryW(WString::from_str(lib_file_name).as_ptr())
				.as_mut()
		}.map(|ptr| Self { ptr })
			.ok_or_else(|| GetLastError())
	}

	/// [`LoadMenu`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadmenuw)
	/// method.
	pub fn LoadMenu(self, resource_id: IdStr) -> WinResult<HMENU> {
		unsafe { user32::LoadMenuW(self.ptr, resource_id.as_ptr()).as_mut() }
			.map(|ptr| HMENU { ptr })
			.ok_or_else(|| GetLastError())
	}

	/// [`LoadResource`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadresource)
	/// method.
	///
	/// For an example, see
	/// [`HINSTANCE::LockResource`](crate::HINSTANCE::LockResource).
	pub fn LoadResource(self, res_info: HRSRC) -> WinResult<HRSRCMEM> {
		unsafe { kernel32::LoadResource(self.ptr, res_info.ptr).as_mut() }
			.map(|ptr| HRSRCMEM { ptr })
			.ok_or_else(|| GetLastError())
	}

	/// [`LoadString`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadstringw)
	/// method.
	pub fn LoadString(self, id: u16) -> WinResult<String> {
		let mut pData: *const u16 = std::ptr::null_mut();
		match unsafe {
			user32::LoadStringW(
				self.ptr,
				id as _,
				&mut pData as *mut _ as  _, 0,
			)
		} {
			0 => Err(GetLastError()),
			len => Ok(WString::from_wchars_count(pData, len as _).to_string())
		}
	}

	/// [`LockResource`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-lockresource)
	/// method.
	///
	/// This method should belong to [`HRSRCMEM`](crate::HRSRCMEM), but in order
	/// to make it safe, we automatically call
	/// [`HINSTANCE::SizeofResource`](crate::HINSTANCE::SizeofResource), so it's
	/// implemented here.
	///
	/// # Examples
	///
	/// The
	/// [Updating Resources](https://docs.microsoft.com/en-us/windows/win32/menurc/using-resources#updating-resources)
	/// example:
	///
	/// ```rust,ignore
	/// use winsafe::{HINSTANCE, HUPDATERSRC, LANGID};
	/// use winsafe::{co, IdStr, RtStr};
	///
	/// const IDD_HAND_ABOUTBOX: u16 = 103;
	/// const IDD_FOOT_ABOUTBOX: u16 = 110;
	///
	/// let hExe = HINSTANCE::LoadLibrary("hand.exe")?;
	///
	/// let hRes = hExe.FindResource(
	///     IdStr::Id(IDD_HAND_ABOUTBOX),
	///     RtStr::Rt(co::RT::DIALOG),
	/// )?;
	///
	/// let hResLoad = hExe.LoadResource(hRes)?;
	/// let lpResLock = hExe.LockResource(hRes, hResLoad)?;
	/// let hUpdateRes = HUPDATERSRC::BeginUpdateResource("foot.exe", false)?;
	///
	/// hUpdateRes.UpdateResource(
	///     RtStr::Rt(co::RT::DIALOG),
	///     IdStr::Id(IDD_FOOT_ABOUTBOX),
	///     LANGID::new(co::LANG::NEUTRAL, co::SUBLANG::NEUTRAL),
	///     lpResLock,
	/// )?;
	///
	/// hUpdateRes.EndUpdateResource(false)?;
	///
	/// hExe.FreeLibrary()?;
	/// ```
	pub fn LockResource<'a>(self,
		res_info: HRSRC, hres_loaded: HRSRCMEM) -> WinResult<&'a [u8]>
	{
		let sz = self.SizeofResource(res_info)?;
		unsafe { kernel32::LockResource(hres_loaded.ptr).as_mut() }
			.map(|ptr| unsafe {
				std::slice::from_raw_parts(ptr as *const _ as _, sz as _, )
			})
			.ok_or_else(|| GetLastError())
	}

	/// [`SizeofResource`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-sizeofresource)
	/// method.
	///
	/// For an example, see
	/// [`HINSTANCE::LockResource`](crate::HINSTANCE::LockResource).
	pub fn SizeofResource(self, res_info: HRSRC) -> WinResult<u32> {
		match unsafe { kernel32::SizeofResource(self.ptr, res_info.ptr) } {
			0 => Err(GetLastError()),
			sz => Ok(sz)
		}
	}
}