everything-direct 0.1.0

Direct IPC bindings for Everything Search Engine on Windows.
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
//! Raw IPC bindings for the Everything search engine.
//!
//! This crate provides low-level IPC (Inter-Process Communication) access to
//! [Everything](https://www.voidtools.com/), a powerful file search utility for Windows.
//! Unlike the official SDK, this implementation uses direct Windows IPC without requiring
//! the Everything DLL, making it suitable for Rust applications that need minimal dependencies.
//!
//! # Features
//!
//! - Direct IPC communication with Everything (no DLL required)
//! - Query file system with advanced search capabilities
//! - Retrieve file metadata (size, dates, attributes, etc.)
//! - Support for filters, sorting, and pagination
//! - Version information and database status queries
//!
//! # Example
//!
//! ```no_run
//! use everything_raw::{EverythingClient, QueryInfo, RequestFlags};
//! use windows::core::h;
//!
//! # fn main() -> windows::core::Result<()> {
//! let client = EverythingClient::try_new(None)?;
//! let query = QueryInfo::new("*.txt")
//!     .request_flag(RequestFlags::NAME | RequestFlags::PATH)
//!     .max_results(10);
//! let results = client.query(&query)?;
//! println!("Found {} files", results.total_items);
//! # Ok(())
//! # }
//! ```

pub mod bindings;
mod utils;

use std::collections::HashMap;
use std::fmt::{Debug, Display};
use std::sync::{Arc, Mutex, OnceLock};
use windows::Win32::Foundation::{
    ERROR_INVALID_DATA, ERROR_LOCK_VIOLATION, FILETIME, HANDLE, HINSTANCE, HWND, LPARAM, LRESULT,
    WPARAM,
};
use windows::Win32::System::DataExchange::COPYDATASTRUCT;
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::WindowsAndMessaging::{
    CreateWindowExW, DefWindowProcW, DestroyWindow, FindWindowW, GetClassInfoExW, GetMessageW,
    GetPropW, IsWindow, MSG, PostMessageW, RegisterClassExW, RegisterWindowMessageW, RemovePropW,
    SendMessageW, SetPropW, WM_APP, WM_COPYDATA, WM_QUIT, WNDCLASSEXW,
};
use windows::core::{HSTRING, PCWSTR, Param, Result, w};

use crate::utils::*;

/// Everything IPC file info enumeration.
#[doc(inline)]
pub use bindings::IpcFileInfo as FileInfo;
/// Everything IPC search flags.
#[doc(inline)]
pub use bindings::IpcSearchFlags as SearchFlags;
/// Everything IPC sort types.
#[doc(inline)]
pub use bindings::IpcSort as SortType;
/// Everything IPC query request flags.
#[doc(inline)]
pub use bindings::Query2RequestFlags as RequestFlags;

/// Target machine architecture for Everything.
#[derive(Debug, Copy, Clone)]
pub enum TargetMachine {
    /// x86 (32-bit Intel/AMD)
    X86,
    /// x64 (64-bit Intel/AMD)
    X64,
    /// ARM (32-bit ARM)
    ARM,
    /// ARM64 (64-bit ARM)
    ARM64,
}

impl Display for TargetMachine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TargetMachine::X86 => write!(f, "x86"),
            TargetMachine::X64 => write!(f, "x64"),
            TargetMachine::ARM => write!(f, "ARM"),
            TargetMachine::ARM64 => write!(f, "ARM64"),
        }
    }
}

type ResponseMapType = Arc<Mutex<HashMap<usize, Arc<OnceLock<QueryResult>>>>>;

const RESPONSE_MAP_PROP: PCWSTR = w!("ResponseMap");

/// Client for communicating with the Everything search engine via IPC.
///
/// This client manages a hidden window for receiving query responses and maintains
/// a connection to the Everything application's IPC interface.
///
/// # Thread Safety
///
/// The client spawns an internal thread to handle Windows messages. All public methods
/// are thread-safe and can be called from multiple threads.
pub struct EverythingClient {
    ipc_hwnd: HWND,
    ipc_window_class: HSTRING,
    client_hwnd: HWND,
    _client_thread: std::thread::JoinHandle<Result<()>>,
    response_map: ResponseMapType,
    max_request_id: Mutex<u32>,
}

