Skip to main content

everything_direct/
lib.rs

1//! Raw IPC bindings for the Everything search engine.
2//!
3//! This crate provides low-level IPC (Inter-Process Communication) access to
4//! [Everything](https://www.voidtools.com/), a powerful file search utility for Windows.
5//! Unlike the official SDK, this implementation uses direct Windows IPC without requiring
6//! the Everything DLL, making it suitable for Rust applications that need minimal dependencies.
7//!
8//! # Features
9//!
10//! - Direct IPC communication with Everything (no DLL required)
11//! - Query file system with advanced search capabilities
12//! - Retrieve file metadata (size, dates, attributes, etc.)
13//! - Support for filters, sorting, and pagination
14//! - Version information and database status queries
15//!
16//! # Example
17//!
18//! ```no_run
19//! use everything_raw::{EverythingClient, QueryInfo, RequestFlags};
20//! use windows::core::h;
21//!
22//! # fn main() -> windows::core::Result<()> {
23//! let client = EverythingClient::try_new(None)?;
24//! let query = QueryInfo::new("*.txt")
25//!     .request_flag(RequestFlags::NAME | RequestFlags::PATH)
26//!     .max_results(10);
27//! let results = client.query(&query)?;
28//! println!("Found {} files", results.total_items);
29//! # Ok(())
30//! # }
31//! ```
32
33pub mod bindings;
34mod utils;
35
36use std::collections::HashMap;
37use std::fmt::{Debug, Display};
38use std::sync::{Arc, Mutex, OnceLock};
39use windows::Win32::Foundation::{
40    ERROR_INVALID_DATA, ERROR_LOCK_VIOLATION, FILETIME, HANDLE, HINSTANCE, HWND, LPARAM, LRESULT,
41    WPARAM,
42};
43use windows::Win32::System::DataExchange::COPYDATASTRUCT;
44use windows::Win32::System::LibraryLoader::GetModuleHandleW;
45use windows::Win32::UI::WindowsAndMessaging::{
46    CreateWindowExW, DefWindowProcW, DestroyWindow, FindWindowW, GetClassInfoExW, GetMessageW,
47    GetPropW, IsWindow, MSG, PostMessageW, RegisterClassExW, RegisterWindowMessageW, RemovePropW,
48    SendMessageW, SetPropW, WM_APP, WM_COPYDATA, WM_QUIT, WNDCLASSEXW,
49};
50use windows::core::{HSTRING, PCWSTR, Param, Result, w};
51
52use crate::utils::*;
53
54/// Everything IPC file info enumeration.
55#[doc(inline)]
56pub use bindings::IpcFileInfo as FileInfo;
57/// Everything IPC search flags.
58#[doc(inline)]
59pub use bindings::IpcSearchFlags as SearchFlags;
60/// Everything IPC sort types.
61#[doc(inline)]
62pub use bindings::IpcSort as SortType;
63/// Everything IPC query request flags.
64#[doc(inline)]
65pub use bindings::Query2RequestFlags as RequestFlags;
66
67/// Target machine architecture for Everything.
68#[derive(Debug, Copy, Clone)]
69pub enum TargetMachine {
70    /// x86 (32-bit Intel/AMD)
71    X86,
72    /// x64 (64-bit Intel/AMD)
73    X64,
74    /// ARM (32-bit ARM)
75    ARM,
76    /// ARM64 (64-bit ARM)
77    ARM64,
78}
79
80impl Display for TargetMachine {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        match self {
83            TargetMachine::X86 => write!(f, "x86"),
84            TargetMachine::X64 => write!(f, "x64"),
85            TargetMachine::ARM => write!(f, "ARM"),
86            TargetMachine::ARM64 => write!(f, "ARM64"),
87        }
88    }
89}
90
91type ResponseMapType = Arc<Mutex<HashMap<usize, Arc<OnceLock<QueryResult>>>>>;
92
93const RESPONSE_MAP_PROP: PCWSTR = w!("ResponseMap");
94
95/// Client for communicating with the Everything search engine via IPC.
96///
97/// This client manages a hidden window for receiving query responses and maintains
98/// a connection to the Everything application's IPC interface.
99///
100/// # Thread Safety
101///
102/// The client spawns an internal thread to handle Windows messages. All public methods
103/// are thread-safe and can be called from multiple threads.
104pub struct EverythingClient {
105    ipc_hwnd: HWND,
106    ipc_window_class: HSTRING,
107    client_hwnd: HWND,
108    _client_thread: std::thread::JoinHandle<Result<()>>,
109    response_map: ResponseMapType,
110    max_request_id: Mutex<u32>,
111}
112
113/// Query information for searching with Everything.
114///
115/// Contains all parameters needed to perform a search, including search string,
116/// flags, sorting, and pagination options.
117#[derive(Default, Debug, Clone)]
118pub struct QueryInfo {
119    /// The search query string.
120    pub search: HSTRING,
121    /// Search behavior flags (case-sensitive, regex, etc.).
122    pub search_flags: SearchFlags,
123    /// Which fields to include in results (name, path, size, etc.).
124    pub request_flags: RequestFlags,
125    /// How to sort the results.
126    pub sort: SortType,
127    /// Number of results to skip (for pagination).
128    pub offset: u32,
129    /// Maximum number of results to return.
130    pub max_results: u32,
131}
132
133impl QueryInfo {
134    /// Creates a new query with the given search string.
135    ///
136    /// Default settings: 50 max results, no special flags, default sorting.
137    pub fn new(search: impl Into<HSTRING>) -> Self {
138        Self {
139            search: search.into(),
140            max_results: 50,
141            ..Default::default()
142        }
143    }
144
145    /// Adds a search flag (e.g., case-sensitive, regex).
146    pub fn search_flag(mut self, flag: SearchFlags) -> Self {
147        self.search_flags |= flag;
148        self
149    }
150
151    /// Adds a request flag to specify which fields to include in results.
152    pub fn request_flag(mut self, flag: RequestFlags) -> Self {
153        self.request_flags |= flag;
154        self
155    }
156
157    /// Sets the sort type for results.
158    pub fn sort_type(mut self, sort: SortType) -> Self {
159        self.sort = sort;
160        self
161    }
162
163    /// Sets the offset for pagination.
164    pub fn offset(mut self, offset: u32) -> Self {
165        self.offset = offset;
166        self
167    }
168
169    /// Sets the maximum number of results to return.
170    pub fn max_results(mut self, max_results: u32) -> Self {
171        self.max_results = max_results;
172        self
173    }
174}
175
176/// A single item in a query result.
177///
178/// Fields are optional and will only be populated if the corresponding
179/// request flag was set in the query.
180#[derive(Default, Debug, Clone)]
181pub struct QueryResultItem {
182    /// Item flags (folder, drive/root).
183    pub flags: bindings::IpcItemFlags,
184    /// File or folder name.
185    pub name: Option<HSTRING>,
186    /// Path to the parent directory.
187    pub path: Option<HSTRING>,
188    /// Full path including filename.
189    pub full_path_and_name: Option<HSTRING>,
190    /// File size in bytes.
191    pub size: Option<i64>,
192    /// File extension.
193    pub extension: Option<HSTRING>,
194    /// Creation date.
195    pub date_created: Option<FILETIME>,
196    /// Last modification date.
197    pub date_modified: Option<FILETIME>,
198    /// Last access date.
199    pub date_accessed: Option<FILETIME>,
200    /// File attributes.
201    pub attributes: Option<u32>,
202    /// File list filename (if from a file list).
203    pub filelist_filename: Option<HSTRING>,
204    /// Number of times run.
205    pub run_count: Option<u32>,
206    /// Last run date.
207    pub date_run: Option<FILETIME>,
208    /// Recently changed date.
209    pub date_recently_changed: Option<FILETIME>,
210    /// Highlighted name (with search matches highlighted).
211    pub highlighted_name: Option<HSTRING>,
212    /// Highlighted path.
213    pub highlighted_path: Option<HSTRING>,
214    /// Highlighted full path and name.
215    pub highlighted_full_path_and_name: Option<HSTRING>,
216}
217
218/// Result of a query operation.
219///
220/// Contains metadata about the query and the list of matching items.
221#[derive(Debug, Clone)]
222pub struct QueryResult {
223    /// Request ID that generated this result.
224    pub request_id: usize,
225
226    /// Total number of items matching the query.
227    pub total_items: u32,
228    /// Number of items in this result set.
229    pub num_items: u32,
230    /// Offset used for this query.
231    pub offset: u32,
232    /// Request flags used for this query.
233    pub request_flags: RequestFlags,
234    /// Sort type used for this query.
235    pub sort_type: SortType,
236
237    /// The matching items.
238    pub items: Vec<QueryResultItem>,
239}
240
241/// Parses a single query result item from IPC data.
242///
243/// # Safety
244///
245/// This function is unsafe because:
246/// - It casts raw bytes to structured types without validation
247/// - It performs pointer arithmetic on the data buffer
248/// - The caller must ensure `data` contains a valid IpcItem2 at `item_offset`
249unsafe fn parse_query_item(
250    item_offset: usize,
251    data: &[u8],
252    flags: bindings::Query2RequestFlags,
253) -> Result<QueryResultItem> {
254    if data.len() < item_offset + std::mem::size_of::<bindings::IpcItem2>() {
255        Err(windows::core::Error::new(
256            ERROR_INVALID_DATA.to_hresult(),
257            "Data too small for IpcItem2",
258        ))?;
259    }
260    // SAFETY: We've checked the buffer size. The cast is safe because
261    // IpcItem2 is a packed struct that matches the IPC protocol layout.
262    unsafe {
263        let ipc_item: &bindings::IpcItem2 =
264            &*(data.as_ptr().add(item_offset) as *const bindings::IpcItem2);
265
266        let mut item = QueryResultItem {
267            flags: bindings::IpcItemFlags::from_bits_truncate(ipc_item.flags),
268            ..Default::default()
269        };
270
271        let mut data_offset = ipc_item.data_offset as usize;
272
273        // The data stores at data + data_offset, with each hstring prefixed by a u32 length
274        // if the corresponding flag is set in the request, the field is present
275        if flags.contains(bindings::Query2RequestFlags::NAME) {
276            item.name = Some(read_wstring(data, &mut data_offset)?);
277        }
278        if flags.contains(bindings::Query2RequestFlags::PATH) {
279            item.path = Some(read_wstring(data, &mut data_offset)?);
280        }
281        if flags.contains(bindings::Query2RequestFlags::FULL_PATH_AND_NAME) {
282            item.full_path_and_name = Some(read_wstring(data, &mut data_offset)?);
283        }
284        if flags.contains(bindings::Query2RequestFlags::EXTENSION) {
285            item.extension = Some(read_wstring(data, &mut data_offset)?);
286        }
287        if flags.contains(bindings::Query2RequestFlags::SIZE) {
288            item.size = Some(read_flat::<i64>(data, &mut data_offset)?);
289        }
290        if flags.contains(bindings::Query2RequestFlags::DATE_CREATED) {
291            item.date_created = Some(read_flat(data, &mut data_offset)?);
292        }
293        if flags.contains(bindings::Query2RequestFlags::DATE_MODIFIED) {
294            item.date_modified = Some(read_flat(data, &mut data_offset)?);
295        }
296        if flags.contains(bindings::Query2RequestFlags::DATE_ACCESSED) {
297            item.date_accessed = Some(read_flat(data, &mut data_offset)?);
298        }
299        if flags.contains(bindings::Query2RequestFlags::ATTRIBUTES) {
300            item.attributes = Some(read_flat(data, &mut data_offset)?);
301        }
302        if flags.contains(bindings::Query2RequestFlags::FILE_LIST_FILE_NAME) {
303            item.filelist_filename = Some(read_wstring(data, &mut data_offset)?);
304        }
305        if flags.contains(bindings::Query2RequestFlags::RUN_COUNT) {
306            item.run_count = Some(read_flat(data, &mut data_offset)?);
307        }
308        if flags.contains(bindings::Query2RequestFlags::DATE_RUN) {
309            item.date_run = Some(read_flat(data, &mut data_offset)?);
310        }
311        if flags.contains(bindings::Query2RequestFlags::DATE_RECENTLY_CHANGED) {
312            item.date_recently_changed = Some(read_flat(data, &mut data_offset)?);
313        }
314        if flags.contains(bindings::Query2RequestFlags::HIGHLIGHTED_NAME) {
315            item.highlighted_name = Some(read_wstring(data, &mut data_offset)?);
316        }
317        if flags.contains(bindings::Query2RequestFlags::HIGHLIGHTED_PATH) {
318            item.highlighted_path = Some(read_wstring(data, &mut data_offset)?);
319        }
320        if flags.contains(bindings::Query2RequestFlags::HIGHLIGHTED_FULL_PATH_AND_NAME) {
321            item.highlighted_full_path_and_name = Some(read_wstring(data, &mut data_offset)?);
322        }
323        Ok(item)
324    }
325}
326
327/// Parses a complete query result from IPC data.
328///
329/// # Safety
330///
331/// This function is unsafe because:
332/// - It casts raw bytes to IpcList2 structure
333/// - It performs pointer dereferencing without complete validation
334/// - The caller must ensure `data` contains a valid IpcList2 structure
335unsafe fn parse_query_result(id: usize, data: &[u8]) -> Result<QueryResult> {
336    if data.len() < std::mem::size_of::<bindings::IpcList2>() {
337        Err(windows::core::Error::new(
338            ERROR_INVALID_DATA.to_hresult(),
339            "Data too small for IpcQuery2Result",
340        ))?;
341    }
342    // SAFETY: We've verified the buffer is large enough for IpcList2.
343    // The cast is safe because IpcList2 is a packed struct matching the protocol.
344    let ipc_list: &bindings::IpcList2 = unsafe { &*(data.as_ptr() as *const bindings::IpcList2) };
345    if ipc_list.sort_type > bindings::IPC_SORT_MAX as u32 {
346        Err(windows::core::Error::new(
347            ERROR_INVALID_DATA.to_hresult(),
348            "Invalid sort type in IpcQuery2Result",
349        ))?;
350    }
351    let mut offset = std::mem::size_of::<bindings::IpcList2>();
352    let mut items = Vec::with_capacity(ipc_list.numitems as usize);
353
354    let request_flags = bindings::Query2RequestFlags::from_bits_truncate(ipc_list.request_flags);
355
356    for _ in 0..ipc_list.numitems {
357        // SAFETY: parse_query_item is unsafe but we trust the IPC data structure
358        items.push(unsafe { parse_query_item(offset, data, request_flags)? });
359        offset += std::mem::size_of::<bindings::IpcItem2>();
360    }
361
362    Ok(QueryResult {
363        request_id: id,
364        total_items: ipc_list.totitems,
365        num_items: ipc_list.numitems,
366        offset: ipc_list.offset,
367        request_flags,
368        // SAFETY: We've validated sort_type is within valid range
369        sort_type: unsafe { std::mem::transmute(ipc_list.sort_type) },
370        items,
371    })
372}
373
374/// Window procedure for the IPC client window.
375///
376/// Handles WM_COPYDATA messages containing query results from Everything.
377///
378/// # Safety
379///
380/// This is a Windows callback function and must follow the stdcall convention.
381/// It's only called by the Windows message loop with valid parameters.
382unsafe extern "system" fn ipc_window_proc(
383    hwnd: HWND,
384    msg: u32,
385    wparam: WPARAM,
386    lparam: LPARAM,
387) -> LRESULT {
388    match msg {
389        WM_COPYDATA => unsafe {
390            // SAFETY: lparam is a valid pointer to COPYDATASTRUCT when msg is WM_COPYDATA
391            if let Some(copydata) = (lparam.0 as *const COPYDATASTRUCT).as_ref() {
392                // Handle the received data in copydata
393                let request_id = copydata.dwData;
394                let data_slice: &[u8] = core::slice::from_raw_parts(
395                    copydata.lpData as *const u8,
396                    copydata.cbData as usize,
397                );
398                if let Ok(query_result) = parse_query_result(request_id as usize, data_slice) {
399                    let response_map = GetPropW(hwnd, RESPONSE_MAP_PROP).0
400                        as *const Arc<Mutex<HashMap<usize, Arc<OnceLock<QueryResult>>>>>;
401                    if response_map.is_null() {
402                        return LRESULT(0);
403                    }
404                    // SAFETY: response_map was set by SetPropW with a valid Arc pointer
405                    if let Some(map_guard) = (*response_map).lock().ok() {
406                        if let Some(once_lock) = map_guard.get(&(request_id as usize)) {
407                            let _ = once_lock.set(query_result.clone());
408                        }
409                    }
410                    return LRESULT(1);
411                }
412            }
413        },
414        _ => {}
415    }
416    // SAFETY: DefWindowProcW is safe to call for unhandled messages
417    unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
418}
419
420impl EverythingClient {
421    /// Creates a new Everything IPC client.
422    ///
423    /// # Arguments
424    ///
425    /// * `instance_name` - Optional instance name for connecting to a specific Everything instance.
426    ///                     Use `None` for the default instance.
427    ///
428    /// # Errors
429    ///
430    /// Returns an error if:
431    /// - The Everything application is not running
432    /// - Window creation fails
433    /// - The message loop thread fails to start
434    ///
435    /// # Example
436    ///
437    /// ```no_run
438    /// use everything_raw::EverythingClient;
439    ///
440    /// # fn main() -> windows::core::Result<()> {
441    /// let client = EverythingClient::try_new(None)?;
442    /// # Ok(())
443    /// # }
444    /// ```
445    pub fn try_new(instance_name: Option<HSTRING>) -> Result<Self> {
446        // SAFETY: EVERYTHING_IPC_WNDCLASSW is a valid null-terminated wide string constant
447        let ipc_windows_class = unsafe {
448            if let Some(name) = instance_name {
449                // Create IPC window for the specified instance
450                join_hstring(
451                    &[
452                        bindings::EVERYTHING_IPC_WNDCLASSW.as_wide(),
453                        w!("_(").as_wide(),
454                        &*name,
455                        w!(")").as_wide(),
456                    ],
457                    w!("").as_wide(),
458                )
459            } else {
460                bindings::EVERYTHING_IPC_WNDCLASSW.to_hstring()
461            }
462        };
463        let client_hwnd: Arc<OnceLock<usize>> = Arc::new(OnceLock::new());
464        let client_hwnd_clone = client_hwnd.clone();
465        let ipc_window_class_clone = ipc_windows_class.clone();
466        let response_map: Arc<Mutex<HashMap<usize, Arc<OnceLock<QueryResult>>>>> =
467            Arc::new(Mutex::new(HashMap::new()));
468        let response_map_clone = response_map.clone();
469
470        let client_thread = std::thread::spawn(move || unsafe {
471            let client_window_class = w!("EVERYTHING_RUST_CLIENT");
472
473            let curr_module: HINSTANCE = GetModuleHandleW(None).map(|h| h.into())?;
474
475            let mut window_class = WNDCLASSEXW::default();
476            if GetClassInfoExW(Some(curr_module), client_window_class, &mut window_class).is_err() {
477                window_class.cbSize = std::mem::size_of::<WNDCLASSEXW>() as u32;
478                window_class.hInstance = curr_module;
479                window_class.lpszClassName = client_window_class;
480                window_class.lpfnWndProc = Some(ipc_window_proc);
481                RegisterClassExW(&window_class);
482            }
483            // SAFETY: All window creation parameters are valid
484            let hwnd = CreateWindowExW(
485                Default::default(),
486                client_window_class,
487                None,
488                Default::default(),
489                0,
490                0,
491                0,
492                0,
493                None,
494                None,
495                Some(curr_module),
496                None,
497            )?;
498            // SAFETY: Store the response map pointer as a window property
499            SetPropW(
500                hwnd,
501                RESPONSE_MAP_PROP,
502                Some(HANDLE(
503                    &response_map_clone as *const _ as *mut std::ffi::c_void,
504                )),
505            )?;
506            client_hwnd.set(hwnd.0 as usize).map_err(|_| {
507                windows::core::Error::new(
508                    ERROR_LOCK_VIOLATION.to_hresult(),
509                    "Failed to set client HWND",
510                )
511            })?;
512            let ipc_created_msg = RegisterWindowMessageW(w!("EVERYTHING_IPC_CREATED"));
513            let mut ipc_window = FindWindowW(&ipc_window_class_clone, None)?;
514
515            let mut msg = MSG::default();
516
517            // SAFETY: Standard Windows message loop
518            while let ret = GetMessageW(&mut msg, None, 0, 0)
519                && ret.as_bool()
520            {
521                if ret.0 == -1 {
522                    break;
523                }
524                if msg.message == ipc_created_msg {
525                    ipc_window = FindWindowW(&ipc_window_class_clone, None)?;
526                } else if msg.message == WM_APP {
527                    let copydata: *const COPYDATASTRUCT = msg.wParam.0 as *const COPYDATASTRUCT;
528                    // SAFETY: Forward the copydata to the Everything IPC window
529                    SendMessageW(
530                        ipc_window,
531                        WM_COPYDATA,
532                        Some(WPARAM(&hwnd as *const HWND as usize)),
533                        Some(LPARAM(copydata as isize)),
534                    );
535                }
536            }
537            drop(response_map_clone);
538            Ok(())
539        });
540        let client_hwnd = *client_hwnd_clone.wait();
541        let mut client = Self {
542            ipc_hwnd: HWND::default(),
543            ipc_window_class: ipc_windows_class,
544            client_hwnd: HWND(client_hwnd as *mut std::ffi::c_void),
545            _client_thread: client_thread,
546            response_map,
547            max_request_id: Mutex::new(0),
548        };
549        client.refresh_ipc_window()?;
550        Ok(client)
551    }
552
553    /// Refreshes the handle to the Everything IPC window.
554    ///
555    /// Call this if Everything was restarted after the client was created.
556    pub fn refresh_ipc_window(&mut self) -> Result<()> {
557        // SAFETY: FindWindowW is safe to call with valid window class name
558        unsafe {
559            self.ipc_hwnd = FindWindowW(&self.ipc_window_class, None)?;
560            Ok(())
561        }
562    }
563
564    /// Checks if the Everything IPC window is available.
565    pub fn is_ipc_available(&self) -> bool {
566        // SAFETY: IsWindow is safe to call with any HWND
567        unsafe { IsWindow(Some(self.ipc_hwnd)).as_bool() }
568    }
569
570    /// Sends a simple DWORD command to Everything.
571    fn send_ipc_dword(&self, command: bindings::TaskbarIpcCommand, data: usize) -> u32 {
572        // SAFETY: SendMessageW is safe for IPC communication
573        unsafe {
574            SendMessageW(
575                self.ipc_hwnd,
576                bindings::EVERYTHING_WM_IPC,
577                Some(WPARAM(command as usize)),
578                Some(LPARAM(data as isize)),
579            )
580            .0 as u32
581        }
582    }
583
584    /// Gets the major version number of Everything.
585    pub fn get_major_version(&self) -> u32 {
586        self.send_ipc_dword(bindings::TaskbarIpcCommand::GetMajorVersion, 0)
587    }
588
589    /// Gets the minor version number of Everything.
590    pub fn get_minor_version(&self) -> u32 {
591        self.send_ipc_dword(bindings::TaskbarIpcCommand::GetMinorVersion, 0)
592    }
593
594    /// Gets the revision number of Everything.
595    pub fn get_revision(&self) -> u32 {
596        self.send_ipc_dword(bindings::TaskbarIpcCommand::GetRevision, 0)
597    }
598
599    /// Gets the build number of Everything.
600    pub fn get_build_number(&self) -> u32 {
601        self.send_ipc_dword(bindings::TaskbarIpcCommand::GetBuildNumber, 0)
602    }
603
604    /// Gets the target machine architecture of Everything.
605    pub fn get_target_machine(&self) -> TargetMachine {
606        match self.send_ipc_dword(bindings::TaskbarIpcCommand::GetTargetMachine, 0) {
607            1 => TargetMachine::X86,
608            2 => TargetMachine::X64,
609            3 => TargetMachine::ARM,
610            4 => TargetMachine::ARM64,
611            _ => TargetMachine::X86,
612        }
613    }
614
615    /// Gets comprehensive build information from Everything.
616    ///
617    /// Returns a tuple of (major, minor, revision, build, target_machine).
618    pub fn get_build_info(&self) -> (u32, u32, u32, u32, TargetMachine) {
619        (
620            self.get_major_version(),
621            self.get_minor_version(),
622            self.get_revision(),
623            self.get_build_number(),
624            self.get_target_machine(),
625        )
626    }
627
628    /// Returns whether Everything is saving to %APPDATA% or beside the executable.
629    ///
630    /// Availability: Everything 1.4+
631    pub fn is_appdata(&self) -> bool {
632        self.send_ipc_dword(bindings::TaskbarIpcCommand::IsAppdata, 0) != 0
633    }
634
635    /// Requests Everything to rebuild its database immediately.
636    ///
637    /// Availability: Everything 1.4+
638    pub fn rebuild_db(&self) -> bool {
639        self.send_ipc_dword(bindings::TaskbarIpcCommand::RebuildDb, 0) != 0
640    }
641
642    /// Queues a database rebuild in Everything.
643    ///
644    /// Availability: Everything 1.5+
645    pub fn queue_rebuild_db(&self) -> bool {
646        self.send_ipc_dword(bindings::TaskbarIpcCommand::QueueRebuildDb, 0) != 0
647    }
648
649    /// Requests Everything to save its database to disk.
650    ///
651    /// Availability: Everything 1.4+
652    pub fn save_db(&self) -> bool {
653        self.send_ipc_dword(bindings::TaskbarIpcCommand::SaveDb, 0) != 0
654    }
655
656    /// Checks if the Everything database is loaded.
657    ///
658    /// Availability: Everything 1.4+
659    pub fn is_db_loaded(&self) -> bool {
660        self.send_ipc_dword(bindings::TaskbarIpcCommand::IsDbLoaded, 0) != 0
661    }
662
663    /// Checks whether the Everything database is currently busy.
664    ///
665    /// Availability: Everything 1.4+
666    pub fn is_db_busy(&self) -> bool {
667        self.send_ipc_dword(bindings::TaskbarIpcCommand::IsDbBusy, 0) != 0
668    }
669
670    /// Checks if Everything is running with administrator privileges.
671    ///
672    /// Availability: Everything 1.4+
673    pub fn is_admin(&self) -> bool {
674        self.send_ipc_dword(bindings::TaskbarIpcCommand::IsAdmin, 0) != 0
675    }
676
677    /// Requests Everything to update all folder indexes.
678    ///
679    /// Availability: Everything 1.4+
680    pub fn update_all_folder_indexes(&self) -> bool {
681        self.send_ipc_dword(bindings::TaskbarIpcCommand::UpdateAllFolderIndexes, 0) != 0
682    }
683
684    /// Requests Everything to save the run history to disk.
685    ///
686    /// Availability: Everything 1.4+
687    pub fn save_run_history(&self) -> bool {
688        self.send_ipc_dword(bindings::TaskbarIpcCommand::SaveRunHistory, 0) != 0
689    }
690
691    /// Requests Everything to delete ALL run history.
692    ///
693    /// Availability: Everything 1.4+
694    pub fn delete_run_history(&self) -> bool {
695        self.send_ipc_dword(bindings::TaskbarIpcCommand::DeleteRunHistory, 0) != 0
696    }
697
698    /// Checks if fast sorting is enabled in Everything.
699    ///
700    /// Availability: Everything 1.4+
701    pub fn is_fast_sort(&self) -> bool {
702        self.send_ipc_dword(bindings::TaskbarIpcCommand::IsFastSort, 0) != 0
703    }
704
705    /// Checks if a specific file information type is indexed by Everything.
706    ///
707    /// # Arguments
708    ///
709    /// * `info_ty` - The type of file information to check (size, dates, attributes, etc.)
710    ///
711    /// # Availability
712    /// Everything 1.4+
713    pub fn is_file_info_indexed(&self, info_ty: FileInfo) -> bool {
714        self.send_ipc_dword(
715            bindings::TaskbarIpcCommand::IsFileInfoIndexed,
716            info_ty as usize,
717        ) != 0
718    }
719
720    fn send_ipc_copydata(
721        &self,
722        command: bindings::IpcCopyData,
723        ptr: *mut std::ffi::c_void,
724        size: u32,
725    ) -> u32 {
726        let copy_data = COPYDATASTRUCT {
727            dwData: command as usize,
728            cbData: size,
729            lpData: ptr as *mut std::ffi::c_void,
730        };
731        // SAFETY: SendMessageW is safe for IPC communication
732        unsafe {
733            let everything_hwnd = FindWindowW(bindings::EVERYTHING_IPC_WNDCLASSW, None).unwrap();
734            SendMessageW(
735                everything_hwnd,
736                WM_COPYDATA,
737                None,
738                Some(LPARAM(&copy_data as *const _ as isize)),
739            )
740            .0 as u32
741        }
742    }
743
744    /// Gets the run count for a specific filename.
745    pub fn get_run_count_from_filename(&self, filename: impl Param<PCWSTR>) -> u32 {
746        // SAFETY: The pointer and size are valid for the filename parameter
747        unsafe {
748            let filename = filename.param();
749            let size = (filename.borrow().len() + 1) * std::mem::size_of::<u16>(); // Include null terminator
750            self.send_ipc_copydata(
751                bindings::IpcCopyData::GetRunCountW,
752                filename.borrow().as_ptr() as *mut _,
753                size as u32,
754            )
755        }
756    }
757
758    /// Increments the run count for a specific filename.
759    ///
760    /// Returns true if the operation was successful.
761    pub fn inc_run_count_from_filename(&self, filename: impl Param<PCWSTR>) -> bool {
762        // SAFETY: The pointer and size are valid for the filename parameter
763        unsafe {
764            let filename = filename.param();
765            let size = (filename.borrow().len() + 1) * std::mem::size_of::<u16>(); // Include null terminator
766            self.send_ipc_copydata(
767                bindings::IpcCopyData::IncRunCountW,
768                filename.borrow().as_ptr() as *mut _,
769                size as u32,
770            ) != 0
771        }
772    }
773
774    /// Sets the run count for a specific filename.
775    ///
776    /// Returns true if the operation was successful.
777    pub fn set_run_count_from_filename(
778        &self,
779        filename: impl Param<PCWSTR>,
780        run_count: u32,
781    ) -> bool {
782        // SAFETY: The pointer and size are valid for the filename parameter
783        unsafe {
784            let filename = filename.param();
785            let size = filename.borrow().len() + 1; // Include null terminator
786            let run_history_struct = bindings::IpcRunHistory { run_count };
787            let mut buffer: Vec<u8> = Vec::with_capacity(
788                std::mem::size_of_val(&run_history_struct) + size * std::mem::size_of::<u16>(),
789            );
790            let filename_bytes: *const u8 = filename.borrow().as_ptr() as *const u8;
791            buffer.extend_from_slice(std::slice::from_raw_parts(
792                &run_history_struct as *const _ as *const u8,
793                std::mem::size_of_val(&run_history_struct),
794            ));
795            buffer.extend_from_slice(std::slice::from_raw_parts(
796                filename_bytes,
797                size * std::mem::size_of::<u16>(),
798            ));
799            self.send_ipc_copydata(
800                bindings::IpcCopyData::SetRunCountW,
801                buffer.as_mut_ptr() as *mut _,
802                buffer.len() as u32,
803            ) != 0
804        }
805    }
806
807    /// Executes a query and waits for the result.
808    ///
809    /// This method sends the query to Everything via IPC and blocks until the result
810    /// is received. The query is processed asynchronously by the message loop thread.
811    ///
812    /// # Arguments
813    ///
814    /// * `request` - The query parameters including search string, flags, and options
815    ///
816    /// # Returns
817    ///
818    /// Returns a `QueryResult` containing matching items and metadata.
819    ///
820    /// # Errors
821    ///
822    /// Returns an error if:
823    /// - The request could not be sent to Everything
824    /// - The internal state locks are poisoned
825    ///
826    /// # Example
827    ///
828    /// ```no_run
829    /// use everything_raw::{EverythingClient, QueryInfo, RequestFlags};
830    ///
831    /// # fn main() -> windows::core::Result<()> {
832    /// let client = EverythingClient::try_new(None)?;
833    /// let query = QueryInfo::new("*.pdf")
834    ///     .request_flag(RequestFlags::NAME | RequestFlags::PATH)
835    ///     .max_results(10);
836    /// let result = client.query(&query)?;
837    /// # Ok(())
838    /// # }
839    /// ```
840    pub fn query(&self, request: &QueryInfo) -> Result<QueryResult> {
841        let request_id = {
842            let mut guard = self.max_request_id.lock().map_err(|_| {
843                windows::core::Error::new(
844                    ERROR_LOCK_VIOLATION.to_hresult(),
845                    "Failed to lock max_request_id",
846                )
847            })?;
848            *guard += 1;
849            *guard
850        };
851        let payload = bindings::IpcQuery2 {
852            reply_hwnd: self.client_hwnd.0 as u32,
853            reply_copydata_message: request_id,
854            search_flags: request.search_flags.bits(),
855            request_flags: request.request_flags.bits(),
856            sort_type: request.sort as u32,
857            offset: request.offset,
858            max_results: request.max_results,
859        };
860        let mut buf: Vec<u8> = Vec::with_capacity(
861            std::mem::size_of::<bindings::IpcQuery2>()
862                + (request.search.len() * std::mem::size_of::<u16>())
863                + std::mem::size_of::<u16>(),
864        );
865        // SAFETY: We're carefully constructing a valid IPC message buffer
866        unsafe {
867            let payload_ptr: *const bindings::IpcQuery2 = &payload;
868            let payload_bytes: *const u8 = payload_ptr as *const u8;
869            buf.extend_from_slice(std::slice::from_raw_parts(
870                payload_bytes,
871                std::mem::size_of::<bindings::IpcQuery2>(),
872            ));
873            let search_wide: &[u16] = &request.search;
874            let search_bytes: *const u8 = search_wide.as_ptr() as *const u8;
875            buf.extend_from_slice(std::slice::from_raw_parts(
876                search_bytes,
877                search_wide.len() * std::mem::size_of::<u16>(),
878            ));
879            // Null terminator
880            buf.extend_from_slice(&[0u8; 2]);
881            let copy_data = COPYDATASTRUCT {
882                dwData: bindings::IpcCopyData::Query2W as usize,
883                cbData: buf.len() as u32,
884                lpData: buf.as_ptr() as *mut std::ffi::c_void,
885            };
886            PostMessageW(
887                Some(self.client_hwnd),
888                WM_APP,
889                WPARAM(&copy_data as *const _ as usize),
890                LPARAM(0),
891            )?;
892            let once_lock: Arc<OnceLock<QueryResult>> = Arc::new(OnceLock::new());
893            {
894                let mut map_guard = self.response_map.lock().map_err(|_| {
895                    windows::core::Error::new(
896                        ERROR_LOCK_VIOLATION.to_hresult(),
897                        "Failed to lock response_map",
898                    )
899                })?;
900                map_guard.insert(request_id as usize, once_lock.clone());
901            };
902            drop(buf);
903            // Wait for the response to arrive and return it
904            Ok(once_lock.wait().clone())
905        }
906    }
907}
908
909impl Drop for EverythingClient {
910    /// Cleanup: sends WM_QUIT to the message loop thread and destroys the client window.
911    fn drop(&mut self) {
912        // SAFETY: These Win32 API calls are safe for cleanup
913        unsafe {
914            PostMessageW(Some(self.client_hwnd), WM_QUIT, WPARAM(0), LPARAM(0)).ok();
915            RemovePropW(self.client_hwnd, RESPONSE_MAP_PROP).ok();
916            DestroyWindow(self.client_hwnd).ok();
917        }
918    }
919}