win-desktop-utils 0.5.2

Windows desktop helpers for shell, shortcuts, app data, elevation, and single-instance Rust apps
Documentation
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Shell-facing helpers for opening files, URLs, Explorer selections, and the Recycle Bin.

#[cfg(feature = "shell")]
use std::ffi::OsStr;
use std::path::Path;
#[cfg(feature = "recycle-bin")]
use std::path::PathBuf;
#[cfg(feature = "shell")]
use std::process::Command;

#[cfg(feature = "recycle-bin")]
use windows::core::PCWSTR;
#[cfg(feature = "recycle-bin")]
use windows::Win32::System::Com::{CoCreateInstance, CLSCTX_INPROC_SERVER};
#[cfg(feature = "recycle-bin")]
use windows::Win32::UI::Shell::{
    FileOperation, IFileOperation, IFileOperationProgressSink, IShellItem,
    SHCreateItemFromParsingName, SHEmptyRecycleBinW, FOFX_RECYCLEONDELETE, FOF_ALLOWUNDO,
    FOF_NOCONFIRMATION, FOF_NOERRORUI, FOF_SILENT, SHERB_NOCONFIRMATION, SHERB_NOPROGRESSUI,
    SHERB_NOSOUND,
};

use crate::error::{Error, Result};
#[cfg(feature = "shell")]
use crate::win::{normalize_nonempty_str, shell_execute};
#[cfg(feature = "recycle-bin")]
use crate::win::{run_in_sta, to_wide_os, ComApartment};

#[cfg(feature = "shell")]
fn normalize_url(url: &str) -> Result<&str> {
    normalize_nonempty_str(url, "url cannot be empty", "url cannot contain NUL bytes")
}

#[cfg(feature = "shell")]
fn normalize_shell_verb(verb: &str) -> Result<&str> {
    normalize_nonempty_str(
        verb,
        "verb cannot be empty",
        "verb cannot contain NUL bytes",
    )
}

#[cfg(feature = "shell")]
fn shell_execute_raw(verb: &str, target: &OsStr) -> Result<()> {
    shell_execute(verb, target, None, "ShellExecuteW")
}

#[cfg(feature = "recycle-bin")]
fn shell_item_from_path(path: &Path) -> Result<IShellItem> {
    let path_w = to_wide_os(path.as_os_str());

    unsafe { SHCreateItemFromParsingName(PCWSTR(path_w.as_ptr()), None) }.map_err(|err| {
        Error::WindowsApi {
            context: "SHCreateItemFromParsingName",
            code: err.code().0,
        }
    })
}

#[cfg(feature = "recycle-bin")]
fn validate_recycle_path(path: &Path) -> Result<()> {
    if path.as_os_str().is_empty() {
        return Err(Error::InvalidInput("path cannot be empty"));
    }

    if !path.is_absolute() {
        return Err(Error::PathNotAbsolute);
    }

    if !path.exists() {
        return Err(Error::PathDoesNotExist);
    }

    Ok(())
}

#[cfg(feature = "recycle-bin")]
fn collect_recycle_paths<I, P>(paths: I) -> Result<Vec<PathBuf>>
where
    I: IntoIterator<Item = P>,
    P: AsRef<Path>,
{
    let mut collected = Vec::new();

    for path in paths {
        let path = path.as_ref();
        validate_recycle_path(path)?;
        collected.push(PathBuf::from(path));
    }

    if collected.is_empty() {
        Err(Error::InvalidInput("paths cannot be empty"))
    } else {
        Ok(collected)
    }
}

#[cfg(feature = "recycle-bin")]
fn queue_recycle_item(operation: &IFileOperation, path: &Path) -> Result<()> {
    let item = shell_item_from_path(path)?;

    unsafe { operation.DeleteItem(&item, Option::<&IFileOperationProgressSink>::None) }.map_err(
        |err| Error::WindowsApi {
            context: "IFileOperation::DeleteItem",
            code: err.code().0,
        },
    )
}

#[cfg(feature = "recycle-bin")]
fn recycle_paths_in_sta(paths: &[PathBuf]) -> Result<()> {
    let _com = ComApartment::initialize_sta("CoInitializeEx")?;
    let operation: IFileOperation = unsafe {
        CoCreateInstance(&FileOperation, None, CLSCTX_INPROC_SERVER)
    }
    .map_err(|err| Error::WindowsApi {
        context: "CoCreateInstance(FileOperation)",
        code: err.code().0,
    })?;

    let flags =
        FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT | FOFX_RECYCLEONDELETE;

    unsafe { operation.SetOperationFlags(flags) }.map_err(|err| Error::WindowsApi {
        context: "IFileOperation::SetOperationFlags",
        code: err.code().0,
    })?;

    for path in paths {
        queue_recycle_item(&operation, path)?;
    }

    unsafe { operation.PerformOperations() }.map_err(|err| Error::WindowsApi {
        context: "IFileOperation::PerformOperations",
        code: err.code().0,
    })?;

    let aborted =
        unsafe { operation.GetAnyOperationsAborted() }.map_err(|err| Error::WindowsApi {
            context: "IFileOperation::GetAnyOperationsAborted",
            code: err.code().0,
        })?;

    if aborted.as_bool() {
        Err(Error::WindowsApi {
            context: "IFileOperation::PerformOperations aborted",
            code: 0,
        })
    } else {
        Ok(())
    }
}