/// Query information for searching with Everything.
///
/// Contains all parameters needed to perform a search, including search string,
/// flags, sorting, and pagination options.
#[derive(Default, Debug, Clone)]
pub struct QueryInfo {
    /// The search query string.
    pub search: HSTRING,
    /// Search behavior flags (case-sensitive, regex, etc.).
    pub search_flags: SearchFlags,
    /// Which fields to include in results (name, path, size, etc.).
    pub request_flags: RequestFlags,
    /// How to sort the results.
    pub sort: SortType,
    /// Number of results to skip (for pagination).
    pub offset: u32,
    /// Maximum number of results to return.
    pub max_results: u32,
}

impl QueryInfo {
    /// Creates a new query with the given search string.
    ///
    /// Default settings: 50 max results, no special flags, default sorting.
    pub fn new(search: impl Into<HSTRING>) -> Self {
        Self {
            search: search.into(),
            max_results: 50,
            ..Default::default()
        }
    }

    /// Adds a search flag (e.g., case-sensitive, regex).
    pub fn search_flag(mut self, flag: SearchFlags) -> Self {
        self.search_flags |= flag;
        self
    }

    /// Adds a request flag to specify which fields to include in results.
    pub fn request_flag(mut self, flag: RequestFlags) -> Self {
        self.request_flags |= flag;
        self
    }

    /// Sets the sort type for results.
    pub fn sort_type(mut self, sort: SortType) -> Self {
        self.sort = sort;
        self
    }

    /// Sets the offset for pagination.
    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = offset;
        self
    }

    /// Sets the maximum number of results to return.
    pub fn max_results(mut self, max_results: u32) -> Self {
        self.max_results = max_results;
        self
    }
}

/// A single item in a query result.
///
/// Fields are optional and will only be populated if the corresponding
/// request flag was set in the query.
#[derive(Default, Debug, Clone)]
pub struct QueryResultItem {
    /// Item flags (folder, drive/root).
    pub flags: bindings::IpcItemFlags,
    /// File or folder name.
    pub name: Option<HSTRING>,
    /// Path to the parent directory.
    pub path: Option<HSTRING>,
    /// Full path including filename.
    pub full_path_and_name: Option<HSTRING>,
    /// File size in bytes.
    pub size: Option<i64>,
    /// File extension.
    pub extension: Option<HSTRING>,
    /// Creation date.
    pub date_created: Option<FILETIME>,
    /// Last modification date.
    pub date_modified: Option<FILETIME>,
    /// Last access date.
    pub date_accessed: Option<FILETIME>,
    /// File attributes.
    pub attributes: Option<u32>,
    /// File list filename (if from a file list).
    pub filelist_filename: Option<HSTRING>,
    /// Number of times run.
    pub run_count: Option<u32>,
    /// Last run date.
    pub date_run: Option<FILETIME>,
    /// Recently changed date.
    pub date_recently_changed: Option<FILETIME>,
    /// Highlighted name (with search matches highlighted).
    pub highlighted_name: Option<HSTRING>,
    /// Highlighted path.
    pub highlighted_path: Option<HSTRING>,
    /// Highlighted full path and name.
    pub highlighted_full_path_and_name: Option<HSTRING>,
}

/// Result of a query operation.
///
/// Contains metadata about the query and the list of matching items.
#[derive(Debug, Clone)]
pub struct QueryResult {
    /// Request ID that generated this result.
    pub request_id: usize,

    /// Total number of items matching the query.
    pub total_items: u32,
    /// Number of items in this result set.
    pub num_items: u32,
    /// Offset used for this query.
    pub offset: u32,
    /// Request flags used for this query.
    pub request_flags: RequestFlags,
    /// Sort type used for this query.
    pub sort_type: SortType,

