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
#![allow(non_snake_case)]

use crate::co;
use crate::decl::*;
use crate::guard::*;
use crate::kernel::privs::*;
use crate::ole::privs::*;
use crate::prelude::*;
use crate::shell::ffi;

/// [`CommandLineToArgv`](https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw)
/// function.
///
/// # Examples
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let args = w::CommandLineToArgv(&w::GetCommandLine())?;
/// for arg in args.iter() {
///     println!("{}", arg);
/// }
/// # w::SysResult::Ok(())
/// ```
#[must_use]
pub fn CommandLineToArgv(cmd_line: &str) -> SysResult<Vec<String>> {
	let mut num_args = i32::default();
	let lp_arr = unsafe {
		ffi::CommandLineToArgvW(
			WString::from_str(cmd_line).as_ptr(),
			&mut num_args,
		)
	};
	if lp_arr.is_null() {
		return Err(GetLastError());
	}

	let mut strs = Vec::with_capacity(num_args as _);
	for lp in unsafe { std::slice::from_raw_parts(lp_arr, num_args as _) }.iter() {
		strs.push(unsafe { WString::from_wchars_nullt(*lp) }.to_string());
	}

	let _ = unsafe { LocalFreeGuard::new(HLOCAL::from_ptr(lp_arr as _)) };
	Ok(strs)
}

/// [`GetAllUsersProfileDirectory`](https://learn.microsoft.com/en-us/windows/win32/api/userenv/nf-userenv-getallusersprofiledirectoryw)
/// function.
///
/// # Related functions
///
/// * [`GetDefaultUserProfileDirectory`](crate::GetDefaultUserProfileDirectory)
/// * [`GetProfilesDirectory`](crate::GetProfilesDirectory)
#[must_use]
pub fn GetAllUsersProfileDirectory() -> SysResult<String> {
	let mut len = u32::default();
	unsafe { ffi::GetAllUsersProfileDirectoryW(std::ptr::null_mut(), &mut len); }
	match GetLastError() {
		co::ERROR::INSUFFICIENT_BUFFER => {},
		e => return Err(e),
	}

	let mut buf = WString::new_alloc_buf(len as _);
	bool_to_sysresult(
		unsafe { ffi::GetAllUsersProfileDirectoryW(buf.as_mut_ptr(), &mut len) },
	).map(|_| buf.to_string())
}

/// [`GetDefaultUserProfileDirectory`](https://learn.microsoft.com/en-us/windows/win32/api/userenv/nf-userenv-getdefaultuserprofiledirectoryw)
/// function.
///
/// # Related functions
///
/// * [`GetAllUsersProfileDirectory`](crate::GetAllUsersProfileDirectory)
/// * [`GetProfilesDirectory`](crate::GetProfilesDirectory)
#[must_use]
pub fn GetDefaultUserProfileDirectory() -> SysResult<String> {
	let mut len = u32::default();
	unsafe { ffi::GetDefaultUserProfileDirectoryW(std::ptr::null_mut(), &mut len); }
	match GetLastError() {
		co::ERROR::INSUFFICIENT_BUFFER => {},
		e => return Err(e),
	}

	let mut buf = WString::new_alloc_buf(len as _);
	bool_to_sysresult(
		unsafe { ffi::GetDefaultUserProfileDirectoryW(buf.as_mut_ptr(), &mut len) },
	).map(|_| buf.to_string())
}

/// [`GetProfilesDirectory`](https://learn.microsoft.com/en-us/windows/win32/api/userenv/nf-userenv-getprofilesdirectoryw)
/// function.
///
/// # Related functions
///
/// * [`GetAllUsersProfileDirectory`](crate::GetAllUsersProfileDirectory)
/// * [`GetDefaultUserProfileDirectory`](crate::GetDefaultUserProfileDirectory)
#[must_use]
pub fn GetProfilesDirectory() -> SysResult<String> {
	let mut len = u32::default();
	unsafe { ffi::GetProfilesDirectoryW(std::ptr::null_mut(), &mut len); }
	match GetLastError() {
		co::ERROR::INSUFFICIENT_BUFFER => {},
		e => return Err(e),
	}

	let mut buf = WString::new_alloc_buf(len as _);
	bool_to_sysresult(
		unsafe { ffi::GetProfilesDirectoryW(buf.as_mut_ptr(), &mut len) },
	).map(|_| buf.to_string())
}

