Skip to content

Local, full Windows search replacement, clipboard manager, and launcher: files, apps, settings and semantic media search with Google's EmbeddingGemma 2.

Release VectorDash 0.3.8 with saved searches and native window fixes

ampersandrua0b419844210
diff --git a/Build-Rust.ps1 b/Build-Rust.ps1
index 591998a..74a1140 100644
--- a/Build-Rust.ps1
+++ b/Build-Rust.ps1
@@ -75,8 +75,8 @@ if (Test-Path $taskPortable) { throw 'Portable staging directory already exists.
New-Item -ItemType Directory -Force $taskPortable | Out-Null
Get-ChildItem -LiteralPath $taskBundle | Copy-Item -Destination $taskPortable -Recurse -Force
Set-Content -LiteralPath (Join-Path $taskPortable 'portable.flag') -Value '' -Encoding ascii
-Compress-Archive -Path (Join-Path $taskPortable '*') -DestinationPath 'dist/installer/VectorDash-Rust-0.3.5-x64.zip' -Force
-$taskInstaller='dist/installer/VectorDash-Rust-Setup-0.3.5-x64.exe'
-$taskZip='dist/installer/VectorDash-Rust-0.3.5-x64.zip'
+Compress-Archive -Path (Join-Path $taskPortable '*') -DestinationPath 'dist/installer/VectorDash-Rust-0.3.8-x64.zip' -Force
+$taskInstaller='dist/installer/VectorDash-Rust-Setup-0.3.8-x64.exe'
+$taskZip='dist/installer/VectorDash-Rust-0.3.8-x64.zip'
@($taskInstaller,$taskZip) | ForEach-Object {((Get-FileHash -LiteralPath $_ -Algorithm SHA256).Hash.ToLowerInvariant()+' '+(Split-Path $_ -Leaf))} | Set-Content 'dist/installer/RUST-SHA256SUMS.txt' -Encoding ascii
Write-Output "Native installer and portable ZIP ready."
diff --git a/README.md b/README.md
index 1baa62e..69ba308 100644
--- a/README.md
+++ b/README.md
@@ -1,41 +1,108 @@
# VectorDash
-**A local Windows 11 search replacement and launcher powered by EmbeddingGemma 2. Built in Rust.**
+**A local, universal search and launcher for Windows 11. Built in Rust.**
-## What it does
+VectorDash is meant to be a **full Windows search replacement**: one search bar for files and folders, installed apps, Windows settings, and quick calculations. Press **Ctrl+Shift+Space** from any app to find what you need.
-- **Quick indexing:** find files and folders across whole drives without loading a model.
-- **Full indexing:** search the meaning of documents, pictures, screenshots, audio and video; jump to matching pages or moments. Nested Full folders override Quick drives.
-- Launch **apps and Windows settings**, or calculate directly in search.
-- A global shortcut opens quick search with previews, file/source filters and familiar keyboard actions. Double Ctrl also works in Explorer and standard Open/Save dialogs.
-- Optional **automatic change indexing** and scheduled scans respect your idle limits. Pause/cancel indexing, reuse unchanged content and inspect the **File log**.
-- Choose CPU, GPU or iGPU, install optional tools, and unload idle models automatically. Names search stays model-free; semantic searches load the model on demand.
-- Customize light/dark themes and the translucent popup. One **Save / Undo** bar handles settings changes; **About** includes updates and changelogs.
-- Optional read-only **MCP server**, bearer authentication and LAN access. The on-disk index is encrypted by default; performance profiles balance memory and speed.
+Search by name or exact words, or describe what you remember. Google's **EmbeddingGemma 2** powers semantic file and media search. Filename search, app launching, settings shortcuts and the calculator work without a model.
-Measured warm searches on a copied million-file index: about **10 ms names / 30 ms semantic** in Balanced mode with encryption and a warm GPU model. Empty UI measured about **115 MiB**, excluding models and helpers. Startup, cold queries and your files/hardware affect results. [Measurements](native/docs/BENCHMARKS.md).
+<img width="1129" height="629" alt="image" src="https://github.com/user-attachments/assets/a3aa357e-a333-4d44-938e-f9cf3861ddc6" />
+
+<img width="1120" height="626" alt="image" src="https://github.com/user-attachments/assets/439fd438-d4e0-477a-ba30-676509e6fb24" />
+
+<img width="1193" height="881" alt="image" src="https://github.com/user-attachments/assets/7f431693-1b7a-4864-aecb-87b05c30c667" />
+
+
+## What you can search
+
+| Search for | Example | What happens |
+| --- | --- | --- |
+| **Files and folders** | `invoice`, `forzahorizon6.exe` | Find names and paths across your selected drives and folders. |
+| **File contents** | `a dog on the beach`, `the clause about pets` | Find matching photos, screenshots, document passages, PDF pages, or audio/video moments. |
+| **Apps** | `chrome`, `app: calculator` | Launch Start menu programs and Windows apps, with their actual icons in results and previews. |
+| **Windows settings** | `bluetooth`, `settings: sound` | Open settings pages such as Wi-Fi, display, storage, sound and Windows Update. |
+| **Calculations** | `24*1.2`, `20% of 150`, `sqrt(81)` | Get an instant local answer; press **Enter** to copy it. |
+
+- **File search:** combine names, exact words and semantic matches. Read PDF, Word, Excel and PowerPoint content; optionally use OCR for screenshot text. Search across 100+ languages and opt into code search.
+- **Quick search and previews:** a frosted popup with adjustable color, transparency and gradient. It stays compact until you type. Preview results, inspect why they matched, and open, copy or reveal files in Explorer.
+- **Your sources, your choice:** index names only for fast drive-wide search, or fully index selected folders. Nested Full folders override Quick drives. Select multiple search sources, exclude files/types or common Windows cache folders, and see Full/Quick counts and recent additions.
+- **Advanced and saved searches:** combine filenames, wildcards, size and dates, such as name:dog*.jpg size:>1MB or ext:pdf modified:today. Save queries together with their modes, sources and exclusions; rename or remove them in Settings.
+- **Automatic updates:** monitor new, modified and removed files, or schedule scans. Automatic changes obey CPU/GPU, inactivity and power conditions even when periodic scanning is Manual. Optional NTFS journal tracking replays saved changes when volume access is available; folder notifications and recovery scans provide fallback. Pause/cancel indexing and inspect VectorDash, model and File logs.
+- **Flexible setup:** choose GPU, iGPU or CPU/system memory; install selected optional features or remove downloaded tools. Models load only when needed and can unload automatically after an adjustable idle period. Optional remote llama-server and read-only [MCP access for agents](docs/MCP.md), with bearer authentication and LAN access.
+- **Make it yours:** light/dark themes, app accent colors, popup tint/transparency/gradient, a collapsible icon sidebar, and one red Save / outlined Undo bar for settings. About includes updates and a changelog covering releases since your installed version.
## Install
-Download the **setup EXE or portable ZIP** from [the latest release](https://github.com/ampersandru/VectorDash/releases/latest). **The EXE is unsigned:** Windows may show SmartScreen or an unknown-publisher warning.
+1. Download the latest **Windows x64 setup EXE** from [Releases](https://github.com/ampersandru/VectorDash/releases) (about **97 MB**), or the **portable ZIP**. Python is not required.
+2. Run the installer. **The EXE is not code-signed**, so Windows may show a SmartScreen or unknown-publisher warning. If you trust the release, choose **More info → Run anyway**, when available, to continue.
+3. **Optional semantic search:** open **Models & hardware → Status**, select features, hardware and model, then click **Download, install and start**. **Q8_0** is the default. For names-only search, skip model setup and select Quick mode in Sources. The calculator and Windows settings shortcuts are ready immediately.
+4. Add folders or drives in **Sources**, then click **Update index**. Start with a small folder to check results.
+
+Enable **Include Start menu programs** in Sources to search installed program shortcuts. The catalog loads at startup. Select a result and press **Enter** to launch its original shortcut, preserving arguments and working folders.
+
+**File/Folder Names** search needs no model. In **Sources**, choose **Quick file / folder names** or **Full index** before adding drives, folders or files. To change existing sources, select entries (or **Select/Deselect all**) and apply a mode, then update the index. In either search window, choose **Both**, **File/Folder Names** or **Semantic**, and use the source dropdown to search some or all sources. More specific folders take priority when sources overlap. Index status shows Full/Quick file counts and how many files have vectors. Enable **Skip Windows system and frequently changing cache folders** in Sources to omit temp files, crash dumps, update staging and selected caches while keeping personal folders and Program Files.
+
+Semantic search needs the model and a compatible llama-server. Image/audio search also needs its matching encoder. You can select existing files instead of downloading them. Changing the model or encoder requires rebuilding the index once.
+
+| Shortcut | Action |
+| --- | --- |
+| **Ctrl+Shift+Space** | Open quick search; change this in Settings |
+| **Space** | Open/close the larger preview |
+| **Enter** | Open a file, launch an app, open settings, or copy a calculator answer |
+| **Ctrl+C** | Copy the selected file, calculator answer or settings link |
+| **Tab / Shift+Tab** | Cycle file categories without moving typing focus |
+| **↑ / ↓** | Select results and scroll the list |
+| **Ctrl+F** | Return to search from settings |
+| **Double Ctrl** | Open quick search in Explorer or a standard Open/Save dialog when enabled |
+
+## Models and tools
+
+Approximate sizes vary by release. Model sizes are individual files; runtime sizes are compressed downloads. Installed files, the index and RAM/VRAM use require additional space.
+
+| [EmbeddingGemma 2](https://huggingface.co/ggml-org/embeddinggemma-2-GGUF) | Text model | Matching image/audio encoder (mmproj) |
+| --- | --- | --- |
+| **Q8_0** — default | 310 MB | 555 MB |
+| **BF16** | 558 MB | 982 MB |
+
+| Tool | What it does | Approx. size |
+| --- | --- | --- |
+| [llama.cpp / llama-server](https://github.com/ggml-org/llama.cpp) — CPU | Runs the model using system memory | 20 MB |
+| llama-server — Vulkan | GPU/iGPU inference with compatible drivers | 32 MB |
+| llama-server — CUDA | NVIDIA GPU inference, including companion runtime | 577–657 MB |
+| [Tesseract OCR](https://github.com/UB-Mannheim/tesseract/wiki) — optional | Reads exact words in screenshots and scanned PDFs | 50 MB |
+| [OCR language packs](https://github.com/tesseract-ocr/tessdata_fast) — optional | Enables OCR for selected languages | English 4 MB |
+| [FFmpeg / FFprobe / FFplay](https://ffmpeg.org/) | Extracts media frames/audio and plays matched moments; bundled | About 150 MB unpacked |
+| [PDFium](https://pdfium.googlesource.com/pdfium/) | PDF extraction and page previews; bundled | About 10–25 MB |
+
+Install only the runtime for your hardware. OCR is optional for image meaning searches; it helps with exact text. FFmpeg and the encoder are needed for media processing.
+
+**Download trouble?** Setup caches official catalogs and retries temporary failures. Rate-limit messages identify GitHub (runtimes) or Hugging Face (models) and suggest when to retry. Optional **GitHub / Hugging Face download tokens** are in **Models & hardware → Download and set up**; save them before retrying. They are protected by your Windows account and sent only to their own service. Interrupted downloads retain partial files for resume, and checksums are still required. You can also select an existing runtime/model manually.
+
+
+## Performance
+
+The database and filename catalog stay on disk. Background indexing uses bounded memory and reuses unchanged files. Each source shows its indexed file count and new additions in the past hour.
+
+Choose **Settings → Search performance**:
+
+| Profile | Search cache limits | Best for |
+| --- | --- | --- |
+| **Low memory** | 8 MiB of database pages per search; vectors streamed from disk | Lowest RAM use |
+| **Balanced** — default | 32 MiB of pages per search; up to 128 MiB of compact vectors total | Fast everyday search |
+| **Fast search** | 64 MiB of pages per search; up to 512 MiB of compact vectors total | Larger semantic indexes |
+
+On a development NVMe test with **1,076,786 files** and **14,123 vectors**, encrypted Balanced searches measured about **9 ms for warm filename searches**, **32 ms for warm semantic retrieval**, and **47 ms for Both**. These are backend timings with warm disk caches and an already loaded GPU model; cold model loading, UI delay and hardware add time. An empty native GUI measured about **115 MiB**, excluding model/helper memory. See [all native profiles, encryption on/off, indexing measurements and limitations](native/docs/BENCHMARKS.md).
-Add sources as Quick or Full, then choose **Models & hardware** for semantic features. Enable automatic change indexing in **Scheduling**, and click the red **Save** button. Notifications work on readable NTFS and exFAT folders while VectorDash is running; recovery scans catch missed changes. No persistent USN journal replay is implemented yet.
+One- and two-character name searches use filename prefixes; longer queries also match substrings. Broad searches return a bounded selection of best candidates. Cache limits are caps, not reserved memory; models and active file-processing helpers use additional RAM/VRAM.
-Existing Rust installations keep their settings/index. Older Python users can import a **copy** of their index in Sources. Portable data is stored beside the EXE; encryption is tied to your Windows account/machine. Conversion retains the original database, including any plaintext copy.
+**Database encryption** is enabled by default. Settings lets you change it and explains the performance tradeoff. Encryption protects stored filenames, extracted text and embeddings but adds processing overhead. Changing it creates a converted database copy without re-embedding; the original is retained, including any plaintext copy. Portable encrypted data is tied to your Windows account/machine. Existing Rust installations retain their settings/index; older Python users can import a copy through Sources.
-## Optional tools
+## Privacy and limitations
-Approximate download sizes vary by release and quantization.
+Local mode keeps indexed content on your computer; setup downloads need internet access. A remote model server receives the content sent for embedding. Enable LAN/MCP access only for trusted clients. See [security details](docs/SECURITY.md).
-| Model/tool | Purpose | Approximate size |
-|---|---|---|
-| EmbeddingGemma 2 GGUF | Semantic query and document embeddings | About 310 MB Q8 / 558 MB BF16 |
-| Matching mmproj GGUF | Image/audio/video encoder for the same model | About 555 MB Q8 / 982 MB BF16 |
-| llama-server | Runs the model on CPU, CUDA or Vulkan | Hundreds of MB; backend-dependent |
-| Tesseract OCR + language data | Exact words inside screenshots/images | About 50–150 MB |
-| FFmpeg / FFprobe / FFplay | Media extraction and playback; bundled | About 150 MB unpacked |
-| PDFium | PDF extraction/page preview; bundled | About 10–25 MB |
+AI search can miss or misrank results. OCR can misread text, and sampled video/audio matches give approximate moments. Check original files before relying on a result. VectorDash was developed with AI assistance.
-[Supported files](docs/RETRIEVAL.md#file-coverage) · [Security](docs/SECURITY.md) · [Build and migration](native/docs/MIGRATION.md)
+[File support](docs/RETRIEVAL.md) · [MCP setup](docs/MCP.md) · [Build from source and migration](native/docs/MIGRATION.md)
-AI search may miss or misrank matches. Developed with AI assistance. Independent project inspired by [DigUp](https://github.com/ARahim3/DigUp); [credits](ACKNOWLEDGEMENTS.md). [MIT license](LICENSE).
+VectorDash is an independent Windows project inspired by [DigUp](https://github.com/ARahim3/DigUp), created by Abdur Rahim. See [acknowledgements](ACKNOWLEDGEMENTS.md). Licensed under [MIT](LICENSE).
diff --git a/docs/SECURITY.md b/docs/SECURITY.md
index 3c9a7d3..4f43f7a 100644
--- a/docs/SECURITY.md
+++ b/docs/SECURITY.md
@@ -4,7 +4,7 @@ This is an implementation review and a set of regression checks, not an independ
## Index and credentials
-Application/model logs and the optional File log are ordinary local text files, separate from the encrypted index. They can contain filenames, paths and processing errors. The File log rotates at approximately 8 MiB and retains one previous file; avoid sharing logs without reviewing them.
+Application/model/playback logs and the optional File log are ordinary local text files, separate from the encrypted index. Saved-search labels/queries are stored in local settings; NTFS cursor state stores source configuration and journal positions. They can contain filenames, paths and processing errors. The File log rotates at approximately 8 MiB and retains one previous file; avoid sharing logs without reviewing them.
The search index is a disk-backed SQLite database. Encryption is enabled by default: SQLCipher encrypts database pages and the WAL, and the random database key is protected by your Windows account using DPAPI. Names, paths, extracted text, OCR, FTS content and embeddings are covered together. Connections use bounded page caches with memory mapping disabled; temporary scan/replacement databases are encrypted separately. Small SQLite sort buffers, current results and query vectors use memory. Low memory mode streams indexed vectors from disk. Balanced and Fast search optionally retain compact vector matrices within explicit 128 MiB / 512 MiB total limits; larger matrices fall back to streaming. The full database and filename catalog are not loaded into the process. Cached vectors and selected excerpts remain readable in process memory while the app is unlocked.
diff --git a/native/Cargo.lock b/native/Cargo.lock
index e133e9c..aa97370 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -4478,7 +4478,7 @@ checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "vectordash"
-version = "0.3.5"
+version = "0.3.8"
dependencies = [
"anyhow",
"base64 0.22.1",
diff --git a/native/Cargo.toml b/native/Cargo.toml
index a9e57ea..3aa8c16 100644
--- a/native/Cargo.toml
+++ b/native/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "vectordash"
-version = "0.3.5"
+version = "0.3.8"
edition = "2024"
license = "MIT"
[dependencies]
@@ -33,7 +33,7 @@ zip = { version = "4", default-features = false, features = ["deflate"] }
[build-dependencies]
embed-resource = "3"
[target.'cfg(windows)'.dependencies]
-windows = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Cryptography", "Win32_System_Memory", "Win32_System_Threading", "Win32_System_JobObjects", "Win32_System_Com", "Win32_System_Ole", "Win32_System_Variant", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging", "Win32_UI_Controls", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_Shell_Common", "Win32_UI_Accessibility", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Performance", "Win32_System_Power", "Win32_System_ProcessStatus", "Win32_System_DataExchange", "Win32_System_SystemInformation", "Win32_Graphics_Gdi", "Win32_Graphics_Dwm", "Win32_Security_Authorization", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock"] }
+windows = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Cryptography", "Win32_System_Memory", "Win32_System_Threading", "Win32_System_JobObjects", "Win32_System_Com", "Win32_System_Ole", "Win32_System_Variant", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging", "Win32_UI_Controls", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_Shell_Common", "Win32_UI_Accessibility", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_Performance", "Win32_System_Power", "Win32_System_ProcessStatus", "Win32_System_DataExchange", "Win32_System_SystemInformation", "Win32_Graphics_Gdi", "Win32_Graphics_Dwm", "Win32_Security_Authorization", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock"] }
[dev-dependencies]
tempfile = "3"
[profile.release]
diff --git a/native/docs/0.3.6.md b/native/docs/0.3.6.md
new file mode 100644
index 0000000..bc9483d
--- /dev/null
+++ b/native/docs/0.3.6.md
@@ -0,0 +1,14 @@
+# VectorDash 0.3.6
+
+- Automatic file-change indexing obeys idle conditions even with periodic scanning set to Manual. Scheduling now explains the difference.
+- Optional NTFS journal replay reads bounded buffers and commits a cursor only after a successful update. Valid saved cursors can replace startup recovery scanning when every source is covered. Expired/replaced journals, unresolved parents, unsupported drives and denied volume access fall back to folder notifications and recovery. No journal is created or reset; no automatic elevation occurs. Fast initial MFT enumeration is not implemented in this phase.
+- Search modes are Both, File/Folder Names and Semantic. Sources is a multi-selection menu with All sources first; inference reuses one short-lived query vector across selected sources.
+- Filename wildcards/name filters, extension lists, size comparisons and local modified-date filters. Examples: `dog*.jpg size:>1MB`, `report ext:pdf modified:>=2026-10-01`, `ext:pdf modified:today`. Metadata filters are applied before semantic candidate limits.
+- Save searches including query, mode, types, source selection and exclusions; rename/remove them in Settings.
+- Ctrl+F and Back to search return from settings. Tab/Shift+Tab cycle types, highlight the selector and retain input focus.
+- Dark slider tint/track improvements; popup material no longer extends an extra rectangular frame outside its clipped client region. DigUp text removed from About; license/README acknowledgements retained.
+- Audio-only playback disables video/album-art display. Playback errors, including a player exiting successfully while reporting an error, become visible in app logs. Starting playback replaces the previous player, Stop/Exit terminate it, and status reports playback progress/completion.
+
+Validation: 65 regression tests passed, including filename/size/date predicates before result limits, metadata-filtered semantic search in Balanced/Low memory, multi-source unions, saved-search serialization, USN record validation and successful-batch-only checkpoint commits, plus automatic indexing with Manual scheduling and idle gates. Live volume access and media/UI checks are recorded separately.
+
+Live checks: standard-user access to C: journal was denied and G: exFAT returned unsupported; fallback remained available. Full live privileged journal replay remains unverified in this environment. Production WAV/MP3 tests seeked to one second, completed playback and reported no errors; a missing-file control correctly returned a visible diagnostic. Actual Windows input confirmed Tab changed the file type, highlighted it, and subsequent typing stayed in the search field. Light popup clipping and source-menu layout were inspected.
diff --git a/native/docs/0.3.7.md b/native/docs/0.3.7.md
new file mode 100644
index 0000000..ce94254
--- /dev/null
+++ b/native/docs/0.3.7.md
@@ -0,0 +1,16 @@
+# 0.3.7 preview
+- Tab and Shift+Tab cycle file types without moving focus into saved searches.
+- Saved searches and Save search share the search-filter row.
+- Popup dragging starts directly from the search icon.
+- Model process shutdown runs on a background thread.
+- File-monitor logs show queued paths, recovery scans, debounce, and idle blocking. Focused UI stalls over one second are logged.
+
+## Testing automatic changes and the NTFS journal
+Enable Automatically index changed files and folders in Scheduling and save. Optionally enable NTFS journal tracking. Watch Schedule status: it reports the number of accessible journals, queued work, and any idle condition blocking updates. Create a uniquely named file in an included source, wait for the 10-second debounce and configured idle conditions, then search its exact filename. Modify it and check File logs for the targeted update.
+
+Journal tracking requires NTFS, an existing active USN journal, and permission to read the volume journal. The app does not create journals or request elevation. If unavailable, recursive Windows folder notifications remain active, including on exFAT. Startup catch-up and notification overflow recovery scans cover missed changes; periodic scans follow the selected schedule. All automatic change updates still obey idle conditions in Manual mode. Both Quick and Full sources are monitored; unsupported Full-source content is still indexed by filename.
+
+A zero journal count means the fallback is active, not that journal replay has been verified. This build's real Windows test covers notification fallback with the journal option enabled; privileged journal replay still needs testing on an accessible active journal.
+
+## Validation
+65 tests passed. Actual Windows notification fallback on H: detected new executable names and new/modified full-index text, with two mock embedding calls. Four-second startup tests returned filename results in both windows: 113/115 frames and maximum frame gaps 175/227 ms under high system load. This does not reproduce or prove the cause of the previously reported transient first-launch freeze.
diff --git a/native/docs/0.3.8.md b/native/docs/0.3.8.md
new file mode 100644
index 0000000..645d1cb
--- /dev/null
+++ b/native/docs/0.3.8.md
@@ -0,0 +1,15 @@
+# VectorDash 0.3.8
+- Main-title and popup-search-icon drag regions are recognized by native Windows hit testing, independent of UI frame timing.
+- Saved-search controls are anchored to the right side of the filter row.
+- UI tests have a background exit deadline, including while hidden, and exit explicitly instead of relying on normal close behavior.
+- Removed three stale isolated QA processes. These used separate temporary test data, not the live user index.
+
+## Enable an NTFS journal
+In an Administrator terminal, first run fsutil usn queryjournal H:. If the journal is inactive, run fsutil usn createjournal m=67108864 a=8388608 H: and query again. This example uses a 64 MiB target with an 8 MiB allocation delta; Windows may temporarily exceed those sizes. Use a drive letter, not a folder path. Do not recreate an existing active journal unnecessarily.
+
+Enable automatic changes and NTFS journal tracking in Scheduling, save, and restart VectorDash so volume availability is reprobed. Read access to the volume is also required: creating a journal does not solve Access denied. This release has no privileged journal service. Folder notifications remain the fallback and automatic updates continue to obey idle conditions. exFAT does not support USN journals.
+
+Reference: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/fsutil-usn
+
+## Validation
+Real desktop drag tests moved the main window by 140/70 pixels and the popup by 141/70 pixels. Saved-search controls were visually confirmed at the right edge. Timed tests exited with code 0; hidden tests now have a background exit deadline. 65 regression tests passed. Setup and portable packages match the verified binary and exclude private settings/index/model data.
diff --git a/native/src/app.rs b/native/src/app.rs
index b92e285..d752000 100644
--- a/native/src/app.rs
+++ b/native/src/app.rs
@@ -51,6 +51,7 @@ pub struct App {
category: String,
scope: String,
scope_indexed: Option<bool>,
+ type_flash: Option<Instant>,
logo: egui::TextureHandle,
exclude_types: String,
hits: Vec<Hit>,
@@ -225,6 +226,7 @@ impl App {
category: "All files".into(),
scope: String::new(),
scope_indexed: None,
+ type_flash: None,
logo: {
let image =
image::load_from_memory(include_bytes!("../assets/vectordash.png"))?.to_rgba8();
@@ -357,6 +359,15 @@ impl App {
app.large_preview = true;
}
}
+ if app.smoke.is_some() {
+ // Hidden popups may stop receiving frames; use a background deadline.
+ let tx = app.engine.tx.clone();
+ let timeout = app.smoke_seconds.saturating_add(2);
+ std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_secs(timeout));
+ let _ = tx.send(Event::Quit);
+ });
+ }
if app.s.mcp_enabled {
app.apply_mcp();
}
@@ -727,7 +738,10 @@ impl App {
self.hits.clear();
self.dirty = true;
self.changed = Instant::now();
- ctx.memory_mut(|m| m.request_focus(egui::Id::new("query")));
+ ctx.memory_mut(|m| {
+ m.move_focus(egui::FocusDirection::None);
+ m.request_focus(egui::Id::new("query"));
+ });
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(
@@ -922,10 +936,24 @@ impl App {
)
.sense(egui::Sense::click_and_drag()),
);
- if response.is_pointer_button_down_on()
- && ctx.input(|i| i.pointer.any_pressed())
+ crate::platform::add_drag_region(
+ [
+ response.rect.min.x,
+ response.rect.min.y,
+ response.rect.max.x,
+ response.rect.max.y,
+ ],
+ ctx.pixels_per_point(),
+ );
+ if response.drag_started()
+ || ctx.input(|i| {
+ i.pointer.primary_pressed()
+ && i.pointer
+ .interact_pos()
+ .is_some_and(|p| response.rect.contains(p))
+ })
{
- ctx.send_viewport_cmd(egui::ViewportCommand::StartDrag);
+ crate::platform::drag_main_window();
}
if !self.quick
&& ui
@@ -942,15 +970,36 @@ impl App {
{
self.collapsed = !self.collapsed;
}
+ if !self.quick
+ && self.page != 0
+ && ui.button("Back to search · Ctrl+F").clicked()
+ {
+ self.page = 0;
+ ctx.memory_mut(|m| m.request_focus(egui::Id::new("query")));
+ }
let reserve = if self.quick { 220.0 } else { 112.0 };
let (_, response) = ui.allocate_exact_size(
egui::vec2((ui.available_width() - reserve).max(0.0), 30.0),
egui::Sense::click_and_drag(),
);
- if response.is_pointer_button_down_on()
- && ctx.input(|i| i.pointer.any_pressed())
+ crate::platform::add_drag_region(
+ [
+ response.rect.min.x,
+ response.rect.min.y,
+ response.rect.max.x,
+ response.rect.max.y,
+ ],
+ ctx.pixels_per_point(),
+ );
+ if response.drag_started()
+ || ctx.input(|i| {
+ i.pointer.primary_pressed()
+ && i.pointer
+ .interact_pos()
+ .is_some_and(|p| response.rect.contains(p))
+ })
{
- ctx.send_viewport_cmd(egui::ViewportCommand::StartDrag);
+ crate::platform::drag_main_window();
}
if response.double_clicked() && !self.quick {
let maximized = ctx.input(|i| i.viewport().maximized.unwrap_or(false));
@@ -1022,12 +1071,32 @@ impl App {
crate::icons::image(crate::icons::Icon::Search, self.accent(), 26.0)
.sense(egui::Sense::drag()),
);
- if self.quick && drag.drag_started() {
- ctx.send_viewport_cmd(egui::ViewportCommand::StartDrag);
+ if self.quick {
+ crate::platform::add_drag_region(
+ [
+ drag.rect.min.x,
+ drag.rect.min.y,
+ drag.rect.max.x,
+ drag.rect.max.y,
+ ],
+ ctx.pixels_per_point(),
+ );
+ }
+ if self.quick
+ && (drag.drag_started()
+ || ctx.input(|i| {
+ i.pointer.primary_pressed()
+ && i.pointer
+ .interact_pos()
+ .is_some_and(|p| drag.rect.contains(p))
+ }))
+ {
+ crate::platform::drag_main_window();
}
let response = ui.add_sized(
[ui.available_width(), 42.0],
egui::TextEdit::singleline(&mut query)
+ .lock_focus(true)
.hint_text("Search Anything")
.font(egui::TextStyle::Heading)
.id(egui::Id::new("query")),
@@ -1046,42 +1115,132 @@ impl App {
self.scope.clone(),
self.exclude_types.clone(),
);
- ui.horizontal_wrapped(|ui| {
+ ui.horizontal(|ui| {
combo(
ui,
"search_mode",
&mut self.mode,
- &["Names", "Semantic", "Both"],
+ &["Both", "Names", "Semantic"],
);
- combo(ui, "category", &mut self.category, &CATEGORIES);
+ let response = combo(ui, "category", &mut self.category, &CATEGORIES);
+ if self
+ .type_flash
+ .is_some_and(|t| t.elapsed() < Duration::from_millis(700))
+ {
+ ui.painter().rect_stroke(
+ response.rect.expand(1.0),
+ 9.0,
+ egui::Stroke::new(2.0, self.accent()),
+ egui::StrokeKind::Outside,
+ );
+ }
+ let mut scopes: Vec<String> = if self.scope.starts_with('[') {
+ serde_json::from_str(&self.scope).unwrap_or_default()
+ } else if self.scope.is_empty() {
+ vec![]
+ } else {
+ vec![self.scope.clone()]
+ };
egui::ComboBox::from_id_salt("scope")
- .selected_text(if self.scope.is_empty() {
- "All sources"
+ .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
+ .selected_text(if scopes.is_empty() {
+ "All sources".into()
+ } else if scopes.len() == 1 {
+ std::path::Path::new(scopes[0].trim_end_matches(['\\', '/']))
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_else(|| scopes[0].clone())
} else {
- self.scope.as_str()
+ format!("{} sources", scopes.len())
})
.width(180.0)
.truncate()
.show_ui(ui, |ui| {
- ui.selectable_value(&mut self.scope, String::new(), "All sources");
- if !self.scope.is_empty() && !self.s.roots.iter().any(|r| r.path == self.scope)
+ if ui
+ .selectable_label(scopes.is_empty(), "All sources")
+ .clicked()
{
- let current = self.scope.clone();
- ui.selectable_value(
- &mut self.scope,
- current.clone(),
- format!("Current folder: {current}"),
- );
+ scopes.clear();
+ }
+ ui.separator();
+ let mut choices = self
+ .s
+ .roots
+ .iter()
+ .map(|r| r.path.clone())
+ .collect::<Vec<_>>();
+ for path in &scopes {
+ if !choices.contains(path) {
+ choices.push(path.clone());
+ }
}
- for root in &self.s.roots {
- ui.selectable_value(&mut self.scope, root.path.clone(), &root.path);
+ for path in choices {
+ let mut selected = scopes.contains(&path);
+ if ui.checkbox(&mut selected, &path).changed() {
+ if selected {
+ scopes.push(path);
+ } else {
+ scopes.retain(|p| p != &path);
+ }
+ }
}
});
+ self.scope = match scopes.len() {
+ 0 => String::new(),
+ 1 => scopes.remove(0),
+ _ => serde_json::to_string(&scopes).unwrap_or_default(),
+ };
ui.add(
egui::TextEdit::singleline(&mut self.exclude_types)
.hint_text("Exclude types: *.zip, *.log")
- .desired_width(190.0),
+ .desired_width(150.0),
);
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ ui.allocate_ui_with_layout(
+ egui::vec2(245.0, ui.spacing().interact_size.y),
+ egui::Layout::left_to_right(egui::Align::Center),
+ |ui| {
+ let mut selected = None;
+ egui::ComboBox::from_id_salt("saved-searches")
+ .selected_text("Saved searches")
+ .width(110.0)
+ .truncate()
+ .show_ui(ui, |ui| {
+ for (i, search) in self.s.saved_searches.iter().enumerate() {
+ if ui.selectable_label(false, &search.name).clicked() {
+ selected = Some(i);
+ }
+ }
+ });
+ if let Some(i) = selected {
+ let saved = self.s.saved_searches[i].clone();
+ self.query = saved.query;
+ self.mode = saved.mode;
+ self.category = saved.category;
+ self.scope = saved.scope;
+ self.exclude_types = saved.excluded;
+ self.changed();
+ }
+ if ui
+ .add_enabled(
+ !self.query.trim().is_empty(),
+ egui::Button::new("Save search"),
+ )
+ .clicked()
+ {
+ self.s.saved_searches.push(crate::config::SavedSearch {
+ name: self.query.clone(),
+ query: self.query.clone(),
+ mode: self.mode.clone(),
+ category: self.category.clone(),
+ scope: self.scope.clone(),
+ excluded: self.exclude_types.clone(),
+ });
+ self.save();
+ }
+ },
+ );
+ });
});
if old
!= (
@@ -1100,6 +1259,7 @@ impl App {
return;
}
if !self.scope.is_empty()
+ && !self.scope.starts_with('[')
&& (self.scope_indexed == Some(false)
|| !self
.s
@@ -1451,10 +1611,20 @@ impl App {
}
if hit.seconds >= 0.0 {
if ui.button("Play from matched moment").clicked() {
- self.run(crate::platform::play_at(&hit.path, hit.seconds));
+ match crate::platform::play_at(&hit.path, hit.seconds) {
+ Ok(()) => {
+ self.status = format!(
+ "Playing from {}:{:02}",
+ hit.seconds as u32 / 60,
+ hit.seconds as u32 % 60
+ )
+ }
+ Err(e) => self.run(Err(e)),
+ }
}
if ui.button("Stop playback").clicked() {
crate::platform::stop_playback();
+ self.status = "Playback stopped".into();
}
ui.label(format!(
"Moment {}:{:02}",
@@ -1990,6 +2160,20 @@ impl App {
}
fn settings(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
ui.heading("Settings");
+ ui.collapsing("Saved searches", |ui| {
+ let mut remove = None;
+ for (i, search) in self.s.saved_searches.iter_mut().enumerate() {
+ ui.horizontal(|ui| {
+ ui.add(egui::TextEdit::singleline(&mut search.name));
+ if ui.button("Remove").clicked() {
+ remove = Some(i);
+ }
+ });
+ }
+ if let Some(i) = remove {
+ self.s.saved_searches.remove(i);
+ }
+ });
ui.heading("Appearance");
combo(ui, "theme", &mut self.s.theme, &["System", "Dark", "Light"]);
ui.horizontal(|ui| {
@@ -2011,7 +2195,7 @@ impl App {
egui::Slider::new(&mut self.s.popup_gradient, 0.0..=1.0)
.text("Popup gradient strength"),
);
- ui.label("Higher transparency reveals more of the blurred desktop. Appearance changes are applied immediately and saved.");
+ ui.label("Higher transparency reveals more of the blurred desktop. Appearance changes preview immediately; click Save to keep them.");
if ui.button("Reset appearance").clicked() {
self.s.accent = [133, 115, 255];
self.s.popup_tone = [138, 115, 168];
@@ -2162,7 +2346,7 @@ impl App {
"License and acknowledgements",
"https://github.com/ampersandru/VectorDash/blob/main/ACKNOWLEDGEMENTS.md",
);
- ui.label("Inspired by DigUp. Developed with AI assistance; verify important results.");
+ ui.label("Developed with AI assistance; verify important results.");
ui.separator();
ui.heading("Updates");
ui.label(format!(
@@ -2233,7 +2417,12 @@ impl App {
} else {
ui.label("File monitoring is off");
}
- ui.label("Changes are queued while busy. A full scan still catches changes missed while VectorDash was closed.");
+ ui.label("Automatic file changes obey the idle conditions below, including when the periodic scan schedule is Manual. Manual only disables periodic scans.");
+ ui.checkbox(
+ &mut self.s.ntfs_journal,
+ "Use NTFS change journal when available",
+ );
+ ui.label("Requires volume-read permission and an existing NTFS journal. Unsupported or inaccessible drives keep using folder notifications and recovery scans.");
ui.separator();
combo(
ui,
@@ -2423,6 +2612,38 @@ impl App {
impl eframe::App for App {
fn update(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
use raw_window_handle::HasWindowHandle;
+ if ctx.input(|i| i.modifiers.ctrl && i.key_pressed(egui::Key::F)) {
+ self.page = 0;
+ ctx.memory_mut(|m| m.request_focus(egui::Id::new("query")));
+ }
+ if self.page == 0 {
+ let forward = ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Tab));
+ let backward = ctx.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::Tab));
+ if forward || backward {
+ let index = CATEGORIES
+ .iter()
+ .position(|v| *v == self.category)
+ .unwrap_or(0);
+ self.category = CATEGORIES[(index
+ + CATEGORIES.len()
+ + if forward { 1 } else { CATEGORIES.len() - 1 })
+ % CATEGORIES.len()]
+ .into();
+ self.type_flash = Some(Instant::now());
+ self.changed();
+ ctx.memory_mut(|m| {
+ m.move_focus(egui::FocusDirection::None);
+ m.request_focus(egui::Id::new("query"));
+ });
+ }
+ }
+ for error in crate::platform::playback_errors() {
+ self.status = error.clone();
+ self.log("Error".into(), error);
+ }
+ if self.status.starts_with("Playing from") && !crate::platform::playback_active() {
+ self.status = "Playback finished".into();
+ }
let appearance = format!(
"{}{:?}{:?}{}{}",
self.s.theme,
@@ -2529,6 +2750,21 @@ impl eframe::App for App {
}
}
let now = Instant::now();
+ let frame_ms = now.duration_since(self.last_frame).as_secs_f64() * 1000.0;
+ if frame_ms > 1000.0
+ && self.frames > 0
+ && ctx.input(|i| i.viewport().focused.unwrap_or(false))
+ {
+ self.engine.log(
+ "Warning",
+ format!(
+ "UI frame delayed {frame_ms:.0} ms; indexing={}, search={}, page={}",
+ self.engine.control.running.load(Ordering::Relaxed),
+ self.searching,
+ self.page
+ ),
+ );
+ }
self.max_frame_ms = self
.max_frame_ms
.max(now.duration_since(self.last_frame).as_secs_f64() * 1000.0);
@@ -2576,10 +2812,6 @@ impl eframe::App for App {
self.dirty = false;
self.dispatch();
}
- if self.engine.models.idle_unload(&self.s) {
- self.engine
- .log("Info", "Idle model unload; local server stopped");
- }
self.indexing = self.engine.control.running.load(Ordering::Relaxed);
let metrics = crate::scheduling::metrics();
self.schedule_status =
@@ -2599,6 +2831,7 @@ impl eframe::App for App {
.unwrap_or_else(|reason| reason)
};
ctx.request_repaint_after(Duration::from_millis(50));
+ crate::platform::clear_drag_regions();
if !self.quick {
self.titlebar(ctx);
}
@@ -2722,7 +2955,7 @@ impl eframe::App for App {
)));
ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(
940.0,
- 200.0 + 370.0 * expansion,
+ 235.0 + 370.0 * expansion,
)));
}
} else {
@@ -2813,19 +3046,7 @@ impl eframe::App for App {
self.close_window(ctx);
}
}
- if self.page == 0 && ctx.input(|i| i.key_pressed(egui::Key::Tab)) {
- let current = CATEGORIES
- .iter()
- .position(|c| *c == self.category)
- .unwrap_or(0);
- self.category = CATEGORIES[if ctx.input(|i| i.modifiers.shift) {
- (current + CATEGORIES.len() - 1) % CATEGORIES.len()
- } else {
- (current + 1) % CATEGORIES.len()
- }]
- .into();
- self.changed();
- }
+
if copy_file_request {
if let Some(hit) = self.hits.get(self.selected).cloned() {
if hit.kind == "calculator" {
@@ -2981,6 +3202,7 @@ impl eframe::App for App {
{
let data = serde_json::json!({"ok":true,"native_rust":true,"model_loaded":self.engine.models.loaded.load(Ordering::Relaxed),"frames":self.frames,"max_frame_interval_ms":self.max_frame_ms,"dark_mode":ctx.style().visuals.dark_mode,"hidden_reopened":self.qa_hidden_reopened,"ocr_enabled":self.s.ocr_enabled,"ocr_setup_selected":self.ocr_setup,"results":self.hits.len(),"selected":self.selected,"result_scroll_offset":self.result_scroll_offset,"scope":self.scope,"quick_look":self.large_preview,"quick_look_size":self.qa_child_size,"cpu":crate::scheduling::metrics().cpu,"gpu":crate::scheduling::metrics().gpu,"query_focus":ctx.memory(|m|m.has_focus(egui::Id::new("query")))});
let _ = std::fs::write(report, data.to_string());
+ self.exiting = true;
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
}
@@ -2998,14 +3220,27 @@ impl eframe::App for App {
self.mcp = None;
}
}
-fn combo(ui: &mut egui::Ui, id: &str, value: &mut String, items: &[&str]) {
+fn combo(ui: &mut egui::Ui, id: &str, value: &mut String, items: &[&str]) -> egui::Response {
egui::ComboBox::from_id_salt(id)
- .selected_text(value.as_str())
+ .selected_text(if *value == "Names" {
+ "File/Folder Names"
+ } else {
+ value.as_str()
+ })
.show_ui(ui, |ui| {
for item in items {
- ui.selectable_value(value, (*item).into(), *item);
+ ui.selectable_value(
+ value,
+ (*item).into(),
+ if *item == "Names" {
+ "File/Folder Names"
+ } else {
+ *item
+ },
+ );
}
- });
+ })
+ .response
}
fn field(ui: &mut egui::Ui, label: &str, value: &mut String) {
ui.horizontal(|ui| {
@@ -3067,3 +3302,77 @@ mod result_navigation_tests {
assert_eq!(super::selection_offset(3, 70.0, 140.0, 350.0), 140.0);
}
}
+
+#[cfg(test)]
+mod tab_focus_tests {
+ #[test]
+ fn consuming_tab_does_not_move_focus_to_the_next_control() {
+ use eframe::egui::{self, Context, Event, Id, Key, Modifiers, RawInput};
+ let ctx = Context::default();
+ let id = Id::new("query");
+ let mut query = "dog".to_owned();
+ let _ = ctx.run(RawInput::default(), |ctx| {
+ egui::CentralPanel::default().show(ctx, |ui| {
+ let r = ui.add(
+ egui::TextEdit::singleline(&mut query)
+ .id(id)
+ .lock_focus(true),
+ );
+ r.request_focus();
+ egui::ComboBox::from_id_salt("saved-searches-test")
+ .selected_text("Saved searches")
+ .show_ui(ui, |ui| {
+ let _ = ui.button("Saved");
+ });
+ let _ = ui.button("Save search");
+ });
+ });
+ let mut input = RawInput::default();
+ input.events = vec![Event::Key {
+ key: Key::Tab,
+ physical_key: None,
+ pressed: true,
+ repeat: false,
+ modifiers: Modifiers::NONE,
+ }];
+ let _ = ctx.run(input, |ctx| {
+ assert!(ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Tab)));
+ ctx.memory_mut(|m| {
+ m.move_focus(egui::FocusDirection::None);
+ m.request_focus(id);
+ });
+ egui::CentralPanel::default().show(ctx, |ui| {
+ ui.add(
+ egui::TextEdit::singleline(&mut query)
+ .id(id)
+ .lock_focus(true),
+ );
+ egui::ComboBox::from_id_salt("saved-searches-test")
+ .selected_text("Saved searches")
+ .show_ui(ui, |ui| {
+ let _ = ui.button("Saved");
+ });
+ let _ = ui.button("Save search");
+ });
+ });
+ let mut input = RawInput::default();
+ input.events = vec![Event::Text("x".into())];
+ let _ = ctx.run(input, |ctx| {
+ egui::CentralPanel::default().show(ctx, |ui| {
+ ui.add(
+ egui::TextEdit::singleline(&mut query)
+ .id(id)
+ .lock_focus(true),
+ );
+ egui::ComboBox::from_id_salt("saved-searches-test")
+ .selected_text("Saved searches")
+ .show_ui(ui, |ui| {
+ let _ = ui.button("Saved");
+ });
+ let _ = ui.button("Save search");
+ });
+ });
+ assert!(query.contains('x'));
+ assert!(ctx.memory(|m| m.has_focus(id)));
+ }
+}
diff --git a/native/src/appearance.rs b/native/src/appearance.rs
index e72cff5..77658d3 100644
--- a/native/src/appearance.rs
+++ b/native/src/appearance.rs
@@ -90,6 +90,12 @@ pub fn apply(ctx: &egui::Context, s: &Settings) {
style.visuals.widgets.open.weak_bg_fill = style.visuals.widgets.hovered.bg_fill;
style.visuals.window_corner_radius = egui::CornerRadius::same(16);
style.visuals.menu_corner_radius = egui::CornerRadius::same(9);
+ if is_dark {
+ style.visuals.widgets.inactive.bg_fill = Color32::from_rgb(55, 48, 78);
+ style.visuals.widgets.active.bg_fill = Color32::from_rgb(68, 57, 95);
+ style.visuals.widgets.inactive.fg_stroke = egui::Stroke::new(2.0, accent);
+ style.visuals.slider_trailing_fill = true;
+ }
style.visuals.handle_shape = egui::style::HandleShape::Rect { aspect_ratio: 0.5 };
style.spacing.item_spacing = egui::vec2(10.0, 8.0);
style.spacing.button_padding = egui::vec2(12.0, 8.0);
diff --git a/native/src/changes.rs b/native/src/changes.rs
index 6827d12..883503e 100644
--- a/native/src/changes.rs
+++ b/native/src/changes.rs
@@ -19,10 +19,20 @@ pub struct Monitor {
last: Option<Instant>,
first: Option<Instant>,
watched: usize,
+ journal: crate::journal::Tracker,
+ journal_inflight: bool,
}
impl Monitor {
pub fn configure(&mut self, s: &Settings, home: &Path, tx: &NotifySender) {
- let signature = format!("{}|{:?}", s.watch_changes, s.roots);
+ let signature = format!(
+ "{}|{}|{:?}|{:?}|{}|{}",
+ s.watch_changes,
+ s.ntfs_journal,
+ s.roots,
+ s.exclusions,
+ s.excluded_types,
+ s.skip_windows_churn
+ );
if signature == self.signature {
return;
}
@@ -34,6 +44,8 @@ impl Monitor {
self.last = None;
self.first = None;
self.watched = 0;
+ self.journal = crate::journal::Tracker::default();
+ self.journal_inflight = false;
if !s.watch_changes {
return;
}
@@ -94,7 +106,8 @@ impl Monitor {
}
}
self.watched = watched.len();
- if self.watched > 0 {
+ let journal_covered = self.journal.configure(s, home, tx);
+ if self.watched > 0 && !journal_covered {
self.recovery = true;
self.last = Some(Instant::now());
self.first = self.last;
@@ -111,6 +124,28 @@ impl Monitor {
));
}
pub fn collect(&mut self, s: &Settings, home: &Path) {
+ let (paths, recovery) = self.journal.poll();
+ if recovery {
+ self.recovery = true;
+ self.last = Some(Instant::now());
+ }
+ for path in paths {
+ if !under(&path.to_string_lossy(), &home.to_string_lossy())
+ && s.roots
+ .iter()
+ .any(|r| under(&path.to_string_lossy(), &r.path))
+ && s.allowed(&path)
+ {
+ if self.pending.len() < 4096 {
+ self.pending.insert(path);
+ } else {
+ self.recovery = true;
+ self.pending.clear();
+ }
+ self.last = Some(Instant::now());
+ }
+ }
+
if self
.overflow
.as_ref()
@@ -192,7 +227,11 @@ impl Monitor {
} else {
"waiting for file changes"
};
- format!("Watching {} sources · {pending} · {waiting}", self.watched)
+ format!(
+ "Watching {} sources · {} NTFS journals · {pending} · {waiting}",
+ self.watched,
+ self.journal.active()
+ )
}
pub fn ready(&self) -> bool {
(self.recovery || !self.pending.is_empty())
@@ -203,7 +242,20 @@ impl Monitor {
.first
.is_some_and(|t| t.elapsed() >= Duration::from_secs(60)))
}
+ pub fn complete(&mut self, success: bool, home: &Path) {
+ if self.journal_inflight {
+ self.journal.finish(success, home);
+ self.journal_inflight = false;
+ if !success {
+ self.recovery = true;
+ self.last = Some(Instant::now());
+ self.first = self.last;
+ }
+ }
+ }
pub fn take(&mut self) -> Option<Vec<PathBuf>> {
+ self.journal.begin();
+ self.journal_inflight = true;
self.last = None;
self.first = None;
if self.recovery {
diff --git a/native/src/config.rs b/native/src/config.rs
index 1817ea4..a156c03 100644
--- a/native/src/config.rs
+++ b/native/src/config.rs
@@ -12,6 +12,15 @@ pub struct Source {
pub mode: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+pub struct SavedSearch {
+ pub name: String,
+ pub query: String,
+ pub mode: String,
+ pub category: String,
+ pub scope: String,
+ pub excluded: String,
+}
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Settings {
pub roots: Vec<Source>,
@@ -19,6 +28,8 @@ pub struct Settings {
pub excluded_types: String,
pub count_files: bool,
pub watch_changes: bool,
+ pub ntfs_journal: bool,
+ pub saved_searches: Vec<SavedSearch>,
pub auto_check_updates: bool,
pub auto_update: bool,
pub skip_windows_churn: bool,
@@ -106,6 +117,8 @@ impl Default for Settings {
excluded_types: String::new(),
count_files: false,
watch_changes: false,
+ ntfs_journal: false,
+ saved_searches: vec![],
auto_check_updates: true,
auto_update: false,
skip_windows_churn: true,
@@ -245,7 +258,7 @@ pub fn excluded_type(path: &Path, spec: &str) -> bool {
}
})
}
-fn wildcard_match(value: &str, pattern: &str) -> bool {
+pub(crate) fn wildcard_match(value: &str, pattern: &str) -> bool {
let (v, p) = (value.as_bytes(), pattern.as_bytes());
let (mut i, mut j, mut star, mut retry) = (0, 0, None, 0);
while i < v.len() {
@@ -771,3 +784,24 @@ mod preference_tests {
assert!(!same_preferences(&a, &b));
}
}
+
+#[cfg(test)]
+mod bookmark_tests {
+ use super::*;
+ #[test]
+ fn saved_searches_and_old_settings_round_trip() {
+ let old: Settings = serde_json::from_str("{}").unwrap();
+ assert!(old.saved_searches.is_empty() && !old.ntfs_journal);
+ let mut s = old;
+ s.saved_searches.push(SavedSearch {
+ name: "Recent PDFs".into(),
+ query: "ext:pdf modified:today".into(),
+ mode: "Names".into(),
+ category: "Documents".into(),
+ scope: r#"["C:\\docs","D:\\notes"]"#.into(),
+ excluded: "*.tmp".into(),
+ });
+ let saved: Settings = serde_json::from_str(&serde_json::to_string(&s).unwrap()).unwrap();
+ assert_eq!(s.saved_searches, saved.saved_searches);
+ }
+}
diff --git a/native/src/db.rs b/native/src/db.rs
index 2eacf68..51e0b51 100644
--- a/native/src/db.rs
+++ b/native/src/db.rs
@@ -412,6 +412,10 @@ pub fn names(
scope: &str,
excluded: &str,
) -> Result<Vec<Hit>> {
+ let filters = crate::search_filters::Filters::parse(query)?;
+ if filters.active() {
+ return filtered_names(db, &filters, s, category, scope, excluded);
+ }
let c = db.connect(true)?;
let q = query.trim().to_lowercase();
if q.is_empty() {
@@ -957,3 +961,133 @@ mod metadata_update_tests {
);
}
}
+
+fn filtered_names(
+ db: &Database,
+ f: &crate::search_filters::Filters,
+ s: &Settings,
+ category: &str,
+ scope: &str,
+ excluded: &str,
+) -> Result<Vec<Hit>> {
+ let c = db.connect(true)?;
+ let pattern = f.pattern.as_deref().unwrap_or("*");
+ let literal = pattern.split(['*', '?', '[']).next().unwrap_or("");
+ let upper = format!("{literal}\u{10ffff}");
+ let low = crate::config::fold(scope);
+ let prefix = format!("{low}\\");
+ let scope_upper = format!("{prefix}\u{10ffff}");
+ let ext = serde_json::to_string(
+ &f.extension
+ .as_deref()
+ .unwrap_or("")
+ .split(',')
+ .filter(|x| !x.is_empty())
+ .collect::<Vec<_>>(),
+ )?;
+ let text = f.text.to_lowercase();
+ let terms = text
+ .split_whitespace()
+ .map(|t| format!("\"{}\"", t.replace('"', "\"\"")))
+ .collect::<Vec<_>>()
+ .join(" AND ");
+ let use_fts = text.chars().count() >= 3;
+ let sql = format!(
+ "SELECT n.path,n.name,n.kind FROM names n WHERE n.base GLOB ?1 AND (?2='' OR (n.base>=?2 AND n.base<?3)) AND n.size>=?4 AND n.size<=?5 AND n.mtime>=?6 AND n.mtime<=?7 AND (?8='[]' OR EXISTS(SELECT 1 FROM json_each(?8) e WHERE n.base GLOB ('*.'||e.value))) AND (?9='' OR n.folded=?9 OR (n.folded>=?10 AND n.folded<?11)) {} LIMIT 1000",
+ if text.is_empty() {
+ ""
+ } else if use_fts {
+ "AND n.rowid IN (SELECT rowid FROM name_words WHERE name_words MATCH ?12)"
+ } else {
+ "AND n.base>=?12 AND n.base<?13"
+ }
+ );
+ let mut stmt = c.prepare(&sql)?;
+ let mut result = vec![];
+ let mut values: Vec<rusqlite::types::Value> = vec![
+ pattern.to_owned().into(),
+ literal.to_owned().into(),
+ upper.into(),
+ f.min_size.into(),
+ f.max_size.into(),
+ f.after.into(),
+ f.before.into(),
+ ext.into(),
+ low.into(),
+ prefix.into(),
+ scope_upper.into(),
+ ];
+ if !text.is_empty() {
+ if use_fts {
+ values.push(terms.into());
+ } else {
+ values.push(text.clone().into());
+ values.push(format!("{text}\u{10ffff}").into());
+ }
+ }
+ for row in stmt.query_map(rusqlite::params_from_iter(values), |r| {
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, String>(2)?,
+ ))
+ })? {
+ add_name(
+ &mut result,
+ row?,
+ if text.is_empty() { literal } else { &text },
+ s,
+ category,
+ scope,
+ excluded,
+ );
+ }
+ result.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.path.cmp(&b.path)));
+ result.truncate(100);
+ Ok(result)
+}
+
+#[cfg(test)]
+mod advanced_filter_tests {
+ use super::*;
+ #[test]
+ fn filters_are_applied_before_result_limit() {
+ let home = tempfile::tempdir().unwrap();
+ let mut s = crate::config::Settings::default();
+ s.encrypt_index = false;
+ let db = Database::new(home.path(), &s).unwrap();
+ let c = db.connect(false).unwrap();
+ for i in 0..1100 {
+ Database::touch_name(
+ &c,
+ Path::new(&format!("C:\\data\\dog{i}.log")),
+ "file",
+ 1,
+ 10,
+ "quick",
+ "C:\\data",
+ 1,
+ )
+ .unwrap();
+ }
+ Database::touch_name(
+ &c,
+ Path::new("C:\\data\\dog_final.pdf"),
+ "file",
+ 1700000000000000000,
+ 4096,
+ "quick",
+ "C:\\data",
+ 1,
+ )
+ .unwrap();
+ let hits = names(&db, "dog*.pdf size:>1KB", &s, "All files", "", "").unwrap();
+ assert_eq!(hits.len(), 1);
+ assert!(hits[0].path.ends_with("dog_final.pdf"));
+ assert!(
+ names(&db, "ext:pdf size:<1KB", &s, "All files", "", "")
+ .unwrap()
+ .is_empty()
+ );
+ }
+}
diff --git a/native/src/engine.rs b/native/src/engine.rs
index 475122c..a9b2b7b 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -142,6 +142,7 @@ pub struct Control {
pub paused: Arc<AtomicBool>,
pub automatic: Arc<AtomicBool>,
pub watching: Arc<AtomicBool>,
+ pub last_run_success: Arc<AtomicBool>,
pub running: Arc<AtomicBool>,
pub automatic_started: Arc<std::sync::atomic::AtomicI64>,
pub schedule: Arc<std::sync::Mutex<Settings>>,
@@ -254,11 +255,18 @@ impl Engine {
let mut last_watch_status = String::new();
while !shutdown.load(Ordering::Relaxed) {
let settings = engine.control.schedule.lock().unwrap().clone();
+ if !engine.control.running.load(Ordering::Relaxed) {
+ changes.complete(
+ engine.control.last_run_success.load(Ordering::Relaxed),
+ &engine.db.home,
+ );
+ }
changes.configure(&settings, &engine.db.home, &engine.tx);
changes.collect(&settings, &engine.db.home);
let watch_status =
changes.status(&settings, engine.control.running.load(Ordering::Relaxed));
if watch_status != last_watch_status {
+ engine.log("Info", format!("File monitoring: {watch_status}"));
let _ = engine.tx.send(Event::WatchStatus(watch_status.clone()));
last_watch_status = watch_status;
}
@@ -351,6 +359,10 @@ impl Engine {
let result = owner
.index_paths(&s, force, paths)
.map_err(|e| e.to_string());
+ owner
+ .control
+ .last_run_success
+ .store(result.is_ok(), Ordering::Relaxed);
if let Err(error) = &result {
owner.log("Error", format!("Index update failed: {error}"));
}
@@ -1002,9 +1014,6 @@ impl Engine {
scope: &str,
excluded: &str,
) -> Result<Vec<Hit>> {
- if q.trim().is_empty() {
- return Ok(vec![]);
- }
let expression = q.replace("% of", "/100*");
if let Ok(value) = meval::eval_str(&expression) {
if q.chars().any(|c| "+-*/^()%".contains(c)) {
@@ -1020,6 +1029,51 @@ impl Engine {
}]);
}
}
+ if scope.starts_with('[') {
+ let scopes: Vec<String> = serde_json::from_str(scope)?;
+ let mut hits = vec![];
+ for root in scopes.into_iter().take(32) {
+ hits.extend(self.search_inner(q, s, mode, category, &root, excluded)?);
+ }
+ rank_hits(
+ &mut hits,
+ if category == "All files" && mode != "Names" {
+ media_intent(q)
+ } else {
+ None
+ },
+ );
+ let mut paths = HashSet::new();
+ hits.retain(|h| paths.insert(h.path.clone()));
+ hits.truncate(100);
+ return Ok(hits);
+ }
+ let filters = crate::search_filters::Filters::parse(q)?;
+ if filters.active() {
+ let mut hits = if mode != "Semantic" || filters.text.is_empty() {
+ crate::db::names(&self.db, q, s, category, scope, excluded)?
+ } else {
+ vec![]
+ };
+ if mode != "Names" && !filters.text.is_empty() && crate::config::full_scope(s, scope) {
+ hits.extend(self.semantic(
+ &filters.text,
+ s,
+ category,
+ scope,
+ excluded,
+ Some(&filters),
+ )?);
+ }
+ rank_hits(&mut hits, None);
+ let mut paths = HashSet::new();
+ hits.retain(|h| paths.insert(h.path.clone()));
+ hits.truncate(100);
+ return Ok(hits);
+ }
+ if q.trim().is_empty() {
+ return Ok(vec![]);
+ }
let mut hits = crate::platform::actions(q, s);
if !scope.is_empty() {
hits.retain(|h| crate::config::under(&h.path, scope));
@@ -1051,7 +1105,7 @@ impl Engine {
.optional()?
.is_some()
{
- hits.extend(self.semantic(q, s, category, scope, excluded)?);
+ hits.extend(self.semantic(q, s, category, scope, excluded, None)?);
}
rank_hits(
&mut hits,
@@ -1073,6 +1127,7 @@ impl Engine {
category: &str,
scope: &str,
excluded: &str,
+ filters: Option<&crate::search_filters::Filters>,
) -> Result<Vec<Hit>> {
let vector = self.models.query(s, q)?;
let conn = self.db.connect(true)?;
@@ -1104,6 +1159,7 @@ impl Engine {
(s.code_search || g.namespace != "code")
&& !(cat == "Images" && g.channel == "text" && !text_intent)
&& crate::db::allowed(&g.path, &g.kind, s, cat, scope, excluded)
+ && metadata_matches(&conn, filters, &g.path)
})
.collect::<Vec<_>>();
for (i, values) in matrix.values.chunks_exact(matrix.dimension).enumerate() {
@@ -1139,6 +1195,7 @@ impl Engine {
}
if !s.code_search && namespace == "code"
|| !crate::db::allowed(&path, &kind, s, cat, scope, excluded)
+ || !metadata_matches(&conn, filters, &path)
{
continue;
}
@@ -1243,7 +1300,9 @@ impl Engine {
},
)? {
let (path, kind, text, loc) = row?;
- if !crate::db::allowed(&path, &kind, s, cat, scope, excluded) {
+ if !crate::db::allowed(&path, &kind, s, cat, scope, excluded)
+ || !metadata_matches(&conn, filters, &path)
+ {
continue;
}
if s.excluded_sensitive && sensitive(&text) {
@@ -1734,3 +1793,186 @@ mod automatic_watch_tests {
std::thread::sleep(Duration::from_millis(1100));
}
}
+
+#[cfg(test)]
+mod multi_scope_tests {
+ use super::*;
+ #[test]
+ fn searches_union_selected_roots_without_unrelated_matches() {
+ let home = tempfile::tempdir().unwrap();
+ let mut s = Settings::default();
+ s.encrypt_index = false;
+ let db = Database::new(home.path(), &s).unwrap();
+ let c = db.connect(false).unwrap();
+ for root in ["C:\\a", "D:\\b", "E:\\other"] {
+ Database::touch_name(
+ &c,
+ std::path::Path::new(&format!("{root}\\dog.txt")),
+ "file",
+ 1,
+ 20,
+ "quick",
+ root,
+ 1,
+ )
+ .unwrap();
+ }
+ let (tx, _) = crossbeam_channel::unbounded();
+ let engine = Engine {
+ db,
+ models: Models::default(),
+ control: Control::default(),
+ tx: NotifySender::new(tx, None),
+ searching: Arc::new(AtomicBool::new(false)),
+ vectors: crate::vector_cache::Cache::default(),
+ };
+ let scope = serde_json::to_string(&vec!["C:\\a", "D:\\b"]).unwrap();
+ let hits = engine
+ .search_inner("dog", &s, "Names", "All files", &scope, "")
+ .unwrap();
+ assert_eq!(hits.len(), 2);
+ assert!(!hits.iter().any(|h| h.path.starts_with("E:")));
+ }
+}
+
+fn metadata_matches(
+ conn: &rusqlite::Connection,
+ filters: Option<&crate::search_filters::Filters>,
+ path: &str,
+) -> bool {
+ filters.is_none_or(|f| {
+ conn.query_row(
+ "SELECT name,size,mtime FROM names WHERE path=?1",
+ [path],
+ |r| {
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, i64>(1)?,
+ r.get::<_, i64>(2)?,
+ ))
+ },
+ )
+ .is_ok_and(|(name, size, mtime)| f.matches(&name, size, mtime))
+ })
+}
+
+#[cfg(test)]
+mod semantic_metadata_tests {
+ use super::*;
+ #[test]
+ fn metadata_filters_apply_before_semantic_candidate_limits() {
+ let home = tempfile::tempdir().unwrap();
+ let mut s = Settings::default();
+ s.encrypt_index = false;
+ s.remote_url = String::new();
+ s.roots = vec![crate::config::Source {
+ path: "C:\\photos".into(),
+ mode: "full".into(),
+ }];
+ let db = Database::new(home.path(), &s).unwrap();
+ let c = db.connect(false).unwrap();
+ c.execute_batch("BEGIN").unwrap();
+ for i in 0..501 {
+ let target = i == 500;
+ let path = format!("C:\\photos\\dog_{i}.jpg");
+ Database::touch_name(
+ &c,
+ std::path::Path::new(&path),
+ "file",
+ 1700000000000000000,
+ if target { 4096 } else { 10 },
+ "full",
+ "C:\\photos",
+ 1,
+ )
+ .unwrap();
+ c.execute(
+ "INSERT INTO segments VALUES(?1,'files','image','','[]',?2)",
+ params![path, "{\"embedding_source\":\"media\",\"seconds\":-1}"],
+ )
+ .unwrap();
+ let id = c.last_insert_rowid();
+ let x = if target { 0.3f32 } else { 0.99f32 };
+ let vector = [x, (1. - x * x).sqrt()]
+ .iter()
+ .flat_map(|v| v.to_le_bytes())
+ .collect::<Vec<_>>();
+ c.execute(
+ "INSERT INTO segment_vectors VALUES(?1,'files','image','image',2,?2,?3)",
+ params![id, vector, path],
+ )
+ .unwrap();
+ }
+ c.execute_batch("COMMIT").unwrap();
+ drop(c);
+ let http = Arc::new(tiny_http::Server::http("127.0.0.1:0").unwrap());
+ s.remote_url = format!("http://{}", http.server_addr());
+ let responder = http.clone();
+ let signal = Arc::new(AtomicBool::new(false));
+ let stop = signal.clone();
+ let worker = std::thread::spawn(move || {
+ while !stop.load(Ordering::Relaxed) {
+ if let Ok(Some(req)) = responder.recv_timeout(Duration::from_millis(100)) {
+ let _ = req.respond(tiny_http::Response::from_string(
+ "{\"data\":[{\"embedding\":[1,0],\"index\":0}]}",
+ ));
+ }
+ }
+ });
+ let (tx, _) = crossbeam_channel::unbounded();
+ let engine = Engine {
+ db,
+ models: Models::default(),
+ control: Control::default(),
+ tx: NotifySender::new(tx, None),
+ searching: Arc::new(AtomicBool::new(false)),
+ vectors: crate::vector_cache::Cache::default(),
+ };
+ for profile in ["Balanced", "Low memory"] {
+ s.performance = profile.into();
+ let hits = engine
+ .search_inner(
+ "dogs name:dog*.jpg size:>1KB",
+ &s,
+ "Semantic",
+ "All files",
+ "",
+ "",
+ )
+ .unwrap();
+ assert_eq!(hits.len(), 1);
+ assert!(hits[0].path.ends_with("dog_500.jpg"));
+ }
+ signal.store(true, Ordering::Relaxed);
+ worker.join().unwrap();
+ }
+}
+
+#[cfg(test)]
+mod calculator_filter_tests {
+ use super::*;
+ #[test]
+ fn arithmetic_is_not_mistaken_for_filename_wildcards() {
+ let home = tempfile::tempdir().unwrap();
+ let mut s = Settings::default();
+ s.encrypt_index = false;
+ let db = Database::new(home.path(), &s).unwrap();
+ let (tx, _) = crossbeam_channel::unbounded();
+ let engine = Engine {
+ db,
+ models: Models::default(),
+ control: Control::default(),
+ tx: NotifySender::new(tx, None),
+ searching: Arc::new(AtomicBool::new(false)),
+ vectors: crate::vector_cache::Cache::default(),
+ };
+ for query in ["2*3", "2 * 3"] {
+ let hits = engine
+ .search_inner(query, &s, "Both", "All files", "", "")
+ .unwrap();
+ assert_eq!(hits[0].kind, "calculator");
+ assert_eq!(hits[0].path, "6");
+ }
+ assert!(!engine.models.loaded.load(Ordering::Relaxed));
+ }
+}
diff --git a/native/src/journal.rs b/native/src/journal.rs
new file mode 100644
index 0000000..c1744a6
--- /dev/null
+++ b/native/src/journal.rs
@@ -0,0 +1,390 @@
+//! Bounded optional NTFS USN replay; persist cursors only after successful indexing.
+use anyhow::{Context, Result};
+use serde::{Deserialize, Serialize};
+use std::{
+ collections::BTreeMap,
+ path::{Path, PathBuf},
+};
+#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
+struct Mark {
+ id: u64,
+ usn: i64,
+}
+#[derive(Default, Serialize, Deserialize)]
+struct Saved {
+ signature: String,
+ marks: BTreeMap<String, Mark>,
+}
+#[derive(Default)]
+pub struct Tracker {
+ signature: String,
+ read: BTreeMap<String, Mark>,
+ committed: BTreeMap<String, Mark>,
+ flight: Option<BTreeMap<String, Mark>>,
+}
+impl Tracker {
+ pub fn configure(
+ &mut self,
+ s: &crate::config::Settings,
+ home: &Path,
+ tx: &crate::engine::NotifySender,
+ ) -> bool {
+ *self = Self::default();
+ if !s.ntfs_journal {
+ return false;
+ }
+ self.signature = format!(
+ "{:?}|{:?}|{}|{}",
+ s.roots, s.exclusions, s.excluded_types, s.skip_windows_churn
+ );
+ let saved = std::fs::read(home.join("ntfs-journal.json"))
+ .ok()
+ .and_then(|b| serde_json::from_slice::<Saved>(&b).ok())
+ .unwrap_or_default();
+ let signature_matches = saved.signature == self.signature;
+ let mut covered = signature_matches;
+ let mut volumes = BTreeMap::new();
+ for root in &s.roots {
+ let path = root.path.as_bytes();
+ if path.len() >= 3 && path[0].is_ascii_alphabetic() && path[1] == b':' {
+ volumes.insert(root.path[..2].to_uppercase(), ());
+ } else {
+ covered = false;
+ }
+ }
+ for (volume, _) in volumes {
+ match query(&volume) {
+ Ok((id, first, next)) => {
+ let old = saved.marks.get(&volume).copied().filter(|m| {
+ signature_matches && m.id == id && m.usn >= first && m.usn <= next
+ });
+ if old.is_none() {
+ covered = false;
+ }
+ let mark = old.unwrap_or(Mark { id, usn: next });
+ self.read.insert(volume.clone(), mark);
+ self.committed.insert(volume, mark);
+ }
+ Err(e) => {
+ covered = false;
+ let _=tx.send(crate::engine::Event::Log("Warning".into(),format!("NTFS journal {volume} unavailable; folder notifications remain active: {e}")));
+ }
+ }
+ }
+ let _ = tx.send(crate::engine::Event::Log(
+ "Info".into(),
+ format!(
+ "NTFS journal: {} accessible volumes; {}",
+ self.read.len(),
+ if covered {
+ "replaying saved cursors"
+ } else {
+ "recovery scan establishes cursors"
+ }
+ ),
+ ));
+ covered && !self.read.is_empty()
+ }
+ pub fn poll(&mut self) -> (Vec<PathBuf>, bool) {
+ let mut paths = vec![];
+ let mut recovery = false;
+ let mut failed = vec![];
+ for (volume, mark) in &mut self.read {
+ match read(volume, *mark) {
+ Ok((next, mut batch)) => {
+ mark.usn = next;
+ paths.append(&mut batch)
+ }
+ Err(_) => {
+ failed.push(volume.clone());
+ recovery = true;
+ }
+ }
+ }
+ for v in failed {
+ self.read.remove(&v);
+ }
+ (paths, recovery)
+ }
+ pub fn begin(&mut self) {
+ self.flight = if self.read.is_empty() {
+ None
+ } else {
+ Some(self.read.clone())
+ };
+ }
+ pub fn finish(&mut self, success: bool, home: &Path) {
+ if let Some(marks) = self.flight.take() {
+ if success {
+ let saved = Saved {
+ signature: self.signature.clone(),
+ marks: marks.clone(),
+ };
+ if let Ok(bytes) = serde_json::to_vec(&saved) {
+ let temp = home.join("ntfs-journal.pending");
+ if std::fs::write(&temp, bytes).is_ok()
+ && std::fs::rename(temp, home.join("ntfs-journal.json")).is_ok()
+ {
+ self.committed = marks;
+ }
+ }
+ } else {
+ self.read = self.committed.clone();
+ }
+ }
+ }
+ pub fn active(&self) -> usize {
+ self.read.len()
+ }
+}
+#[derive(Debug)]
+struct Record {
+ parent: u64,
+ name: String,
+ reason: u32,
+ attributes: u32,
+}
+fn parse(buffer: &[u8]) -> Result<(i64, Vec<Record>)> {
+ anyhow::ensure!(buffer.len() >= 8, "Truncated USN cursor");
+ let next = i64::from_le_bytes(buffer[..8].try_into()?);
+ let mut records = vec![];
+ let mut offset = 8;
+ while offset < buffer.len() {
+ let r = &buffer[offset..];
+ anyhow::ensure!(r.len() >= 60, "Truncated USN header");
+ let length = u32::from_le_bytes(r[..4].try_into()?) as usize;
+ let version = u16::from_le_bytes(r[4..6].try_into()?);
+ anyhow::ensure!(
+ version == 2 && length >= 60 && length <= r.len(),
+ "Unsupported/malformed USN record"
+ );
+ let name_len = u16::from_le_bytes(r[56..58].try_into()?) as usize;
+ let name_offset = u16::from_le_bytes(r[58..60].try_into()?) as usize;
+ anyhow::ensure!(
+ name_offset >= 60 && name_len % 2 == 0 && name_offset + name_len <= length,
+ "Invalid USN filename"
+ );
+ let utf16 = r[name_offset..name_offset + name_len]
+ .chunks_exact(2)
+ .map(|c| u16::from_le_bytes([c[0], c[1]]))
+ .collect::<Vec<_>>();
+ let name = String::from_utf16(&utf16)?;
+ anyhow::ensure!(
+ !name.contains(['\\', '/', char::from(0)]) && name != "." && name != "..",
+ "Invalid journal path component"
+ );
+ records.push(Record {
+ parent: u64::from_le_bytes(r[16..24].try_into()?),
+ reason: u32::from_le_bytes(r[40..44].try_into()?),
+ attributes: u32::from_le_bytes(r[52..56].try_into()?),
+ name,
+ });
+ offset += length;
+ }
+ Ok((next, records))
+}
+#[cfg(windows)]
+mod win {
+ use super::*;
+ use windows::{
+ Win32::{
+ Foundation::{CloseHandle, GENERIC_READ, HANDLE},
+ Storage::FileSystem::*,
+ System::{IO::DeviceIoControl, Ioctl::*},
+ },
+ core::PCWSTR,
+ };
+ struct Volume(HANDLE);
+ impl Drop for Volume {
+ fn drop(&mut self) {
+ unsafe {
+ let _ = CloseHandle(self.0);
+ }
+ }
+ }
+ fn open(volume: &str) -> Result<Volume> {
+ let name = format!("\\\\.\\{volume}")
+ .encode_utf16()
+ .chain(Some(0))
+ .collect::<Vec<_>>();
+ Ok(Volume(unsafe {
+ CreateFileW(
+ PCWSTR(name.as_ptr()),
+ GENERIC_READ.0,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ None,
+ OPEN_EXISTING,
+ FILE_FLAGS_AND_ATTRIBUTES(0),
+ None,
+ )
+ }?))
+ }
+ pub(super) fn query(volume: &str) -> Result<(u64, i64, i64)> {
+ let handle = open(volume)?;
+ let mut data = USN_JOURNAL_DATA_V0::default();
+ let mut count = 0;
+ unsafe {
+ DeviceIoControl(
+ handle.0,
+ FSCTL_QUERY_USN_JOURNAL,
+ None,
+ 0,
+ Some(&mut data as *mut _ as _),
+ std::mem::size_of_val(&data) as u32,
+ Some(&mut count),
+ None,
+ )
+ }?;
+ anyhow::ensure!(
+ count as usize >= std::mem::size_of_val(&data),
+ "Incomplete journal information"
+ );
+ Ok((
+ data.UsnJournalID,
+ data.FirstUsn.max(data.LowestValidUsn),
+ data.NextUsn,
+ ))
+ }
+ pub(super) fn read(volume: &str, mark: Mark) -> Result<(i64, Vec<PathBuf>)> {
+ let handle = open(volume)?;
+ let input = READ_USN_JOURNAL_DATA_V0 {
+ StartUsn: mark.usn,
+ ReasonMask: u32::MAX,
+ ReturnOnlyOnClose: 0,
+ Timeout: 0,
+ BytesToWaitFor: 0,
+ UsnJournalID: mark.id,
+ };
+ let mut buffer = vec![0u8; 65536];
+ let mut count = 0;
+ unsafe {
+ DeviceIoControl(
+ handle.0,
+ FSCTL_READ_USN_JOURNAL,
+ Some(&input as *const _ as _),
+ std::mem::size_of_val(&input) as u32,
+ Some(buffer.as_mut_ptr() as _),
+ buffer.len() as u32,
+ Some(&mut count),
+ None,
+ )
+ }?;
+ anyhow::ensure!(
+ count as usize <= buffer.len(),
+ "Invalid journal buffer size"
+ );
+ let (next, records) = parse(&buffer[..count as usize])?;
+ let mut parents = BTreeMap::new();
+ let mut paths = vec![];
+ for r in records {
+ if r.reason & !0x80000000 == 0 {
+ continue;
+ }
+ if r.attributes & 0x10 != 0 && r.reason & (0x100 | 0x200 | 0x1000 | 0x2000) == 0 {
+ continue;
+ }
+ let parent = if let Some(p) = parents.get(&r.parent) {
+ PathBuf::clone(p)
+ } else {
+ let id = FILE_ID_DESCRIPTOR {
+ dwSize: std::mem::size_of::<FILE_ID_DESCRIPTOR>() as u32,
+ Type: FileIdType,
+ Anonymous: FILE_ID_DESCRIPTOR_0 {
+ FileId: r.parent as i64,
+ },
+ };
+ let parent = Volume(
+ unsafe {
+ OpenFileById(
+ handle.0,
+ &id,
+ 0,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ None,
+ FILE_FLAG_BACKUP_SEMANTICS,
+ )
+ }
+ .context("Journal parent unavailable; recovery needed")?,
+ );
+ let mut text = vec![0u16; 32768];
+ let n = unsafe {
+ GetFinalPathNameByHandleW(
+ parent.0,
+ &mut text,
+ GETFINALPATHNAMEBYHANDLE_FLAGS(0),
+ )
+ } as usize;
+ anyhow::ensure!(n > 0 && n < text.len(), "Cannot resolve journal parent");
+ let text = String::from_utf16(&text[..n])?;
+ let path = PathBuf::from(text.strip_prefix("\\\\?\\").unwrap_or(&text));
+ if parents.len() < 512 {
+ parents.insert(r.parent, path.clone());
+ }
+ path
+ };
+ paths.push(parent.join(r.name));
+ }
+ Ok((next, paths))
+ }
+}
+#[cfg(windows)]
+use win::{query, read};
+#[cfg(not(windows))]
+fn query(_: &str) -> Result<(u64, i64, i64)> {
+ anyhow::bail!("NTFS journals require Windows")
+}
+#[cfg(not(windows))]
+fn read(_: &str, _: Mark) -> Result<(i64, Vec<PathBuf>)> {
+ anyhow::bail!("NTFS journals require Windows")
+}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn untrusted_records_are_bounded() {
+ assert!(parse(&[0; 7]).is_err());
+ assert!(parse(&[0; 8]).unwrap().1.is_empty());
+ let mut b = vec![0; 68];
+ b[8..12].copy_from_slice(&60u32.to_le_bytes());
+ b[12..14].copy_from_slice(&3u16.to_le_bytes());
+ assert!(parse(&b).is_err());
+ b[12..14].copy_from_slice(&2u16.to_le_bytes());
+ b[66..68].copy_from_slice(&60u16.to_le_bytes());
+ assert!(parse(&b).is_ok());
+ b[64..66].copy_from_slice(&100u16.to_le_bytes());
+ assert!(parse(&b).is_err());
+ }
+}
+
+#[cfg(test)]
+mod checkpoint_tests {
+ use super::*;
+ #[test]
+ fn only_successful_batch_cursors_commit() {
+ let home = tempfile::tempdir().unwrap();
+ let mut tracker = Tracker::default();
+ tracker.signature = "fixture".into();
+ tracker
+ .committed
+ .insert("C:".into(), Mark { id: 1, usn: 10 });
+ tracker.read.insert("C:".into(), Mark { id: 1, usn: 20 });
+ tracker.begin();
+ tracker.read.get_mut("C:").unwrap().usn = 30;
+ tracker.finish(true, home.path());
+ let saved: Saved =
+ serde_json::from_slice(&std::fs::read(home.path().join("ntfs-journal.json")).unwrap())
+ .unwrap();
+ assert_eq!(saved.marks["C:"].usn, 20);
+ tracker.begin();
+ tracker.finish(false, home.path());
+ assert_eq!(tracker.read["C:"].usn, 20);
+ }
+}
+
+pub fn probe(volume: &str) -> Result<serde_json::Value> {
+ let (id, first, next) = query(volume)?;
+ let (_, records) = read(volume, Mark { id, usn: next })?;
+ Ok(
+ serde_json::json!({"accessible":true,"id":id,"first":first,"next":next,"pending_paths":records.len()}),
+ )
+}
diff --git a/native/src/main.rs b/native/src/main.rs
index f1fa9fb..447cd46 100644
--- a/native/src/main.rs
+++ b/native/src/main.rs
@@ -8,12 +8,14 @@ mod content;
mod db;
mod engine;
mod icons;
+mod journal;
mod mcp;
mod models;
mod pdf;
mod platform;
mod previews;
mod scheduling;
+mod search_filters;
mod setup;
mod updates;
mod vector_cache;
@@ -33,6 +35,37 @@ fn run() -> anyhow::Result<()> {
unsafe {
std::env::set_var("VECTORDASH_MODEL_LOG", home.join("model.log"));
}
+ if let Some(i) = args.iter().position(|a| a == "--journal-probe") {
+ let result=journal::probe(args.get(i+1).ok_or_else(||anyhow::anyhow!("Missing volume"))?).unwrap_or_else(|e|serde_json::json!({"accessible":false,"fallback":"folder notifications","error":e.to_string()}));
+ if let Some(i) = args.iter().position(|a| a == "--report") {
+ std::fs::write(&args[i + 1], serde_json::to_vec(&result)?)?;
+ }
+ return Ok(());
+ }
+ if let Some(i) = args.iter().position(|a| a == "--test-audio-playback") {
+ let path = args
+ .get(i + 1)
+ .ok_or_else(|| anyhow::anyhow!("Missing test audio path"))?;
+ platform::play_at(path, 1.0)?;
+ let start = std::time::Instant::now();
+ let mut errors = vec![];
+ while start.elapsed() < std::time::Duration::from_secs(4) {
+ std::thread::sleep(std::time::Duration::from_millis(100));
+ errors.extend(platform::playback_errors());
+ }
+ if platform::playback_active() {
+ errors.push("Audio did not finish within the test deadline".into());
+ }
+ platform::stop_playback();
+ if let Some(i) = args.iter().position(|a| a == "--report") {
+ std::fs::write(
+ &args[i + 1],
+ serde_json::to_vec(&serde_json::json!({"ok":errors.is_empty(),"errors":errors}))?,
+ )?;
+ }
+ anyhow::ensure!(errors.is_empty(), "Audio playback failed: {:?}", errors);
+ return Ok(());
+ }
if cli::run(&home, &args)? {
return Ok(());
}
diff --git a/native/src/models.rs b/native/src/models.rs
index 8776135..b05af83 100644
--- a/native/src/models.rs
+++ b/native/src/models.rs
@@ -16,6 +16,7 @@ pub struct Models {
agent: ureq::Agent,
pub loaded: Arc<AtomicBool>,
active: Arc<AtomicUsize>,
+ query_cache: Arc<Mutex<Option<(String, Instant, Vec<f32>)>>>,
}
struct Activity<'a>(&'a Models);
impl Drop for Activity<'_> {
@@ -61,6 +62,7 @@ impl Default for Models {
.into(),
loaded: Arc::new(AtomicBool::new(false)),
active: Arc::new(AtomicUsize::new(0)),
+ query_cache: Arc::new(Mutex::new(None)),
}
}
}
@@ -401,10 +403,31 @@ impl Models {
Ok(out)
}
pub fn query(&self, s: &Settings, q: &str) -> Result<Vec<f32>> {
- self.text_batch(s, &[format!("task: search result | query: {q}")])?
+ // One short-lived query vector avoids repeating inference for multi-source searches.
+ let key = format!(
+ "{}|{}|{}|{}|{}",
+ Self::url(s),
+ s.remote_key,
+ s.model,
+ s.server,
+ q
+ );
+ let mut cache = self
+ .query_cache
+ .lock()
+ .map_err(|_| anyhow::anyhow!("Query cache unavailable"))?;
+ if let Some((saved, when, vector)) = &*cache {
+ if *saved == key && when.elapsed() < Duration::from_secs(2) {
+ return Ok(vector.clone());
+ }
+ }
+ let vector = self
+ .text_batch(s, &[format!("task: search result | query: {q}")])?
.into_iter()
.next()
- .context("Missing query embedding")
+ .context("Missing query embedding")?;
+ *cache = Some((key, Instant::now(), vector.clone()));
+ Ok(vector)
}
}
pub fn normalize(mut v: Vec<f32>) -> Vec<f32> {
diff --git a/native/src/platform.rs b/native/src/platform.rs
index 39068ad..dc5aad5 100644
--- a/native/src/platform.rs
+++ b/native/src/platform.rs
@@ -1009,7 +1009,7 @@ pub fn material(hwnd: isize, popup: bool, accent: [u8; 3], opacity: f32) {
std::mem::size_of_val(&rounded) as u32,
);
let margins = windows::Win32::UI::Controls::MARGINS {
- cxLeftWidth: if popup { -1 } else { 0 },
+ cxLeftWidth: 0,
cxRightWidth: 0,
cyTopHeight: 0,
cyBottomHeight: 0,
@@ -1282,12 +1282,24 @@ pub fn local_network(ip: std::net::Ipv4Addr) -> bool {
pub fn play_at(path: &str, seconds: f32) -> Result<()> {
let player = std::env::current_exe()?.with_file_name("ffplay.exe");
anyhow::ensure!(player.is_file(), "Bundled media player missing");
+ stop_playback();
+ let log = std::env::var_os("VECTORDASH_MODEL_LOG")
+ .map(std::path::PathBuf::from)
+ .map(|p| p.with_file_name("playback.log"))
+ .unwrap_or_else(|| std::env::temp_dir().join("vectordash-playback.log"));
+ let stderr = std::fs::File::create(&log)?;
let mut command = Command::new(player);
+ if audio_only(path) {
+ command.args(["-nodisp", "-vn"]);
+ }
+
command
.args([
"-loglevel",
"error",
"-autoexit",
+ "-nostats",
+ "-hide_banner",
"-ss",
&seconds.max(0.0).to_string(),
"-window_title",
@@ -1295,32 +1307,84 @@ pub fn play_at(path: &str, seconds: f32) -> Result<()> {
])
.arg(path)
.stdout(std::process::Stdio::null())
- .stderr(std::process::Stdio::null());
+ .stderr(std::process::Stdio::from(stderr));
crate::content::hidden(&mut command);
let child = command.spawn()?;
PLAYBACK
.get_or_init(|| std::sync::Mutex::new(vec![]))
.lock()
.map_err(|_| anyhow::anyhow!("Playback state unavailable"))?
- .push(child);
+ .push(Playback { child, log });
Ok(())
}
#[cfg(not(windows))]
pub fn play_at(_: &str, _: f32) -> Result<()> {
Ok(())
}
-static PLAYBACK: std::sync::OnceLock<std::sync::Mutex<Vec<Child>>> = std::sync::OnceLock::new();
+struct Playback {
+ child: Child,
+ log: std::path::PathBuf,
+}
+static PLAYBACK: std::sync::OnceLock<std::sync::Mutex<Vec<Playback>>> = std::sync::OnceLock::new();
pub fn stop_playback() {
if let Some(players) = PLAYBACK.get() {
if let Ok(mut players) = players.lock() {
- for mut child in players.drain(..) {
- let _ = child.kill();
- let _ = child.wait();
+ for mut player in players.drain(..) {
+ let _ = player.child.kill();
+ let _ = player.child.wait();
}
}
}
}
+fn audio_only(path: &str) -> bool {
+ matches!(
+ std::path::Path::new(path)
+ .extension()
+ .and_then(|v| v.to_str())
+ .unwrap_or("")
+ .to_lowercase()
+ .as_str(),
+ "mp3" | "wav" | "flac" | "aac" | "m4a" | "ogg" | "opus" | "wma" | "aiff" | "aif"
+ )
+}
+pub fn playback_active() -> bool {
+ PLAYBACK
+ .get()
+ .is_some_and(|players| players.lock().is_ok_and(|p| !p.is_empty()))
+}
+pub fn playback_errors() -> Vec<String> {
+ let mut errors = vec![];
+ if let Some(players) = PLAYBACK.get() {
+ if let Ok(mut players) = players.lock() {
+ let mut i = 0;
+ while i < players.len() {
+ if let Ok(Some(status)) = players[i].child.try_wait() {
+ let player = players.remove(i);
+ use std::io::Read;
+ let mut text = String::new();
+ if let Ok(file) = std::fs::File::open(player.log) {
+ let _ = file.take(65536).read_to_string(&mut text);
+ }
+ text = playback_message(&text);
+ if !status.success() || !text.trim().is_empty() {
+ errors.push(format!(
+ "Media playback failed: {}",
+ if text.trim().is_empty() {
+ status.to_string()
+ } else {
+ text.trim().to_owned()
+ }
+ ));
+ }
+ } else {
+ i += 1;
+ }
+ }
+ }
+ }
+ errors
+}
pub fn parse_devices(text: &str) -> Vec<(String, String)> {
text.lines()
.filter_map(|line| {
@@ -1390,8 +1454,99 @@ fn store_apps() -> Result<Vec<Hit>> {
}
static MAIN_WINDOW: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(0);
+static DRAG_REGIONS: std::sync::OnceLock<std::sync::Mutex<Vec<[i32; 4]>>> =
+ std::sync::OnceLock::new();
+pub fn clear_drag_regions() {
+ DRAG_REGIONS
+ .get_or_init(Default::default)
+ .lock()
+ .unwrap()
+ .clear();
+}
+pub fn add_drag_region(rect: [f32; 4], scale: f32) {
+ DRAG_REGIONS
+ .get_or_init(Default::default)
+ .lock()
+ .unwrap()
+ .push(rect.map(|v| (v * scale).round() as i32));
+}
+#[cfg(windows)]
+unsafe extern "system" fn window_hit_test(
+ hwnd: windows::Win32::Foundation::HWND,
+ message: u32,
+ wparam: windows::Win32::Foundation::WPARAM,
+ lparam: windows::Win32::Foundation::LPARAM,
+ _: usize,
+ _: usize,
+) -> windows::Win32::Foundation::LRESULT {
+ use windows::Win32::{
+ Foundation::{LRESULT, POINT},
+ Graphics::Gdi::ScreenToClient,
+ UI::{
+ Shell::DefSubclassProc,
+ WindowsAndMessaging::{HTCAPTION, WM_NCHITTEST},
+ },
+ };
+ if message == WM_NCHITTEST {
+ let mut p = POINT {
+ x: lparam.0 as i16 as i32,
+ y: (lparam.0 >> 16) as i16 as i32,
+ };
+ if unsafe { ScreenToClient(hwnd, &mut p) }.as_bool()
+ && DRAG_REGIONS.get().is_some_and(|regions| {
+ regions.try_lock().is_ok_and(|regions| {
+ regions
+ .iter()
+ .any(|r| p.x >= r[0] && p.y >= r[1] && p.x < r[2] && p.y < r[3])
+ })
+ })
+ {
+ return LRESULT(HTCAPTION as isize);
+ }
+ }
+ unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
+}
+
+/// Start the Windows move loop directly while the pointer button is down.
+/// A queued viewport drag command can arrive after input/capture state changes.
+#[cfg(windows)]
+pub fn drag_main_window() {
+ use windows::Win32::{
+ Foundation::{HWND, LPARAM, POINT, WPARAM},
+ UI::{Input::KeyboardAndMouse::ReleaseCapture, WindowsAndMessaging::*},
+ };
+ let value = MAIN_WINDOW.load(std::sync::atomic::Ordering::Relaxed);
+ if value == 0 {
+ return;
+ }
+ unsafe {
+ let mut cursor = POINT::default();
+ if GetCursorPos(&mut cursor).is_ok() {
+ let _ = ReleaseCapture();
+ let packed = (cursor.x as u16 as u32) | ((cursor.y as u16 as u32) << 16);
+ let _ = PostMessageW(
+ Some(HWND(value as *mut _)),
+ WM_NCLBUTTONDOWN,
+ WPARAM(HTCAPTION as usize),
+ LPARAM(packed as i32 as isize),
+ );
+ }
+ }
+}
+#[cfg(not(windows))]
+pub fn drag_main_window() {}
+
pub fn register_main_window(hwnd: isize) {
MAIN_WINDOW.store(hwnd, std::sync::atomic::Ordering::Relaxed);
+ #[cfg(windows)]
+ unsafe {
+ let _ = windows::Win32::UI::Shell::SetWindowSubclass(
+ windows::Win32::Foundation::HWND(hwnd as *mut _),
+ Some(window_hit_test),
+ 0x5644,
+ 0,
+ );
+ }
}
#[cfg(windows)]
pub fn wake_main_window() {
@@ -1470,3 +1625,45 @@ mod clipboard_tests {
}
}
}
+
+#[cfg(test)]
+mod audio_tests {
+ #[test]
+ fn audio_preview_skips_album_art_and_display() {
+ assert!(super::audio_only("podcast.MP3"));
+ assert!(super::audio_only("note.opus"));
+ assert!(!super::audio_only("clip.mp4"));
+ }
+}
+
+fn playback_message(text: &str) -> String {
+ let mut out = String::new();
+ let mut chars = text.chars().peekable();
+ while let Some(c) = chars.next() {
+ if c == char::from(27) {
+ if chars.peek() == Some(&'[') {
+ chars.next();
+ for c in chars.by_ref() {
+ if ('@'..='~').contains(&c) {
+ break;
+ }
+ }
+ }
+ } else if !c.is_control() || c == '\n' || c == '\t' {
+ out.push(c);
+ }
+ }
+ out.trim().to_owned()
+}
+#[cfg(test)]
+mod playback_diagnostics_tests {
+ #[test]
+ fn terminal_controls_are_not_playback_errors() {
+ let esc = char::from(27);
+ assert!(super::playback_message(&format!("{esc}[2K")).is_empty());
+ assert_eq!(
+ super::playback_message(&format!("{esc}[31mAudio device failed{esc}[0m")),
+ "Audio device failed"
+ );
+ }
+}
diff --git a/native/src/search_filters.rs b/native/src/search_filters.rs
new file mode 100644
index 0000000..1286e92
--- /dev/null
+++ b/native/src/search_filters.rs
@@ -0,0 +1,156 @@
+use anyhow::{Result, bail};
+#[derive(Default, Debug)]
+pub struct Filters {
+ pub text: String,
+ pub pattern: Option<String>,
+ pub min_size: i64,
+ pub max_size: i64,
+ pub after: i64,
+ pub before: i64,
+ pub extension: Option<String>,
+}
+impl Filters {
+ pub fn active(&self) -> bool {
+ self.pattern.is_some()
+ || self.extension.is_some()
+ || self.min_size > 0
+ || self.max_size < i64::MAX
+ || self.after > 0
+ || self.before < i64::MAX
+ }
+ pub fn parse(query: &str) -> Result<Self> {
+ let mut f = Self {
+ max_size: i64::MAX,
+ before: i64::MAX,
+ ..Self::default()
+ };
+ let mut words = vec![];
+ for word in query.split_whitespace() {
+ let low = word.to_lowercase();
+ if let Some(v) = low.strip_prefix("size:") {
+ let (op, v) = comparison(v);
+ let n = size(v)?;
+ match op {
+ ">" => f.min_size = n.saturating_add(1),
+ ">=" => f.min_size = n,
+ "<" => f.max_size = n.saturating_sub(1),
+ "<=" => f.max_size = n,
+ "=" => {
+ f.min_size = n;
+ f.max_size = n;
+ }
+ _ => unreachable!(),
+ }
+ } else if let Some(v) = low
+ .strip_prefix("modified:")
+ .or_else(|| low.strip_prefix("date:"))
+ {
+ let (op, v) = comparison(v);
+ let date = if v == "today" {
+ chrono::Local::now().date_naive()
+ } else {
+ chrono::NaiveDate::parse_from_str(v, "%Y-%m-%d").map_err(|_| {
+ anyhow::anyhow!(
+ "Use modified:YYYY-MM-DD, modified:>=YYYY-MM-DD or modified:today"
+ )
+ })?
+ };
+ use chrono::TimeZone;
+ let midnight = chrono::Local
+ .from_local_datetime(&date.and_hms_opt(0, 0, 0).unwrap())
+ .earliest()
+ .ok_or_else(|| anyhow::anyhow!("Invalid local date"))?
+ .timestamp_nanos_opt()
+ .unwrap_or(i64::MAX);
+ let end = chrono::Local
+ .from_local_datetime(
+ &date
+ .succ_opt()
+ .unwrap_or(date)
+ .and_hms_opt(0, 0, 0)
+ .unwrap(),
+ )
+ .earliest()
+ .map(|t| t.timestamp_nanos_opt().unwrap_or(i64::MAX))
+ .unwrap_or(i64::MAX);
+ match op {
+ ">" => f.after = end,
+ ">=" => f.after = midnight,
+ "<" => f.before = midnight.saturating_sub(1),
+ "<=" => f.before = end.saturating_sub(1),
+ _ => {
+ f.after = midnight;
+ f.before = end.saturating_sub(1);
+ }
+ }
+ } else if let Some(v) = low.strip_prefix("ext:") {
+ if v.is_empty() {
+ bail!("Use ext:pdf or ext:jpg,png");
+ }
+ f.extension = Some(v.trim_start_matches('.').into());
+ } else if let Some(v) = word.strip_prefix("name:") {
+ f.pattern = Some(v.to_lowercase());
+ } else if word.contains(['*', '?']) {
+ f.pattern = Some(low);
+ } else {
+ words.push(word);
+ }
+ }
+ f.text = words.join(" ");
+ Ok(f)
+ }
+ pub fn matches(&self, name: &str, size: i64, mtime: i64) -> bool {
+ size >= self.min_size
+ && size <= self.max_size
+ && mtime >= self.after
+ && mtime <= self.before
+ && self
+ .pattern
+ .as_ref()
+ .is_none_or(|p| crate::config::wildcard_match(&name.to_lowercase(), p))
+ && self.extension.as_ref().is_none_or(|e| {
+ e.split(',')
+ .any(|x| name.to_lowercase().ends_with(&format!(".{x}")))
+ })
+ }
+}
+fn comparison(v: &str) -> (&str, &str) {
+ for op in [">=", "<=", ">", "<", "="] {
+ if let Some(v) = v.strip_prefix(op) {
+ return (op, v);
+ }
+ }
+ ("=", v)
+}
+fn size(v: &str) -> Result<i64> {
+ let split = v
+ .find(|c: char| !c.is_ascii_digit() && c != '.')
+ .unwrap_or(v.len());
+ let number: f64 = v[..split]
+ .parse()
+ .map_err(|_| anyhow::anyhow!("Use size:>10MB, size:<1GB or size:1024"))?;
+ let scale = match &v[split..] {
+ "" | "b" => 1.,
+ "kb" | "kib" => 1024.,
+ "mb" | "mib" => 1024. * 1024.,
+ "gb" | "gib" => 1024. * 1024. * 1024.,
+ _ => bail!("Size units: B, KB, MB or GB"),
+ };
+ if !number.is_finite() || number < 0. {
+ bail!("Invalid size")
+ }
+ Ok((number * scale).min(i64::MAX as f64) as i64)
+}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn filenames_sizes_and_dates() {
+ let f = Filters::parse("dog*.jpg size:>1KB modified:>=2026-01-01").unwrap();
+ assert!(f.matches("dogs.jpg", 2048, i64::MAX));
+ assert!(!f.matches("cat.jpg", 2048, i64::MAX));
+ assert!(!f.matches("dogs.jpg", 512, i64::MAX));
+ assert!(Filters::parse("size:banana").is_err());
+ assert!(Filters::parse("modified:no-date").is_err());
+ }
+}
diff --git a/packaging/VectorDash-Rust.iss b/packaging/VectorDash-Rust.iss
index e14d9f2..2b1b84f 100644
--- a/packaging/VectorDash-Rust.iss
+++ b/packaging/VectorDash-Rust.iss
@@ -1,7 +1,7 @@
[Setup]
AppId={{5ACFE4A2-EC45-4B54-95C7-25B862C57DC9}
AppName=VectorDash
-AppVersion=0.3.5
+AppVersion=0.3.8
AppPublisher=VectorDash contributors
AppPublisherURL=https://github.com/ampersandru/VectorDash
DefaultDirName={localappdata}\Programs\VectorDashRust
@@ -11,7 +11,7 @@ ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
MinVersion=10.0.22000
OutputDir=..\dist\installer
-OutputBaseFilename=VectorDash-Rust-Setup-0.3.5-x64
+OutputBaseFilename=VectorDash-Rust-Setup-0.3.8-x64
SetupIconFile=VectorDash.ico
UninstallDisplayIcon={app}\VectorDash.exe
LicenseFile=..\LICENSE