    /// The matching items.
    pub items: Vec<QueryResultItem>,
}

/// Parses a single query result item from IPC data.
///
/// # Safety
///
/// This function is unsafe because:
/// - It casts raw bytes to structured types without validation
/// - It performs pointer arithmetic on the data buffer
/// - The caller must ensure `data` contains a valid IpcItem2 at `item_offset`
unsafe fn parse_query_item(
    item_offset: usize,
    data: &[u8],
    flags: bindings::Query2RequestFlags,
) -> Result<QueryResultItem> {
    if data.len() < item_offset + std::mem::size_of::<bindings::IpcItem2>() {
        Err(windows::core::Error::new(
            ERROR_INVALID_DATA.to_hresult(),
            "Data too small for IpcItem2",
        ))?;
    }
    // SAFETY: We've checked the buffer size. The cast is safe because
    // IpcItem2 is a packed struct that matches the IPC protocol layout.
    unsafe {
        let ipc_item: &bindings::IpcItem2 =
            &*(data.as_ptr().add(item_offset) as *const bindings::IpcItem2);

        let mut item = QueryResultItem {
            flags: bindings::IpcItemFlags::from_bits_truncate(ipc_item.flags),
            ..Default::default()
        };

        let mut data_offset = ipc_item.data_offset as usize;

        // The data stores at data + data_offset, with each hstring prefixed by a u32 length
        // if the corresponding flag is set in the request, the field is present
        if flags.contains(bindings::Query2RequestFlags::NAME) {
            item.name = Some(read_wstring(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::PATH) {
            item.path = Some(read_wstring(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::FULL_PATH_AND_NAME) {
            item.full_path_and_name = Some(read_wstring(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::EXTENSION) {
            item.extension = Some(read_wstring(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::SIZE) {
            item.size = Some(read_flat::<i64>(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::DATE_CREATED) {
            item.date_created = Some(read_flat(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::DATE_MODIFIED) {
            item.date_modified = Some(read_flat(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::DATE_ACCESSED) {
            item.date_accessed = Some(read_flat(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::ATTRIBUTES) {
            item.attributes = Some(read_flat(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::FILE_LIST_FILE_NAME) {
            item.filelist_filename = Some(read_wstring(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::RUN_COUNT) {
            item.run_count = Some(read_flat(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::DATE_RUN) {
            item.date_run = Some(read_flat(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::DATE_RECENTLY_CHANGED) {
            item.date_recently_changed = Some(read_flat(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::HIGHLIGHTED_NAME) {
            item.highlighted_name = Some(read_wstring(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::HIGHLIGHTED_PATH) {
            item.highlighted_path = Some(read_wstring(data, &mut data_offset)?);
        }
        if flags.contains(bindings::Query2RequestFlags::HIGHLIGHTED_FULL_PATH_AND_NAME) {
            item.highlighted_full_path_and_name = Some(read_wstring(data, &mut data_offset)?);
        }
        Ok(item)
    }
}

/// Parses a complete query result from IPC data.
///
/// # Safety
///
/// This function is unsafe because:
/// - It casts raw bytes to IpcList2 structure
/// - It performs pointer dereferencing without complete validation
/// - The caller must ensure `data` contains a valid IpcList2 structure
unsafe fn parse_query_result(id: usize, data: &[u8]) -> Result<QueryResult> {
    if data.len() < std::mem::size_of::<bindings::IpcList2>() {
        Err(windows::core::Error::new(
            ERROR_INVALID_DATA.to_hresult(),
            "Data too small for IpcQuery2Result",
        ))?;
    }
    // SAFETY: We've verified the buffer is large enough for IpcList2.
    // The cast is safe because IpcList2 is a packed struct matching the protocol.
    let ipc_list: &bindings::IpcList2 = unsafe { &*(data.as_ptr() as *const bindings::IpcList2) };
    if ipc_list.sort_type > bindings::IPC_SORT_MAX as u32 {
        Err(windows::core::Error::new(
            ERROR_INVALID_DATA.to_hresult(),
            "Invalid sort type in IpcQuery2Result",
        ))?;
    }
    let mut offset = std::mem::size_of::<bindings::IpcList2>();
    let mut items = Vec::with_capacity(ipc_list.numitems as usize);

    let request_flags = bindings::Query2RequestFlags::from_bits_truncate(ipc_list.request_flags);

    for _ in 0..ipc_list.numitems {
        // SAFETY: parse_query_item is unsafe but we trust the IPC data structure
        items.push(unsafe { parse_query_item(offset, data, request_flags)? });
        offset += std::mem::size_of::<bindings::IpcItem2>();
    }

    Ok(QueryResult {
        request_id: id,
        total_items: ipc_list.totitems,
        num_items: ipc_list.numitems,
        offset: ipc_list.offset,
        request_flags,
        // SAFETY: We've validated sort_type is within valid range
        sort_type: unsafe { std::mem::transmute(ipc_list.sort_type) },
        items,
    })
}

/// Window procedure for the IPC client window.
///
/// Handles WM_COPYDATA messages containing query results from Everything.
///
/// # Safety
///
/// This is a Windows callback function and must follow the stdcall convention.
/// It's only called by the Windows message loop with valid parameters.
unsafe extern "system" fn ipc_window_proc(
    hwnd: HWND,
    msg: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> LRESULT {
    match msg {
        WM_COPYDATA => unsafe {
            // SAFETY: lparam is a valid pointer to COPYDATASTRUCT when msg is WM_COPYDATA
            if let Some(copydata) = (lparam.0 as *const COPYDATASTRUCT).as_ref() {
                // Handle the received data in copydata
                let request_id = copydata.dwData;
                let data_slice: &[u8] = core::slice::from_raw_parts(
                    copydata.lpData as *const u8,
                    copydata.cbData as usize,
                );
                if let Ok(query_result) = parse_query_result(request_id as usize, data_slice) {
                    let response_map = GetPropW(hwnd, RESPONSE_MAP_PROP).0
                        as *const Arc<Mutex<HashMap<usize, Arc<OnceLock<QueryResult>>>>>;
                    if response_map.is_null() {
                        return LRESULT(0);
                    }
                    // SAFETY: response_map was set by SetPropW with a valid Arc pointer
                    if let Some(map_guard) = (*response_map).lock().ok() {
                        if let Some(once_lock) = map_guard.get(&(request_id as usize)) {
                            let _ = once_lock.set(query_result.clone());
                        }
                    }
                    return LRESULT(1);
                }
            }
        },
        _ => {}
    }
    // SAFETY: DefWindowProcW is safe to call for unhandled messages
    unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
}

impl EverythingClient {
    /// Creates a new Everything IPC client.
    ///
    /// # Arguments
    ///
    /// * `instance_name` - Optional instance name for connecting to a specific Everything instance.
    ///                     Use `None` for the default instance.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The Everything application is not running
    /// - Window creation fails
    /// - The message loop thread fails to start
    ///
    /// # Example
    ///
    /// ```no_run
    /// use everything_raw::EverythingClient;
    ///
    /// # fn main() -> windows::core::Result<()> {
    /// let client = EverythingClient::try_new(None)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn try_new(instance_name: Option<HSTRING>) -> Result<Self> {
        // SAFETY: EVERYTHING_IPC_WNDCLASSW is a valid null-terminated wide string constant
        let ipc_windows_class = unsafe {
            if let Some(name) = instance_name {
                // Create IPC window for the specified instance
                join_hstring(
                    &[
                        bindings::EVERYTHING_IPC_WNDCLASSW.as_wide(),
                        w!("_(").as_wide(),
                        &*name,
                        w!(")").as_wide(),
                    ],
                    w!("").as_wide(),
                )
            } else {
                bindings::EVERYTHING_IPC_WNDCLASSW.to_hstring()
            }
        };
        let client_hwnd: Arc<OnceLock<usize>> = Arc::new(OnceLock::new());
        let client_hwnd_clone = client_hwnd.clone();
        let ipc_window_class_clone = ipc_windows_class.clone();
        let response_map: Arc<Mutex<HashMap<usize, Arc<OnceLock<QueryResult>>>>> =
            Arc::new(Mutex::new(HashMap::new()));
        let response_map_clone = response_map.clone();

        let client_thread = std::thread::spawn(move || unsafe {
            let client_window_class = w!("EVERYTHING_RUST_CLIENT");

            let curr_module: HINSTANCE = GetModuleHandleW(None).map(|h| h.into())?;

            let mut window_class = WNDCLASSEXW::default();
            if GetClassInfoExW(Some(curr_module), client_window_class, &mut window_class).is_err() {
                window_class.cbSize = std::mem::size_of::<WNDCLASSEXW>() as u32;
                window_class.hInstance = curr_module;
                window_class.lpszClassName = client_window_class;
                window_class.lpfnWndProc = Some(ipc_window_proc);
                RegisterClassExW(&window_class);
            }
            // SAFETY: All window creation parameters are valid
            let hwnd = CreateWindowExW(
                Default::default(),
                client_window_class,
                None,
                Default::default(),
                0,
                0,
                0,
                0,
                None,
                None,
                Some(curr_module),
                None,
            )?;
            // SAFETY: Store the response map pointer as a window property
            SetPropW(
                hwnd,
                RESPONSE_MAP_PROP,
                Some(HANDLE(
                    &response_map_clone as *const _ as *mut std::ffi::c_void,
                )),
            )?;
            client_hwnd.set(hwnd.0 as usize).map_err(|_| {
                windows::core::Error::new(
                    ERROR_LOCK_VIOLATION.to_hresult(),
                    "Failed to set client HWND",
                )
            })?;
            let ipc_created_msg = RegisterWindowMessageW(w!("EVERYTHING_IPC_CREATED"));
            let mut ipc_window = FindWindowW(&ipc_window_class_clone, None)?;

            let mut msg = MSG::default();

            // SAFETY: Standard Windows message loop
            while let ret = GetMessageW(&mut msg, None, 0, 0)
                && ret.as_bool()
            {
                if ret.0 == -1 {
                    break;
                }
                if msg.message == ipc_created_msg {
                    ipc_window = FindWindowW(&ipc_window_class_clone, None)?;
                } else if msg.message == WM_APP {
                    let copydata: *const COPYDATASTRUCT = msg.wParam.0 as *const COPYDATASTRUCT;
                    // SAFETY: Forward the copydata to the Everything IPC window
                    SendMessageW(
                        ipc_window,
                        WM_COPYDATA,
                        Some(WPARAM(&hwnd as *const HWND as usize)),
                        Some(LPARAM(copydata as isize)),
                    );
                }
            }
            drop(response_map_clone);
            Ok(())
        });
        let client_hwnd = *client_hwnd_clone.wait();
        let mut client = Self {
            ipc_hwnd: HWND::default(),
            ipc_window_class: ipc_windows_class,
            client_hwnd: HWND(client_hwnd as *mut std::ffi::c_void),
            _client_thread: client_thread,
            response_map,
            max_request_id: Mutex::new(0),
        };
        client.refresh_ipc_window()?;
        Ok(client)
    }

    /// Refreshes the handle to the Everything IPC window.
    ///
    /// Call this if Everything was restarted after the client was created.
    pub fn refresh_ipc_window(&mut self) -> Result<()> {
        // SAFETY: FindWindowW is safe to call with valid window class name
        unsafe {
            self.ipc_hwnd = FindWindowW(&self.ipc_window_class, None)?;
            Ok(())
        }
    }

    /// Checks if the Everything IPC window is available.
    pub fn is_ipc_available(&self) -> bool {
        // SAFETY: IsWindow is safe to call with any HWND
        unsafe { IsWindow(Some(self.ipc_hwnd)).as_bool() }
    }

    /// Sends a simple DWORD command to Everything.
    fn send_ipc_dword(&self, command: bindings::TaskbarIpcCommand, data: usize) -> u32 {
        // SAFETY: SendMessageW is safe for IPC communication
        unsafe {
            SendMessageW(
                self.ipc_hwnd,
                bindings::EVERYTHING_WM_IPC,
                Some(WPARAM(command as usize)),
                Some(LPARAM(data as isize)),
            )
            .0 as u32
        }
    }

    /// Gets the major version number of Everything.
    pub fn get_major_version(&self) -> u32 {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::GetMajorVersion, 0)
    }

    /// Gets the minor version number of Everything.
    pub fn get_minor_version(&self) -> u32 {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::GetMinorVersion, 0)
    }

    /// Gets the revision number of Everything.
    pub fn get_revision(&self) -> u32 {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::GetRevision, 0)
    }

    /// Gets the build number of Everything.
    pub fn get_build_number(&self) -> u32 {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::GetBuildNumber, 0)
    }

    /// Gets the target machine architecture of Everything.
    pub fn get_target_machine(&self) -> TargetMachine {
        match self.send_ipc_dword(bindings::TaskbarIpcCommand::GetTargetMachine, 0) {
            1 => TargetMachine::X86,
            2 => TargetMachine::X64,
            3 => TargetMachine::ARM,
            4 => TargetMachine::ARM64,
            _ => TargetMachine::X86,
        }
    }

    /// Gets comprehensive build information from Everything.
    ///
    /// Returns a tuple of (major, minor, revision, build, target_machine).
    pub fn get_build_info(&self) -> (u32, u32, u32, u32, TargetMachine) {
        (
            self.get_major_version(),
            self.get_minor_version(),
            self.get_revision(),
            self.get_build_number(),
            self.get_target_machine(),
        )
    }

    /// Returns whether Everything is saving to %APPDATA% or beside the executable.
    ///
    /// Availability: Everything 1.4+
    pub fn is_appdata(&self) -> bool {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::IsAppdata, 0) != 0
    }

    /// Requests Everything to rebuild its database immediately.
    ///
    /// Availability: Everything 1.4+
    pub fn rebuild_db(&self) -> bool {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::RebuildDb, 0) != 0
    }

    /// Queues a database rebuild in Everything.
    ///
    /// Availability: Everything 1.5+
    pub fn queue_rebuild_db(&self) -> bool {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::QueueRebuildDb, 0) != 0
    }

    /// Requests Everything to save its database to disk.
    ///
    /// Availability: Everything 1.4+
    pub fn save_db(&self) -> bool {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::SaveDb, 0) != 0
    }

    /// Checks if the Everything database is loaded.
    ///
    /// Availability: Everything 1.4+
    pub fn is_db_loaded(&self) -> bool {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::IsDbLoaded, 0) != 0
    }

    /// Checks whether the Everything database is currently busy.
    ///
    /// Availability: Everything 1.4+
    pub fn is_db_busy(&self) -> bool {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::IsDbBusy, 0) != 0
    }

    /// Checks if Everything is running with administrator privileges.
    ///
    /// Availability: Everything 1.4+
    pub fn is_admin(&self) -> bool {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::IsAdmin, 0) != 0
    }

    /// Requests Everything to update all folder indexes.
    ///
    /// Availability: Everything 1.4+
    pub fn update_all_folder_indexes(&self) -> bool {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::UpdateAllFolderIndexes, 0) != 0
    }

    /// Requests Everything to save the run history to disk.
    ///
    /// Availability: Everything 1.4+
    pub fn save_run_history(&self) -> bool {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::SaveRunHistory, 0) != 0
    }

    /// Requests Everything to delete ALL run history.
    ///
    /// Availability: Everything 1.4+
    pub fn delete_run_history(&self) -> bool {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::DeleteRunHistory, 0) != 0
    }

    /// Checks if fast sorting is enabled in Everything.
    ///
    /// Availability: Everything 1.4+
    pub fn is_fast_sort(&self) -> bool {
        self.send_ipc_dword(bindings::TaskbarIpcCommand::IsFastSort, 0) != 0
    }

    /// Checks if a specific file information type is indexed by Everything.
    ///
    /// # Arguments
    ///
    /// * `info_ty` - The type of file information to check (size, dates, attributes, etc.)
    ///
    /// # Availability
    /// Everything 1.4+
    pub fn is_file_info_indexed(&self, info_ty: FileInfo) -> bool {
        self.send_ipc_dword(
            bindings::TaskbarIpcCommand::IsFileInfoIndexed,
            info_ty as usize,
        ) != 0
    }

    fn send_ipc_copydata(
        &self,
        command: bindings::IpcCopyData,
        ptr: *mut std::ffi::c_void,
        size: u32,
    ) -> u32 {
        let copy_data = COPYDATASTRUCT {
            dwData: command as usize,
            cbData: size,
            lpData: ptr as *mut std::ffi::c_void,
        };
        // SAFETY: SendMessageW is safe for IPC communication
        unsafe {
            let everything_hwnd = FindWindowW(bindings::EVERYTHING_IPC_WNDCLASSW, None).unwrap();
            SendMessageW(
                everything_hwnd,
                WM_COPYDATA,
                None,
                Some(LPARAM(&copy_data as *const _ as isize)),
            )
            .0 as u32
        }
    }

    /// Gets the run count for a specific filename.
    pub fn get_run_count_from_filename(&self, filename: impl Param<PCWSTR>) -> u32 {
        // SAFETY: The pointer and size are valid for the filename parameter
        unsafe {
            let filename = filename.param();
            let size = (filename.borrow().len() + 1) * std::mem::size_of::<u16>(); // Include null terminator
            self.send_ipc_copydata(
                bindings::IpcCopyData::GetRunCountW,
                filename.borrow().as_ptr() as *mut _,
                size as u32,
            )
        }
    }

    /// Increments the run count for a specific filename.
    ///
    /// Returns true if the operation was successful.
    pub fn inc_run_count_from_filename(&self, filename: impl Param<PCWSTR>) -> bool {
        // SAFETY: The pointer and size are valid for the filename parameter
        unsafe {
            let filename = filename.param();
            let size = (filename.borrow().len() + 1) * std::mem::size_of::<u16>(); // Include null terminator
            self.send_ipc_copydata(
                bindings::IpcCopyData::IncRunCountW,
                filename.borrow().as_ptr() as *mut _,
                size as u32,
            ) != 0
        }
    }

    /// Sets the run count for a specific filename.
    ///
    /// Returns true if the operation was successful.
    pub fn set_run_count_from_filename(
        &self,
        filename: impl Param<PCWSTR>,
        run_count: u32,
    ) -> bool {
        // SAFETY: The pointer and size are valid for the filename parameter
        unsafe {
            let filename = filename.param();
            let size = filename.borrow().len() + 1; // Include null terminator
            let run_history_struct = bindings::IpcRunHistory { run_count };
            let mut buffer: Vec<u8> = Vec::with_capacity(
                std::mem::size_of_val(&run_history_struct) + size * std::mem::size_of::<u16>(),
            );
            let filename_bytes: *const u8 = filename.borrow().as_ptr() as *const u8;
            buffer.extend_from_slice(std::slice::from_raw_parts(
                &run_history_struct as *const _ as *const u8,
                std::mem::size_of_val(&run_history_struct),
            ));
            buffer.extend_from_slice(std::slice::from_raw_parts(
                filename_bytes,
                size * std::mem::size_of::<u16>(),
            ));
            self.send_ipc_copydata(
                bindings::IpcCopyData::SetRunCountW,
                buffer.as_mut_ptr() as *mut _,
                buffer.len() as u32,
            ) != 0
        }
    }

    /// Executes a query and waits for the result.
    ///
    /// This method sends the query to Everything via IPC and blocks until the result
    /// is received. The query is processed asynchronously by the message loop thread.
    ///
    /// # Arguments
    ///
    /// * `request` - The query parameters including search string, flags, and options
    ///
    /// # Returns
    ///
    /// Returns a `QueryResult` containing matching items and metadata.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The request could not be sent to Everything
    /// - The internal state locks are poisoned
    ///
    /// # Example
    ///
    /// ```no_run
    /// use everything_raw::{EverythingClient, QueryInfo, RequestFlags};
    ///
    /// # fn main() -> windows::core::Result<()> {
    /// let client = EverythingClient::try_new(None)?;
    /// let query = QueryInfo::new("*.pdf")
    ///     .request_flag(RequestFlags::NAME | RequestFlags::PATH)
    ///     .max_results(10);
    /// let result = client.query(&query)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn query(&self, request: &QueryInfo) -> Result<QueryResult> {
        let request_id = {
            let mut guard = self.max_request_id.lock().map_err(|_| {
                windows::core::Error::new(
                    ERROR_LOCK_VIOLATION.to_hresult(),
                    "Failed to lock max_request_id",
                )
            })?;
            *guard += 1;
            *guard
        };
        let payload = bindings::IpcQuery2 {
            reply_hwnd: self.client_hwnd.0 as u32,
            reply_copydata_message: request_id,
            search_flags: request.search_flags.bits(),
            request_flags: request.request_flags.bits(),
            sort_type: request.sort as u32,
            offset: request.offset,
            max_results: request.max_results,
        };
        let mut buf: Vec<u8> = Vec::with_capacity(
            std::mem::size_of::<bindings::IpcQuery2>()
                + (request.search.len() * std::mem::size_of::<u16>())
                + std::mem::size_of::<u16>(),
        );
        // SAFETY: We're carefully constructing a valid IPC message buffer
        unsafe {
            let payload_ptr: *const bindings::IpcQuery2 = &payload;
            let payload_bytes: *const u8 = payload_ptr as *const u8;
            buf.extend_from_slice(std::slice::from_raw_parts(
                payload_bytes,
                std::mem::size_of::<bindings::IpcQuery2>(),
            ));
            let search_wide: &[u16] = &request.search;
            let search_bytes: *const u8 = search_wide.as_ptr() as *const u8;
            buf.extend_from_slice(std::slice::from_raw_parts(
                search_bytes,
                search_wide.len() * std::mem::size_of::<u16>(),
            ));
            // Null terminator
            buf.extend_from_slice(&[0u8; 2]);
            let copy_data = COPYDATASTRUCT {
                dwData: bindings::IpcCopyData::Query2W as usize,
                cbData: buf.len() as u32,
                lpData: buf.as_ptr() as *mut std::ffi::c_void,
            };
            PostMessageW(
                Some(self.client_hwnd),
                WM_APP,
                WPARAM(&copy_data as *const _ as usize),
                LPARAM(0),
            )?;
            let once_lock: Arc<OnceLock<QueryResult>> = Arc::new(OnceLock::new());
            {
                let mut map_guard = self.response_map.lock().map_err(|_| {
                    windows::core::Error::new(
                        ERROR_LOCK_VIOLATION.to_hresult(),
                        "Failed to lock response_map",
                    )
                })?;
                map_guard.insert(request_id as usize, once_lock.clone());
            };
            drop(buf);
            // Wait for the response to arrive and return it
            Ok(once_lock.wait().clone())
        }
    }
}

impl Drop for EverythingClient {
    /// Cleanup: sends WM_QUIT to the message loop thread and destroys the client window.
    fn drop(&mut self) {
        // SAFETY: These Win32 API calls are safe for cleanup
        unsafe {
            PostMessageW(Some(self.client_hwnd), WM_QUIT, WPARAM(0), LPARAM(0)).ok();
            RemovePropW(self.client_hwnd, RESPONSE_MAP_PROP).ok();
            DestroyWindow(self.client_hwnd).ok();
        }
    }
}