/// [`PathCombine`](https://learn.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-pathcombinew)
/// function.
///
/// # Examples
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let full = w::PathCombine(
///     Some("C:"),
///     Some("One\\Two\\Three"),
/// )?;
///
/// // full = "C:\\One\\Two\\Three"
/// # w::SysResult::Ok(())
/// ```
pub fn PathCombine(
	str_dir: Option<&str>,
	str_file: Option<&str>,
) -> SysResult<String>
{
	let mut buf = WString::new_alloc_buf(MAX_PATH);
	ptr_to_sysresult(
		unsafe {
			ffi::PathCombineW(
				buf.as_mut_ptr(),
				WString::from_opt_str(str_dir).as_ptr(),
				WString::from_opt_str(str_file).as_ptr(),
			) as _
		},
	).map(|_| buf.to_string())
}

/// [`PathCommonPrefix`](https://learn.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-pathcommonprefixw)
/// function.
///
/// # Examples
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// if let Some(common_prefix) = w::PathCommonPrefix(
///     "C:\\temp\\one\\foo.txt",
///     "C:\\temp\\two\\bar.txt",
/// ) {
///     println!("Common prefix: {}", common_prefix); // "C:\\temp"
/// }
/// ```
pub fn PathCommonPrefix(file1: &str, file2: &str) -> Option<String> {
	let mut buf = WString::new_alloc_buf(MAX_PATH);
	match unsafe {
		ffi::PathCommonPrefixW(
			WString::from_str(file1).as_ptr(),
			WString::from_str(file2).as_ptr(),
			buf.as_mut_ptr(),
		)
	} {
		0 => None,
		_ => Some(buf.to_string()),
	}
}

/// [`PathSkipRoot`](https://learn.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-pathskiprootw)
/// function.
pub fn PathSkipRoot(str_path: &str) -> Option<String> {
	let buf = WString::from_str(str_path);
	unsafe { ffi::PathSkipRootW(buf.as_ptr()).as_ref() }
		.map(|ptr| unsafe { WString::from_wchars_nullt(ptr) }.to_string())
}

/// [`PathStripPath`](https://learn.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-pathstrippathw)
/// function.
pub fn PathStripPath(str_path: &str) -> String {
	let mut buf = WString::from_str(str_path);
	unsafe { ffi::PathStripPathW(buf.as_mut_ptr()); }
	buf.to_string()
}

/// [`PathUndecorate`](https://learn.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-pathundecoratew)
/// function.
pub fn PathUndecorate(str_path: &str) -> String {
	let mut buf = WString::from_str(str_path);
	unsafe { ffi::PathUndecorateW(buf.as_mut_ptr()); }
	buf.to_string()
}

/// [`PathUnquoteSpaces`](https://learn.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-pathunquotespacesw)
/// function.
pub fn PathUnquoteSpaces(str_path: &str) -> String {
	let mut buf = WString::from_str(str_path);
	unsafe { ffi::PathUnquoteSpacesW(buf.as_mut_ptr()); }
	buf.to_string()
}

/// [`SHAddToRecentDocs`](https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shaddtorecentdocs)
/// function.
///
/// # Safety
///
/// The `pv` type varies according to `uFlags`. If you set it wrong, you're
/// likely to cause a buffer overrun.
pub unsafe fn SHAddToRecentDocs<T>(flags: co::SHARD, pv: &T) {
	ffi::SHAddToRecentDocs(flags.raw(), pv as *const _ as _);
}

/// [`SHCreateItemFromParsingName`](https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-shcreateitemfromparsingname)
/// function.
///
/// # Examples
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let shi = w::SHCreateItemFromParsingName::<w::IShellItem2>(
///     "C:\\Temp\\foo.txt",
///     None::<&w::IBindCtx>,
/// )?;
/// # w::HrResult::Ok(())
/// ```
#[must_use]
pub fn SHCreateItemFromParsingName<T>(
	file_or_folder_path: &str,
	bind_ctx: Option<&impl ole_IBindCtx>,
) -> HrResult<T>
	where T: shell_IShellItem,
{
	let mut queried = unsafe { T::null() };
	ok_to_hrresult(
		unsafe {
			ffi::SHCreateItemFromParsingName(
				WString::from_str(file_or_folder_path).as_ptr(),
				bind_ctx.map_or(std::ptr::null_mut(), |i| i.ptr() as _),
				&T::IID as *const _ as _,
				queried.as_mut(),
			)
		},
	).map(|_| queried)
}

/// [`SHCreateMemStream`](https://learn.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-shcreatememstream)
/// function.
///
/// # Examples
///
/// Loading from a `Vec`:
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let raw_data: Vec<u8>; // initialized somewhere
/// # let raw_data = Vec::<u8>::default();
///
/// let stream = w::SHCreateMemStream(&raw_data)?;
/// # w::HrResult::Ok(())
/// ```
#[must_use]
pub fn SHCreateMemStream(src: &[u8]) -> HrResult<IStream> {
	let p = unsafe { ffi::SHCreateMemStream(vec_ptr(src), src.len() as _) };
	if p.is_null() {
		Err(co::HRESULT::E_OUTOFMEMORY)
	} else {
		Ok(unsafe { IStream::from_ptr(p) })
	}
}

/// [`Shell_NotifyIcon`](https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shell_notifyiconw)
/// function.
pub fn Shell_NotifyIcon(
	message: co::NIM,
	data: &mut NOTIFYICONDATA,
) -> SysResult<()>
{
	bool_to_sysresult(
		unsafe { ffi::Shell_NotifyIconW(message.raw(), data as *mut _ as _) },
	)
}

/// [`ShellExecuteEx`](https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecuteexw)
/// function.
///
/// # Safety
///
/// The [`SHELLEXECUTEINFO`](crate::SHELLEXECUTEINFO) struct is tricky. Improper
/// use can lead to invalid memory
/// access.
///
/// # Examples
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let mut sei = w::SHELLEXECUTEINFO::default();
/// unsafe { w::ShellExecuteEx(&mut sei)?; }
/// # w::SysResult::Ok(())
/// ```
pub unsafe fn ShellExecuteEx(
	exec_info: &mut SHELLEXECUTEINFO,
) -> SysResult<()> {
	bool_to_sysresult(unsafe { ffi::ShellExecuteExW(exec_info as *mut _ as _) })
}

/// [`SHFileOperation`](https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shfileoperationw)
/// function.
pub fn SHFileOperation(file_op: &mut SHFILEOPSTRUCT) -> SysResult<()> {
	bool_to_sysresult( unsafe { ffi::SHFileOperationW(file_op as *mut _ as _) })
}

/// [`SHGetFileInfo`](https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shgetfileinfow)
/// function.
pub fn SHGetFileInfo(
	path: &str,
	file_attrs: co::FILE_ATTRIBUTE,
	flags: co::SHGFI,
) -> SysResult<(u32, DestroyIconShfiGuard)>
{
	let mut shfi = SHFILEINFO::default();
	unsafe {
		match ffi::SHGetFileInfoW(
			WString::from_str(path).as_ptr(),
			file_attrs.raw(),
			&mut shfi as *mut _ as _,
			std::mem::size_of::<SHFILEINFO>() as _,
			flags.raw(),
		) {
			0 => Err(GetLastError()),
			n => Ok((n as _, DestroyIconShfiGuard::new(shfi))),
		}
	}
}

/// [`SHGetKnownFolderPath`](https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath)
/// function.
///
/// # Examples
///
/// Retrieving documents folder:
///
/// ```no_run
/// use winsafe::{self as w, prelude::*, co};
///
/// let docs_folder = w::SHGetKnownFolderPath(
///     &co::KNOWNFOLDERID::Documents,
///     co::KF::DEFAULT,
///     None,
/// )?;
///
/// println!("Docs folder: {}", docs_folder);
/// # w::HrResult::Ok(())
/// ```
#[must_use]
pub fn SHGetKnownFolderPath(
	folder_id: &co::KNOWNFOLDERID,
	flags: co::KF,
	token: Option<&HACCESSTOKEN>,
) -> HrResult<String>
{
	let mut pstr = std::ptr::null_mut::<u16>();
	ok_to_hrresult(
		unsafe {
			ffi::SHGetKnownFolderPath(
				folder_id as *const _ as _,
				flags.raw(),
				token.map_or(std::ptr::null_mut(), |t| t.ptr()),
				&mut pstr,
			)
		},
	).map(|_| {
		let path = unsafe { WString::from_wchars_nullt(pstr) };
		let _ = unsafe { CoTaskMemFreeGuard::new(pstr as _, 0) };
		path.to_string()
	})
}

/// [`SHGetStockIconInfo`](https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shgetstockiconinfo)
/// function.
///
/// # Examples
///
/// Loading the small (16x16 pixels) camera icon from the system:
///
/// ```no_run
/// use winsafe::{self as w, prelude::*, co};
///
/// let sii = w::SHGetStockIconInfo(
///     co::SIID::DEVICECAMERA,
///     co::SHGSI::ICON | co::SHGSI::SMALLICON,
/// )?;
///
/// println!("HICON handle: {}", sii.hIcon);
/// # w::AnyResult::Ok(())
/// ```
pub fn SHGetStockIconInfo(
	siid: co::SIID,
	flags: co::SHGSI,
) -> HrResult<DestroyIconSiiGuard>
{
	let mut sii = SHSTOCKICONINFO::default();
	unsafe {
		ok_to_hrresult(
			ffi::SHGetStockIconInfo(
				siid.raw(),
				flags.raw(),
				&mut sii as *mut _ as _,
			),
		).map(|_| DestroyIconSiiGuard::new(sii))
	}
}