#[cfg(feature = "recycle-bin")]
fn empty_recycle_bin_raw(root_path: Option<&Path>) -> Result<()> {
    let root_w = root_path.map(|path| to_wide_os(path.as_os_str()));
    let root_ptr = root_w
        .as_ref()
        .map_or(PCWSTR::null(), |path| PCWSTR(path.as_ptr()));
    let flags = SHERB_NOCONFIRMATION | SHERB_NOPROGRESSUI | SHERB_NOSOUND;

    unsafe { SHEmptyRecycleBinW(None, root_ptr, flags) }.map_err(|err| Error::WindowsApi {
        context: "SHEmptyRecycleBinW",
        code: err.code().0,
    })
}

#[cfg(feature = "recycle-bin")]
fn run_in_shell_sta<T, F>(work: F) -> Result<T>
where
    T: Send + 'static,
    F: FnOnce() -> Result<T> + Send + 'static,
{
    run_in_sta("shell STA worker thread panicked", work)
}

/// Opens a file or directory with the user's default Windows handler.
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if `target` is empty.
/// Returns [`Error::PathDoesNotExist`] if the target path does not exist.
/// Returns [`Error::WindowsApi`] if `ShellExecuteW` reports failure.
///
/// # Examples
///
/// ```no_run
/// win_desktop_utils::open_with_default(r"C:\Windows\notepad.exe")?;
/// # Ok::<(), win_desktop_utils::Error>(())
/// ```
#[cfg(feature = "shell")]
pub fn open_with_default(target: impl AsRef<Path>) -> Result<()> {
    open_with_verb("open", target)
}

/// Opens a file or directory using a specific Windows shell verb.
///
/// Common verbs include `open`, `edit`, `print`, and `properties`, depending on
/// what the target path's registered handler supports.
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if `verb` is empty, whitespace only, or contains
/// NUL bytes, or if `target` is empty.
/// Returns [`Error::PathDoesNotExist`] if the target path does not exist.
/// Returns [`Error::WindowsApi`] if `ShellExecuteW` reports failure.
///
/// # Examples
///
/// ```no_run
/// win_desktop_utils::open_with_verb("properties", r"C:\Windows\notepad.exe")?;
/// # Ok::<(), win_desktop_utils::Error>(())
/// ```
#[cfg(feature = "shell")]
pub fn open_with_verb(verb: &str, target: impl AsRef<Path>) -> Result<()> {
    let verb = normalize_shell_verb(verb)?;
    let path = target.as_ref();

    if path.as_os_str().is_empty() {
        return Err(Error::InvalidInput("target cannot be empty"));
    }

    if !path.exists() {
        return Err(Error::PathDoesNotExist);
    }

    shell_execute_raw(verb, path.as_os_str())
}

/// Opens the Windows Properties sheet for a file or directory.
///
/// This is a convenience wrapper around [`open_with_verb`] using the `properties`
/// shell verb.
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if `target` is empty.
/// Returns [`Error::PathDoesNotExist`] if the target path does not exist.
/// Returns [`Error::WindowsApi`] if `ShellExecuteW` reports failure.
///
/// # Examples
///
/// ```no_run
/// win_desktop_utils::show_properties(r"C:\Windows\notepad.exe")?;
/// # Ok::<(), win_desktop_utils::Error>(())
/// ```
#[cfg(feature = "shell")]
pub fn show_properties(target: impl AsRef<Path>) -> Result<()> {
    open_with_verb("properties", target)
}

/// Prints a file using its registered default print shell verb.
///
/// Not every file type has a registered `print` verb; unsupported handlers are
/// reported as Windows shell errors.
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if `target` is empty.
/// Returns [`Error::PathDoesNotExist`] if the target path does not exist.
/// Returns [`Error::WindowsApi`] if `ShellExecuteW` reports failure.
///
/// # Examples
///
/// ```no_run
/// win_desktop_utils::print_with_default(r"C:\Users\Public\Documents\sample.txt")?;
/// # Ok::<(), win_desktop_utils::Error>(())
/// ```
#[cfg(feature = "shell")]
pub fn print_with_default(target: impl AsRef<Path>) -> Result<()> {
    open_with_verb("print", target)
}

