diff --git a/plugins/local-fsearch/CHANGELOG.md b/plugins/local-fsearch/CHANGELOG.md new file mode 100644 index 000000000..5594d2191 --- /dev/null +++ b/plugins/local-fsearch/CHANGELOG.md @@ -0,0 +1,10 @@ +# 更新记录 + +## 0.0.2 + +- 一个插件支持 Windows(Everything)和 macOS(FSearch)。 +- 文件名、完整路径、分类、目录、扩展名、修改时间、大小筛选与分页。 +- 图片缩略图与独立大图窗口,支持滚轮定位缩放和任意比例自由拖动。 +- fs / find 快捷入口、搜索预设、主搜索推送和上次条件恢复。 +- Windows 提供官网下载入口、连接检测,并随包提供官方 ES;Everything 客户端由用户自行安装。 +- 公开作者:lifeek。 diff --git a/plugins/local-fsearch/LICENSE b/plugins/local-fsearch/LICENSE new file mode 100644 index 000000000..25e8f99d2 --- /dev/null +++ b/plugins/local-fsearch/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 lifeek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/local-fsearch/README.md b/plugins/local-fsearch/README.md new file mode 100644 index 000000000..134345626 --- /dev/null +++ b/plugins/local-fsearch/README.md @@ -0,0 +1,51 @@ +# FSearch 文件搜索 + +作者:**lifeek** · 版本:**0.0.2** · Windows / macOS + +在 ZTools 中输入 fs 或 find,快速查找本机文件和文件夹。 + +## 主要功能 + +- 按文件名或完整路径搜索,支持字符模糊、正则和大小写匹配。 +- 按类型、位置、扩展名、修改时间和大小筛选,支持排除目录。 +- 图片列表显示缩略图;大图在独立窗口打开,支持滚轮定位缩放、自由拖动和最大化。 +- 保存常用搜索为预设,也可生成 ZTools 独立指令。 +- 可开启主搜索推送,在 ZTools 搜索框直接输入 fs 关键词查看匹配。 + +## 首次使用 + +**Windows**:从 [Everything 官网](https://www.voidtools.com/downloads/) 安装 Everything 完整版并启动客户端,然后在插件“使用与连接”点击“检测连接”。插件已附带官方 ES 命令行工具,不需要另外下载;不包含 Everything 客户端安装程序。 + +**macOS**:单独安装 [noahdunnagan/fsearch](https://github.com/noahdunnagan/fsearch)。正文、代码定义、Git 状态、常用优先和 Quick Look 为 macOS 专属功能。 + +## 数据与隐私 + +查询和预览在本机完成,插件不上传文件名、图片或正文,不建立额外索引。设置和预设保存在 ZTools 本地存储中。 + +## 兼容说明 + +Windows 已在 ZTools 3.2.0 与 Everything 1.4.1.1026 环境检查主要功能。macOS 最新图片窗口体验仍待实机确认。更多信息见安装和隐私说明。 + +## 功能预览 + +截图来自 Windows ZTools,使用专门生成的演示文件和图片;可点击查看原图。 + +### 文件搜索 + + + +### 图片缩略图 + + + +### 独立大图预览 + + + +### 主搜索推送 + + + +### 搜索预设 + + diff --git a/plugins/local-fsearch/THIRD_PARTY_NOTICES.md b/plugins/local-fsearch/THIRD_PARTY_NOTICES.md new file mode 100644 index 000000000..6ef5a2f30 --- /dev/null +++ b/plugins/local-fsearch/THIRD_PARTY_NOTICES.md @@ -0,0 +1,45 @@ +# 第三方说明 + +本项目是第三方 ZTools 插件,不隶属于 FSearch 或 ZTools 官方。 + +## 外部引擎:noahdunnagan/fsearch + +项目:https://github.com/noahdunnagan/fsearch\ +已验证版本:v0.2.1(macOS Apple Silicon)\ +许可证:MIT。FSearch 由用户独立安装,本插件不捆绑其二进制、不复制其索引或实现代码,仅使用公开的 JSON Lines 接口。以下保留其许可声明以便用户了解依赖。 + +```text +MIT License + +Copyright (c) 2026 Noah Dunnagan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +## Windows:Everything 和 ES + +Everything 索引服务由用户独立安装。随包提供 voidtools 官方 ES 1.1.0.38 命令行工具(x64、ARM64、x86),用于查询已运行的 Everything。官方来源、MIT 许可证及 SHA-256 见 [vendor/es](vendor/es/README.md)。不包含 Everything 客户端安装程序。 + +## 宿主与图标 + +ZTools 由用户独立安装。本项目调用公开插件 API,不捆绑宿主代码或二进制;宿主许可证以其项目声明为准:https://github.com/ZToolsCenter/ZTools 。 + +插件 Logo 的 SVG 源文件及 PNG 导出随本项目 MIT 许可证分发。渲染导出使用 @resvg/resvg-js 2.6.2(MPL-2.0),渲染器不进入运行文件或安装产物。本项目没有 npm 运行时第三方依赖。 + +若后续改为捆绑引擎或引入第三方实现,需要重新核查所有随包组件的许可与声明;此文档不代表官方市场已审核。 diff --git a/plugins/local-fsearch/app.js b/plugins/local-fsearch/app.js new file mode 100644 index 000000000..0833365f0 --- /dev/null +++ b/plugins/local-fsearch/app.js @@ -0,0 +1,776 @@ +(() => { + const api = window.fsearchApi + const $ = id => document.getElementById(id) + const windows = api.windows + const modifier = windows ? 'Ctrl+' : '⌘' + const modifiedKey = event => windows ? event.ctrlKey : event.metaKey + const indexLabel = windows ? 'Everything 索引' : 'FSearch 索引' + if (windows) { + for (const value of ['content', 'symbol', 'engine']) $('match-field').querySelector(`[value="${value}"]`).remove() + $('match-field').value = 'name' + $('git').closest('label').hidden = true + $('boost').closest('label').hidden = true + $('editor').closest('.editor-controls').hidden = true + $('exclude').placeholder = 'C:\\Users\\用户名\\Downloads' + $('pref-auto-hide').nextSibling.textContent = ' 打开或定位成功后收起主窗口' + document.querySelector('.shortcuts').textContent = '↑↓ 选择 · ↵ 打开 · 空格 预览图片 · Ctrl+↵ 定位 · Ctrl+L 搜索 · Ctrl+C 路径' + } + const icons = { + search: '', + grid: '', + folder: '', + file: '', + table: '', + slides: '', + image: '', + video: '', + audio: '', + code: '', + archive: '', + copy: '', + refresh: '' + } + let query = '', category = 'all', rows = [], selected = 0, generation = 0, timer, toastTimer + let connectionReport = null, connectionBlocked = false, connectionGeneration = 0 + let lifecycle = 0, statusWarning = '', resultsValid = false, composing = false, frameId = null, lastTiming = null + let scheduledAt = 0, filterFocus = null, phase = 'idle', restoreState = null, sourceFile = null, contentFile = null, basePage = 0 + const preferenceDefaults = { autoHide: true, copyHide: false, remember: true, mainPush: false, workspace: '' } + const widePreview = window.matchMedia('(min-width: 1100px)') + let settings = { presets: [], editor: 'vscode' }, detailGeneration = 0, lastOptions = null, lastFocused = null + let pageOffsets = [0], pageStarts = [0], pageIndex = 0, nextOffset = null, loading = false + let thumbnailObserver, thumbnailJobs = [], thumbnailRunning = 0, imagePreviewUrl, imagePreviewResize, imagePreviewPreviousHeight, imageWindow + + const isImage = item => item.kind === 'file' && Boolean(api.imageType(item.path)) + const imageUrl = ({ bytes, type }) => URL.createObjectURL(new Blob([bytes], { type })) + function resetThumbnails() { thumbnailObserver?.disconnect(); thumbnailJobs = [] } + function pumpThumbnails() { + while (thumbnailRunning < 2 && thumbnailJobs.length) { + const button = thumbnailJobs.shift() + if (!button.isConnected) continue + thumbnailRunning++ + void loadThumbnail(button).finally(() => { thumbnailRunning--; pumpThumbnails() }) + } + } + async function loadThumbnail(button) { + let url + try { + const file = await api.readImage(button.dataset.imagePath) + if (!button.isConnected) return + url = imageUrl(file) + const source = new Image() + source.src = url + await source.decode() + if (!button.isConnected || !source.naturalWidth || !source.naturalHeight) return + // 结果页只保留小图,原图与对象 URL 在生成后释放。 + const canvas = document.createElement('canvas') + const scale = Math.min(1, 96 / Math.max(source.naturalWidth, source.naturalHeight)) + canvas.width = Math.max(1, Math.round(source.naturalWidth * scale)) + canvas.height = Math.max(1, Math.round(source.naturalHeight * scale)) + canvas.getContext('2d').drawImage(source, 0, 0, canvas.width, canvas.height) + const thumb = new Image() + thumb.alt = ''; thumb.src = canvas.toDataURL() + button.replaceChildren(thumb) + } catch { /* 图片不可读时保留图标,点击可查看原因或用系统应用打开。 */ } + finally { if (url) URL.revokeObjectURL(url) } + } + function observeThumbnails(list) { + thumbnailObserver ||= new IntersectionObserver(entries => { + for (const entry of entries) if (entry.isIntersecting && entry.target.isConnected) { + thumbnailObserver.unobserve(entry.target); thumbnailJobs.push(entry.target) + } + pumpThumbnails() + }, { root: list.parentElement, rootMargin: '80px' }) + for (const button of list.querySelectorAll('.image-thumb')) thumbnailObserver.observe(button) + } + + /** 跟随 ZTools 的实际主题及实时变更,宿主手动选色时也保持一致。 */ + function applyTheme(info) { document.documentElement.dataset.theme = info.isDark ? 'dark' : 'light'; document.documentElement.style.colorScheme = info.isDark ? 'dark' : 'light' } + applyTheme(window.ztools.getThemeInfo()) + window.ztools.onThemeChange(applyTheme) + + /** 仅把固定图标路径插入 SVG;所有文件名和路径始终用 textContent。 */ + function svg(name) { return `${icons[name] || icons.file}` } + function showToast(text) { $('toast').textContent = text; $('toast').hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => { $('toast').hidden = true }, 1800) } + function showNotice(text) { const message = [statusWarning, text].filter(Boolean).join('\n'); $('notice').textContent = message; $('notice').hidden = !message } + function formatSize(size) { if (size < 1024) return `${size} B`; const n = Math.floor(Math.log(size) / Math.log(1024)); return `${(size / 1024 ** n).toFixed(1)} ${['B', 'KB', 'MB', 'GB', 'TB'][n] || 'TB'}` } + function formatDate(seconds) { return seconds ? new Date(seconds * 1000).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }) : '—' } + function isEditing(target) { return target instanceof Element && Boolean(target.closest('input,textarea,select,[contenteditable="true"]')) } + + /** 复制按钮、路径文本和快捷键共用同一入口;不复制缩略的 ~/ 显示路径。 */ + async function copyPath(item) { + try { await api.copy(item.path); showToast('已复制完整路径') } + catch (error) { showNotice(error.message) } + } + + /** + * 读取一个原生分页结果;每次查询保存代次,翻页和条件变化都不能接受旧响应。 + * @param {number} version 本次请求代次 + * @returns {Promise} 当前页加载结束 + */ + async function search(version) { + if (!query.trim() && isContent()) { + loading = false; rows = []; resultsValid = true; setResultState(); render(); emptyState('查找文本内容', '请输入正文关键词或代码定义名称。'); $('result-summary').textContent = ''; updatePagination(); return + } + $('result-summary').textContent = '搜索中…'; showNotice('') + const options = searchOptions() + lastOptions = options + const requestedAt = performance.now() + try { + const response = await api.search(options) + if (version !== generation) return + const renderAt = performance.now(), previousPath = rows[selected]?.path + const restoring = restoreState; restoreState = null + rows = response.hits; selected = Math.max(0, rows.findIndex(item => item.path === (restoring?.selectedPath || previousPath))); nextOffset = response.next; loading = false; resultsValid = true; setResultState(); render() + const range = rows.length ? `${pageStarts[pageIndex] + 1}–${pageStarts[pageIndex] + rows.length}` : '0' + $('result-summary').textContent = `${range} ${response.recent ? '项最近文件' : response.content ? '个文件' : '项'} · 已更新` + if (!rows.length) { + if (response.content) emptyState(response.next !== null ? '本批次没有命中' : '没有找到文本命中', response.next !== null ? '可继续下一页,或缩小目录范围。' : '此范围未找到文本命中。索引可能受文件类型、大小、忽略规则或权限限制,可查看「索引状态」。') + else if (response.recent) emptyState('暂无最近文件', windows ? '这里按修改时间显示 Everything 索引中的文件。也可以勾选「空关键词浏览筛选结果」。' : '从插件打开文件后会记录在这里;也可以勾选「空关键词浏览筛选结果」。') + else emptyState(pageIndex ? '本页已无结果' : '没有找到匹配文件', pageIndex ? '索引实时变化,可以返回上一页或重新搜索。' : '试试更短的关键词,或切换匹配方式和搜索范围。') + } + if (response.contentIndexing > 0) showNotice('内容索引正在更新,部分文本结果可能暂未纳入,可稍后刷新。') + if (response.content && response.complete === false && response.next === null) showNotice('本次文本检索尚未完成,请缩小目录范围后重试。') + if (response.windowLimited) showNotice(response.windowMessage || '已达到引擎 20,000 项检索窗口上限,请缩小关键词、分类或目录范围。') + updatePagination() + $('results').parentElement.scrollTop = restoring?.scrollTop || 0 + lastTiming = { totalMs: performance.now() - scheduledAt, waitMs: requestedAt - scheduledAt, requestMs: renderAt - requestedAt, renderMs: performance.now() - renderAt, engineMs: Number.isFinite(response.took_us) ? response.took_us / 1000 : null, ...response.timings } + if (frameId !== null) cancelAnimationFrame(frameId) + frameId = requestAnimationFrame(() => { frameId = null; if (version === generation && lastTiming) lastTiming.frameMs = performance.now() - scheduledAt }) + } catch (error) { + if (version !== generation) return + loading = false; nextOffset = null; resultsValid = false; setResultState(); updatePagination(); $('result-summary').textContent = rows.length ? '更新失败 · 下方为上次结果,暂不可操作' : '更新失败'; if (!rows.length) emptyState('搜索未完成', '请检查上方提示,修改条件后重试。'); if (error.name !== 'AbortError') showNotice(error.message) + } + } + + /** 条件一变化立即重置游标并废弃在途请求,不能沿用上一次搜索的页码。 */ + function schedule() { + closeDetail(); updateFilterSummary(); basePage = 0; restoreState = null; pageOffsets = [0]; pageStarts = [0]; pageIndex = 0; queueSearch(true) + } + + /** 翻页立即执行,输入变化才防抖;加载期间禁止重复翻页。 */ + function queueSearch(debounce = false) { + if (connectionBlocked) { clearTimeout(timer); showNotice('请先通过“使用与连接”检查搜索引擎,再点击“重新检测”。'); return } + const version = ++generation + clearTimeout(timer); api.invalidateSearch?.(); nextOffset = null; loading = true; resultsValid = false + if (frameId !== null) { cancelAnimationFrame(frameId); frameId = null } + scheduledAt = performance.now(); setResultState(); updatePagination(); showNotice('') + $('result-summary').textContent = rows.length ? '正在更新 · 下方为上次结果,暂不可操作' : '正在搜索…' + if (!rows.length) emptyState(composing ? '输入完成后搜索' : '正在搜索', '') + if (composing) return + if (debounce) timer = setTimeout(() => search(version), isContent() || $('match-mode').value === 'regex' ? 180 : 75) + else search(version) + } + /** 旧列表仍可阅读,但不能打开、复制或翻页,防止对过期结果执行操作。 */ + function setResultState() { + $('results').inert = !resultsValid + $('results').setAttribute('aria-busy', String(loading)) + $('results').parentElement.classList.toggle('stale', !resultsValid && rows.length > 0) + } + + /** 采用服务给出的 next 游标记录历史,不根据页大小猜测下一页位置。 */ + function changePage(direction) { + if (loading || !resultsValid) return + if (direction < 0) { if (!pageIndex) return; pageIndex-- } + else { + if (nextOffset === null) return + pageOffsets = pageOffsets.slice(0, pageIndex + 1); pageOffsets.push(nextOffset); pageStarts = pageStarts.slice(0, pageIndex + 1); pageStarts.push(pageStarts[pageIndex] + rows.length); pageIndex++ + if (pageOffsets.length > 32) { pageOffsets.shift(); pageStarts.shift(); pageIndex--; basePage++ } + } + queueSearch() + } + function updatePagination() { + $('previous-page').title = basePage > 0 && pageIndex === 0 ? '仅保留最近 32 页历史,可用新搜索从头查询' : '上一页' + $('previous-page').disabled = !resultsValid || loading || pageIndex === 0 + $('next-page').disabled = !resultsValid || loading || nextOffset === null + $('page-summary').textContent = `第 ${basePage + pageIndex + 1} 页` + $('pagination').setAttribute('aria-busy', String(loading)) + } + function isContent() { return ['content', 'symbol'].includes($('match-field').value) } + /** 兼容性限制直接反映到控件,不把原生大小写不敏感伪装成 Aa 已生效。 */ + function updateModeHint() { + const field = $('match-field').value, content = isContent(), symbol = field === 'symbol', native = field === 'engine' + const previous = $('match-mode').value + const modes = native ? [['native', '模糊查找']] : symbol ? [['literal', '定义识别']] : [['literal', content ? '文本包含' : '精确包含'], ...(!content ? [['fuzzy', '字符模糊']] : []), ['regex', '正则表达式']] + $('match-mode').replaceChildren(...modes.map(([value, label]) => new Option(label, value))) + $('match-mode').value = modes.some(([value]) => value === previous) ? previous : modes[0][0] + $('match-mode').hidden = native || symbol; $('mode-label').hidden = native || symbol + $('match-case').hidden = native; $('match-case').disabled = native + $('content-note').hidden = !content; $('boost').disabled = content + const hints = { literal: symbol ? '仅搜索定义' : content ? '逐行包含原文' : '连续包含输入原文', fuzzy: '字符按顺序出现', native: '包含父目录 · 不区分大小写', regex: windows ? '正则表达式匹配' : 'Rust 正则语法' } + $('mode-hint').textContent = hints[$('match-mode').value] + $('match-mode').title = $('match-mode').value === 'regex' && !windows ? '不支持前后查找和反向引用;内联标志可覆盖 Aa' : hints[$('match-mode').value] + $('match-case').classList.toggle('active', $('match-case').getAttribute('aria-pressed') === 'true') + } + function emptyState(title, description) { $('empty-title').textContent = title; $('empty-description').textContent = description; $('empty').hidden = false } + + /** 选择只更新样式和焦点,不重建列表,保留滚动位置和键盘操作目标。 */ + function select(index, focus = false) { + if (!resultsValid) return + const followPreview = index !== selected && document.body.classList.contains('preview-docked') + if (index !== selected) closeDetail(false) + selected = index + Array.from($('results').children).forEach((row, i) => { row.classList.toggle('selected', i === index); row.setAttribute('aria-selected', String(i === index)) }) + const item = rows[index] + $('selection-summary').textContent = item ? `${pageStarts[pageIndex] + index + 1} · ${item.matches ? item.matches.length + ' 处命中预览' : item.kind === 'dir' ? '文件夹' : formatSize(item.size)}` : indexLabel + if (focus && item) { const row = $('results').children[index]; row.focus({ preventScroll: true }); row.scrollIntoView({ block: 'nearest' }) } + if (followPreview && item?.matches) previewItem(item) + } + + /** 列表用安全文本构建,完整路径可直接点击复制;每项保留明确的复制按钮。 */ + function render() { + resetThumbnails() + const list = $('results'); list.replaceChildren(); $('empty').hidden = rows.length > 0 + const fragment = document.createDocumentFragment() + rows.forEach((item, index) => { + const row = document.createElement('li'); row.className = 'result' + (item.kind === 'dir' ? ' folder' : ''); row.tabIndex = -1; row.setAttribute('role', 'option') + const picture = isImage(item) + const icon = document.createElement(picture ? 'button' : 'span') + icon.className = picture ? 'image-thumb' : 'file-icon' + icon.innerHTML = svg(picture ? 'image' : item.kind === 'dir' ? 'folder' : 'file') + if (picture) { + row.classList.add('image-result') + icon.dataset.imagePath = item.path + icon.title = '预览大图(空格)' + icon.setAttribute('aria-label', '预览大图:' + api.name(item.path)) + icon.onclick = event => { event.stopPropagation(); select(index); previewImage(item) } + } + const detail = document.createElement('div'); detail.className = 'file-detail' + const head = document.createElement('div'); head.className = 'file-head' + const name = document.createElement('div'); name.className = 'file-name'; name.textContent = api.name(item.path); name.title = name.textContent + const type = document.createElement('span'); type.className = 'file-type'; type.textContent = item.kind === 'dir' ? '文件夹' : item.kind === 'link' ? '链接' : (name.textContent.includes('.') ? name.textContent.split('.').pop().toUpperCase() : '文件') + head.append(name, type) + if (item.git) { const badge = document.createElement('span'); badge.className = 'git-badge'; badge.textContent = gitLabel(item.git); head.append(badge) } + const full = document.createElement('button'); full.className = 'file-path'; + const display = item.path.startsWith(api.home() + '/') ? '~/' + item.path.slice(api.home().length + 1) : item.path + const cut = windows ? Math.max(display.lastIndexOf('/'), display.lastIndexOf('\\')) : display.lastIndexOf('/'), parent = document.createElement('span'), leaf = document.createElement('span'), parentText = document.createElement('bdi') + parent.className = 'path-parent'; parentText.dir = 'ltr'; parentText.textContent = display.slice(0, cut + 1); parent.append(parentText) + leaf.className = 'path-leaf'; leaf.textContent = display.slice(cut + 1); full.append(parent, leaf); full.title = '点击复制完整路径:' + item.path; full.setAttribute('aria-label', '复制完整路径:' + item.path) + full.onclick = event => { event.stopPropagation(); select(index); copyPath(item) } + const foot = document.createElement('div'); foot.className = 'file-foot' + const meta = document.createElement('span'); meta.className = 'file-meta'; meta.textContent = item.matches ? `${item.matches.length} 处命中预览` : `${item.kind === 'dir' ? '文件夹' : formatSize(item.size)} · ${formatDate(item.mtime)}` + const actions = document.createElement('div'); actions.className = 'actions' + ;[...(picture ? [['预览大图', () => previewImage(item)]] : !windows ? [['预览', () => previewItem(item)]] : []), ['打开', api.open], ['定位', api.reveal], ['复制路径', () => copyPath(item)]].forEach(([label, action]) => { + const button = document.createElement('button'); button.className = label === '复制路径' ? 'copy-action' : 'secondary-action' + if (label === '复制路径') button.innerHTML = svg('copy') + button.append(document.createTextNode(label)); button.title = label === '复制路径' ? `复制完整绝对路径(选中结果后 ${modifier}C)` : label === '定位' ? (windows ? '在文件资源管理器中显示' : '在 Finder 中显示') : label === '预览大图' ? '在插件内查看大图(空格)' : label === '预览' ? item.matches ? '展开正文命中及上下文' : '使用 macOS 快速预览' : '用默认应用打开' + button.onclick = event => { event.stopPropagation(); select(index); Promise.resolve().then(() => action(item.path)).catch(error => showNotice(error.message)) } + actions.append(button) + }) + const menu = document.createElement('details'); menu.className = 'row-menu' + const toggle = document.createElement('summary'); toggle.textContent = '更多'; toggle.setAttribute('aria-label', '更多操作:' + name.textContent) + const menuBody = document.createElement('div') + ;[...(!windows ? [['快速预览', () => api.quickLook(item.path)]] : []), ['粘贴文件到原应用', () => api.pasteFile(item.path)], ['粘贴路径到原应用', () => api.pastePath(item.path)], ['复制文件', async () => { await api.copyFile(item.path); showToast('已复制文件,可直接粘贴') }], ...(item.matches?.length ? [['编辑器跳转首个命中', () => api.openLine(item.path, item.matches[0].line, settings.editor)]] : [])].forEach(([label, action]) => { const button = document.createElement('button'); button.textContent = label; button.onclick = event => { event.stopPropagation(); menu.open = false; select(index); Promise.resolve().then(action).catch(error => showNotice(error.message)) }; menuBody.append(button) }) + menu.addEventListener('toggle', () => { if (menu.open) { const boundary = $('results').parentElement.getBoundingClientRect(); menu.classList.toggle('menu-up', menu.getBoundingClientRect().bottom + menuBody.offsetHeight + 6 > boundary.bottom) } }) + menu.onclick = event => event.stopPropagation(); menu.append(toggle, menuBody); actions.append(menu) + head.insertBefore(meta, type); foot.append(actions); detail.append(head, full); if (item.matches?.length) detail.append(renderSummary(item)); detail.append(foot); row.append(icon, detail) + row.onclick = () => { if (!window.getSelection()?.toString()) select(index, true) } + row.ondblclick = event => { if (!event.target.closest('button')) Promise.resolve().then(() => api.open(item.path)).catch(error => showNotice(error.message)) } + fragment.append(row) + }) + list.append(fragment); if (list.querySelector('.image-thumb')) observeThumbnails(list); select(selected) + } + /** 列表只构建首处命中的一行摘要,完整上下文留给按需预览。 */ + function renderSummary(item) { + const match = item.matches[0], line = document.createElement('div'); line.className = 'content-summary' + const number = document.createElement('button'); number.className = 'jump-line'; number.textContent = match.line; number.setAttribute('aria-label', `第 ${match.line} 行`) + number.title = '在编辑器中打开命中行'; number.onclick = event => { event.stopPropagation(); api.openLine(item.path, match.line, settings.editor).catch(error => showNotice(error.message)) } + const code = document.createElement('code') + if (match.outsidePreview) code.textContent = '命中位于行预览范围外,展开查看' + else match.parts.forEach(part => { const node = document.createElement(part.matched ? 'mark' : 'span'); node.textContent = part.text; code.append(node) }) + line.append(number, code); return line + } + /** 行号和高亮都来自引擎,正文只作为文本节点插入,不能执行其中的 HTML。 */ + function renderSnippets(matches, target) { + const container = document.createElement('div'); container.className = 'content-snippets' + function line(number, parts, context = false) { + const row = document.createElement('div'); row.className = 'snippet-line' + (context ? ' context-line' : ' match-line') + const label = document.createElement(target && !context ? 'button' : 'span'); label.className = 'line-number' + (target && !context ? ' jump-line' : ''); + if (target && !context) { label.title = '在编辑器中打开第 ' + number + ' 行'; label.onclick = event => { event.stopPropagation(); api.openLine(target, number, settings.editor).catch(error => showNotice(error.message)) } } label.textContent = number; label.setAttribute('aria-label', `第 ${number} 行`) + const code = document.createElement('code') + parts.forEach(part => { const node = document.createElement(part.matched ? 'mark' : 'span'); node.textContent = part.text; code.append(node) }) + row.append(label, code); return row + } + // 相邻命中的上下文可能重叠,按行号合并,命中样式优先,避免重复展示同一行。 + const lines = new Map() + matches.forEach(match => { + for (const item of [...match.before, ...match.after]) if (!lines.has(item.line)) lines.set(item.line, { number: item.line, parts: [{ text: item.text }], context: true }) + lines.set(match.line, { number: match.line, parts: match.parts, context: false, outside: match.outsidePreview }) + }) + let group, previous = -2 + for (const item of [...lines.values()].sort((a, b) => a.number - b.number)) { + if (item.number !== previous + 1) { group = document.createElement('div'); group.className = 'snippet-group'; container.append(group) } + group.append(line(item.number, item.parts, item.context)) + if (item.outside) { const note = document.createElement('div'); note.className = 'snippet-note'; note.textContent = '命中位置超出本行预览,打开文件查看。'; group.append(note) } + previous = item.number + } + return container + } + function updateCategoryTitle() { + const item = api.categories.find(item => item.id === category) + $('category-title').textContent = isContent() ? ($('match-field').value === 'symbol' ? '代码定义' : category === 'all' ? '文件内容' : item.contentLabel || item.label) : item.label + } + function renderCategories() { + $('categories').replaceChildren() + const content = isContent() + api.categories.filter(item => !content || item.contentSupported).forEach(item => { + const button = document.createElement('button'); button.disabled = Boolean(contentFile && isContent()); button.className = 'category' + (category === item.id ? ' active' : ''); button.setAttribute('aria-pressed', String(category === item.id)); button.innerHTML = svg(item.icon); button.append(document.createTextNode(content ? item.contentLabel || item.label : item.label)) + button.onclick = () => { category = item.id; updateCategoryTitle(); renderCategories(); schedule() } + $('categories').append(button) + }) + } + + /** 首次连接失败停止自动搜索;显式重试才重新检测,不让输入触发重复启动。 */ + async function refreshStatus(recheck = false) { + const active = lifecycle, attempt = ++connectionGeneration + if (recheck) { connectionBlocked = true; generation++; clearTimeout(timer); api.invalidateSearch?.(); resultsValid = false; setResultState(); updatePagination() } + try { + const report = await api.connection({ recheck }) + if (active !== lifecycle || attempt !== connectionGeneration) return null + connectionReport = report + if (!report.usable) { + connectionBlocked = true; statusWarning = ''; resultsValid = false; rows = []; render(); setResultState(); updatePagination() + $('index-summary').textContent = '未就绪'; $('status-dot').classList.remove('ready') + emptyState(report.title, report.message + ' 点击“使用与连接”查看指引。'); showNotice(report.detail); return false + } + const data = report.status + if (active !== lifecycle || attempt !== connectionGeneration) return null + connectionBlocked = false + if (windows) { + $('index-summary').textContent = 'Everything 已连接' + $('index-summary').title = 'Everything ' + data.version + $('status-dot').classList.add('ready') + statusWarning = ''; showNotice('') + return true + } + $('index-summary').textContent = `${(data.entries / 10000).toFixed(1)} 万项` + $('index-summary').title = `已索引 ${data.entries.toLocaleString()} 个文件和目录;${data.full_disk_access ? '完整磁盘访问可用' : '权限受限'}` + $('status-dot').classList.add('ready') + statusWarning = data.full_disk_access ? '' : '完整磁盘访问未开启,部分受保护目录可能未纳入索引。可在“使用与连接”查看授权指引。' + showNotice(data.content_pending > 0 ? `正文索引待更新 ${data.content_pending} 个文件。` : '') + return true + } catch (error) { + if (active !== lifecycle || attempt !== connectionGeneration) return null + connectionBlocked = true; $('index-summary').textContent = '未就绪'; $('status-dot').classList.remove('ready'); showNotice(error.message); return false + } + } + /** 当前条件只保存字符串和开关;不保存结果或正文,预设最多 20 条。 */ + function searchOptions() { + return { query, category, directory: $('directory').value.trim(), mode: $('match-mode').value, field: $('match-field').value, caseSensitive: $('match-field').value !== 'engine' && $('match-case').getAttribute('aria-pressed') === 'true', pageSize: Number($('page-size').value), offset: pageOffsets[pageIndex], extensions: $('extensions').value.trim(), modified: $('modified').value, size: $('size').value.trim(), exclude: $('exclude').value.trim(), git: $('git').value, file: isContent() ? contentFile || undefined : undefined, boost: $('boost').checked && !isContent(), browse: $('browse').checked || Boolean($('git').value) } + } + function gitLabel(value) { return ({ modified: '已修改', staged: '已暂存', untracked: '未跟踪', conflict: '冲突', clean: '未修改', tracked: '已跟踪', ignored: '已忽略', added: '新增', renamed: '重命名', deleted: '已删除' })[value] || value } + function updateFilterSummary() { + const single = Boolean(contentFile && isContent()) + for (const id of ['directory', 'location', 'apply', 'clear', 'extensions', 'modified', 'size', 'exclude', 'git']) $(id).disabled = single + $('directory').placeholder = single ? '当前文件:' + api.name(contentFile) : '所有索引位置' + const chips = $('filter-chips'); chips.replaceChildren() + if (contentFile && isContent()) addChip('单文件正文', () => { contentFile = null; renderCategories(); schedule() }, contentFile) + const fields = { extensions: '类型', modified: '时间', size: '大小', exclude: '排除', git: 'Git' } + for (const [id, label] of Object.entries(fields)) { + const value = $(id).value.trim(); if (!value) continue + const text = id === 'exclude' ? `${value.split('\n').filter(Boolean).length} 个目录` : id === 'git' ? $('git').selectedOptions[0].textContent : value + addChip(`${label}:${text}`, () => { $(id).value = ''; schedule() }) + } + if ($('directory').value.trim()) addChip('指定目录', () => { $('directory').value = ''; schedule() }, $('directory').value) + if ($('boost').checked && !isContent()) addChip('常用优先', () => { $('boost').checked = false; schedule() }) + if ($('browse').checked) addChip('浏览', () => { $('browse').checked = false; schedule() }) + $('filter-summary').textContent = single ? '当前直接搜索单个文件;移除「单文件正文」条件后可使用其他筛选。' : chips.children.length ? `当前 ${chips.children.length} 项条件;修改后自动更新结果。` : '未限制额外条件。' + function addChip(text, remove, title = text) { const button = document.createElement('button'); button.className = 'filter-chip'; button.textContent = text + ' ×'; button.title = title + '(点击移除)'; button.setAttribute('aria-label', '移除筛选:' + text); button.onclick = remove; chips.append(button) } + } + /** 宽屏正文作为侧栏,不阻塞列表;窄屏与筛选使用可关闭的模态面板。 */ + function syncPanelLayout() { + const detail = !$('detail-panel').hidden, filter = !$('advanced').hidden + const docked = detail && $('detail-panel').dataset.kind === 'preview' && widePreview.matches + document.body.classList.toggle('preview-docked', docked) + $('detail-panel').setAttribute('role', docked ? 'region' : 'dialog') + $('detail-panel').setAttribute('aria-modal', String(!docked)) + document.querySelector('.workspace').inert = filter || (detail && !docked) + $('panel-backdrop').hidden = !(filter || (detail && !docked)) + } + function closeFilters(restore = true) { + $('advanced').hidden = true; syncPanelLayout() + if (restore && filterFocus?.isConnected) filterFocus.focus({ preventScroll: true }); filterFocus = null + } + function closeDetail(restore = true) { + imagePreviewResize?.(); imagePreviewResize = null + detailGeneration++; api.invalidatePreview?.(); $('detail-panel').hidden = true; $('detail-body').replaceChildren(); $('detail-actions').replaceChildren(); syncPanelLayout() + if (imagePreviewUrl) { URL.revokeObjectURL(imagePreviewUrl); imagePreviewUrl = null } + if (imagePreviewPreviousHeight !== undefined) { + const height = imagePreviewPreviousHeight; imagePreviewPreviousHeight = undefined + requestPreviewHeight(height) + } + if (restore && lastFocused?.isConnected) lastFocused.focus({ preventScroll: true }); lastFocused = null + } + function openDetail(title, kind = 'diagnostics') { + closeFilters(false); closeDetail(false); lastFocused = document.activeElement + $('detail-title').textContent = title; $('detail-panel').dataset.kind = kind; $('detail-panel').hidden = false; syncPanelLayout(); if ($('detail-panel').getAttribute('aria-modal') === 'true') $('close-detail').focus() + return ++detailGeneration + } + widePreview.addEventListener('change', () => { syncPanelLayout(); if (!$('detail-panel').hidden && $('detail-panel').getAttribute('aria-modal') === 'true') $('close-detail').focus() }) + function detailText(text) { const p = document.createElement('p'); p.textContent = text; $('detail-body').append(p) } + function detailButton(text, action, disabled = false) { + const button = document.createElement('button'); button.textContent = text; button.disabled = disabled + button.onclick = () => { const version = detailGeneration; Promise.resolve().then(action).catch(error => { if (version === detailGeneration) detailText(error.message) }) } + $('detail-actions').append(button) + } + function requestPreviewHeight(height) { + // 旧宿主可能不支持调整高度;面板仍按当前可用空间布局。 + try { Promise.resolve(window.ztools.setExpendHeight?.(height)).catch(() => {}) } catch {} + } + function expandImagePreview() { + if (typeof window.ztools.setExpendHeight !== 'function') return + let windowType + try { windowType = window.ztools.getWindowType?.() } catch {} + if (windowType && windowType !== 'main') return + // 为接近全宽的 16:9 画布预留工具栏高度,同时给宿主标题栏和屏幕边缘留空间。 + const height = Math.min(Math.ceil(window.innerWidth * 9 / 16 + 118), screen.availHeight - 90) + if (height > window.innerHeight) { + imagePreviewPreviousHeight = window.innerHeight + requestPreviewHeight(height) + } + } + function openImageWindow(item) { + if (typeof window.ztools.createBrowserWindow !== 'function' || location.protocol !== 'file:') return false + const url = new URL('image-preview.html', location.href) + url.hash = encodeURIComponent(item.path) + let area + try { + const point = window.ztools.getCursorScreenPoint?.() + if (point) area = window.ztools.getDisplayNearestPoint?.(point)?.workArea + } catch {} + const availableWidth = area?.width || screen.availWidth, availableHeight = area?.height || screen.availHeight + const width = Math.floor(availableWidth * 0.92), height = Math.floor(availableHeight * 0.91) + const position = area ? { x: area.x + Math.floor((availableWidth - width) / 2), y: area.y + Math.floor((availableHeight - height) / 2) } : {} + try { + const next = window.ztools.createBrowserWindow(url.href, { ...position, width, height, + title: '图片预览', resizable: true, maximizable: true, webPreferences: { preload: 'image-window-preload.js' } }) + if (!Number.isInteger(next?.id)) return false + const previous = imageWindow; imageWindow = next + try { if (previous && !previous.isDestroyed()) previous.close() } catch {} + return true + } catch { return false } + } + async function previewImage(item) { + if (openImageWindow(item)) return + const version = openDetail(api.name(item.path), 'image') + expandImagePreview() + detailText('正在加载图片…') + detailButton('用默认应用打开', () => api.open(item.path)) + detailButton('复制路径', () => copyPath(item)) + try { + const file = await api.readImage(item.path) + if (version !== detailGeneration) return + imagePreviewUrl = imageUrl(file) + const image = new Image() + image.className = 'image-preview'; image.alt = api.name(item.path); image.src = imagePreviewUrl + try { await image.decode() } catch { throw new Error('无法预览此图片,格式可能不受支持或文件已损坏。') } + if (version !== detailGeneration) return + imagePreviewResize = window.mountImageViewer($('detail-body'), image, formatSize(file.bytes.byteLength)) + } catch (error) { + if (version !== detailGeneration) return + if (imagePreviewUrl) { URL.revokeObjectURL(imagePreviewUrl); imagePreviewUrl = null } + $('detail-body').replaceChildren(); detailText(error.message) + } + } + /** 仅选中文件请求有限上下文;代次阻止旧文件响应覆盖新选择,不缓存全文。 */ + async function previewItem(item) { + if (!item.matches) return api.quickLook(item.path) + const version = openDetail(api.name(item.path) + ' · 正文命中', 'preview') + const options = { ...lastOptions } + async function load() { + $('detail-body').replaceChildren(); $('detail-actions').replaceChildren(); detailText('读取命中上下文…') + try { + const response = await api.preview(options, item.path) + if (version !== detailGeneration) return + $('detail-body').replaceChildren() + detailText(item.path) + if (response.matches.length) $('detail-body').append(renderSnippets(response.matches, item.path)) + else detailText('当前文件未返回命中,可能在搜索后已被修改。') + detailText('最多展开前 100 处命中,前后各 3 行;点击命中行号可跳转编辑器。') + if (response.limited) detailText('已显示前 100 处命中;更多内容可在编辑器中查看。') + if (response.complete === false) detailText('此文件读取未完成,可关闭后重试。') + detailButton('系统预览', () => api.quickLook(item.path)) + detailButton('复制路径', () => copyPath(item)) + } catch (error) { if (version === detailGeneration) { $('detail-body').replaceChildren(); detailText(error.message) } } + } + await load() + } + /** 诊断只读取引擎状态和有限的忽略配置;不为解释空结果偷偷重扫全盘。 */ + async function diagnostics() { + const version = openDetail('索引状态与搜索覆盖'); detailText('读取引擎状态…') + try { + const { status: data, skipped, config } = await api.diagnostics() + if (version !== detailGeneration) return + $('detail-body').replaceChildren() + if (windows) detailText(`Everything ${data.version} 已连接。\n搜索范围以 Everything 的索引配置为准,可在 Everything 的「工具 → 选项」查看卷、文件夹和排除设置。`) + else detailText(`名称索引:${data.entries.toLocaleString()} 项\n内容索引:${(data.content_docs || 0).toLocaleString()} 个文件\n待更新正文:${data.content_pending || 0} 个\n名称索引磁盘大小:${formatSize(data.index_bytes)}\n正文索引磁盘大小:${formatSize(data.content_bytes)}\n完整磁盘访问:${data.full_disk_access ? '可用' : '未开启,受保护目录可能被跳过'}`) + if (lastTiming) { + const metric = value => Number.isFinite(value) ? value.toFixed(1) + ' ms' : '未提供' + detailText(`最近一次搜索耗时\n结果就绪(含防抖与 DOM 更新):${metric(lastTiming.totalMs)}\n等待发送:${metric(lastTiming.waitMs)}\n后台排队:${metric(lastTiming.queueMs)}\n异步目录校验:${metric(lastTiming.validationMs)}\n本地通信(含引擎处理):${metric(lastTiming.transportMs)}\n引擎处理:${metric(lastTiming.engineMs)}\n页面请求往返:${metric(lastTiming.requestMs)}\nDOM 更新:${metric(lastTiming.renderMs)}\n下一帧回调:${metric(lastTiming.frameMs)}\n以上耗时部分互相包含,不能相加;只保存最近一条测量。`) + } + if (!windows) detailText('正文索引规则:普通目录文本文件最大 1 MB,Git 项目内最大 10 MB;会跳过 Git 忽略、依赖与构建产物、锁文件、100 KB 及以上 JSON、压缩混淆资源等。名称可搜到不代表正文已被索引。') + detailText('空结果也可能来自筛选条件交集为空或文件已变更。这里展示覆盖规则,无法仅凭空结果断定某个文件的具体原因。') + const push = api.pushStatus?.(); if (push) detailText(`主搜索推送:${push.enabled ? '已启用(还需宿主开关)' : '关闭'}${push.lastError ? '\n最近错误:' + push.lastError : ''}`) + if (!windows) { + detailText('内容额外排除配置:' + config) + const pre = document.createElement('pre'); pre.textContent = skipped || '未配置额外排除目录'; $('detail-body').append(pre) + } + detailButton('重新读取状态', diagnostics) + } catch (error) { if (version === detailGeneration) { $('detail-body').replaceChildren(); detailText(error.message) } } + } + /** 安装及权限只提供指引;不自动下载、不调整系统权限、不创建另一份索引。 */ + function connectionHelp() { + const version = openDetail('使用与连接') + if (windows) { + detailText('1. 从官网下载并安装 Everything 完整版,启动客户端并等待索引完成。只启动系统服务无法搜索。') + detailText('2. 插件已附带官方 ES 命令行工具,无需另外下载。Everything 客户端仍需自行安装,插件不会代为安装或启动。') + detailText('3. 安装并启动 Everything 后,点击“检测连接”。只有需要使用其他版本的 ES 时,才需要“更换 ES(可选)”。') + if (connectionReport) detailText(connectionReport.usable ? 'Everything ' + connectionReport.status.version + ' 已连接。' : connectionReport.title + '\n' + connectionReport.detail) + } else { + detailText('macOS 版是连接独立 FSearch 引擎的第三方插件。初始验证:Apple Silicon、ZTools 3.3.0-beta.2、FSearch 0.2.1;Intel Mac 尚未实机验证。') + detailText('1. 从 FSearch 官方 v0.2.1 发布页下载适合本机的程序,按文档执行 ./fsearch install。标准安装位置为 ~/.local/bin/fsearch。插件不会自动下载或覆盖引擎。') + detailText('2. 在“系统设置 → 隐私与安全性 → 完全磁盘访问权限”按 FSearch 文档授权。登录项方式需要授权 ~/.local/bin/fsearch;从终端启动则注意终端的权限。权限不足仍可搜索可访问目录。') + detailText('3. 在终端运行 ~/.local/bin/fsearch status,首次索引建立需要时间。返回插件点击“重新检测”。无需开放 HTTP 端口,也无需为插件另装 Node.js。') + if (connectionReport) { + const r = connectionReport + if (!r.usable) detailText(`${r.title}\n${r.message}\n具体原因:${r.detail}`) + else { + detailText(`连接状态:${r.state === 'limited' ? '可用,部分目录权限受限' : r.state === 'content-indexing' ? '可用,正文索引更新中' : '可用'}\n已验证:${r.capabilities.join('、')}\n安装文件:${r.identity.version ? '与官方 FSearch ' + r.identity.version + ' 文件一致' : '不在已验证指纹列表内,当前接口探针通过'}\n检测时间:${new Date(r.checkedAt).toLocaleString('zh-CN')}`) + if (r.identity.warning) detailText(r.identity.warning) + if (r.arch !== 'arm64') detailText('当前架构未实机验证;接口检测通过不代表所有系统操作都已验收。') + detailText('安装文件指纹不能证明正在运行的守护进程版本。接口探针不等于全盘覆盖或所有筛选、分页行为的完整验收。') + } + detailText(`程序:${r.binaryPath}\n本地连接:${r.socketPath}`) + } + } + detailText('索引由本地引擎管理。插件不上传文件名或正文;会在 ZTools 本地保存偏好、预设和可关闭的上次搜索条件。打开帮助网页才会连接对应网站;提供反馈前请移除私人路径与搜索内容。') + const recheckConnection = async () => { + const active = lifecycle, ready = await refreshStatus(true) + if (ready === null || active !== lifecycle) return + if (ready) queueSearch() + // 用户已关闭或切换面板时不重新弹出;旧检测也不能覆盖新一轮检测。 + if (version === detailGeneration && !$('detail-panel').hidden) connectionHelp() + } + detailButton(windows ? '检测连接' : '重新检测', recheckConnection) + if (windows && api.chooseEverythingCli) detailButton('更换 ES(可选)', async () => { if (await api.chooseEverythingCli()) await recheckConnection() }) + if (api.openHelp) { + if (windows) detailButton('打开 Everything 官网', () => api.openHelp('everything')) + else { detailButton('FSearch 安装文档', () => api.openHelp('install')); detailButton('权限说明', () => api.openHelp('permissions')) } + detailButton('插件仓库', () => api.openHelp('project')) + } + } + /** 按范围更新控件后再应用模式,防止原生模式的动态选项丢失。 */ + function applyOptions(options = {}) { + const o = { query: '', category: 'all', directory: '', mode: windows ? 'literal' : 'native', field: windows ? 'name' : 'engine', caseSensitive: false, pageSize: 50, extensions: '', modified: '', size: '', exclude: '', git: '', boost: false, browse: false, ...options } + if (windows) { + if (!['name', 'path'].includes(o.field)) Object.assign(o, { field: 'name', mode: 'literal' }) + Object.assign(o, { file: undefined, git: '', boost: false }) + } + if (typeof o.query !== 'string' || !api.categories.some(c => c.id === o.category) || !['name', 'path', 'content', 'symbol', 'engine'].includes(o.field)) throw new Error('搜索条件格式无效') + query = o.query; category = o.category; contentFile = o.file || null; $('match-field').value = o.field; updateModeHint() + $('match-mode').value = o.mode + if (!$('match-mode').value) throw new Error('当前范围不支持保存的匹配模式') + for (const [key, id] of Object.entries({ directory: 'directory', pageSize: 'page-size', extensions: 'extensions', modified: 'modified', size: 'size', exclude: 'exclude', git: 'git' })) $(id).value = o[key] + $('match-case').setAttribute('aria-pressed', String(o.caseSensitive)); $('boost').checked = o.boost; $('browse').checked = o.browse + updateModeHint(); renderCategories(); updateCategoryTitle(); updateFilterSummary() + } + async function newSearch() { + if (phase !== 'active') { await enter({ code: 'search-new', type: 'text' }); api.focusInput(true); return } + applyOptions(); sourceFile = null; renderSourceFile(); basePage = 0; pageOffsets = [0]; pageStarts = [0]; pageIndex = 0; restoreState = null + await window.ztools.setSubInputValue(''); schedule(); api.focusInput(true) + } + function renderSourceFile() { + $('source-file').hidden = !sourceFile; $('source-file-actions').replaceChildren() + if (!sourceFile) return + const targetFile = sourceFile + $('source-file-name').textContent = '来自文件:' + api.name(sourceFile); $('source-file-name').title = sourceFile + const actions = [['打开', () => api.open(targetFile)], ['定位', () => api.reveal(targetFile)], ['复制路径', () => copyPath({ path: targetFile })]] + if (!windows) actions.push(['搜此文件正文', async () => { + const target = targetFile + applyOptions({ field: 'content', mode: 'literal', file: target }); sourceFile = target; renderSourceFile(); await window.ztools.setSubInputValue(''); schedule(); api.focusInput(true) + }]) + for (const [label, action] of actions) { const button = document.createElement('button'); button.textContent = label; button.onclick = () => Promise.resolve().then(action).catch(error => showNotice(error.message)); $('source-file-actions').append(button) } + } + function renderPreferences() { + for (const [key, id] of Object.entries({ autoHide: 'pref-auto-hide', copyHide: 'pref-copy-hide', remember: 'pref-remember', mainPush: 'pref-push' })) $(id).checked = settings.integration[key] + $('pref-workspace').value = settings.integration.workspace + } + function changePreference() { + try { + const prefs = { autoHide: $('pref-auto-hide').checked, copyHide: $('pref-copy-hide').checked, remember: $('pref-remember').checked, mainPush: $('pref-push').checked, workspace: $('pref-workspace').value.trim() } + saveSettings({ ...settings, integration: prefs }) + } catch (error) { renderPreferences(); showNotice(error.message) } + } + ;['pref-auto-hide', 'pref-copy-hide', 'pref-remember', 'pref-push', 'pref-workspace'].forEach(id => $(id).addEventListener('change', changePreference)) + $('shortcut-settings').onclick = () => { try { api.shortcutSettings() } catch (error) { showNotice(error.message) } } + $('new-search').onclick = () => newSearch().catch(error => showNotice(error.message)) + function renderPresets() { + const previousName = $('presets').value === '' ? null : $('presets').selectedOptions[0]?.textContent + $('presets').replaceChildren(new Option('选择已保存预设', '')) + settings.presets.forEach((preset, index) => $('presets').append(new Option(preset.name, String(index)))) + const index = settings.presets.findIndex(p => p.name === previousName) + if (index >= 0) $('presets').value = String(index) + $('delete-preset').disabled = index < 0 + } + function saveSettings(next) { + // 宿主存储可能失败,成功前不能更新内存或显示保存成功。 + api.saveSettings(next); settings = next; renderPresets(); showToast('设置已保存') + } + try { + const saved = api.loadSettings?.() + if (saved) { + if (!Array.isArray(saved.presets) || saved.presets.length > 20 || saved.presets.some(p => typeof p.name !== 'string' || !p.options) || !['vscode', 'cursor'].includes(saved.editor)) throw new Error('搜索设置格式无效') + settings = { ...saved, integration: { ...preferenceDefaults, ...saved.integration } } + } + } catch (error) { showNotice(error.message) } + settings.integration = { ...preferenceDefaults, ...settings.integration } + $('editor').value = settings.editor; renderPresets(); renderPreferences() + $('close-detail').onclick = () => closeDetail() + $('open-filters').onclick = () => { closeDetail(false); filterFocus = document.activeElement; $('advanced').hidden = false; syncPanelLayout(); $('close-filters').focus() } + $('close-filters').onclick = () => closeFilters() + $('panel-backdrop').onclick = () => { closeFilters(); closeDetail() } + $('diagnostics').onclick = diagnostics + $('connection-help').onclick = connectionHelp + $('location').onchange = () => { const value = $('location').value; if (!value) return; $('directory').value = value === 'all' ? '' : value === 'home' ? api.home() : api.home() + '/' + value; schedule() } + ;['extensions', 'size', 'exclude'].forEach(id => $(id).addEventListener('input', schedule)) + ;['modified', 'git', 'boost', 'browse'].forEach(id => $(id).addEventListener('change', schedule)) + $('reset-filters').onclick = () => { ['extensions', 'modified', 'size', 'exclude', 'git'].forEach(id => { $(id).value = '' }); $('boost').checked = false; $('browse').checked = false; schedule() } + $('editor').onchange = () => { try { saveSettings({ ...settings, editor: $('editor').value }) } catch (error) { $('editor').value = settings.editor; showNotice(error.message) } } + $('save-preset').onclick = () => { + try { + const name = $('preset-name').value.trim() + if (!name) throw new Error('请输入预设名称') + const options = { ...searchOptions(), offset: 0 } + const presets = settings.presets.slice(), found = presets.findIndex(p => p.name === name) + if (found >= 0) presets[found] = { name, options, command: $('preset-command').checked } + else { if (presets.length >= 20) throw new Error('最多保存 20 个预设,请先删除不用的预设'); presets.push({ name, options, command: $('preset-command').checked }) } + saveSettings({ ...settings, presets }); $('presets').value = String(presets.findIndex(p => p.name === name)); $('delete-preset').disabled = false + } catch (error) { showNotice(error.message) } + } + $('delete-preset').onclick = () => { try { const index = Number($('presets').value); if ($('presets').value !== '') saveSettings({ ...settings, presets: settings.presets.filter((_, i) => i !== index) }) } catch (error) { showNotice(error.message) } } + $('presets').onchange = async () => { + if ($('presets').value === '') { $('delete-preset').disabled = true; return } + const active = lifecycle, preset = settings.presets[Number($('presets').value)], o = preset.options + applyOptions(o); sourceFile = o.file || null; renderSourceFile(); $('preset-name').value = preset.name; $('preset-command').checked = preset.command !== false; $('delete-preset').disabled = false + await window.ztools.setSubInputValue(query); if (active === lifecycle) schedule() + } + $('refresh').innerHTML = svg('refresh'); $('empty-icon').innerHTML = svg('search') + $('refresh').onclick = async () => { showNotice(''); if (await refreshStatus(true)) queueSearch() } + $('match-mode').onchange = () => { updateModeHint(); schedule() } + $('match-field').onchange = () => { + if (isContent() && !api.categories.find(item => item.id === category).contentSupported) category = 'all' + updateModeHint(); updateCategoryTitle(); renderCategories(); schedule() + } + $('match-case').onclick = () => { + const enabled = $('match-case').getAttribute('aria-pressed') !== 'true' + $('match-case').setAttribute('aria-pressed', String(enabled)); updateModeHint(); schedule() + } + $('page-size').onchange = schedule + $('previous-page').onclick = () => changePage(-1) + $('next-page').onclick = () => changePage(1) + $('apply').onclick = schedule + $('clear').onclick = () => { $('directory').value = ''; schedule() } + document.addEventListener('compositionstart', event => { if (isEditing(event.target)) { composing = true; schedule() } }) + document.addEventListener('compositionend', event => { if (isEditing(event.target)) { composing = false; schedule() } }) + $('results').addEventListener('click', event => { if (!resultsValid) { event.preventDefault(); event.stopImmediatePropagation() } }, true) + $('directory').addEventListener('keydown', event => { if (event.key === 'Enter' && !event.isComposing && !composing) { event.preventDefault(); event.stopPropagation(); schedule() } }) + document.addEventListener('keydown', event => { + if (event.isComposing || composing || event.keyCode === 229) return + if (modifiedKey(event) && event.key.toLowerCase() === 'l') { event.preventDefault(); api.focusInput(true); return } + if (modifiedKey(event) && event.key.toLowerCase() === 'n' && !isEditing(event.target)) { event.preventDefault(); newSearch().catch(error => showNotice(error.message)); return } + const modal = !$('advanced').hidden ? $('advanced') : !$('detail-panel').hidden && $('detail-panel').getAttribute('aria-modal') === 'true' ? $('detail-panel') : null + if (event.key === 'Tab' && modal) { + const controls = [...modal.querySelectorAll('button:not(:disabled),input:not(:disabled),select:not(:disabled),textarea:not(:disabled),[tabindex="0"]')].filter(element => !element.hidden) + const first = controls[0], last = controls.at(-1) + if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus() } + else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus() } + } + if (event.key === 'Tab' && !modal && !(event.target instanceof Element && event.target.closest('input,textarea,select,button,summary'))) { + event.preventDefault() + if (event.target === document.body || event.target === document) { api.focusResults(); if (resultsValid && rows.length) select(selected, true) } + else api.focusInput(false) + return + } + if (event.key === 'Escape') { + if (!$('advanced').hidden) { event.preventDefault(); closeFilters(); return } + if (!$('detail-panel').hidden) { event.preventDefault(); closeDetail(); return } + } + // 编辑输入框或选中文本时保留系统复制;只有结果区选择才复制文件完整路径。 + if (isEditing(event.target) || !resultsValid || !rows.length || window.getSelection()?.toString() || (!$('detail-panel').hidden && $('detail-panel').getAttribute('aria-modal') === 'true') || (event.target instanceof Element && event.target.closest('#detail-panel'))) return + if (modifiedKey(event) && event.key.toLowerCase() === 'c') { event.preventDefault(); if (event.shiftKey) Promise.resolve().then(() => api.copyFile(rows[selected].path)).then(() => showToast('已复制文件,可直接粘贴')).catch(error => showNotice(error.message)); else copyPath(rows[selected]); return } + if (event.target instanceof Element && event.target.closest('button,summary')) return + if (event.key === ' ' && (isImage(rows[selected]) || !windows)) { + event.preventDefault() + if (isImage(rows[selected])) void previewImage(rows[selected]) + else Promise.resolve().then(() => api.quickLook(rows[selected].path)).catch(error => showNotice(error.message)) + return + } + if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); select((selected + (event.key === 'ArrowDown' ? 1 : -1) + rows.length) % rows.length, true) } + else if (event.key === 'Enter') { event.preventDefault(); Promise.resolve().then(() => (modifiedKey(event) ? api.reveal : api.open)(rows[selected].path)).catch(error => showNotice(error.message)) } + }) + /** 只保存条件、32 页游标和选中路径;退出不持有结果数组或正文。 */ + function snapshot() { + return { options: searchOptions(), sourceFile, selectedPath: resultsValid ? rows[selected]?.path || null : null, scrollTop: resultsValid ? $('results').parentElement.scrollTop : 0, pageOffsets: pageOffsets.slice(), pageStarts: pageStarts.slice(), pageIndex, basePage } + } + function remember() { try { api.saveSession(snapshot()) } catch (error) { showNotice(error.message) } } + function releaseUI(final) { + generation++; connectionGeneration++; clearTimeout(timer); clearTimeout(toastTimer); if (frameId !== null) cancelAnimationFrame(frameId); frameId = null + closeFilters(false); closeDetail(false); composing = false; resultsValid = false; loading = false; rows = []; restoreState = null; lastTiming = null + resetThumbnails(); $('results').replaceChildren(); $('toast').hidden = true; setResultState() + if (final) api.dispose(); else api.suspend() + } + /** 宿主重新进入优先使用显式参数;普通唤起才恢复会话,避免覆盖选中文本或 Finder 上下文。 */ + async function enter(action = { code: 'search' }) { + const active = ++lifecycle; phase = 'entering' + try { + // 先消费本次 mainPush 令牌,再释放后台推送缓存,避免「更多结果」丢失入口参数。 + const pendingPlan = api.resolveEntry(action) + releaseUI(false); connectionBlocked = true; showNotice('') + const plan = await pendingPlan + if (active !== lifecycle || phase !== 'entering') return + let session = plan.kind === 'resume' ? api.loadSession() : null + if (session) { + if (!Array.isArray(session.pageOffsets) || !Array.isArray(session.pageStarts) || session.pageOffsets.length > 32 || session.pageOffsets.length !== session.pageStarts.length || !Number.isSafeInteger(session.pageIndex) || session.pageIndex < 0 || session.pageIndex >= session.pageOffsets.length || session.pageOffsets.some(n => !Number.isSafeInteger(n) || n < 0) || session.pageStarts.some(n => !Number.isSafeInteger(n) || n < 0)) throw new Error('上次搜索状态无效,请使用「新搜索」') + } + applyOptions(session?.options || plan.options || {}) + sourceFile = session?.sourceFile || plan.sourceFile || null; renderSourceFile() + pageOffsets = session?.pageOffsets || [0]; pageStarts = session?.pageStarts || [0]; pageIndex = session?.pageIndex || 0; basePage = session?.basePage || 0 + restoreState = session ? { selectedPath: session.selectedPath, scrollTop: session.scrollTop } : { selectedPath: plan.selectPath, scrollTop: 0 } + render(); updatePagination() + await window.ztools.setSubInput(input => { + if (phase !== 'active') return + const value = typeof input === 'string' ? input : input.text + if (query === value && !composing && !input?.isComposing) return + closeFilters(false); closeDetail(false) + if (document.activeElement instanceof HTMLElement) document.activeElement.blur() + query = value; composing = typeof input === 'object' && input.isComposing === true; schedule() + }, windows ? '输入文件名或路径 · Ctrl+L 返回搜索框' : '输入文件名、正文或定义 · ⌘L 返回搜索框', true) + if (active !== lifecycle || phase !== 'entering') return + await window.ztools.setSubInputValue(query) + if (active !== lifecycle || phase !== 'entering') return + phase = 'active' + if (plan.configureWorkspace) { + showNotice(plan.notice); emptyState('设置工作目录', plan.notice); $('open-filters').click(); $('pref-workspace').focus(); return + } + const ready = await refreshStatus() + if (ready && active === lifecycle && phase === 'active') { queueSearch(); if (api.integrationError) showNotice(api.integrationError) } + } catch (error) { if (active === lifecycle) { phase = 'error'; emptyState('未能开始搜索', error.message); showNotice(error.message) } } + } + window.ztools.onPluginEnter(enter) + window.ztools.onPluginOut(isKill => { + const hiddenReturn = !isKill && phase === 'suspended' + if (phase === 'active') remember() + lifecycle++; phase = 'out' + // 宿主隐藏后的自动返回也会发普通退出,不能因此杀掉正在看的系统预览。 + // 可见退出、终止进程或 beforeunload 会释放预览;隐藏时保留的预览由用户关闭。 + releaseUI(!hiddenReturn); window.ztools.removeSubInput() + }) + window.ztools.onPluginDetach?.(() => api.setDetached(true)) + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden' && ['active', 'entering'].includes(phase)) { if (phase === 'active') remember(); lifecycle++; phase = 'suspended'; releaseUI(false) } + else if (document.visibilityState === 'visible' && phase === 'suspended') void enter() + }) + // 宿主把导航键发送给插件 WebContents;失去焦点时清除旧按钮焦点,避免顶部回车误触旧按钮。 + window.addEventListener('blur', () => { if (phase === 'active' && $('advanced').hidden && $('detail-panel').hidden && document.activeElement instanceof HTMLElement) document.activeElement.blur() }) + window.addEventListener('beforeunload', () => { if (phase === 'active') remember(); api.dispose() }) + renderCategories(); updateModeHint(); updateCategoryTitle(); updatePagination() +})() diff --git a/plugins/local-fsearch/categories.cjs b/plugins/local-fsearch/categories.cjs new file mode 100644 index 000000000..e0a37925d --- /dev/null +++ b/plugins/local-fsearch/categories.cjs @@ -0,0 +1,15 @@ +/** 分类使用引擎端过滤,不能先取前 100 条再按扩展名筛选。 */ +module.exports = [ + { id: 'all', label: '全部文件', icon: 'grid', contentSupported: true }, + { id: 'folder', label: '文件夹', icon: 'folder', kind: 'dir' }, + { id: 'text', label: '文本', icon: 'file', contentSupported: true, ext: 'txt,text,md,mdx,markdown,rst,org,tex,json,jsonc,json5,jsonl,ndjson,yaml,yml,toml,xml,ini,cfg,conf,env,properties,plist,log,diff,patch,srt,vtt,rtf,csv,tsv' }, + { id: 'code', label: '代码', icon: 'code', contentSupported: true, ext: 'rs,c,h,cc,cpp,cxx,hpp,hh,m,mm,swift,go,py,pyi,js,mjs,cjs,ts,mts,cts,tsx,jsx,java,kt,kts,scala,rb,php,cs,fs,sh,zsh,bash,fish,lua,sql,html,htm,css,scss,sass,less,vue,svelte,astro,zig,nim,hs,ml,mli,ex,exs,erl,clj,dart,r,jl,metal,glsl,wgsl,hlsl,proto,graphql,gql,nix,tf,hcl,gradle,cmake,mk,make,dockerfile,pl,pm,ps1,bat,vim,el,lisp,scm,rkt,elm,purs,sol,v,sv,vhd,asm,s,d,cr,pas,f90,cmd,service,desktop,gitignore,editorconfig' }, + { id: 'excel', label: '表格', icon: 'table', contentSupported: true, contentLabel: '文本表格', contentExt: 'csv,tsv', ext: 'xls,xlsx,xlsm,xlsb,csv,numbers,ods' }, + { id: 'word', label: '文档', icon: 'file', ext: 'doc,docx,docm,rtf,odt,pages' }, + { id: 'ppt', label: '演示文稿', icon: 'slides', ext: 'ppt,pptx,pptm,pps,ppsx,key,odp' }, + { id: 'pdf', label: 'PDF', icon: 'file', ext: 'pdf' }, + { id: 'image', label: '图片', icon: 'image', ext: 'jpg,jpeg,png,gif,webp,bmp,heic,svg,tif,tiff,avif' }, + { id: 'video', label: '视频', icon: 'video', ext: 'mp4,mov,m4v,avi,mkv,flv,wmv,webm' }, + { id: 'audio', label: '音频', icon: 'audio', ext: 'mp3,wav,m4a,aac,flac,ogg,aiff' }, + { id: 'archive', label: '压缩文件', icon: 'archive', ext: 'zip,rar,7z,tar,gz,bz2,xz,tgz' } +] diff --git a/plugins/local-fsearch/client.cjs b/plugins/local-fsearch/client.cjs new file mode 100644 index 000000000..1d8a28510 --- /dev/null +++ b/plugins/local-fsearch/client.cjs @@ -0,0 +1,91 @@ +const net = require('node:net') +const os = require('node:os') +const path = require('node:path') +const fs = require('node:fs/promises') +const { aborted, checkAbort } = require('./latest.cjs') +const { execFile } = require('node:child_process') +const socketPath = path.join(os.homedir(), 'Library/Application Support/FSearch/fsearch.sock') +const binaryPath = path.join(os.homedir(), '.local/bin/fsearch') +let starting = null +const connections = new Set() + +/** + * 发送一条 JSON Lines 请求;每次请求独立连接,避免旧查询阻塞新查询的响应归属。 + * @param {object} payload FSearch 请求对象 + * @param {string} target 测试或本地服务的 Unix Socket 路径 + * @returns {Promise} 成功的服务响应 + */ +function exchange(payload, target = socketPath, { signal } = {}) { + return new Promise((resolve, reject) => { + try { checkAbort(signal) } catch (error) { reject(error); return } + const socket = net.createConnection(target) + let chunks = [], bytes = 0, settled = false + const cancel = () => finish(aborted()) + const finish = (error, value) => { + if (settled) return + settled = true; chunks = []; bytes = 0 + connections.delete(cancel); signal?.removeEventListener('abort', cancel) + socket.destroy(); error ? reject(error) : resolve(value) + } + connections.add(cancel); signal?.addEventListener('abort', cancel, { once: true }) + socket.setTimeout(8000, () => finish(new Error('FSearch 响应超时,请稍后重试'))) + socket.on('connect', () => socket.write(JSON.stringify(payload) + '\n')) + socket.on('data', chunk => { + if (settled) return + const newline = chunk.indexOf(10), part = newline < 0 ? chunk : chunk.subarray(0, newline) + bytes += part.length + // 按真实字节限制单条响应;只拼接一次,避免逐片字符串复制与 UTF-8 边界问题。 + if (bytes > 8 * 1024 * 1024) return finish(new Error('FSearch 响应超过大小限制')) + chunks.push(part) + if (newline < 0) return + try { + const response = JSON.parse(Buffer.concat(chunks, bytes).toString('utf8')) + if (response.ok !== true) { + const error = new Error(response.error || 'FSearch 返回无效状态') + if (typeof response.error !== 'string') error.code = 'FSEARCH_PROTOCOL' + return finish(error) + } + finish(null, response) + } catch (error) { error.code = 'FSEARCH_PROTOCOL'; finish(error) } + }) + socket.on('error', error => finish(error)) + socket.on('close', () => { if (!settled) finish(new Error('FSearch 连接已关闭,未收到完整响应')) }) + }) +} + +/** 退出只释放本插件的连接,不停止共享的 FSearch 守护进程。 */ +function closeConnections() { for (const cancel of [...connections]) cancel() } + +/** + * 使用已安装的官方 CLI 启动守护进程;共享启动任务避免并发创建多个服务。 + * @returns {Promise} 启动命令结束 + */ +function startService() { + if (starting) return starting + starting = fs.access(binaryPath).catch(cause => { if (cause.code !== 'ENOENT') throw cause; const error = new Error('未安装 FSearch,预期位置:' + binaryPath); error.code = 'FSEARCH_MISSING'; throw error }).then(() => new Promise((resolve, reject) => { + // 仅调用已安装的本地二进制,不拼接 shell,不自动下载或变更系统权限。 + execFile(binaryPath, ['status'], { timeout: 12000, maxBuffer: 1024 * 1024 }, error => { + if (!error) return resolve() + const failure = new Error('FSearch 启动失败:' + error.message); failure.code = ['EACCES', 'EPERM'].includes(error.code) ? error.code : 'FSEARCH_START_FAILED'; reject(failure) + }) + })).finally(() => { starting = null }) + return starting +} + +/** + * 请求本地服务,仅在 Socket 不存在或拒绝连接时启动服务;业务错误原样报告。 + * @param {object} payload FSearch 请求 + * @returns {Promise} 服务响应 + */ +async function request(payload, { signal } = {}) { + checkAbort(signal) + try { return await exchange(payload, socketPath, { signal }) } + catch (error) { + if (!['ENOENT', 'ECONNREFUSED'].includes(error.code)) throw error + checkAbort(signal) + await startService() + checkAbort(signal) + return exchange(payload, socketPath, { signal }) + } +} +module.exports = { request, exchange, closeConnections } diff --git a/plugins/local-fsearch/compatibility.json b/plugins/local-fsearch/compatibility.json new file mode 100644 index 000000000..46d557599 --- /dev/null +++ b/plugins/local-fsearch/compatibility.json @@ -0,0 +1,16 @@ +{ + "testedAt": "2026-11-06", + "platform": "darwin", + "architecture": "arm64", + "macOS": "27.0.1", + "ztools": "3.3.0-beta.2", + "fsearch": { + "version": "0.2.1", + "repository": "noahdunnagan/fsearch", + "releaseUrl": "https://github.com/noahdunnagan/fsearch/releases/tag/v0.2.1", + "archive": "fsearch-aarch64-apple-darwin.tar.gz", + "archiveSha256": "08f68fe10362732f701be3ddf59cb370920c5a08af63e76b15addf8aca118d2f", + "binarySha256": "008faa677348e1161596d545fdcc7f3a8427eb47ce68bc40f67a93cd2992add1" + }, + "note": "安装文件指纹不代表正在运行的守护进程版本;运行时能力通过有界探针验证。Intel Mac 尚未实机验证。" +} diff --git a/plugins/local-fsearch/content.cjs b/plugins/local-fsearch/content.cjs new file mode 100644 index 000000000..81eda4ad4 --- /dev/null +++ b/plugins/local-fsearch/content.cjs @@ -0,0 +1,62 @@ +/** + * 将引擎的 UTF-8 字节区间转成安全的文本片段,中文前缀不能按 JavaScript 下标切割。 + * @param {object} match 引擎返回的一条行命中 + * @returns {object} 带行号、上下文及高亮片段的预览 + */ +function normalizeMatch(match) { + if (!Number.isSafeInteger(match.line) || match.line < 1 || typeof match.text !== 'string' || !Array.isArray(match.ranges)) { + throw new Error('FSearch 返回的内容命中格式无效') + } + const bytes = Buffer.from(match.text, 'utf8') + const parts = [] + let position = 0 + for (const range of match.ranges) { + const [start, end] = range + if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < position || end < start || end > bytes.length) { + throw new Error('FSearch 返回的命中区间无效') + } + if (start > position) parts.push({ text: bytes.subarray(position, start).toString('utf8'), matched: false }) + parts.push({ text: bytes.subarray(start, end).toString('utf8'), matched: true }) + position = end + } + if (position < bytes.length) parts.push({ text: bytes.subarray(position).toString('utf8'), matched: false }) + return { + line: match.line, + parts, + before: (match.before || []).map((text, index, lines) => ({ line: match.line - lines.length + index, text })), + after: (match.after || []).map((text, index) => ({ line: match.line + index + 1, text })), + // 引擎只返回每行开头的有限预览,不能把末尾命中伪装成已显示的高亮。 + outsidePreview: match.ranges.length === 0 && match.col >= bytes.length + } +} + +/** + * 内容检索的下一页是候选游标,不是结果条数;返回它的原值供下一次请求使用。 + * @param {object} response 官方 grep 响应 + * @param {number} cursor 本次候选游标 + * @returns {object} 当前页文件及预览、下一游标、内容索引状态 + */ +function normalizeContent(response, cursor) { + if (!Array.isArray(response.files)) throw new Error('FSearch 返回的内容结果格式无效') + const next = response.next + if (next !== undefined && (!Number.isSafeInteger(next) || next <= cursor)) { + throw new Error('内容检索暂未能继续,请稍后刷新或缩小目录范围') + } + const hits = response.files.map(file => { + if (typeof file.path !== 'string' || !Array.isArray(file.matches)) throw new Error('FSearch 返回的文件命中格式无效') + return { path: file.path, kind: 'file', git: file.git, matches: file.matches.map(normalizeMatch) } + }) + return { + hits, + took_us: response.took_us, + offset: cursor, + next: next === undefined ? null : next, + windowLimited: false, + content: true, + complete: response.complete, + contentIndexing: response.indexing, + source: response.source + } +} + +module.exports = { normalizeMatch, normalizeContent } diff --git a/plugins/local-fsearch/docs/COMPATIBILITY.md b/plugins/local-fsearch/docs/COMPATIBILITY.md new file mode 100644 index 000000000..852119ca5 --- /dev/null +++ b/plugins/local-fsearch/docs/COMPATIBILITY.md @@ -0,0 +1,10 @@ +# 系统要求 + +| 平台 | 需要安装 | 可用功能 | +| --- | --- | --- | +| Windows | Everything 完整客户端(ES 已随包提供) | 名称/路径、分类与筛选、图片预览、预设与主搜索推送 | +| macOS | noahdunnagan/fsearch | 通用功能,以及正文、代码定义、Git 状态、常用优先和 Quick Look | + +Everything 客户端由用户从官网下载,插件不捆绑它的安装程序;官方 ES 命令行工具随插件提供,保留来源和 MIT 许可证。只运行 Everything 系统服务不够,还需启动客户端并等待索引就绪。 + +Windows 已在 ZTools 3.2.0、Everything 1.4.1.1026 环境试用。macOS 以 Apple Silicon、ZTools 3.3.0-beta.2 和 FSearch 0.2.1 为参考;最新图片窗口的 macOS 实机体验仍待确认。其他环境如遇异常,可提供系统与引擎版本反馈。 diff --git a/plugins/local-fsearch/docs/INSTALL.md b/plugins/local-fsearch/docs/INSTALL.md new file mode 100644 index 000000000..252f20138 --- /dev/null +++ b/plugins/local-fsearch/docs/INSTALL.md @@ -0,0 +1,80 @@ +# 安装与首次使用 + +## Windows + +1. 从 https://www.voidtools.com/downloads/ 安装 Everything 完整版并启动客户端,等待索引就绪。仅运行系统服务不足以查询。 +2. 导入本插件的运行文件 ZIP,或用 ZTools 开发者工具选择 plugin.json。 +3. 输入 fs / find;默认按名称包含搜索。在“使用与连接”确认 Everything 版本。 +4. 插件已附带官方 ES 命令行工具,无需另外下载 ES 或安装 Node.js。Everything 客户端需自行安装并启动,再到“使用与连接”点击“检测连接”。命名实例可在启动 ZTools 前设置 ZTOOLS_EVERYTHING_INSTANCE;替换 ES 使用 ZTOOLS_EVERYTHING_ES 绝对路径。 +5. 正文/定义/Git/Quick Look 为 macOS 专属,不会在 Windows 注册。 + +连接失败先确认 Everything 客户端已启动。覆盖不足请在 Everything 设置中检查卷、文件夹及排除规则,不需要打开 HTTP 服务。 + +## macOS + + +本文记录 macOS 版的 **noahdunnagan/fsearch** 安装流程。Windows 使用 Everything,见 [README](../README.md#安装与发布准备)。插件与索引引擎分别安装,索引由引擎维护。 + +## 已验证组合 + +- Apple Silicon(arm64),macOS 27.0.1。 +- ZTools 3.3.0-beta.2。 +- FSearch v0.2.1 官方 Apple Silicon 发布文件。 + +这不是最低系统版本声明。其他 macOS / ZTools 版本、Intel Mac 尚未完成实机验证;不要将此列表理解为“任意 Mac 均兼容”。 + +## 1. 安装引擎 + +官方发布页:https://github.com/noahdunnagan/fsearch/releases/tag/v0.2.1 + +Apple Silicon 用户可在一个新建的临时目录中执行以下步骤。下载只在用户自行执行命令时发生,插件不会自动下载。 + +```sh +mkdir fsearch-0.2.1-install +cd fsearch-0.2.1-install +curl -fL -O https://github.com/noahdunnagan/fsearch/releases/download/v0.2.1/fsearch-aarch64-apple-darwin.tar.gz +printf '%s\n' '08f68fe10362732f701be3ddf59cb370920c5a08af63e76b15addf8aca118d2f fsearch-aarch64-apple-darwin.tar.gz' | shasum -a 256 -c - +# 上一步必须输出 OK;校验失败时停止,不解压执行。 +tar -xzf fsearch-aarch64-apple-darwin.tar.gz +./fsearch install +``` + +标准安装位置为 `~/.local/bin/fsearch`。当前插件只从该位置尝试自动启动;若已有服务处于运行状态,可直接连接标准 Socket,但仍会提示缺少标准安装文件,无法保证重启。 + +需要开机自动运行时,可自行执行 `~/.local/bin/fsearch install --login`,这会创建 FSearch 登录项;不是使用插件的必需步骤。不要以 root/sudo 启动插件或引擎。 + +如果 macOS 阻止运行下载的程序,按系统“隐私与安全性”中的提示确认来源;插件不移除隔离属性、不绕过系统保护。 + +## 2. 授权与初始索引 + +在“系统设置 → 隐私与安全性 → 完全磁盘访问权限”按 [FSearch 官方说明](https://github.com/noahdunnagan/fsearch#full-disk-access) 授权。登录项方式需要授权 `~/.local/bin/fsearch`;通过终端启动时,应注意终端的权限来源。引擎重装或重新编译后,可能需要重新授权。 + +```sh +~/.local/bin/fsearch status +``` + +首次建立索引需要时间。权限不足时引擎会跳过受保护目录;权限允许也不意味着系统不可访问的文件或远端未下载内容一定可搜。插件不会额外重扫磁盘,也不会代替用户修改权限。 + +## 3. 加载插件 + +仓库不附带安装包。开发者可以在 ZTools 的开发者工具中选择本项目 `plugin.json` 加载源码,或通过 ZTools 导入构建后的安装包。不要把 GitHub 源码 ZIP 当成 zpx。 + +输入 `fs` / `find` 唤起;首次进入默认“模糊查找”。“使用与连接”可查看状态、安装说明、受限权限与手动重检入口。 + +需要自行开发和测试才安装 Node.js 18+。普通使用者不需要 Node.js 或 Rust(使用引擎预编译文件时)。 + +## 故障排查 + +| 现象 | 操作 | +| --- | --- | +| 请先安装 FSearch | 确认标准程序位置,再运行 status | +| 启动失败 | 在终端运行 status 查看原始错误,检查运行权限与系统拦截 | +| 初始索引建立中 | 等待后点击“重新检测”,插件不轮询 | +| 部分目录搜不到 | 查看完全磁盘访问状态、目录筛选与引擎覆盖规则 | +| 接口不兼容 | 参考已验证版本,升级或回到对应引擎后重检;不会悄悄换搜索模式 | +| 安装指纹未识别 | 仅代表不是已记录的发布文件;能力探针会单独验证,不能据此推断守护进程版本 | +| 更新程序后行为异常 | 按引擎文档重启 FSearch,再手动重检;插件隐藏不会停止共享引擎 | + +## 卸载与数据 + +在 ZTools 中卸载插件不会自动卸载 FSearch 或删除其索引。插件设置由 ZTools 的存储机制管理,卸载后是否保留以宿主行为为准。引擎登录项可按其文档执行 `fsearch uninstall`;该命令保留索引,不要误以为已清除所有数据。 diff --git a/plugins/local-fsearch/docs/MARKET_SUBMISSION.md b/plugins/local-fsearch/docs/MARKET_SUBMISSION.md new file mode 100644 index 000000000..b1f01f2f5 --- /dev/null +++ b/plugins/local-fsearch/docs/MARKET_SUBMISSION.md @@ -0,0 +1,51 @@ +# FSearch 文件搜索 + +作者:**lifeek** · 版本:**0.0.2** · Windows / macOS + +在 ZTools 中输入 fs 或 find,快速查找本机文件和文件夹。 + +## 主要功能 + +- 按文件名或完整路径搜索,支持字符模糊、正则和大小写匹配。 +- 按类型、位置、扩展名、修改时间和大小筛选,支持排除目录。 +- 图片列表显示缩略图;大图在独立窗口打开,支持滚轮定位缩放、自由拖动和最大化。 +- 保存常用搜索为预设,也可生成 ZTools 独立指令。 +- 可开启主搜索推送,在 ZTools 搜索框直接输入 fs 关键词查看匹配。 + +## 首次使用 + +**Windows**:从 [Everything 官网](https://www.voidtools.com/downloads/) 安装 Everything 完整版并启动客户端,然后在插件“使用与连接”点击“检测连接”。插件已附带官方 ES 命令行工具,不需要另外下载;不包含 Everything 客户端安装程序。 + +**macOS**:单独安装 [noahdunnagan/fsearch](https://github.com/noahdunnagan/fsearch)。正文、代码定义、Git 状态、常用优先和 Quick Look 为 macOS 专属功能。 + +## 数据与隐私 + +查询和预览在本机完成,插件不上传文件名、图片或正文,不建立额外索引。设置和预设保存在 ZTools 本地存储中。 + +## 兼容说明 + +Windows 已在 ZTools 3.2.0 与 Everything 1.4.1.1026 环境检查主要功能。macOS 最新图片窗口体验仍待实机确认。更多信息见安装和隐私说明。 + +## 功能预览 + +截图来自 Windows ZTools,使用专门生成的演示文件和图片;可点击查看原图。 + +### 文件搜索 + + + +### 图片缩略图 + + + +### 独立大图预览 + + + +### 主搜索推送 + + + +### 搜索预设 + + diff --git a/plugins/local-fsearch/docs/PRIVACY.md b/plugins/local-fsearch/docs/PRIVACY.md new file mode 100644 index 000000000..8fd48800f --- /dev/null +++ b/plugins/local-fsearch/docs/PRIVACY.md @@ -0,0 +1,33 @@ +# 隐私与本地数据 + +版本 0.0.2;作者 lifeek。 + +## 查询与索引 + +macOS 经本机 Unix Socket 向独立 FSearch 守护进程发送关键词、路径与筛选。Windows 通过参数数组启动随包官方 es.exe(或用户主动选择的其他 ES),使用 Everything 本地 IPC 查询;不拼接 shell、不开放 HTTP 服务。 + +插件不上传文件名、正文或关键词,不含遥测、广告和账号服务,不建立第二份索引。索引由外部引擎维护,其安装、权限和覆盖设置由用户管理。 + +选择的 ES 程序路径保存在 ZTools 本地 fsearch-everything-es 设置中,仅用于查询,不上传。 + +## 图片与内容读取 + +结果页只保留当前一页(25/50/100 条)。可见图片缩略图按需读取本地文件,最多两个读取任务同时执行,生成小图后释放原图对象 URL。用户预览大图时读取选中图片,32 MB 上限;窗口关闭后释放对象 URL。图片路径在本地预览窗口 URL 的 hash 中传递,可能出现在本机调试信息中,不作为网络请求发送。 + +macOS 正文由 FSearch 读取,预览有命中数量及文件大小限制。未知或损坏图片显示失败提示,不上传转换。 + +## 宿主存储 + +ZTools dbStorage 保存 fsearch-settings 和 fsearch-session:偏好、最多 20 个预设、编辑器、工作目录及可关闭的上次搜索条件、选中路径、滚动位置和有界游标元数据。会话序列化上限 32 KiB,不存结果列表、图片或正文。关闭恢复偏好会清除会话。ZTools 自身备份/同步策略以宿主设置为准。 + +## 用户操作与外部帮助 + +只有用户操作才打开、定位、复制、粘贴或打开帮助网站。macOS 成功打开后向 FSearch 写入常用记录。Windows 不维护额外打开历史。帮助链接为固定官网/项目地址,不附带搜索词和本地路径。 + +## 连接检测 + +macOS 首次或手动重检创建自己的临时小文件,测试后删除;流式计算安装程序指纹。崩溃可能留下 ztools-fsearch-check-* 临时目录。Windows 读取 Everything 版本确认连接。无后台轮询。 + +## 反馈 + +不自动发送诊断。公开反馈应使用本次官方市场投稿 PR(上线后补 PR/插件页链接);截图和问题描述请移除私人文件路径、账号、文件正文和密钥。作者源码仓库是否公开尚待用户选择,本稿不把未验证可公开访问的地址作为唯一支持渠道。 diff --git a/plugins/local-fsearch/docs/VALIDATION.md b/plugins/local-fsearch/docs/VALIDATION.md new file mode 100644 index 000000000..6aca7d718 --- /dev/null +++ b/plugins/local-fsearch/docs/VALIDATION.md @@ -0,0 +1,9 @@ +# 使用检查 + +当前版本:0.0.2。作者:lifeek。 + +Windows 已检查:fs 打开搜索、名称/路径匹配、分类与筛选、翻页、搜索预设、主搜索推送、图片缩略图和独立大图窗口。图片缩小后也可以拖动,拖动后滚轮仍以鼠标所在位置缩放。 + +打开文件、在资源管理器定位和复制路径已核对到 ZTools 调用接口;最终打开应用、选中文件和系统粘贴效果尚需人工确认。macOS 最新图片窗口体验仍待实机确认。 + +截图仅使用公开演示样本,没有个人文档或账号信息。 diff --git a/plugins/local-fsearch/docs/screenshots/market-0.0.2/01-windows-search.png b/plugins/local-fsearch/docs/screenshots/market-0.0.2/01-windows-search.png new file mode 100644 index 000000000..2e0e769c4 Binary files /dev/null and b/plugins/local-fsearch/docs/screenshots/market-0.0.2/01-windows-search.png differ diff --git a/plugins/local-fsearch/docs/screenshots/market-0.0.2/02-windows-images.png b/plugins/local-fsearch/docs/screenshots/market-0.0.2/02-windows-images.png new file mode 100644 index 000000000..645e7cce1 Binary files /dev/null and b/plugins/local-fsearch/docs/screenshots/market-0.0.2/02-windows-images.png differ diff --git a/plugins/local-fsearch/docs/screenshots/market-0.0.2/03-large-preview.png b/plugins/local-fsearch/docs/screenshots/market-0.0.2/03-large-preview.png new file mode 100644 index 000000000..f6337ddc2 Binary files /dev/null and b/plugins/local-fsearch/docs/screenshots/market-0.0.2/03-large-preview.png differ diff --git a/plugins/local-fsearch/docs/screenshots/market-0.0.2/04-main-push.png b/plugins/local-fsearch/docs/screenshots/market-0.0.2/04-main-push.png new file mode 100644 index 000000000..78d7b58c5 Binary files /dev/null and b/plugins/local-fsearch/docs/screenshots/market-0.0.2/04-main-push.png differ diff --git a/plugins/local-fsearch/docs/screenshots/market-0.0.2/05-preset-command.png b/plugins/local-fsearch/docs/screenshots/market-0.0.2/05-preset-command.png new file mode 100644 index 000000000..60009409c Binary files /dev/null and b/plugins/local-fsearch/docs/screenshots/market-0.0.2/05-preset-command.png differ diff --git a/plugins/local-fsearch/everything.cjs b/plugins/local-fsearch/everything.cjs new file mode 100644 index 000000000..49eb325df --- /dev/null +++ b/plugins/local-fsearch/everything.cjs @@ -0,0 +1,179 @@ +const path = require('node:path') +const { execFile } = require('node:child_process') +const fs = require('node:fs/promises') +const { performance } = require('node:perf_hooks') +const categories = require('./categories.cjs') +const { applyFilters, resolveDirectories } = require('./filters.cjs') +const { escapeRegex, PAGE_SIZES, SEARCH_WINDOW } = require('./search.cjs') +const { checkAbort, aborted } = require('./latest.cjs') + +const literal = value => escapeRegex(value).replace(/&/g, '\\x26').replace(/"/g, '\\x22') +function sizeTerm(value) { + // Everything 1.4 对带单位的范围及 >= / <= 解释不一致。统一使用整数字节。 + const bytes = text => { + const [, number, unit = 'b'] = /^([\d.]+)(b|kb|mb|gb|tb)?$/i.exec(text) + const result = Number(number) * 1024 ** ['b', 'kb', 'mb', 'gb', 'tb'].indexOf(unit.toLowerCase()) + if (!Number.isFinite(result) || result >= Number.MAX_SAFE_INTEGER) throw new Error('文件大小超出可检索范围') + return result + } + if (value.includes('..')) { + const [min, max] = value.split('..').map(bytes) + const low = Math.ceil(min), high = Math.floor(max) + return low <= high ? `size:"${low}..${high}"` : null + } + const [, op, text] = /^([<>]=?)?(.*)$/.exec(value) + const size = bytes(text) + if (op === '>=') return size === 0 ? 'file:' : `size:">${Math.ceil(size) - 1}"` + if (op === '>') return `size:">${Math.floor(size)}"` + if (op === '<=') return `size:"<${Math.floor(size) + 1}"` + if (op === '<') return `size:"<${Math.ceil(size)}"` + return Number.isInteger(size) ? `size:${size}` : null +} +function directoryTerm(value, exclude = false) { + const directory = path.win32.normalize(value).replace(/\\+$/, '') + return `path:nocase:regex:"^${literal(directory)}${exclude ? '(?:\\\\|$)' : '\\\\'}"` +} + +function compile(options, limit) { + const { query, field = 'name', mode = 'literal', category = 'all', caseSensitive = false, pageSize = 50, offset = 0 } = options + if (typeof query !== 'string' || /[\x00-\x1f]/.test(query) || query.length > 1024) throw new Error('请输入不超过 1024 字的单行关键词') + if (!['name', 'path'].includes(field) || !['literal', 'fuzzy', 'regex'].includes(mode) || options.file || options.git || options.boost) throw new Error('此搜索条件在 Everything 中不可用') + if (typeof caseSensitive !== 'boolean' || !PAGE_SIZES.includes(pageSize) || !Number.isSafeInteger(offset) || offset < 0 || offset >= SEARCH_WINDOW) throw new Error('无效的搜索或分页设置') + const categoryInfo = categories.find(item => item.id === category) + if (!categoryInfo) throw new Error('未知的文件分类') + const filter = { q: '', kind: categoryInfo.kind } + if (!applyFilters(filter, { ...options, exclude: '' }, categoryInfo, false)) return null + + // Everything 也可索引含相对路径的 EFU 文件列表;它们不能直接打开。 + const terms = ['path:nocase:regex:"^(?:[a-z]:\\\\|\\\\\\\\)"'] + const recent = !query.trim() && !options.browse + if (filter.kind === 'file' || (recent && filter.kind !== 'dir')) terms.push('file:') + if (filter.kind === 'dir') terms.push('folder:') + if (filter.ext) terms.push('ext:' + filter.ext.split(',').join(';')) + if (filter.size) { + const term = sizeTerm(filter.size) + if (!term) return null + terms.push('file:', term) + } + if (filter.mtime === '>1y') { + const cutoff = new Date() + cutoff.setDate(cutoff.getDate() - 365) + const date = [cutoff.getFullYear(), cutoff.getMonth() + 1, cutoff.getDate()].map(n => String(n).padStart(2, '0')).join('-') + terms.push(`dm:"<${date}"`) + } else if (filter.mtime) terms.push(`dm:past${Number(filter.mtime.slice(1, -1)) * 24}hours`) + if (filter.in) terms.push(directoryTerm(filter.in)) + for (const dir of (options.exclude || '').split('\n').map(value => value.trim()).filter(Boolean)) terms.push('!' + directoryTerm(dir, true)) + if (query.trim()) { + let expression = mode === 'regex' ? query : literal(query.trim()) + if (mode === 'fuzzy') expression = Array.from(query.trim()).filter(character => !/\s/u.test(character)).map(literal).join('.*') + if (mode === 'regex') { + // 避免引号关闭 Everything 搜索项;用正则转义写法表示双引号。 + if (query.includes('"')) throw new Error('正则中的双引号请写作 \\x22') + try { new RegExp(query) } catch (error) { throw new Error('正则表达式无效:' + error.message) } + } + terms.push(`${field === 'path' ? 'path:' : ''}${caseSensitive ? 'case' : 'nocase'}:regex:"${expression}"`) + } + const sort = recent ? 'date-modified-descending' : 'path-ascending' + const search = terms.join(' ') + return { search, sort, recent, offset, limit: Math.min(limit || pageSize, SEARCH_WINDOW - offset) } +} + +function parseResults(stdout) { + const json = stdout.replace(/^\uFEFF/, '').trim() + if (!json) return [] + let rows + try { rows = JSON.parse(json) } catch { throw new Error('Everything 返回的结果格式无效') } + if (!Array.isArray(rows)) throw new Error('Everything 返回的结果格式无效') + return rows.map(row => { + if (!row || typeof row.filename !== 'string' || !path.win32.isAbsolute(row.filename) || !Number.isInteger(row.attributes)) throw new Error('Everything 返回的文件信息无效') + const kind = row.attributes & 16 ? 'dir' : 'file' + const target = path.win32.normalize(row.filename) + return { path: target === path.win32.parse(target).root ? target : target.replace(/\\$/, ''), kind, + size: kind === 'file' && Number.isFinite(row.size) && row.size >= 0 ? row.size : undefined, + mtime: row.date_modified > 116444736000000000 ? Math.round((row.date_modified - 116444736000000000) / 10000000) : undefined } + }) +} + +function createEverything({ run = execFile, env = process.env, arch = process.arch, getConfiguredPath = () => '' } = {}) { + async function executable() { + const configured = env.ZTOOLS_EVERYTHING_ES || getConfiguredPath() + if (configured) { + if (typeof configured !== 'string' || !path.isAbsolute(configured) || !/\.exe$/i.test(configured) || /["\x00-\x1f]/.test(configured)) throw new Error('请选择官方 ES 的 es.exe 文件') + return configured + } + const root = /\.asar$/i.test(__dirname) ? __dirname + '.unpacked' : __dirname + const bundled = path.join(root, 'vendor', 'es', arch, 'es.exe') + try { if ((await fs.stat(bundled)).isFile()) return bundled } catch (error) { if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error } + for (const root of [env.ProgramW6432, env.ProgramFiles, env['ProgramFiles(x86)']].filter(Boolean)) { + const target = path.join(root, 'Everything', 'es.exe') + try { if ((await fs.stat(target)).isFile()) return target } catch (error) { if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error } + } + return 'es.exe' // 兼容自定义平台的外置 ES;不自动下载或安装任何程序。 + } + const active = new Set() + function execute(args, signal) { + checkAbort(signal) + const instance = env.ZTOOLS_EVERYTHING_INSTANCE + if (instance && /["\x00-\x1f]/.test(instance)) throw new Error('Everything 实例名称无效') + if (instance) args = ['-instance', `"${instance}"`, ...args] + return new Promise((resolve, reject) => { + const controller = new AbortController() + const cancel = () => controller.abort() + active.add(cancel); signal?.addEventListener('abort', cancel, { once: true }) + // -search* 后的查询是原样文本。没有 shell,也不会将查询重新解释为 ES 开关。 + const finish = (error, stdout) => { + active.delete(cancel); signal?.removeEventListener('abort', cancel) + if (controller.signal.aborted) return reject(aborted()) + if (!error || error.code === 9) return resolve(stdout) + if (error.code === 'ENOENT') return reject(new Error('找不到 es.exe。请重新安装插件以恢复随包 ES,或在“使用与连接”中更换 ES。')) + if (error.code === 8 || error.code === 7) return reject(new Error('无法连接 Everything,请启动 Everything 客户端;使用命名实例时请设置 ZTOOLS_EVERYTHING_INSTANCE')) + reject(new Error(error.killed ? 'Everything 响应超时,请稍后重试' : `Everything 查询失败(${error.code || error.message})`)) + } + void executable().then(binary => { + checkAbort(controller.signal) + run(binary, args, { windowsVerbatimArguments: true, windowsHide: true, signal: controller.signal, timeout: 8000, maxBuffer: 8 * 1024 * 1024 }, finish) + }).catch(finish) + }) + } + async function search(options, { signal, queueMs = 0, isCurrent = () => true } = {}, limit) { + const started = performance.now() + compile(options, limit) + const resolved = await resolveDirectories(options, { signal }) + const request = compile(resolved, limit) + checkAbort(signal) + if (!isCurrent()) throw aborted() + if (!request) return { hits: [], offset: options.offset || 0, next: null, windowLimited: false } + const validated = performance.now() + const { search, sort, offset, limit: count, recent } = request + // 多取一项来判断下一页,避免整页刚好填满时显示一个空白下一页。 + const stdout = await execute(['-json', '-columns', 'filename;attributes;size;date-modified', '-date-format', '2', + '-no-match-path', '-no-case', '-no-whole-word', '-no-diacritics', '-no-pause', '-no-empty-search-help', '-no-hide-empty-search-results', + '-no-ipc1', '-sort', sort, '-viewport-offset', String(offset), '-viewport-count', String(count + 1), '-search*', search], signal) + checkAbort(signal) + const rows = parseResults(stdout) + const windowLimited = rows.length > count && offset + count >= SEARCH_WINDOW + return { hits: rows.slice(0, count), offset, next: rows.length > count && !windowLimited ? offset + count : null, + windowLimited, recent, timings: { queueMs, validationMs: validated - started, transportMs: performance.now() - validated } } + } + async function status({ signal } = {}) { + const version = (await execute(['-get-everything-version'], signal)).trim() + if (!/^\d+(?:\.\d+){2,3}$/.test(version)) throw new Error('无法读取 Everything 版本') + return { version } + } + return { + search, + push: (options, context) => search(options, context, 5), + status, + async inspect(options) { + try { return { usable: true, state: 'ready', status: await status(options) } } + catch (error) { + if (error.name === 'AbortError') throw error + return { usable: false, state: 'connection', title: 'Everything 未就绪', + message: '确认 Everything 客户端已启动,再点击“重新检测”。', detail: error.message } + } + }, + closeConnections() { for (const cancel of active) cancel() } + } +} + +module.exports = { createEverything } diff --git a/plugins/local-fsearch/filters.cjs b/plugins/local-fsearch/filters.cjs new file mode 100644 index 000000000..2876ed4cc --- /dev/null +++ b/plugins/local-fsearch/filters.cjs @@ -0,0 +1,90 @@ +const fs = require('node:fs/promises') +const { checkAbort } = require('./latest.cjs') +const os = require('node:os') +const path = require('node:path') + +/** 纯路径展开,不在查询编译或页面线程中同步访问磁盘。 */ +function directoryPath(value) { + if (typeof value !== 'string') throw new Error('目录必须是文本') + const expanded = value === '~' ? os.homedir() : value.startsWith('~/') || (process.platform === 'win32' && value.startsWith('~\\')) ? path.join(os.homedir(), value.slice(2)) : value + if (!path.isAbsolute(expanded)) throw new Error('请输入绝对目录路径,或以 ~/ 开头的路径') + return path.resolve(expanded) +} + +/** 每次有效查询异步验证目录;不缓存文件系统状态,失效/无权限不能静默退回全盘。 */ +async function resolveDirectories(options, { signal, io = fs } = {}) { + checkAbort(signal) + async function resolve(value, required) { + const expanded = directoryPath(value) + try { + if (required) { + const stat = await io.stat(expanded); checkAbort(signal) + if (!stat.isDirectory()) throw new Error('搜索位置必须是文件夹') + } + const real = await io.realpath(expanded); checkAbort(signal); return real + } catch (error) { + checkAbort(signal) + if (!required && error.code === 'ENOENT') return expanded + throw new Error('无法访问搜索目录:' + error.message) + } + } + const output = { ...options } + if (options.file) { + const target = directoryPath(options.file), stat = await io.stat(target); checkAbort(signal) + if (!stat.isFile()) throw new Error('正文搜索对象不是文件') + if (stat.size > 10 * 1024 * 1024) throw new Error('文件超过引擎单文件读取上限(10 MB)') + output.file = await io.realpath(target); checkAbort(signal) + } + if (options.directory) output.directory = await resolve(options.directory, true) + const excluded = (options.exclude || '').split('\n').map(s => s.trim()).filter(Boolean) + if (excluded.length > 20) throw new Error('最多排除 20 个目录') + const real = [] + // 顺序读取至多 20 个目录,避免一次提交过多文件系统任务。 + for (const value of excluded) { checkAbort(signal); real.push(await resolve(value, false)) } + output.exclude = real.join('\n') + checkAbort(signal); return output +} + +/** 筛选在服务分页之前执行;分类与用户扩展名取交集,不能被扩展名条件扩大。 */ +function applyFilters(payload, options, category, content) { + const { extensions = '', modified = '', size = '', exclude = '', directory = '', git = '', boost = false } = options + if (typeof extensions !== 'string' || typeof exclude !== 'string') throw new Error('扩展名和排除目录必须是文本') + const userExts = extensions.toLowerCase().split(/[,,\s]+/).filter(Boolean).map(s => s.replace(/^\./, '')) + if (userExts.length > 30 || userExts.some(s => !/^[a-z0-9_+-]+$/.test(s))) throw new Error('扩展名请用逗号分隔,如 txt,md,py(最多 30 种)') + const base = (content ? category.contentExt || category.ext : category.ext)?.split(',') + const exts = userExts.length && base ? base.filter(s => userExts.includes(s)) : userExts.length ? userExts : base + if (exts) { + // 空交集显式返回无结果,不能把空 ext 发成“所有类型”。 + if (!exts.length) return false + payload.ext = exts.join(',') + payload.kind = 'file' + } + if (modified) { + if (!['<1d', '<7d', '<30d', '<90d', '>1y'].includes(modified)) throw new Error('未知的修改时间条件') + payload.mtime = modified + } + if (size) { + if (!/^(?:[<>]=?)?\d+(?:\.\d+)?(?:b|kb|mb|gb|tb)?(?:\.\.\d+(?:\.\d+)?(?:b|kb|mb|gb|tb)?)?$/i.test(size)) throw new Error('大小格式示例:>100mb、<1mb、1mb..10mb') + if (size.includes('..') && /^[<>]/.test(size)) throw new Error('大小范围不能同时使用比较符') + payload.size = size + } + if (directory) payload.in = directoryPath(directory) + const excluded = exclude.split('\n').map(s => s.trim()).filter(Boolean) + if (excluded.length > 20) throw new Error('最多排除 20 个目录') + for (const value of excluded) { + // 引擎 q 支持带引号的目录 glob,保留正文原生 cursor 分支;不使用前端过滤。 + const absolute = directoryPath(value, false) + if (absolute === '/') return false + if (/["*?\[\]{}\n\r]/.test(absolute)) throw new Error('排除目录不能含引号或 glob 元字符') + payload.q += ` "!${absolute === '/' ? '' : absolute}/"` + } + if (git) { + if (!['modified', 'staged', 'untracked', 'clean', 'tracked', 'ignored', 'conflict'].includes(git)) throw new Error('未知的 Git 状态') + if (!directory) throw new Error('Git 筛选需要先指定项目目录') + payload.q += ` git:${git}` + if (!content) payload.git = true + } + if (!content && boost) payload.boost = true + return true +} +module.exports = { applyFilters, directoryPath, resolveDirectories } diff --git a/plugins/local-fsearch/host.cjs b/plugins/local-fsearch/host.cjs new file mode 100644 index 000000000..e4762106a --- /dev/null +++ b/plugins/local-fsearch/host.cjs @@ -0,0 +1,86 @@ +const fs = require('node:fs/promises') +const path = require('node:path') +const os = require('node:os') +const { spawn } = require('node:child_process') +const { checkAbort, aborted } = require('./latest.cjs') +const { normalizeMatch } = require('./content.cjs') + +/** 宿主集成只处理当前选中文件,不建立索引,不预读文件集;系统进程仅同时保留一个预览。 */ +function createHost(ztools, request, launch = spawn, { everything } = {}) { + let previewProcess = null, previewTarget = null, previewGeneration = 0 + const validPath = target => { + if (typeof target !== 'string' || !path.isAbsolute(target) || target.includes('\0')) throw new Error('文件路径无效') + return target + } + function result(value, label) { + if (!value || value.success !== true) throw new Error(value?.error || label + '失败') + } + const dispose = () => { previewGeneration++; if (previewProcess) { previewProcess.kill(); previewProcess = null; previewTarget = null } } + return { + dispose, + async open(target) { + validPath(target) + result(await ztools.shellOpenPath(target), '打开文件') + if (everything) return + // 打开成功后才写入 FSearch 的 frecency;记录失败明确报告,不伪称已保存。 + try { await request({ op: 'open', path: target }) } + catch (error) { return { warning: new Error('文件已打开,但最近记录未保存:' + error.message) } } + }, + async openLine(target, line, editor = 'vscode') { + if (everything) throw new Error('Windows 暂不支持正文跳行') + validPath(target) + if (!Number.isSafeInteger(line) || line < 1) throw new Error('命中行号无效') + if (!['vscode', 'cursor'].includes(editor)) throw new Error('未知编辑器') + const encoded = target.split('/').map(encodeURIComponent).join('/') + result(await ztools.shellOpenExternal(`${editor}://file${encoded}:${line}:1`), '跳转编辑器') + try { await request({ op: 'open', path: target }) } catch (error) { return { warning: new Error('编辑器已打开,但最近记录未保存:' + error.message) } } + }, + copyFile(target) { + validPath(target) + if (ztools.copyFile(target) !== true) throw new Error('复制文件失败') + return true + }, + async quickLook(target) { + if (everything) throw new Error('快速预览仅在 macOS 可用') + validPath(target) + const version = ++previewGeneration + await fs.access(target) + if (version !== previewGeneration) throw aborted() + if (previewProcess && previewTarget === target) { dispose(); return } + dispose() + // 参数数组避免路径中的空格/元字符被 shell 执行;关闭插件时释放子进程。 + await new Promise((resolve, reject) => { + const child = launch('/usr/bin/qlmanage', ['-p', target], { stdio: 'ignore' }) + previewProcess = child; previewTarget = target + child.once('error', error => { if (previewProcess === child) { previewProcess = null; previewTarget = null }; reject(error) }) + child.once('spawn', resolve) + child.once('exit', code => { if (previewProcess === child) { previewProcess = null; previewTarget = null }; if (code && code !== 0) ztools.showNotification?.('系统快速预览失败,请确认文件仍可访问') }) + }) + }, + /** 单文件正文仍由引擎读取,每次最多 100 处命中和各 3 行上下文,不缓存整篇正文。 */ + async preview(options, target, { signal, isCurrent = () => true } = {}) { + if (everything) throw new Error('Windows 暂不支持正文预览') + validPath(target) + if (!['content', 'symbol'].includes(options.field)) throw new Error('请先切换文件内容或定义搜索') + const stat = await fs.stat(target) + if (!stat.isFile()) throw new Error('预览对象不是文件') + if (stat.size > 10 * 1024 * 1024) throw new Error('文件超过引擎单文件读取上限(10 MB)') + checkAbort(signal); if (!isCurrent()) throw aborted() + const response = await request({ op: 'grep', file: target, pattern: options.query, mode: options.field === 'symbol' ? 'symbol' : options.mode, case: options.caseSensitive ? 'sensitive' : 'insensitive', context: 3, per_file: 100 }, { signal }) + if (!Array.isArray(response.files)) throw new Error('正文预览响应无效') + return { matches: response.files[0]?.matches.map(normalizeMatch) || [], limited: response.files[0]?.matches.length === 100, complete: response.complete } + }, + async diagnostics() { + if (everything) return { status: await everything.status() } + const status = await request({ op: 'status' }) + const config = path.join(os.homedir(), 'Library/Application Support/FSearch/content-skip.txt') + let skipped = '' + try { + const handle = await fs.open(config, 'r') + try { const buffer = Buffer.alloc(16384); const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0); skipped = buffer.subarray(0, bytesRead).toString('utf8') } finally { await handle.close() } + } catch (error) { if (error.code !== 'ENOENT') throw error } + return { status, skipped, config } + } + } +} +module.exports = { createHost } diff --git a/plugins/local-fsearch/image-preview.html b/plugins/local-fsearch/image-preview.html new file mode 100644 index 000000000..1d97753f6 --- /dev/null +++ b/plugins/local-fsearch/image-preview.html @@ -0,0 +1,21 @@ + + + + + + + 图片预览 + + + + + 图片预览关闭 + 正在加载图片… + + 用默认应用打开复制路径 + + + + + + diff --git a/plugins/local-fsearch/image-viewer.js b/plugins/local-fsearch/image-viewer.js new file mode 100644 index 000000000..e4301b493 --- /dev/null +++ b/plugins/local-fsearch/image-viewer.js @@ -0,0 +1,78 @@ +window.mountImageViewer = function (body, image, sizeLabel) { + const toolbar = document.createElement('div'); toolbar.className = 'image-zoom-toolbar' + toolbar.setAttribute('role', 'group'); toolbar.setAttribute('aria-label', '图片缩放') + const stage = document.createElement('div'); stage.className = 'image-stage'; stage.tabIndex = 0 + stage.setAttribute('role', 'region'); stage.setAttribute('aria-label', '图片预览画布') + stage.title = '滚轮以指针为中心缩放 · 任意比例均可拖动' + const frame = document.createElement('div'); frame.className = 'image-frame'; frame.append(stage) + image.draggable = false; stage.append(image) + const percent = document.createElement('output'); percent.setAttribute('aria-live', 'polite') + let scale = 1, fitted = true, drag = null, left = 0, top = 0 + const viewWidth = () => stage.offsetWidth - 2 * stage.clientLeft + const viewHeight = () => stage.offsetHeight - 2 * stage.clientTop + const fit = () => Math.min(1, viewWidth() / image.naturalWidth, viewHeight() / image.naturalHeight) + const minScale = () => Math.min(0.1, fit()) + function button(text, label, action) { + const control = document.createElement('button'); control.type = 'button'; control.textContent = text + control.setAttribute('aria-label', label); control.onclick = action; return control + } + const out = button('−', '缩小', () => zoom(scale / 1.25)) + const plus = button('+', '放大', () => zoom(scale * 1.25)) + const fitButton = button('适应窗口', '适应窗口', () => zoom(fit(), true)) + const actual = button('原始大小', '原始大小', () => zoom(1)) + function position(x, y) { + left = x; top = y + image.style.transform = `translate(${x}px, ${y}px)` + } + function zoom(next, isFit = false, event) { + if (!stage.clientWidth || !stage.clientHeight) return + const view = stage.getBoundingClientRect(), before = image.getBoundingClientRect() + const x = event?.clientX ?? view.left + stage.clientWidth / 2 + const y = event?.clientY ?? view.top + stage.clientHeight / 2 + // 滚轮的锚点可以在图像外。夹紧到边缘会让留白上的指针把图片吸过来。 + const ratio = (value, start, span) => { + if (!span) return 0.5 + const fraction = (value - start) / span + return event ? fraction : Math.max(0, Math.min(1, fraction)) + } + const u = ratio(x, before.left, before.width), v = ratio(y, before.top, before.height) + fitted = isFit; scale = Math.max(minScale(), Math.min(8, next)) + const width = Math.max(1, Math.floor(image.naturalWidth * scale)) + const height = Math.max(1, Math.floor(image.naturalHeight * scale)) + image.style.width = width + 'px'; image.style.height = height + 'px' + position(isFit ? (viewWidth() - width) / 2 : x - view.left - stage.clientLeft - u * width, + isFit ? (viewHeight() - height) / 2 : y - view.top - stage.clientTop - v * height) + percent.textContent = `${Number((scale * 100).toFixed(scale < 0.1 ? 1 : 0))}%` + out.disabled = scale <= minScale(); plus.disabled = scale >= 8 + fitButton.setAttribute('aria-pressed', String(fitted)); actual.setAttribute('aria-pressed', String(!fitted && scale === 1)) + } + toolbar.append(out, percent, plus, fitButton, actual) + const info = document.createElement('p'); info.textContent = `${image.naturalWidth} × ${image.naturalHeight} · ${sizeLabel}` + body.replaceChildren(toolbar, frame, info) + zoom(fit(), true) + const resize = new ResizeObserver(() => { if (fitted && stage.isConnected) zoom(fit(), true) }) + resize.observe(stage) + stage.addEventListener('wheel', event => { + if (!event.deltaY) return + event.preventDefault() + const delta = event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? stage.clientHeight : 1) + zoom(scale * Math.pow(1.25, -Math.max(-240, Math.min(240, delta)) / 100), false, event) + }, { passive: false }) + stage.addEventListener('keydown', event => { + const action = { '+': () => zoom(scale * 1.25), '=': () => zoom(scale * 1.25), '-': () => zoom(scale / 1.25), '0': () => zoom(fit(), true), '1': () => zoom(1) }[event.key] + if (action) { event.preventDefault(); action() } + }) + stage.addEventListener('pointerdown', event => { + if (drag || event.button !== 0) return + event.preventDefault(); stage.focus({ preventScroll: true }); stage.setPointerCapture(event.pointerId) + drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left, top } + stage.classList.add('dragging') + }) + stage.addEventListener('pointermove', event => { + if (drag?.id !== event.pointerId || (event.clientX === drag.x && event.clientY === drag.y && fitted)) return + fitted = false; fitButton.setAttribute('aria-pressed', 'false') + position(drag.left + event.clientX - drag.x, drag.top + event.clientY - drag.y) + }) + stage.addEventListener('lostpointercapture', () => { drag = null; stage.classList.remove('dragging') }) + return () => resize.disconnect() +} diff --git a/plugins/local-fsearch/image-window-preload.js b/plugins/local-fsearch/image-window-preload.js new file mode 100644 index 000000000..f948b540e --- /dev/null +++ b/plugins/local-fsearch/image-window-preload.js @@ -0,0 +1,3 @@ +const { readImage } = require('./images.cjs') +const path = require('node:path') +window.imagePreviewApi = { readImage, name: target => path.basename(target) } diff --git a/plugins/local-fsearch/image-window.js b/plugins/local-fsearch/image-window.js new file mode 100644 index 000000000..abe033462 --- /dev/null +++ b/plugins/local-fsearch/image-window.js @@ -0,0 +1,41 @@ +(() => { + const $ = id => document.getElementById(id) + const host = window.ztools + const api = window.imagePreviewApi + let target, url, cleanup + function action(id, run) { + $(id).onclick = async () => { + try { $('image-message').textContent = await run() || '' } + catch (error) { $('image-message').textContent = error.message } + } + } + action('image-open', async () => { + const result = await host.shellOpenPath(target) + if (!result?.success) throw new Error(result?.error || '打开失败') + }) + action('image-copy', () => { + if (host.copyText(target) !== true) throw new Error('复制路径失败') + return '已复制路径' + }) + $('image-close').onclick = () => window.close() + window.addEventListener('keydown', event => { if (event.key === 'Escape') window.close() }) + window.addEventListener('beforeunload', () => { cleanup?.(); if (url) URL.revokeObjectURL(url) }) + function theme(info) { + document.documentElement.dataset.theme = info?.isDark ? 'dark' : 'light' + document.documentElement.style.colorScheme = info?.isDark ? 'dark' : 'light' + } + theme(host?.getThemeInfo?.()); host?.onThemeChange?.(theme) + void (async () => { + try { + target = decodeURIComponent(location.hash.slice(1)) + const name = api.name(target) + $('image-title').textContent = name; document.title = name + ' · 图片预览' + const file = await api.readImage(target) + url = URL.createObjectURL(new Blob([file.bytes], { type: file.type })) + const image = new Image(); image.alt = name; image.className = 'image-preview'; image.src = url + try { await image.decode() } catch { throw new Error('无法预览此图片,格式可能不受支持或文件已损坏。') } + const bytes = file.bytes.byteLength + cleanup = window.mountImageViewer($('image-body'), image, bytes >= 1048576 ? (bytes / 1048576).toFixed(1) + ' MB' : (bytes / 1024).toFixed(1) + ' KB') + } catch (error) { $('image-body').querySelector('p').textContent = error.message } + })() +})() diff --git a/plugins/local-fsearch/images.cjs b/plugins/local-fsearch/images.cjs new file mode 100644 index 000000000..01ec9b365 --- /dev/null +++ b/plugins/local-fsearch/images.cjs @@ -0,0 +1,35 @@ +const fs = require('node:fs/promises') +const { constants } = require('node:fs') +const path = require('node:path') + +const types = { + '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', + '.gif': 'image/gif', '.webp': 'image/webp', '.bmp': 'image/bmp', + '.svg': 'image/svg+xml', '.avif': 'image/avif', '.ico': 'image/x-icon', + '.heic': 'image/heic', '.tif': 'image/tiff', '.tiff': 'image/tiff' +} +const imageType = target => typeof target === 'string' ? types[path.extname(target).toLowerCase()] : undefined +const maxBytes = 32 * 1024 * 1024 + +async function readImage(target) { + const type = imageType(target) + if (!type || !path.isAbsolute(target)) throw new Error('图片路径或格式无效') + // Unix 上即使文件被替换成管道,open 也不会阻塞;只读取普通文件。 + const flags = process.platform === 'win32' ? constants.O_RDONLY : constants.O_RDONLY | constants.O_NONBLOCK + const file = await fs.open(target, flags) + try { + const { size, mode } = await file.stat() + if ((mode & constants.S_IFMT) !== constants.S_IFREG || !size) throw new Error('图片为空或不可读取') + if (size > maxBytes) throw new Error('图片超过 32 MB,请用默认应用打开') + const bytes = new Uint8Array(size) + let offset = 0 + while (offset < size) { + const { bytesRead } = await file.read(bytes, offset, size - offset, offset) + if (!bytesRead) throw new Error('图片在读取时发生变化,请重试') + offset += bytesRead + } + return { type, bytes } + } finally { await file.close() } +} + +module.exports = { imageType, readImage } diff --git a/plugins/local-fsearch/index.html b/plugins/local-fsearch/index.html new file mode 100644 index 000000000..245a00388 --- /dev/null +++ b/plugins/local-fsearch/index.html @@ -0,0 +1,63 @@ + + +FSearch 文件搜索 + + + + + + 全部文件新搜索索引状态使用与连接 + + 搜索文件名完整路径文件内容代码定义模糊查找 + 匹配精确包含字符模糊正则表达式 + Aa包含输入原文 + + 位置常用目录所有位置下载文档桌面用户目录应用清除 + 筛选与预设 + 搜索 TXT、Markdown、配置及代码等纯文本;遵循引擎的文件大小和忽略规则。列表展示首处摘要,展开可查看更多命中。 + + + + 查找本机文件在上方输入文件名,也可以先选择左侧分类。 + + 每页 2550100 项 + 上一页第 1 页下一页 + + + + + + 筛选与预设完成 + + 扩展名 + 修改时间不限时间最近一天最近 7 天最近 30 天最近 90 天一年以前 + 大小 + Git 状态不限状态全部变更(含未跟踪)已暂存未跟踪有冲突已跟踪未修改被忽略 + 排除目录(每行一个绝对路径或 ~/ 路径) + + 常用优先 空关键词浏览筛选结果清空筛选 + 选择已保存预设保存删除 + 保存为 ZTools 独立指令,可设置快捷键或固定到超级面板命中行编辑器VS CodeCursor使用已安装编辑器的 URL 协议打开 + ZTools 集成 + 打开、定位或跳行成功后收起主窗口 + 复制路径或文件后收起主窗口 + 再次唤起时恢复上次搜索 + 启用主搜索推送(fs + 空格 + 至少 2 个字) + 推送默认关闭,仅返回最多 5 项。还需在 ZTools 插件设置中开启「搜索栏推送」。 + 工作目录 + 设置搜索快捷键 + + + + 关闭 + + + + + + + diff --git a/plugins/local-fsearch/integration.cjs b/plugins/local-fsearch/integration.cjs new file mode 100644 index 000000000..767ca3500 --- /dev/null +++ b/plugins/local-fsearch/integration.cjs @@ -0,0 +1,216 @@ +const fs = require('node:fs/promises') +const path = require('node:path') +const crypto = require('node:crypto') +const os = require('node:os') +const { createLatest, checkAbort } = require('./latest.cjs') +const { buildRequest } = require('./search.cjs') +const { resolveDirectories } = require('./filters.cjs') +const DEFAULTS = { autoHide: true, copyHide: false, remember: true, mainPush: false, workspace: '' } +const OPTIONS = { query: '', category: 'all', directory: '', field: 'engine', mode: 'native', caseSensitive: false, pageSize: 50, extensions: '', modified: '', size: '', exclude: '', git: '', boost: false, browse: false } +const PREFIX = 'fsearch.preset.' +const commands = new Set(['fs', 'find', 'fsearch', '全盘搜索', 'FSearch 文件搜索']) +const presetCode = name => PREFIX + crypto.createHash('sha256').update(name).digest('hex').slice(0, 20) +const macFeatures = [ + { code: 'search-content', explain: 'FSearch 正文搜索', platform: ['darwin'], cmds: ['搜正文', 'FSearch 正文'] }, + { code: 'search-symbol', explain: 'FSearch 代码定义', platform: ['darwin'], cmds: ['搜代码定义', 'FSearch 定义'] } +] + +// 旧版 ZTools 可能忽略静态 feature 的 platform;只在 macOS 写入这两条指令。 +function syncPlatformFeatures(ztools, platform) { + const previous = new Map(ztools.getFeatures().map(feature => [feature.code, feature])) + for (const feature of macFeatures) { + const current = previous.get(feature.code) + if (platform === 'darwin' && JSON.stringify(current) !== JSON.stringify(feature)) { + const result = ztools.setFeature(feature) + if (result?.success !== true) throw new Error(result?.error || '创建 macOS 搜索指令失败') + } else if (platform === 'win32' && current && ztools.removeFeature(feature.code) !== true) { + throw new Error('移除当前平台不可用的搜索指令失败') + } + } +} + +/** 宿主桥只保存条件、单个会话和最多六个推送令牌;不保存搜索结果集或正文。 */ +function createIntegration(ztools, host, pushRequest, { windows = false, searchPush } = {}) { + const defaults = windows ? { ...OPTIONS, field: 'name', mode: 'literal' } : OPTIONS + let detached = false + let issued = new Map(), pushError = '', session = null + const notify = error => ztools.showNotification?.(error.message || String(error)) + const stored = key => ztools.dbStorage.getItem(key) + function write(key, value) { + const error = ztools.dbStorage.setItem(key, value) + if (error !== undefined) throw new Error(error.error || '宿主存储写入失败') + } + function loadSettings() { + const saved = stored('fsearch-settings') + const value = saved || { presets: [], editor: 'vscode' } + if (!Array.isArray(value.presets) || value.presets.length > 20 || !['vscode', 'cursor'].includes(value.editor)) throw new Error('搜索设置格式无效') + const integration = { ...DEFAULTS, ...value.integration } + for (const key of ['autoHide', 'copyHide', 'remember', 'mainPush']) if (typeof integration[key] !== 'boolean') throw new Error('集成开关格式无效') + if (typeof integration.workspace !== 'string') throw new Error('工作目录格式无效') + return { ...value, integration } + } + function features(settings) { + return settings.presets.filter(p => p.command !== false).map(p => { + if (typeof p.name !== 'string' || !p.name.trim() || p.name.length > 30 || !p.options) throw new Error('预设格式无效') + return { code: presetCode(p.name), explain: 'FSearch 搜索预设:' + p.name, platform: [windows ? 'win32' : 'darwin'], cmds: ['FSearch · ' + p.name] } + }) + } + /** 只同步本插件拥有的预设指令;失败恢复旧指令,不能显示虚假的保存成功。 */ + function syncFeatures(settings) { + const previous = ztools.getFeatures().filter(f => f.code?.startsWith(PREFIX)) + const wanted = features(settings), byCode = new Map(wanted.map(f => [f.code, f])) + const set = feature => { const result = ztools.setFeature(feature); if (result?.success !== true) throw new Error(result?.error || '创建 ZTools 指令失败') } + try { + for (const f of wanted) if (JSON.stringify(previous.find(p => p.code === f.code)) !== JSON.stringify(f)) set(f) + for (const f of previous) if (!byCode.has(f.code) && ztools.removeFeature(f.code) !== true) throw new Error('删除 ZTools 指令失败') + } catch (error) { + try { for (const f of previous) set(f); for (const f of wanted) if (!previous.some(p => p.code === f.code)) ztools.removeFeature(f.code) } + catch (rollback) { throw new Error(error.message + ';指令恢复失败:' + rollback.message) } + throw error + } + return previous + } + function saveSettings(settings) { + const normalized = { ...settings, integration: { ...DEFAULTS, ...settings.integration } } + if (normalized.integration.workspace.trim()) require('./filters.cjs').directoryPath(normalized.integration.workspace.trim()) + const previous = syncFeatures(normalized) + const oldSettings = stored('fsearch-settings') || null, oldSession = stored('fsearch-session') || null + try { + write('fsearch-settings', normalized) + if (!normalized.integration.remember) write('fsearch-session', null) + } + catch (error) { + try { write('fsearch-settings', oldSettings); write('fsearch-session', oldSession); const old = new Map(previous.map(f => [f.code, f])); for (const f of features(normalized)) if (!old.has(f.code)) ztools.removeFeature(f.code); for (const f of previous) { const r = ztools.setFeature(f); if (!r?.success) throw new Error(r?.error || '指令恢复失败') } } + catch (rollback) { throw new Error(error.message + ';' + rollback.message) } + throw error + } + if (!normalized.integration.remember) session = null + issued.clear(); push.invalidate() + } + function saveSession(value) { + if (!loadSettings().integration.remember) return + // 游标历史只留 32 页;序列化后设硬上限,不能把异常大的输入持久保存。 + if (Buffer.byteLength(JSON.stringify(value), 'utf8') > 32768) throw new Error('搜索状态过大,未保存本次恢复状态') + session = structuredClone(value); write('fsearch-session', session) + } + function loadSession() { const value = loadSettings().integration.remember ? session || stored('fsearch-session') : null; return value ? structuredClone(value) : null } + function focusInput(select = true) { return select ? ztools.subInputSelect() : ztools.subInputFocus() } + async function finishAction(copy = false) { + const prefs = loadSettings().integration + if (detached) return + if (copy ? prefs.copyHide : prefs.autoHide) await ztools.hideMainWindow(copy) + } + const actions = { + async open(target) { const result = await host.open(target); await finishAction(); if (result?.warning) notify(result.warning) }, + async openLine(target, line, editor) { const result = await host.openLine(target, line, editor); await finishAction(); if (result?.warning) notify(result.warning) }, + async reveal(target) { await fs.access(target); await ztools.shellShowItemInFolder(target); await finishAction() }, + async copy(target) { if (typeof target !== 'string' || !path.isAbsolute(target)) throw new Error('文件路径无效'); if (ztools.copyText(target) !== true) throw new Error('复制路径失败'); await finishAction(true); return true }, + async copyFile(target) { await fs.access(target); host.copyFile(target); await finishAction(true); return true }, + async pasteFile(target) { + await fs.access(target) + // 仅点击动作才调用宿主恢复原窗口并粘贴;不追加回车或发送操作。 + if (ztools.hideMainWindowPasteFile(target) !== true) throw new Error('未能向原应用粘贴文件,请检查宿主权限;独立窗口中请使用复制文件') + return true + }, + async pastePath(target) { + if (typeof target !== 'string' || !path.isAbsolute(target)) throw new Error('文件路径无效') + if (ztools.hideMainWindowPasteText(target) !== true) throw new Error('未能向原应用粘贴路径,请检查宿主权限') + return true + } + } + /** 进入参数只解释已声明的入口;普通选中文本中的 fs 前缀不会被误删。 */ + async function resolveEntry(action = {}) { + const settings = loadSettings(), code = action.code || 'search', type = action.type || 'text', payload = action.payload + if (code.startsWith(PREFIX)) { + const preset = settings.presets.find(p => presetCode(p.name) === code) + if (!preset) throw new Error('此预设已删除,请从 ZTools 指令中重新选择') + return { kind: 'search', options: { ...defaults, ...preset.options } } + } + if (type === 'files') { + if (!Array.isArray(payload) || payload.length !== 1) throw new Error('请一次交入一个文件或文件夹') + const target = typeof payload[0] === 'string' ? payload[0] : payload[0]?.path + if (typeof target !== 'string' || !path.isAbsolute(target)) throw new Error('交入的文件路径无效') + const stat = await fs.stat(target), real = await fs.realpath(target) + if (stat.isDirectory()) return { kind: 'search', options: { ...defaults, directory: real, browse: true } } + if (!stat.isFile()) throw new Error('此入口只接收普通文件或文件夹') + return { kind: 'search', options: { ...defaults, field: 'name', mode: 'literal', directory: path.dirname(real), query: path.basename(real) }, sourceFile: real, selectPath: real } + } + let text = typeof payload === 'string' ? payload : typeof payload?.query === 'string' ? payload.query : '' + if (action.option?.fsearchToken) { + const record = issued.get(action.option.fsearchToken) + if (!record || record.action !== 'more') throw new Error('主搜索结果已过期,请重新搜索') + return { kind: 'search', options: { ...defaults, query: record.query } } + } + if (code === 'search-query') { + const match = /^(?:fs|find)\s+([\s\S]+)$/i.exec(text) + if (!match) throw new Error('参数入口格式为 fs 关键词或 find 关键词') + text = match[1] + } else if (code === 'search-content' || code === 'search-symbol' || code === 'search-workspace' || code === 'search-new') { + if (type === 'text' && typeof payload === 'string') { + const labels = { 'search-content': ['搜正文', 'FSearch 正文'], 'search-symbol': ['搜代码定义', 'FSearch 定义'], 'search-workspace': ['搜工作目录', 'FSearch 工作目录'], 'search-new': ['FSearch 新搜索'] }[code] + const label = labels.find(label => text === label || text.startsWith(label + ' ')) + if (label) text = text.slice(label.length).trimStart() + if (code === 'search-new') text = '' + } + } else if (type === 'text' && commands.has(text.trim())) text = '' + else if (code === 'search' && type === 'text' && action.from !== 'redirect') { + const match = /^(?:fs|find|fsearch|全盘搜索|FSearch 文件搜索)\s+([\s\S]+)$/i.exec(text) + if (match) text = match[1] + } + if (code === 'search' && !text.trim() && !payload?.query) return { kind: 'resume' } + const options = { ...defaults, query: text } + if (windows && ['search-content', 'search-symbol'].includes(code)) throw new Error('Windows 暂不支持正文或代码定义搜索') + if (code === 'search-content') Object.assign(options, { field: 'content', mode: 'literal' }) + if (code === 'search-symbol') Object.assign(options, { field: 'symbol', mode: 'literal' }) + if (code === 'search-workspace') { + if (!settings.integration.workspace.trim()) return { kind: 'search', options, configureWorkspace: true, notice: '请先设置工作目录,再使用工作目录搜索指令' } + options.directory = settings.integration.workspace.trim() + } + return { kind: 'search', options } + } + const push = createLatest(async (query, context) => { + // 仅按 fs 前缀触发,延迟后再判断是否过期;普通 ZTools 输入不查询、不启动服务。 + await new Promise(resolve => setTimeout(resolve, 150)); checkAbort(context.signal) + if (!context.isCurrent()) return [] + let response + const options = { ...defaults, field: 'name', mode: 'literal', query } + if (searchPush) response = await searchPush(options, context) + else { + const payload = buildRequest(await resolveDirectories(options, context)); payload.limit = 5 + if (!context.isCurrent()) return [] + response = await pushRequest(payload, { signal: context.signal }) + } + if (!context.isCurrent()) return [] + if (!Array.isArray(response.hits)) throw new Error('主搜索推送响应无效') + issued.clear() + const issue = record => { const token = crypto.randomUUID(); issued.set(token, record); return token } + const hits = response.hits.slice(0, 5).map(hit => ({ text: path.basename(hit.path), title: hit.path, fsearchToken: issue({ action: 'open', path: hit.path, query }) })) + hits.push({ text: '更多结果…', title: '进入 FSearch 完整搜索', fsearchToken: issue({ action: 'more', query }) }) + pushError = ''; return hits + }) + async function queryPush(data = {}) { + issued.clear() + const text = typeof data.inputState?.searchQuery === 'string' ? data.inputState.searchQuery : typeof data.payload === 'string' ? data.payload : '' + const match = /^fs\s+(.{2,120})$/i.exec(text) + if (!loadSettings().integration.mainPush || !match) { push.invalidate(); return [] } + try { return await push.submit(match[1]) } + catch (error) { if (error.name !== 'AbortError') pushError = error.message; return [] } + } + function selectPush(data = {}) { + const token = data.option?.fsearchToken + const record = issued.get(token) + if (!record) { notify(new Error('主搜索结果已过期,请重新搜索')); return false } + if (record.action === 'more') return true + // 不自动收起时,同一批其他结果仍在宿主界面上;只消费被点击的文件令牌。 + issued.delete(token); void actions.open(record.path).catch(notify); return false + } + return { ...actions, loadSettings, saveSettings, saveSession, loadSession, focusInput, focusResults: () => ztools.subInputBlur(), resolveEntry, + syncFeatures: () => syncFeatures(loadSettings()), + queryPush, selectPush, pushStatus: () => ({ enabled: loadSettings().integration.mainPush, lastError: pushError }), + suspend() { push.dispose(); issued.clear() }, + setDetached: value => { detached = value }, + shortcutSettings: () => ztools.redirectHotKeySetting('FSearch 文件搜索'), + home: () => os.homedir() + } +} +module.exports = { createIntegration, syncPlatformFeatures, presetCode, DEFAULTS, OPTIONS } diff --git a/plugins/local-fsearch/latest.cjs b/plugins/local-fsearch/latest.cjs new file mode 100644 index 000000000..aff579220 --- /dev/null +++ b/plugins/local-fsearch/latest.cjs @@ -0,0 +1,33 @@ +const { performance } = require('node:perf_hooks') + +function aborted() { const error = new Error('查询已被更新或取消'); error.name = 'AbortError'; return error } +function checkAbort(signal) { if (signal?.aborted) throw aborted() } + +/** 最多一个执行任务与一个最新待执行任务。过期任务读完再启动新任务,避免断开连接后引擎仍计算导致并发膨胀。 */ +function createLatest(run) { + let active = null, pending = null + function pump() { + if (active || !pending) return + const item = pending; pending = null; active = item + Promise.resolve().then(() => run(item.value, { signal: item.controller.signal, queueMs: performance.now() - item.created, isCurrent: () => !item.obsolete })).then( + value => item.obsolete ? item.reject(aborted()) : item.resolve(value), + error => item.reject(item.obsolete ? aborted() : error) + ).finally(() => { if (active === item) active = null; pump() }) + } + function invalidate() { + if (active) active.obsolete = true + if (pending) { pending.reject(aborted()); pending = null } + } + return { + submit(value) { + invalidate() + return new Promise((resolve, reject) => { + pending = { value, resolve, reject, controller: new AbortController(), created: performance.now(), obsolete: false } + pump() + }) + }, + invalidate, + dispose() { invalidate(); active?.controller.abort() } + } +} +module.exports = { createLatest, aborted, checkAbort } diff --git a/plugins/local-fsearch/logo.png b/plugins/local-fsearch/logo.png new file mode 100644 index 000000000..284cb5722 Binary files /dev/null and b/plugins/local-fsearch/logo.png differ diff --git a/plugins/local-fsearch/plugin.json b/plugins/local-fsearch/plugin.json new file mode 100644 index 000000000..f77cebd5e --- /dev/null +++ b/plugins/local-fsearch/plugin.json @@ -0,0 +1,109 @@ +{ + "name": "local-fsearch", + "title": "FSearch 文件搜索", + "description": "本地文件搜索 · macOS 使用 FSearch · Windows 使用 Everything", + "version": "0.0.2", + "author": "lifeek", + "main": "index.html", + "preload": "preload.js", + "logo": "logo.png", + "pluginSetting": { + "height": 600, + "single": true + }, + "features": [ + { + "code": "search", + "explain": "搜索本机文件与文件夹", + "platform": [ + "darwin", + "win32" + ], + "cmds": [ + "fs", + "find", + "fsearch", + "全盘搜索", + "FSearch 文件搜索" + ], + "mainPush": true + }, + { + "code": "search-query", + "explain": "FSearch 带关键词搜索", + "platform": [ + "darwin", + "win32" + ], + "cmds": [ + { + "type": "regex", + "label": "FSearch 搜索参数", + "match": "/^(?:fs|find)\\s+\\S[\\s\\S]*$/i", + "minLength": 4, + "maxLength": 1024 + } + ] + }, + { + "code": "search-text", + "explain": "搜索选中的文字", + "platform": [ + "darwin", + "win32" + ], + "cmds": [ + { + "type": "over", + "label": "用 FSearch 搜索文字", + "minLength": 1, + "maxLength": 512 + } + ] + }, + { + "code": "search-files", + "explain": "在文件夹中搜索或操作文件", + "platform": [ + "darwin", + "win32" + ], + "cmds": [ + { + "type": "files", + "label": "用 FSearch 搜索文件或目录", + "minLength": 1, + "maxLength": 1 + } + ] + }, + { + "code": "search-workspace", + "explain": "FSearch 工作目录搜索", + "platform": [ + "darwin", + "win32" + ], + "cmds": [ + "搜工作目录", + "FSearch 工作目录" + ] + }, + { + "code": "search-new", + "explain": "FSearch 新搜索(清空上次条件)", + "platform": [ + "darwin", + "win32" + ], + "cmds": [ + "FSearch 新搜索" + ] + } + ], + "platform": [ + "darwin", + "win32" + ], + "unpack": "vendor/es/**/es.exe" +} diff --git a/plugins/local-fsearch/preload.js b/plugins/local-fsearch/preload.js new file mode 100644 index 000000000..a1a155569 --- /dev/null +++ b/plugins/local-fsearch/preload.js @@ -0,0 +1,61 @@ +const { createLatest } = require('./latest.cjs') +const mac = require('./client.cjs') +const categories = require('./categories.cjs') +const path = require('node:path') +const { createSearch } = require('./search.cjs') +const os = require('node:os') +const { createHost } = require('./host.cjs') +const { createIntegration, syncPlatformFeatures } = require('./integration.cjs') +const { imageType, readImage } = require('./images.cjs') +const windows = process.platform === 'win32' +const everything = windows ? require('./everything.cjs').createEverything({ getConfiguredPath: () => window.ztools.dbStorage.getItem('fsearch-everything-es') || '' }) : null +const closeConnections = everything?.closeConnections || mac.closeConnections +const host = createHost(window.ztools, mac.request, undefined, { everything }) +const integration = createIntegration(window.ztools, host, (payload, context) => mac.exchange(payload, undefined, context), { windows, searchPush: everything?.push }) +const readiness = everything || require('./readiness.cjs').createReadiness(mac.request) +window.ztools.onMainPush(integration.queryPush, integration.selectPush) +const search = createLatest(everything?.search || createSearch(mac.request)) +const preview = createLatest((value, context) => host.preview(value.options, value.path, context)) + +window.fsearchApi = { + windows, + imageType, + readImage, + categories: categories.map(({ id, label, icon, contentSupported = false, contentLabel }) => ({ id, label, icon, contentSupported, contentLabel })), + status: everything?.status || (() => mac.request({ op: 'status' })), + connection: options => readiness.inspect(options), + async chooseEverythingCli() { + if (!windows) return false + const files = await window.ztools.showOpenDialog({ title: '选择从 Everything 官网下载的 es.exe', properties: ['openFile'], filters: [{ name: 'ES 命令行工具', extensions: ['exe'] }] }) + if (!files?.length) return false + const target = files[0] + if (!path.isAbsolute(target) || path.basename(target).toLowerCase() !== 'es.exe') throw new Error('请选择 ES 命令行工具 es.exe,不是 Everything.exe') + const stat = await require('node:fs/promises').stat(target) + if (!stat.isFile()) throw new Error('ES 路径不是文件') + const error = window.ztools.dbStorage.setItem('fsearch-everything-es', target) + if (error !== undefined) throw new Error(error.error || '保存 ES 路径失败') + return true + }, + async openHelp(topic) { + const links = { everything: 'https://www.voidtools.com/downloads/', install: 'https://github.com/noahdunnagan/fsearch/releases/tag/v0.2.1', permissions: 'https://github.com/noahdunnagan/fsearch#full-disk-access', project: 'https://github.com/lifeek23/ztools-fsearch' } + if (!Object.hasOwn(links, topic)) throw new Error('未知的帮助入口') + const result = await window.ztools.shellOpenExternal(links[topic]) + if (result?.success !== true) throw new Error(result?.error || '未能打开帮助网页') + return true + }, + ...host, + search: value => search.submit(value), + invalidateSearch: () => search.invalidate(), + preview: (options, path) => preview.submit({ options, path }), + invalidatePreview: () => preview.invalidate(), + dispose() { search.dispose(); preview.dispose(); integration.suspend(); closeConnections(); host.dispose() }, + ...integration, + suspend() { search.dispose(); preview.dispose(); integration.suspend(); closeConnections() }, + name: target => path.basename(target), + home: () => os.homedir() +} + +try { + syncPlatformFeatures(window.ztools, process.platform) + integration.syncFeatures() +} catch (error) { window.fsearchApi.integrationError = error.message } diff --git a/plugins/local-fsearch/readiness.cjs b/plugins/local-fsearch/readiness.cjs new file mode 100644 index 000000000..3d4359093 --- /dev/null +++ b/plugins/local-fsearch/readiness.cjs @@ -0,0 +1,89 @@ +const fs = require('node:fs/promises') +const { createReadStream } = require('node:fs') +const { createHash } = require('node:crypto') +const os = require('node:os') +const path = require('node:path') +const compatibility = require('./compatibility.json') +const { checkAbort } = require('./latest.cjs') +const binaryPath = path.join(os.homedir(), '.local/bin/fsearch') +const socketPath = path.join(os.homedir(), 'Library/Application Support/FSearch/fsearch.sock') + +/** 错误保留真实原因;仅将已知的安装、权限、建索引与协议错误转成可操作说明。 */ +function failure(error) { + const detail = error.message || String(error) + let state = 'connection', title = '暂时无法连接 FSearch', message = '确认 FSearch 已安装,稍后点击“重新检测”。' + if (error.code === 'FSEARCH_MISSING') { state = 'missing'; title = '请先安装 FSearch'; message = '插件不附带搜索引擎。按安装指引安装后,点击“重新检测”。' } + else if (['EACCES', 'EPERM'].includes(error.code)) { state = 'permission'; title = '无法访问本地服务'; message = '检查当前用户是否可访问 FSearch 程序和 Socket;不要用 sudo 启动插件。' } + else if (/indexing|index not ready|initial scan/i.test(detail)) { state = 'indexing'; title = 'FSearch 正在建立初始索引'; message = '等待引擎完成后点击“重新检测”;插件不会额外扫描磁盘。' } + else if (error.code === 'FSEARCH_PROTOCOL' || /unknown (op|mode|case)|unsupported/i.test(detail)) { state = 'incompatible'; title = 'FSearch 接口不兼容'; message = '请使用安装指引中已验证的 FSearch 版本,再重新检测。不会自动切换搜索方式。' } + else if (error.code === 'FSEARCH_START_FAILED') { state = 'start-failed'; title = 'FSearch 启动失败'; message = '在终端执行 ~/.local/bin/fsearch status 查看原因,确认 macOS 允许运行此程序。' } + return { usable: false, state, title, message, detail, binaryPath, socketPath } +} + +/** 流式计算已安装文件的指纹,不读取整个二进制到内存;不据此推断正在运行的守护进程版本。 */ +async function installedIdentity() { + try { + const hash = createHash('sha256') + for await (const chunk of createReadStream(binaryPath)) hash.update(chunk) + const sha256 = hash.digest('hex') + return { sha256, version: sha256 === compatibility.fsearch.binarySha256 ? compatibility.fsearch.version : null } + } catch (error) { + if (error.code === 'ENOENT') return { version: null, warning: '服务可连接,但标准安装位置没有二进制,无法自动重启或核对安装版本。' } + return { version: null, warning: '无法核对安装文件指纹:' + error.message } + } +} + +/** + * 每个插件进程只保留一份微小能力报告;状态每次重读,手动重检才重新执行探针。 + * 探针直接读取临时小文件,不等索引、不搜索用户正文,结束后删除。 + */ +function createReadiness(request, { io = fs, platform = process.platform, arch = process.arch, identity = installedIdentity, tempRoot = os.tmpdir() } = {}) { + let verified = null, checking = null + const protocol = message => { const error = new Error(message); error.code = 'FSEARCH_PROTOCOL'; throw error } + async function probe() { + const folder = await io.mkdtemp(path.join(tempRoot, 'ztools-fsearch-check-')) + try { + const target = path.join(folder, 'probe.rs') + await io.writeFile(target, 'fn ProbeCaseToken() {}\n// probecasetoken\n') + const file = await io.realpath(target) + const grep = async (pattern, mode, sensitivity) => { + const result = await request({ op: 'grep', file, pattern, mode, case: sensitivity, per_file: 3, context: 1 }) + if (!Array.isArray(result.files) || result.complete !== true) protocol('正文探针未返回完整的 files 响应') + const matches = result.files.flatMap(item => item.matches || []) + if (matches.some(item => !Number.isSafeInteger(item.line) || !Array.isArray(item.ranges) || !Array.isArray(item.before) || !Array.isArray(item.after))) protocol('正文行号、高亮或上下文接口不兼容') + return matches.map(item => item.line) + } + const insensitive = await grep('ProbeCaseToken', 'literal', 'insensitive') + const sensitive = await grep('ProbeCaseToken', 'literal', 'sensitive') + const regex = await grep('(?i:probe.*token)', 'regex', 'sensitive') + const symbol = await grep('ProbeCaseToken', 'symbol', 'sensitive') + if (JSON.stringify(insensitive) !== '[1,2]' || JSON.stringify(sensitive) !== '[1]' || JSON.stringify(regex) !== '[1,2]' || JSON.stringify(symbol) !== '[1]') protocol('文本包含、Aa、正则或定义搜索的实际语义与插件要求不一致') + // 限定探针目录和一条结果,仅确认名称及最近列表接口结构;不修改引擎的打开记录。 + for (const payload of [{ q: 'probe', in: folder, limit: 1, offset: 0 }, { op: 'recent', in: folder, limit: 1 }]) { + const result = await request(payload) + if (!Array.isArray(result.hits)) protocol('名称搜索或最近列表接口不兼容') + } + return { checkedAt: new Date().toISOString(), identity: await identity(), capabilities: ['名称接口', '最近文件接口', '文本包含', 'Aa', '正则', '代码定义', '行号与上下文'] } + } finally { await io.rm(folder, { recursive: true, force: true }) } + } + return { + /** 无后台轮询;失败不缓存,稍后重试会重新确认服务与能力。 */ + async inspect({ recheck = false, signal } = {}) { + if (platform !== 'darwin') return { ...failure(new Error('此插件仅支持 macOS')), state: 'platform', title: '仅支持 macOS' } + try { + checkAbort(signal) + const status = await request({ op: 'status' }, { signal }) + if (!Number.isSafeInteger(status.entries) || status.entries < 0 || typeof status.full_disk_access !== 'boolean' || !Number.isSafeInteger(status.content_pending)) protocol('status 缺少插件需要的索引与权限字段') + if (recheck) verified = null + if (!verified) { + // 并发进入共用一次检查;检查期间只有这一个极小任务,不增加查询并行度。 + if (!checking) checking = probe().then(result => { verified = result; return result }).finally(() => { checking = null }) + await checking + } + checkAbort(signal) + return { usable: true, state: !status.full_disk_access ? 'limited' : status.content_pending > 0 ? 'content-indexing' : 'ready', status, ...verified, arch, binaryPath, socketPath } + } catch (error) { if (error.name === 'AbortError') throw error; return failure(error) } + } + } +} +module.exports = { createReadiness, failure, installedIdentity } diff --git a/plugins/local-fsearch/search.cjs b/plugins/local-fsearch/search.cjs new file mode 100644 index 000000000..4ab1f498c --- /dev/null +++ b/plugins/local-fsearch/search.cjs @@ -0,0 +1,125 @@ +const categories = require('./categories.cjs') +const { normalizeContent } = require('./content.cjs') +const { performance } = require('node:perf_hooks') +const { checkAbort, aborted } = require('./latest.cjs') +const { applyFilters, resolveDirectories } = require('./filters.cjs') + +// 文件名/路径的分页检索窗口为 20,000;正文使用独立的候选游标,不受此窗口限制。 +const SEARCH_WINDOW = 20000 +const PAGE_SIZES = [25, 50, 100] + +/** 将文本转成正则字面量,避免精确模式意外执行用户输入的元字符。 */ +function escapeRegex(text) { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +/** + * 将各匹配模式编译为引擎条件;所有范围、大小写和分类过滤先于分页执行。 + * @param {object} options 用户原文、模式、范围、Aa、分类、目录、页大小和游标 + * @returns {object} 可直接发送到 FSearch 的请求 + */ +function buildRequest(options = {}) { + const { query, mode = 'literal', field = 'name', caseSensitive = false, category = 'all', pageSize = 50, offset = 0 } = options + const content = ['content', 'symbol'].includes(field) + if (typeof query !== 'string') throw new Error('搜索内容必须是文本') + if (!['literal', 'fuzzy', 'regex', 'native'].includes(mode)) throw new Error('未知的匹配模式') + if (!['name', 'path', 'content', 'symbol', 'engine'].includes(field)) throw new Error('未知的搜索范围') + if (typeof caseSensitive !== 'boolean') throw new Error('Aa 状态必须是布尔值') + if (!PAGE_SIZES.includes(pageSize)) throw new Error('每页条数必须是 25、50 或 100') + if (!Number.isSafeInteger(offset) || offset < 0 || (!content && offset >= SEARCH_WINDOW)) throw new Error('分页位置超出检索窗口,请缩小搜索条件') + const filter = categories.find(item => item.id === category) + if (!filter) throw new Error('未知的文件分类') + + if (field === 'symbol' && mode !== 'literal') throw new Error('定义搜索使用引擎的符号模式,不能同时指定其他匹配模式') + if (content && ['fuzzy', 'native'].includes(mode)) throw new Error('文件内容支持文本包含和正则表达式,请切换匹配模式') + if (content && !filter.contentSupported) throw new Error('该分类不支持纯文本内容搜索') + + if ((mode === 'native') !== (field === 'engine')) throw new Error('模糊查找使用名称及父目录范围') + if (mode === 'native' && caseSensitive) throw new Error('模糊查找不支持区分大小写,请切换精确或字符模糊模式') + if (mode === 'native' && query.trim() && (!/^[\p{L}\p{M}\p{N}_ .\/\-]+$/u.test(query) || query.trim().split(/[\s/]+/).length > 8)) throw new Error('模糊查找请输入最多 8 个普通词;特殊符号请使用精确或正则模式') + + // 文本模式保留词间空格;模糊模式按字符顺序匹配,空格作为字符间隔。 + const text = query.trim() + let expression + if (mode === 'regex') expression = query + else if (mode === 'literal') expression = escapeRegex(text) + else expression = '(?s:' + Array.from(text).filter(character => !/\s/u.test(character)).map(escapeRegex).join('.*') + ')' + const pattern = `(?${caseSensitive ? '-i' : 'i'}:${expression})` + + // 精确/正则/字符模糊严格限制字段;原生模式另行交给引擎的名称与父目录评分器。 + const payload = content + ? { op: 'grep', q: '', pattern: query, mode: field === 'symbol' ? 'symbol' : mode, case: caseSensitive ? 'sensitive' : 'insensitive', context: 1, per_file: 3, limit: pageSize, cursor: offset, kind: 'file' } + : { q: '', [field === 'name' ? 're' : 'path']: pattern, limit: pageSize, offset } + if (options.file) { + if (!content || !require('node:path').isAbsolute(options.file)) throw new Error('单文件正文范围无效') + if (offset !== 0) throw new Error('单文件正文不支持文件分页') + if (options.git || options.extensions || options.modified || options.size || options.exclude || category !== 'all') throw new Error('单文件正文不使用分类及目录筛选,请先清空这些筛选') + payload.file = options.file; delete payload.cursor + } + if (filter.kind) payload.kind = filter.kind + if (mode === 'native') { delete payload.re; delete payload.path; payload.q = query.trim() } + if (!applyFilters(payload, options, filter, content)) payload.noResults = true + if (content && options.git) { + // Git 正文走服务的过滤分页分支,next 是结果偏移,不能当成内容候选游标。 + if (offset >= 2000) throw new Error('Git 正文检索达到 2,000 项窗口,请缩小条件') + delete payload.cursor; payload.offset = offset + } + return payload +} + +/** + * 创建搜索适配器;只保留当前页,直接采用服务返回的下一页位置,不缓存整个结果集。 + * @param {Function} request 调用官方服务的请求函数 + * @returns {Function} 返回命中、下一页游标和窗口限制状态的异步搜索函数 + */ +function createSearch(request) { + return async function search(options = {}, { signal, queueMs = 0, isCurrent = () => true } = {}) { + const started = performance.now() + // 先做纯参数校验,再异步访问目录;异步结束后仍校验取消状态。 + buildRequest(options) + const resolved = await resolveDirectories(options, { signal }) + const payload = buildRequest(resolved) + checkAbort(signal) + if (!isCurrent()) throw aborted() + const validated = performance.now() + const content = ['content', 'symbol'].includes(options.field) + const offset = options.offset || 0 + if (payload.noResults || (!options.query.trim() && content)) return { hits: [], took_us: 0, offset, next: null, windowLimited: false, content } + if (!options.query.trim() && !options.browse) { + if (options.git) throw new Error('最近文件不支持 Git 状态,请输入关键词或选择浏览筛选结果') + payload.op = 'recent'; delete payload.offset; delete payload.re; delete payload.path; delete payload.boost + } + let response + try { response = await request(payload, { signal }) } + catch (error) { + if (options.mode === 'regex' && /regex parse error|regex syntax|regex.*error|unclosed|repetition operator/i.test(error.message)) { + throw new Error('正则表达式无效:' + error.message) + } + throw error + } + checkAbort(signal) + const timings = { queueMs, validationMs: validated - started, transportMs: performance.now() - validated } + if (content) { + const result = normalizeContent(response, offset) + if (options.git && result.next >= 2000) { result.next = null; result.windowLimited = true; result.windowMessage = 'Git 正文检索达到 2,000 项窗口,请缩小条件' } + return { ...result, timings } + } + if (!Array.isArray(response.hits)) throw new Error('FSearch 返回的结果格式无效') + const next = response.next + if (next !== undefined && (!Number.isSafeInteger(next) || next <= offset)) { + throw new Error('引擎未能继续当前检索,请缩小条件后重试') + } + const windowLimited = (next !== undefined && next >= SEARCH_WINDOW) || offset + response.hits.length >= SEARCH_WINDOW + return { + timings, + hits: response.hits, + took_us: response.took_us, + offset, + recent: payload.op === 'recent', + next: next === undefined || windowLimited ? null : next, + windowLimited + } + } +} + +module.exports = { buildRequest, createSearch, escapeRegex, PAGE_SIZES, SEARCH_WINDOW } diff --git a/plugins/local-fsearch/styles.css b/plugins/local-fsearch/styles.css new file mode 100644 index 000000000..2403f366c --- /dev/null +++ b/plugins/local-fsearch/styles.css @@ -0,0 +1,30 @@ +:root{font:13px -apple-system,BlinkMacSystemFont,"Helvetica Neue",sans-serif;color-scheme:light;--bg:#fff;--sidebar:#f5f5f7;--text:#28282d;--muted:#686872;--line:#e5e5eb;--field:#fff;--hover:#f5f5f8;--selected:#f1edf8;--accent:#7356aa;--active-text:#644397;--icon:#858590;--folder-icon:#7893a5;--notice:#faf3e4;--notice-text:#795c28;--shadow:0 6px 28px #0002;--toast:#303036;--toast-text:#fff;--mark:#f0dfa2} +:root[data-theme="dark"]{color-scheme:dark;--bg:#26262a;--sidebar:#222226;--text:#e7e7eb;--muted:#aaaab4;--line:#3a3a42;--field:#303036;--hover:#2d2d33;--selected:#393342;--accent:#baa1df;--active-text:#d8c6f0;--icon:#93939f;--folder-icon:#9ab2c4;--notice:#3b3425;--notice-text:#e0c68d;--shadow:0 6px 28px #0006;--toast:#e8e8ec;--toast-text:#26262a;--mark:#66582d} +*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);overflow:hidden}button,input,select,textarea{font:inherit;color:inherit}button{cursor:pointer;border:1px solid var(--line);border-radius:5px;background:var(--field);padding:5px 8px;white-space:nowrap}button:hover{background:var(--hover)}button:disabled{opacity:.5;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible,.result:focus-visible,summary:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}input,select,textarea{background:var(--field);border:1px solid var(--line);border-radius:5px;padding:5px 7px;min-width:0}select{max-width:100%}svg{vertical-align:middle}[hidden]{display:none!important} +.workspace{height:100vh;display:grid;grid-template-columns:134px minmax(0,1fr);grid-template-rows:minmax(0,1fr)}.sidebar{background:var(--sidebar);border-right:1px solid var(--line);display:flex;flex-direction:column;padding:16px 8px 0;min-height:0}.sidebar-label{font-size:12px;color:var(--muted);font-weight:500;padding:0 9px 9px}#categories{display:flex;flex-direction:column;gap:2px;overflow:auto}.category{display:flex;align-items:center;gap:9px;width:100%;text-align:left;padding:8px 9px;border:0;background:none;border-radius:5px}.category svg{width:16px;height:16px;color:var(--icon);flex-shrink:0}.category.active{background:var(--selected);color:var(--active-text);font-weight:600}.category.active svg{color:var(--accent)}.category:hover:not(.active){background:var(--line)}.sidebar-bottom{display:flex;align-items:center;gap:5px;margin-top:auto;padding:11px 2px;font-size:11px;color:var(--muted);white-space:nowrap}.status-dot{width:5px;height:5px;border-radius:50%;background:#999;flex-shrink:0}.status-dot.ready{background:#75a082}.icon-button{display:inline-flex;align-items:center;justify-content:center;border:0;background:none;color:var(--muted);padding:4px}.icon-button svg{width:15px;height:15px}.sidebar-bottom .icon-button{margin-left:auto;width:22px;height:24px}main{min-width:0;min-height:0;display:flex;flex-direction:column;height:100%;position:relative}.toolbar{padding:13px 16px 10px;border-bottom:1px solid var(--line);flex-shrink:0}.heading{display:flex;align-items:center;gap:10px;margin-bottom:10px}h1{font-size:15px;font-weight:600;margin:0}#result-summary{font-size:11px;color:var(--muted)}.heading-action{margin-left:auto;font-size:11px;padding:3px 6px;color:var(--muted)}.match-controls{display:flex;align-items:center;gap:7px;margin-bottom:9px;flex-wrap:wrap;font-size:12px}.match-controls label,.scope-controls label{color:var(--muted)}.match-controls select{padding:4px 6px;max-width:220px}.case-toggle{font-size:12px;font-weight:600;padding:4px 7px}.case-toggle.active{color:var(--active-text);border-color:var(--accent);background:var(--selected)}#mode-hint{font-size:11px;color:var(--muted)}.scope-controls{display:flex;align-items:center;gap:7px;font-size:12px}.scope-controls input{flex:1;width:0}.scope-controls select{font-size:11px;max-width:88px}.scope-controls button{font-size:12px;padding:5px 8px}.scope-controls .quiet{border:0;color:var(--muted);background:none;padding:5px}.filter-strip{display:flex;align-items:flex-start;gap:7px;margin-top:9px}.filter-strip>button{font-size:11px;padding:4px 7px;color:var(--muted);flex-shrink:0}#filter-chips{display:flex;flex-wrap:wrap;gap:4px;min-width:0;max-height:60px;overflow:auto}.filter-chip{padding:4px 6px;border-color:transparent;background:var(--selected);color:var(--active-text);font-size:11px;max-width:180px;overflow:hidden;text-overflow:ellipsis}.content-note{font-size:11px;line-height:1.5;color:var(--muted);margin:8px 0 0}.notice{font-size:12px;padding:8px 16px;background:var(--notice);color:var(--notice-text);border-bottom:1px solid var(--line);white-space:pre-wrap;max-height:100px;overflow:auto} +.results-scroll{position:relative;flex:1;min-height:0;overflow:auto}.results-scroll.stale{opacity:.62;cursor:progress}.results-scroll.stale #results{pointer-events:none}#results{list-style:none;margin:0;padding:2px 0 8px}.result{position:relative;padding:9px 14px;display:grid;grid-template-columns:22px minmax(0,1fr);gap:9px;border-left:2px solid transparent;border-bottom:1px solid var(--line);cursor:default}.result:hover{background:var(--hover)}.result.selected{background:var(--selected);border-left-color:var(--accent)}.file-icon{color:var(--icon);padding-top:1px}.file-icon svg{width:20px;height:23px}.result.folder .file-icon{color:var(--folder-icon)}.file-detail{min-width:0}.file-head{display:flex;align-items:center;gap:9px;min-width:0;line-height:20px}.file-name{font-size:13px;font-weight:500;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;flex:1}.file-type,.file-meta,.git-badge{font-size:11px;color:var(--muted);flex-shrink:0;white-space:nowrap}.git-badge{color:var(--accent)}.file-path{display:flex;width:100%;text-align:left;border:0;border-radius:2px;padding:0;margin-top:2px;color:var(--muted);font-size:12px;overflow:hidden;white-space:nowrap;background:none;cursor:copy;line-height:18px}.file-path:hover{background:none;color:var(--accent)}.path-parent{flex:0 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;direction:rtl;text-align:left}.path-leaf{max-width:65%;overflow:hidden;text-overflow:ellipsis;flex-shrink:0}.file-foot{position:absolute;top:7px;right:10px}.actions{display:flex;align-items:center;gap:3px;visibility:hidden;opacity:0;pointer-events:none;background:var(--bg);border-radius:4px}.result.selected .actions{background:var(--selected)}.result:hover .actions{background:var(--hover)}.result.selected .actions,.result:hover .actions,.result:focus-within .actions{visibility:visible;opacity:1;pointer-events:auto}.result.selected .file-head,.result:hover .file-head,.result:focus-within .file-head{padding-right:225px}.result.selected .file-meta,.result:hover .file-meta,.result:focus-within .file-meta,.result.selected .file-type,.result:hover .file-type,.result:focus-within .file-type{display:none}.actions button{padding:4px 5px;font-size:11px}.secondary-action{border:0;background:none;color:var(--muted)}.copy-action{display:inline-flex;align-items:center;gap:4px;background:var(--field)}.copy-action svg{width:12px;height:12px}.row-menu{position:relative;font-size:11px}.row-menu>summary{cursor:pointer;list-style:none;color:var(--muted);padding:4px}.row-menu>div{position:absolute;right:0;top:27px;min-width:130px;background:var(--field);border:1px solid var(--line);box-shadow:var(--shadow);padding:4px;border-radius:5px;z-index:3}.row-menu button{display:block;width:100%;text-align:left;border:0;font-size:12px}.content-summary{display:flex;gap:6px;align-items:baseline;margin-top:4px;line-height:19px;overflow:hidden;min-width:0}.content-summary code{font:12px/19px ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre;overflow:hidden;text-overflow:ellipsis;user-select:text;min-width:0}.jump-line{border:0;background:none;color:var(--accent);padding:0 3px;font:11px/19px ui-monospace,SFMono-Regular,Menlo,monospace;cursor:pointer}.jump-line:hover{text-decoration:underline}mark{background:var(--mark);color:inherit;border-radius:2px}.empty{position:absolute;top:46%;left:50%;transform:translate(-50%,-50%);text-align:center;width:calc(100% - 40px);color:var(--muted);pointer-events:none}.empty-icon svg{width:32px;height:32px;color:var(--icon)}.empty h2{font-size:14px;font-weight:500;color:var(--text);margin:14px 0 8px}.empty p{font-size:12px;line-height:1.7;margin:0;white-space:pre-wrap}.pagination{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-shrink:0;min-height:36px;padding:5px 13px;border-top:1px solid var(--line);font-size:11px;color:var(--muted)}.page-controls{display:flex;align-items:center;gap:10px}.page-controls button{font-size:11px;padding:4px 8px}#page-summary{min-width:48px;text-align:center;white-space:nowrap}.pagination select{padding:2px 4px;font-size:11px}.pagination label{white-space:nowrap}footer{height:32px;display:flex;align-items:center;justify-content:space-between;gap:10px;border-top:1px solid var(--line);padding:0 13px;color:var(--muted);font-size:11px;flex-shrink:0}#selection-summary{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.shortcuts{white-space:nowrap;font-size:10px}.shortcut-divider{padding:0 3px}.toast{position:fixed;bottom:44px;left:50%;transform:translateX(-50%);padding:9px 14px;border-radius:6px;background:var(--toast);color:var(--toast-text);font-size:12px;box-shadow:var(--shadow);max-width:90%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;z-index:12} +.panel-backdrop{position:fixed;inset:0;background:#0002;z-index:5}.filter-panel,.detail-panel{position:fixed;z-index:6;display:flex;flex-direction:column;background:var(--bg);border:1px solid var(--line);border-radius:7px;box-shadow:var(--shadow);min-height:0}.filter-panel{top:16px;right:16px;bottom:16px;width:min(430px,calc(100vw - 32px));font-size:12px}.detail-panel{inset:16px 20px 20px 150px}.detail-header{display:flex;gap:10px;align-items:center;padding:12px;border-bottom:1px solid var(--line);flex-shrink:0}.detail-header h2{margin:0;font-size:14px;font-weight:600;flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.detail-body,.filter-body{overflow:auto;flex:1;padding:13px;min-height:0}.detail-body p,.filter-body p{font-size:12px;color:var(--muted);line-height:1.7;white-space:pre-wrap;overflow-wrap:anywhere}.detail-body p:first-child{margin-top:0}.detail-body pre{font:12px/1.6 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere}.detail-actions{display:flex;flex-wrap:wrap;gap:7px;padding:10px 12px;border-top:1px solid var(--line);font-size:12px;flex-shrink:0}.detail-actions button{font-size:12px}.filter-grid{display:grid;grid-template-columns:1fr;gap:11px}.filter-grid label{display:flex;align-items:center;gap:9px;color:var(--muted)}.filter-grid input,.filter-grid select{flex:1;width:0}.filter-grid .wide{display:block}.wide textarea{display:block;width:100%;resize:vertical;max-height:130px;margin-top:6px}.filter-actions{display:flex;flex-wrap:wrap;align-items:center;gap:10px;margin:13px 0}.filter-actions label{display:flex;align-items:center;gap:4px}.filter-actions button{margin-left:auto;font-size:11px}.preset-controls{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:6px;border-top:1px solid var(--line);padding-top:13px}.preset-controls select{grid-column:1/-1}.preset-controls input{width:100%}.preset-controls button{font-size:12px}.editor-controls{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-top:14px;color:var(--muted);font-size:12px}.editor-controls span{font-size:11px;flex-basis:100%}.content-snippets{border-left:2px solid var(--line);padding:1px 0 1px 7px;overflow:hidden}.snippet-group+.snippet-group{margin-top:9px}.snippet-line{display:flex;gap:8px;line-height:21px;font-size:12px;min-width:0}.line-number{font:11px/21px ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted);min-width:24px;text-align:right;flex-shrink:0;user-select:none}.line-number.jump-line{color:var(--accent)}.snippet-line code{font:12px/21px ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre;overflow:auto;min-width:0;tab-size:2;user-select:text}.context-line code{color:var(--muted)}.snippet-note{font-size:11px;line-height:19px;color:var(--muted);padding-left:32px} +@media(min-width:1100px){body.preview-docked .workspace{margin-right:410px;width:calc(100% - 410px)}body.preview-docked .detail-panel{left:auto;right:0;top:0;bottom:0;width:410px;border-radius:0;border-width:0 0 0 1px;box-shadow:none}body.preview-docked footer .shortcuts{display:none}} +@media(max-width:720px){#mode-hint{display:none}.file-meta{display:none}.result{padding:9px 9px}.toolbar{padding:11px 12px}.shortcuts{display:none}.detail-panel{inset:14px}.file-head{gap:5px}.scope-controls{gap:5px}.match-controls{gap:5px}.file-name{font-size:13px}.filter-chip{max-width:140px}} +@media(max-width:550px){.workspace{grid-template-columns:108px minmax(0,1fr)}.sidebar{padding-left:5px;padding-right:5px}.category{font-size:12px;padding:8px 6px;gap:6px}.sidebar-bottom{font-size:10px}.heading{flex-wrap:wrap;gap:6px}.heading-action{font-size:10px}.result.selected .file-head,.result:hover .file-head,.result:focus-within .file-head{padding-right:0}.file-foot{position:static;height:0;overflow:hidden}.result.selected .file-foot,.result:focus-within .file-foot{height:25px;overflow:visible}.actions{justify-content:flex-end}.scope-controls select{max-width:65px}.page-controls{gap:4px}.pagination{padding:5px 8px}.match-controls select{max-width:180px}} + +.row-menu.menu-up>div{top:auto;bottom:27px} + +.result.image-result{grid-template-columns:48px minmax(0,1fr)} +.image-thumb{width:48px;height:48px;padding:0;display:grid;place-items:center;overflow:hidden;color:var(--icon);cursor:zoom-in} +.image-thumb svg{width:22px;height:22px} +.image-thumb img{display:block;width:100%;height:100%;object-fit:contain} +.detail-panel[data-kind="image"]{inset:5px} +.image-window .detail-panel[data-kind="image"]{inset:0;border:0;border-radius:0} +.detail-panel[data-kind="image"] .detail-header,.detail-panel[data-kind="image"] .detail-actions{padding:5px 8px} +.detail-panel[data-kind="image"] .detail-body{display:flex;flex-direction:column;align-items:center;gap:4px;padding:5px 7px;text-align:center} +.detail-panel[data-kind="image"] .detail-body p{margin:0} +.image-zoom-toolbar{display:flex;flex-wrap:wrap;justify-content:center;align-items:center;gap:6px;flex:none} +.image-zoom-toolbar output{min-width:5ch;font-variant-numeric:tabular-nums} +.image-zoom-toolbar button[aria-pressed="true"]{color:var(--accent);border-color:var(--accent)} +.image-frame{width:100%;flex:1;min-height:0;container-type:size;display:grid;place-items:center} +.image-stage{position:relative;width:min(100cqw,calc(100cqh * 16 / 9));aspect-ratio:16 / 9;min-width:0;min-height:0;overflow:clip;touch-action:none;overscroll-behavior:contain;background:var(--field);border:1px solid var(--line);border-radius:5px;cursor:grab} +.image-preview{display:block;position:absolute;top:0;left:0;max-width:none;max-height:none;user-select:none} +.image-stage.dragging{cursor:grabbing} + +.host-preferences{margin:17px 0 0;padding:11px;border:1px solid var(--line);border-radius:5px;min-width:0}.host-preferences legend{color:var(--muted);padding:0 5px}.host-preferences>label{display:flex;align-items:center;gap:5px;margin:7px 0;font-size:12px}.host-preferences p{font-size:11px;line-height:1.6}.host-preferences .workspace-pref{display:block}.workspace-pref input{display:block;width:100%;margin-top:5px}.host-preferences>button{font-size:11px}.preset-command{display:flex;align-items:flex-start;gap:5px;margin-top:9px;font-size:11px;line-height:1.6;color:var(--muted)}.source-file{padding:8px 15px;display:flex;align-items:center;gap:8px;border-bottom:1px solid var(--line);font-size:12px}.source-file>span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1}.source-file>div{display:flex;gap:5px}.source-file button{font-size:11px;padding:4px 6px}.heading #new-search{margin-left:auto}.heading #diagnostics{margin-left:0}@media(max-width:720px){.source-file{flex-wrap:wrap}.source-file>span{flex-basis:100%}.heading{flex-wrap:wrap}} diff --git a/plugins/local-fsearch/vendor/es/LICENSE b/plugins/local-fsearch/vendor/es/LICENSE new file mode 100644 index 000000000..e156308b9 --- /dev/null +++ b/plugins/local-fsearch/vendor/es/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 voidtools + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/local-fsearch/vendor/es/README.md b/plugins/local-fsearch/vendor/es/README.md new file mode 100644 index 000000000..51bb1660c --- /dev/null +++ b/plugins/local-fsearch/vendor/es/README.md @@ -0,0 +1,3 @@ +# Everything Command-line Interface + +Official ES 1.1.0.38 binaries from the [voidtools downloads page](https://www.voidtools.com/downloads/). The `ia32` directory contains the official x86 build. All three are distributed under the [MIT license](LICENSE); upstream source is available in the [voidtools/es repository](https://github.com/voidtools/es). diff --git a/plugins/local-fsearch/vendor/es/SHA256SUMS b/plugins/local-fsearch/vendor/es/SHA256SUMS new file mode 100644 index 000000000..2f2335d3a --- /dev/null +++ b/plugins/local-fsearch/vendor/es/SHA256SUMS @@ -0,0 +1,3 @@ +f7378761cf6e01f51c4123a485e628d70e3fea147d341f473ce2820844e5cee5 x64/es.exe +7fc406610559f686a95a9bfc4472acffdebcc143b485ae9371b5ef4590e7ec31 arm64/es.exe +d3fef37ce9f25a44bb2898848b8eca0f44b0b22766b644c6e4e436b7f9d4b4fe ia32/es.exe diff --git a/plugins/local-fsearch/vendor/es/arm64/es.exe b/plugins/local-fsearch/vendor/es/arm64/es.exe new file mode 100644 index 000000000..cf58ff044 Binary files /dev/null and b/plugins/local-fsearch/vendor/es/arm64/es.exe differ diff --git a/plugins/local-fsearch/vendor/es/ia32/es.exe b/plugins/local-fsearch/vendor/es/ia32/es.exe new file mode 100644 index 000000000..afe80f74e Binary files /dev/null and b/plugins/local-fsearch/vendor/es/ia32/es.exe differ diff --git a/plugins/local-fsearch/vendor/es/x64/es.exe b/plugins/local-fsearch/vendor/es/x64/es.exe new file mode 100644 index 000000000..a0e79c39d Binary files /dev/null and b/plugins/local-fsearch/vendor/es/x64/es.exe differ
正在加载图片…
搜索 TXT、Markdown、配置及代码等纯文本;遵循引擎的文件大小和忽略规则。列表展示首处摘要,展开可查看更多命中。
在上方输入文件名,也可以先选择左侧分类。
推送默认关闭,仅返回最多 5 项。还需在 ZTools 插件设置中开启「搜索栏推送」。