/// Opens a URL with the user's default browser or registered handler.
///
/// Surrounding whitespace is trimmed before the URL is passed to the Windows shell.
/// URL validation is otherwise delegated to the Windows shell.
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if `url` is empty, whitespace only, or contains NUL bytes.
/// Returns [`Error::WindowsApi`] if `ShellExecuteW` reports failure.
///
/// # Examples
///
/// ```no_run
/// win_desktop_utils::open_url("https://www.rust-lang.org")?;
/// # Ok::<(), win_desktop_utils::Error>(())
/// ```
#[cfg(feature = "shell")]
pub fn open_url(url: &str) -> Result<()> {
    let url = normalize_url(url)?;
    shell_execute_raw("open", OsStr::new(url))
}

/// Opens Explorer and selects the requested path.
///
/// This function starts `explorer.exe` with `/select,` and the provided path.
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if `path` is empty.
/// Returns [`Error::PathDoesNotExist`] if the path does not exist.
/// Returns [`Error::Io`] if spawning `explorer.exe` fails.
///
/// # Examples
///
/// ```no_run
/// win_desktop_utils::reveal_in_explorer(r"C:\Windows\notepad.exe")?;
/// # Ok::<(), win_desktop_utils::Error>(())
/// ```
#[cfg(feature = "shell")]
pub fn reveal_in_explorer(path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();

    if path.as_os_str().is_empty() {
        return Err(Error::InvalidInput("path cannot be empty"));
    }

    if !path.exists() {
        return Err(Error::PathDoesNotExist);
    }

    Command::new("explorer.exe")
        .arg("/select,")
        .arg(path)
        .spawn()?;

    Ok(())
}

/// Opens the directory containing an existing file or directory.
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if `path` is empty or has no containing directory.
/// Returns [`Error::PathDoesNotExist`] if the path does not exist.
/// Returns [`Error::WindowsApi`] if `ShellExecuteW` reports failure.
///
/// # Examples
///
/// ```no_run
/// win_desktop_utils::open_containing_folder(r"C:\Windows\notepad.exe")?;
/// # Ok::<(), win_desktop_utils::Error>(())
/// ```
#[cfg(feature = "shell")]
pub fn open_containing_folder(path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();

    if path.as_os_str().is_empty() {
        return Err(Error::InvalidInput("path cannot be empty"));
    }

    if !path.exists() {
        return Err(Error::PathDoesNotExist);
    }

    let parent = path.parent().ok_or(Error::InvalidInput(
        "path does not have a containing folder",
    ))?;

    if parent.as_os_str().is_empty() {
        return Err(Error::InvalidInput(
            "path does not have a containing folder",
        ));
    }

    open_with_default(parent)
}

/// Sends a file or directory to the Windows Recycle Bin.
///
/// The path must be absolute and must exist.
///
/// This function uses `IFileOperation` on a dedicated STA thread so it can request
/// recycle-bin behavior through the modern Shell API.
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if `path` is empty.
/// Returns [`Error::PathNotAbsolute`] if the path is not absolute.
/// Returns [`Error::PathDoesNotExist`] if the path does not exist.
/// Returns [`Error::WindowsApi`] if the shell operation fails or is aborted.
///
/// # Examples
///
/// ```no_run
/// let path = std::env::current_dir()?.join("temporary-file.txt");
/// std::fs::write(&path, "temporary file")?;
/// win_desktop_utils::move_to_recycle_bin(&path)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "recycle-bin")]
pub fn move_to_recycle_bin(path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    validate_recycle_path(path)?;

    let path = PathBuf::from(path);
    run_in_shell_sta(move || recycle_paths_in_sta(std::slice::from_ref(&path)))
}

/// Sends multiple files or directories to the Windows Recycle Bin in one shell operation.
///
/// Every path must be absolute and must exist. All paths are validated before any shell
/// operation is started.
///
/// This function uses `IFileOperation` on a dedicated STA thread so it can request
/// recycle-bin behavior through the modern Shell API.
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if the path collection is empty or any path is empty.
/// Returns [`Error::PathNotAbsolute`] if any path is not absolute.
/// Returns [`Error::PathDoesNotExist`] if any path does not exist.
/// Returns [`Error::WindowsApi`] if the shell operation fails or is aborted.
///
/// # Examples
///
/// ```no_run
/// let first = std::env::current_dir()?.join("temporary-file-a.txt");
/// let second = std::env::current_dir()?.join("temporary-file-b.txt");
/// std::fs::write(&first, "temporary file")?;
/// std::fs::write(&second, "temporary file")?;
/// win_desktop_utils::move_paths_to_recycle_bin([&first, &second])?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "recycle-bin")]
pub fn move_paths_to_recycle_bin<I, P>(paths: I) -> Result<()>
where
    I: IntoIterator<Item = P>,
    P: AsRef<Path>,
{
    let paths = collect_recycle_paths(paths)?;
    run_in_shell_sta(move || recycle_paths_in_sta(&paths))
}

/// Permanently empties the Recycle Bin for all drives without shell UI.
///
/// This operation cannot be undone through this crate.
///
/// # Errors
///
/// Returns [`Error::WindowsApi`] if `SHEmptyRecycleBinW` reports failure.
///
/// # Examples
///
/// ```no_run
/// win_desktop_utils::empty_recycle_bin()?;
/// # Ok::<(), win_desktop_utils::Error>(())
/// ```
#[cfg(feature = "recycle-bin")]
pub fn empty_recycle_bin() -> Result<()> {
    empty_recycle_bin_raw(None)
}

/// Permanently empties the Recycle Bin for a specific drive root without shell UI.
///
/// `root_path` should be an existing absolute drive root such as `C:\`.
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if `root_path` is empty.
/// Returns [`Error::PathNotAbsolute`] if `root_path` is not absolute.
/// Returns [`Error::PathDoesNotExist`] if `root_path` does not exist.
/// Returns [`Error::WindowsApi`] if `SHEmptyRecycleBinW` reports failure.
///
/// # Examples
///
/// ```no_run
/// win_desktop_utils::empty_recycle_bin_for_root(r"C:\")?;
/// # Ok::<(), win_desktop_utils::Error>(())
/// ```
#[cfg(feature = "recycle-bin")]
pub fn empty_recycle_bin_for_root(root_path: impl AsRef<Path>) -> Result<()> {
    let root_path = root_path.as_ref();

    if root_path.as_os_str().is_empty() {
        return Err(Error::InvalidInput("root_path cannot be empty"));
    }

    if !root_path.is_absolute() {
        return Err(Error::PathNotAbsolute);
    }

    if !root_path.exists() {
        return Err(Error::PathDoesNotExist);
    }

    empty_recycle_bin_raw(Some(root_path))
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "recycle-bin")]
    use super::collect_recycle_paths;
    #[cfg(feature = "shell")]
    use super::{normalize_shell_verb, normalize_url};
    #[cfg(feature = "recycle-bin")]
    use std::path::PathBuf;

    #[cfg(feature = "shell")]
    #[test]
    fn normalize_url_rejects_empty_string() {
        let result = normalize_url("");
        assert!(matches!(
            result,
            Err(crate::Error::InvalidInput("url cannot be empty"))
        ));
    }

    #[cfg(feature = "shell")]
    #[test]
    fn normalize_url_rejects_whitespace_only() {
        let result = normalize_url("   ");
        assert!(matches!(
            result,
            Err(crate::Error::InvalidInput("url cannot be empty"))
        ));
    }

    #[cfg(feature = "shell")]
    #[test]
    fn normalize_url_trims_surrounding_whitespace() {
        assert_eq!(
            normalize_url("  https://example.com/docs  ").unwrap(),
            "https://example.com/docs"
        );
    }

    #[cfg(feature = "shell")]
    #[test]
    fn normalize_url_rejects_nul_bytes() {
        let result = normalize_url("https://example.com/\0hidden");
        assert!(matches!(
            result,
            Err(crate::Error::InvalidInput("url cannot contain NUL bytes"))
        ));
    }

    #[cfg(feature = "shell")]
    #[test]
    fn normalize_shell_verb_rejects_empty_string() {
        let result = normalize_shell_verb("");
        assert!(matches!(
            result,
            Err(crate::Error::InvalidInput("verb cannot be empty"))
        ));
    }

    #[cfg(feature = "shell")]
    #[test]
    fn normalize_shell_verb_rejects_whitespace_only() {
        let result = normalize_shell_verb("   ");
        assert!(matches!(
            result,
            Err(crate::Error::InvalidInput("verb cannot be empty"))
        ));
    }

    #[cfg(feature = "shell")]
    #[test]
    fn normalize_shell_verb_trims_surrounding_whitespace() {
        assert_eq!(
            normalize_shell_verb("  properties  ").unwrap(),
            "properties"
        );
    }

    #[cfg(feature = "shell")]
    #[test]
    fn normalize_shell_verb_rejects_nul_bytes() {
        let result = normalize_shell_verb("pro\0perties");
        assert!(matches!(
            result,
            Err(crate::Error::InvalidInput("verb cannot contain NUL bytes"))
        ));
    }

    #[cfg(feature = "recycle-bin")]
    #[test]
    fn collect_recycle_paths_rejects_empty_collection() {
        let paths: [PathBuf; 0] = [];
        let result = collect_recycle_paths(paths);
        assert!(matches!(
            result,
            Err(crate::Error::InvalidInput("paths cannot be empty"))
        ));
    }
}