@li-canghai/dsh-paper 0.0.0-stage → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +150 -2
- package/cordis.patch.yml +4 -0
- package/lib/annotate-tool.js +334 -0
- package/lib/arxiv-id.js +74 -0
- package/lib/asset-routes.js +210 -0
- package/lib/bibliography-formats.js +126 -0
- package/lib/bibliography-import.js +105 -0
- package/lib/bibliography-service.js +43 -0
- package/lib/bibliography.js +42 -0
- package/lib/block-authors.js +292 -0
- package/lib/block-cache.js +39 -0
- package/lib/blocks-markdown.js +157 -0
- package/lib/blocks-reconcile.js +218 -0
- package/lib/blocks.js +1344 -0
- package/lib/citation-metadata.js +260 -0
- package/lib/citation-styles.js +120 -0
- package/lib/client-parts/01-pure-helpers.js +2762 -0
- package/lib/client-parts/02-author-year.js +95 -0
- package/lib/client.js +10381 -0
- package/lib/code-source.js +68 -0
- package/lib/concurrency-gate.js +91 -0
- package/lib/context.js +233 -0
- package/lib/csl/SOURCES.md +10 -0
- package/lib/csl/gb-t-7714.csl +441 -0
- package/lib/csl/ieee.csl +520 -0
- package/lib/csl/locales-zh-CN.xml +438 -0
- package/lib/csl/nature.csl +190 -0
- package/lib/discussion.js +400 -0
- package/lib/documents.js +67 -0
- package/lib/export.js +848 -0
- package/lib/file-lock.js +177 -0
- package/lib/gloss.js +181 -0
- package/lib/glossary.js +279 -0
- package/lib/index.js +3862 -0
- package/lib/inline-html.js +53 -0
- package/lib/install-dependency.js +120 -0
- package/lib/item-ops.js +83 -0
- package/lib/job-facade.js +58 -0
- package/lib/json-store.js +54 -0
- package/lib/library-model.js +132 -0
- package/lib/library-service.js +180 -0
- package/lib/library-tool.js +982 -0
- package/lib/library.js +814 -0
- package/lib/markdown-assets.js +138 -0
- package/lib/markdown-literals.js +93 -0
- package/lib/metadata-enrichment.js +516 -0
- package/lib/metadata-fetch.js +146 -0
- package/lib/metadata-node.js +158 -0
- package/lib/metadata-proxy.ps1 +35 -0
- package/lib/mineru-config.js +95 -0
- package/lib/mineru-sdk-helper.py +123 -0
- package/lib/mineru-sdk.js +182 -0
- package/lib/mineru.js +268 -0
- package/lib/mirror-export.js +240 -0
- package/lib/outline.js +296 -0
- package/lib/page-image-helper.py +308 -0
- package/lib/page-image.js +454 -0
- package/lib/paper-metadata.js +242 -0
- package/lib/parse-export.js +631 -0
- package/lib/pdf-analysis-tool.js +750 -0
- package/lib/pdf-metadata-helper.py +75 -0
- package/lib/pdf-metadata.js +141 -0
- package/lib/pdf-page.js +261 -0
- package/lib/pdf-scan.js +134 -0
- package/lib/pdf-text.js +68 -0
- package/lib/picker.js +305 -0
- package/lib/portable.js +379 -0
- package/lib/purge.js +170 -0
- package/lib/read-tool.js +660 -0
- package/lib/reader-store.js +497 -0
- package/lib/reading-order.js +207 -0
- package/lib/rename-document.js +480 -0
- package/lib/rename.js +372 -0
- package/lib/renderer-status.js +161 -0
- package/lib/resolver.js +1152 -0
- package/lib/result-archive.js +157 -0
- package/lib/revisions.js +330 -0
- package/lib/search-database.js +62 -0
- package/lib/search-index.js +601 -0
- package/lib/search-scan.js +185 -0
- package/lib/search-source.js +23 -0
- package/lib/search-terms.js +539 -0
- package/lib/section-audit.js +209 -0
- package/lib/selection-message.js +332 -0
- package/lib/serial-tail.js +21 -0
- package/lib/slicing.js +425 -0
- package/lib/source-resolver.js +581 -0
- package/lib/stem-repair.js +189 -0
- package/lib/storage.js +562 -0
- package/lib/store-paths.js +253 -0
- package/lib/table-gfm.js +236 -0
- package/lib/tasks.js +270 -0
- package/lib/tex-align.js +509 -0
- package/lib/tex-blocks.js +653 -0
- package/lib/tex-fetch.js +455 -0
- package/lib/tex-figures.js +140 -0
- package/lib/tex-inline.js +166 -0
- package/lib/tex-merge.js +279 -0
- package/lib/tex-pipeline.js +242 -0
- package/lib/tex-prepare.js +746 -0
- package/lib/tex-tables.js +210 -0
- package/lib/text-similarity.js +85 -0
- package/lib/tool-contract.js +86 -0
- package/lib/tool-host.js +1058 -0
- package/lib/tool-identity.js +214 -0
- package/lib/translatable-text.js +48 -0
- package/lib/translate-prompts.js +709 -0
- package/lib/translate-queue.js +418 -0
- package/lib/translate-task.js +158 -0
- package/lib/translate.js +909 -0
- package/lib/update-check.js +438 -0
- package/lib/update-contracts.js +75 -0
- package/lib/usage.js +282 -0
- package/package.json +55 -4
package/lib/pdf-text.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PDF 文本层:调 pdftotext 拿逐行文本与坐标。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独成一个模块:它是整条源码管线里**唯一需要外部命令**的一步。把它隔开之后,
|
|
5
|
+
* 对齐、合并、判定树全部保持纯函数,测试不需要本机装 poppler。
|
|
6
|
+
*
|
|
7
|
+
* 失败一律返回空数组(不抛错):没有文本层时上层判 align 降级、整篇退回 MinerU,
|
|
8
|
+
* 那本来就是正确行为;抛错会让一次「拿不到坐标」看起来像「解析失败」。
|
|
9
|
+
*/
|
|
10
|
+
import { execFile } from 'node:child_process'
|
|
11
|
+
import { promisify } from 'node:util'
|
|
12
|
+
|
|
13
|
+
import { parseBboxLayout } from './tex-align.js'
|
|
14
|
+
|
|
15
|
+
const execFileAsync = promisify(execFile)
|
|
16
|
+
|
|
17
|
+
/** 默认执行器:pdftotext 把 XML 打到 stdout。 */
|
|
18
|
+
async function defaultRun(command, args) {
|
|
19
|
+
try {
|
|
20
|
+
const { stdout } = await execFileAsync(command, args, { maxBuffer: 64 * 1024 * 1024, windowsHide: true })
|
|
21
|
+
return { code: 0, stdout: String(stdout ?? ''), stderr: '' }
|
|
22
|
+
} catch (error) {
|
|
23
|
+
return { code: Number.isInteger(error?.code) ? error.code : 1, stdout: String(error?.stdout ?? ''), stderr: String(error?.stderr ?? '') }
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 取一篇 PDF 的文本行。
|
|
29
|
+
*
|
|
30
|
+
* @param {string} pdfPath
|
|
31
|
+
* @param {{run?: (command: string, args: string[]) => Promise<{code?: number, stdout?: string}>}} [options]
|
|
32
|
+
* @returns {Promise<Array<{page: number, text: string, bbox: number[], height: number}>>}
|
|
33
|
+
*/
|
|
34
|
+
export async function extractPdfLines(pdfPath, { run = defaultRun } = {}) {
|
|
35
|
+
if (typeof pdfPath !== 'string' || pdfPath === '') return []
|
|
36
|
+
if (typeof run !== 'function') return []
|
|
37
|
+
try {
|
|
38
|
+
const result = await run('pdftotext', ['-bbox-layout', pdfPath, '-'])
|
|
39
|
+
if (result?.code !== 0 && result?.code !== undefined) return []
|
|
40
|
+
return parseBboxLayout(String(result?.stdout ?? ''))
|
|
41
|
+
} catch {
|
|
42
|
+
return []
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 取**某一页**的文本行(`-f n -l n`)。
|
|
48
|
+
*
|
|
49
|
+
* 存在的理由是先认来源、再取全文:出版版 PDF 首页没有 arXiv 水印,这一篇在首页就是
|
|
50
|
+
* 决定性证据 —— 不必为它跑一遍全文档的 bbox 抽取。失败同样返回空数组。
|
|
51
|
+
*
|
|
52
|
+
* @param {string} pdfPath
|
|
53
|
+
* @param {number} page 1 起;非正整数时取第一页
|
|
54
|
+
* @param {{run?: (command: string, args: string[]) => Promise<{code?: number, stdout?: string}>}} [options]
|
|
55
|
+
* @returns {Promise<Array<{page: number, text: string, bbox: number[], height: number}>>}
|
|
56
|
+
*/
|
|
57
|
+
export async function extractPageLines(pdfPath, page = 1, { run = defaultRun } = {}) {
|
|
58
|
+
if (typeof pdfPath !== 'string' || pdfPath === '') return []
|
|
59
|
+
if (typeof run !== 'function') return []
|
|
60
|
+
const target = Number.isInteger(page) && page >= 1 ? page : 1
|
|
61
|
+
try {
|
|
62
|
+
const result = await run('pdftotext', ['-f', String(target), '-l', String(target), '-bbox-layout', pdfPath, '-'])
|
|
63
|
+
if (result?.code !== 0 && result?.code !== undefined) return []
|
|
64
|
+
return parseBboxLayout(String(result?.stdout ?? ''))
|
|
65
|
+
} catch {
|
|
66
|
+
return []
|
|
67
|
+
}
|
|
68
|
+
}
|
package/lib/picker.js
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { createHash } from 'node:crypto'
|
|
3
|
+
import { platform } from 'node:os'
|
|
4
|
+
import { childEnvironment } from './mineru-sdk.js'
|
|
5
|
+
|
|
6
|
+
// 系统选择窗口经 Windows PowerShell 的 Windows Forms / shell 对话框实现:
|
|
7
|
+
// dsh 宿主是普通 node 进程(无原生对话框 API),powershell 随 Windows 自带,
|
|
8
|
+
// 对话框是宿主同一交互会话里的顶层窗口,挂在一个真 Show 出来的透明置顶锚点上,
|
|
9
|
+
// 否则会被 DSH 窗口压到后面(用户看到的是按钮一直转圈、找不到弹窗)。
|
|
10
|
+
// spawn 的 timeout 选项(Node ≥15.13 文档化)超时后 killSignal 终止子进程,
|
|
11
|
+
// 'close' 事件带 signal 触发,picker 据此拒绝。
|
|
12
|
+
export const PICKER_TIMEOUT_MS = 10 * 60 * 1000
|
|
13
|
+
|
|
14
|
+
// 互操作源码编译一次缓存成 DLL(按源码哈希命名)——同机实测冷跑即时编译 886ms、热跑只加载
|
|
15
|
+
// 程序集 400ms(都含 powershell 起停),即每次点击省 ~490ms,是点击到弹出延迟的大头。
|
|
16
|
+
// 哈希进了文件名,改源码自动重建。
|
|
17
|
+
//
|
|
18
|
+
// 里面两块:DPI 声明(高缩放屏不发虚)与文件夹选择。文件夹选择必须走 IFileOpenDialog:
|
|
19
|
+
// 本机 Windows PowerShell 5.1 载的是 .NET Framework 4.0 的 System.Windows.Forms,
|
|
20
|
+
// FolderBrowserDialog 没有 AutoUpgradeEnabled(反射实测属性只有 Description/RootFolder/
|
|
21
|
+
// SelectedPath/ShowNewFolderButton),弹出来是经典"浏览文件夹"树视图,且无视 SelectedPath。
|
|
22
|
+
const INTEROP_CSHARP = `using System;
|
|
23
|
+
using System.Runtime.InteropServices;
|
|
24
|
+
|
|
25
|
+
public static class DshPaperDpi {
|
|
26
|
+
[DllImport("user32.dll")] public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
|
|
27
|
+
[DllImport("shcore.dll")] public static extern int SetProcessDpiAwareness(int awareness);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
public static class DshPaperFolder {
|
|
31
|
+
const uint FOS_PICKFOLDERS = 0x20;
|
|
32
|
+
const uint FOS_FORCEFILESYSTEM = 0x40;
|
|
33
|
+
const uint FOS_DONTADDTORECENT = 0x2000000;
|
|
34
|
+
const uint SIGDN_FILESYSPATH = 0x80058000;
|
|
35
|
+
|
|
36
|
+
[ComImport, Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")] class FileOpenDialogRCW { }
|
|
37
|
+
|
|
38
|
+
[ComImport, Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
|
39
|
+
interface IShellItem {
|
|
40
|
+
void BindToHandler(IntPtr pbc, ref Guid bhid, ref Guid riid, out IntPtr ppvOut);
|
|
41
|
+
void GetParent(out IShellItem ppsi);
|
|
42
|
+
void GetDisplayName(uint sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
|
|
43
|
+
void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);
|
|
44
|
+
void Compare(IShellItem psi, uint hint, out int piOrder);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// IFileOpenDialog 继承 IFileDialog 继承 IModalWindow,C# 要把整张 vtable 摊平声明,顺序错一位就调错函数。
|
|
48
|
+
[ComImport, Guid("d57c7288-d4ad-4768-be02-9d969532d960"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
|
49
|
+
interface IFileOpenDialog {
|
|
50
|
+
[PreserveSig] int Show(IntPtr hwndOwner);
|
|
51
|
+
void SetFileTypes(uint cFileTypes, IntPtr rgFilterSpec);
|
|
52
|
+
void SetFileTypeIndex(uint iFileType);
|
|
53
|
+
void GetFileTypeIndex(out uint piFileType);
|
|
54
|
+
void Advise(IntPtr pfde, out uint pdwCookie);
|
|
55
|
+
void Unadvise(uint dwCookie);
|
|
56
|
+
void SetOptions(uint fos);
|
|
57
|
+
void GetOptions(out uint pfos);
|
|
58
|
+
void SetDefaultFolder(IShellItem psi);
|
|
59
|
+
void SetFolder(IShellItem psi);
|
|
60
|
+
void GetFolder(out IShellItem ppsi);
|
|
61
|
+
void GetCurrentSelection(out IShellItem ppsi);
|
|
62
|
+
void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string pszName);
|
|
63
|
+
void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
|
|
64
|
+
void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
|
|
65
|
+
void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string pszText);
|
|
66
|
+
void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
|
|
67
|
+
void GetResult(out IShellItem ppsi);
|
|
68
|
+
void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
|
|
69
|
+
void Close(int hr);
|
|
70
|
+
void SetClientGuid(ref Guid guid);
|
|
71
|
+
void ClearClientData();
|
|
72
|
+
void SetFilter(IntPtr pStream);
|
|
73
|
+
void GetResults(out IntPtr ppenum);
|
|
74
|
+
void GetSelectedItems(out IntPtr ppsai);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
[DllImport("shell32.dll")] static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, out IShellItem ppv);
|
|
78
|
+
|
|
79
|
+
static IFileOpenDialog Configure(string initial, string title) {
|
|
80
|
+
var dialog = (IFileOpenDialog)new FileOpenDialogRCW();
|
|
81
|
+
dialog.SetOptions(FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_DONTADDTORECENT);
|
|
82
|
+
if (!string.IsNullOrEmpty(title)) dialog.SetTitle(title);
|
|
83
|
+
if (!string.IsNullOrEmpty(initial)) {
|
|
84
|
+
Guid riid = typeof(IShellItem).GUID;
|
|
85
|
+
IShellItem item;
|
|
86
|
+
// 初始目录不存在时这里返回失败码,跳过即可——不能因为工作目录被删就开不出窗口。
|
|
87
|
+
if (SHCreateItemFromParsingName(initial, IntPtr.Zero, ref riid, out item) == 0 && item != null) dialog.SetFolder(item);
|
|
88
|
+
}
|
|
89
|
+
return dialog;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// 无 UI 自检:建实例、设选项与初始目录,但不弹窗口。测试与排障用它证明互操作在本机可用。
|
|
93
|
+
public static string Probe(string initial) {
|
|
94
|
+
try { Configure(initial, null); return ""; } catch (Exception error) { return error.Message; }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// 取消或关掉窗口返回 $null;确定返回文件系统绝对路径。
|
|
98
|
+
public static string Pick(IntPtr owner, string initial, string title) {
|
|
99
|
+
var dialog = Configure(initial, title);
|
|
100
|
+
if (dialog.Show(owner) != 0) return null;
|
|
101
|
+
IShellItem result;
|
|
102
|
+
dialog.GetResult(out result);
|
|
103
|
+
string path;
|
|
104
|
+
result.GetDisplayName(SIGDN_FILESYSPATH, out path);
|
|
105
|
+
return path;
|
|
106
|
+
}
|
|
107
|
+
}`
|
|
108
|
+
const DLL_NAME = `dsh-paper-dialog-${createHash('sha256').update(INTEROP_CSHARP).digest('hex').slice(0, 12)}.dll`
|
|
109
|
+
|
|
110
|
+
function pickerError(message) {
|
|
111
|
+
const error = new Error(message)
|
|
112
|
+
error.status = 501
|
|
113
|
+
return error
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// 两种对话框(选文件 / 选文件夹)共用的前置:关掉进度流、声明 DPI 感知、备好顶层 owner。
|
|
117
|
+
function dialogPrelude() {
|
|
118
|
+
return [
|
|
119
|
+
// 进度流会以 CLIXML 形式混入 stdout,先关掉;真实输出再用 BEGIN/END 标记包住。
|
|
120
|
+
"$ProgressPreference = 'SilentlyContinue'",
|
|
121
|
+
// stdout 被管道接管时,PowerShell 按控制台代码页编码输出;OEM 码不是 65001 的机器上,中文
|
|
122
|
+
// 目录名会被我们按 UTF-8 解成乱码、再被报成"无法打开文件夹"。显式钉成 UTF-8;宿主取值
|
|
123
|
+
// 失败(非交互、无控制台等)只影响这一行,不能让整次选择失败,所以吞掉并保留默认编码。
|
|
124
|
+
'try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch { }',
|
|
125
|
+
// 互操作源码只以 here-string 内嵌**一次**并放进 $cs,三处使用(补建 DLL、无缓存目录即时编译、
|
|
126
|
+
// 缓存损坏后回退)都引用它。整脚本文本经 UTF-16LE base64 作为 -EncodedCommand 传给
|
|
127
|
+
// powershell.exe,而 CreateProcess 的命令行上限是 32767 个字符——源码(约 3.6KB,含
|
|
128
|
+
// IFileOpenDialog 摊平的整张 vtable)一旦像之前那样重复三遍,编码后就是 36080 字符,
|
|
129
|
+
// spawn 直接 ENAMETOOLONG、两个选择窗口全塌。test/picker.test.js 钉住这条长度契约。
|
|
130
|
+
"$cs = @'",
|
|
131
|
+
INTEROP_CSHARP,
|
|
132
|
+
"'@",
|
|
133
|
+
// 进程默认无 DPI 感知(实测 powershell.exe awareness=0),高缩放屏上对话框会被
|
|
134
|
+
// 位图拉伸发虚;先声明 per-monitor v2,旧系统不支持 context API 时退回 shcore。
|
|
135
|
+
// 互操作编译一次缓存成 DLL(runtime/dsh-paper/cache,按源码哈希命名),
|
|
136
|
+
// 之后每次点击只加载程序集;DLL 缺失时即时编译补建,损坏时删除后回退即时编译。
|
|
137
|
+
'$cache = $env:DSH_PAPER_CACHE_DIR',
|
|
138
|
+
'if ($cache -and -not (Test-Path -LiteralPath $cache)) { New-Item -ItemType Directory -Path $cache -Force | Out-Null }',
|
|
139
|
+
`$dll = if ($cache) { Join-Path $cache '${DLL_NAME}' } else { $null }`,
|
|
140
|
+
'try {',
|
|
141
|
+
' if ($dll -and -not (Test-Path -LiteralPath $dll)) { Add-Type -TypeDefinition $cs -OutputAssembly $dll | Out-Null }',
|
|
142
|
+
' if ($dll) { Add-Type -Path $dll | Out-Null } else { Add-Type -TypeDefinition $cs | Out-Null }',
|
|
143
|
+
'} catch {',
|
|
144
|
+
' if ($dll) { Remove-Item -LiteralPath $dll -Force -ErrorAction SilentlyContinue | Out-Null }',
|
|
145
|
+
' Add-Type -TypeDefinition $cs | Out-Null',
|
|
146
|
+
'}',
|
|
147
|
+
'if (-not [DshPaperDpi]::SetProcessDpiAwarenessContext([IntPtr](-4))) { [DshPaperDpi]::SetProcessDpiAwareness(2) | Out-Null }',
|
|
148
|
+
'Add-Type -AssemblyName System.Windows.Forms | Out-Null',
|
|
149
|
+
'Add-Type -AssemblyName System.Drawing | Out-Null',
|
|
150
|
+
// owner 必须真的显示出来:TopMost 只对已创建的窗口生效,从没 Show 过的 Form 只是个还没建
|
|
151
|
+
// 句柄的对象,对话框因此会被 DSH 桌面窗口压到后面——实测表现为按钮"一直在选择中"却找不到窗口。
|
|
152
|
+
// 1×1、Opacity 0 的透明锚点放在主屏工作区中央:看不见,但对话框以它为中心且浮在最上层。
|
|
153
|
+
// 整段可失败:没有窗口站/无主屏(服务上下文、RDP 边界)时退回 $null owner,
|
|
154
|
+
// 对话框照样能开(只是可能不在最前),不能因为锚点建不出来就让选择功能报错。
|
|
155
|
+
'$owner = $null',
|
|
156
|
+
'try {',
|
|
157
|
+
' $anchor = New-Object System.Windows.Forms.Form',
|
|
158
|
+
' $anchor.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None',
|
|
159
|
+
' $anchor.TopMost = $true',
|
|
160
|
+
' $anchor.ShowInTaskbar = $false',
|
|
161
|
+
' $anchor.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual',
|
|
162
|
+
' $anchor.Size = New-Object System.Drawing.Size(1, 1)',
|
|
163
|
+
' $screen = [System.Windows.Forms.Screen]::PrimaryScreen',
|
|
164
|
+
' if ($screen) { $bounds = $screen.WorkingArea; $anchor.Location = New-Object System.Drawing.Point([int]($bounds.X + $bounds.Width / 2), [int]($bounds.Y + $bounds.Height / 2)) }',
|
|
165
|
+
' $anchor.Opacity = 0',
|
|
166
|
+
' $anchor.Show() | Out-Null',
|
|
167
|
+
' $anchor.Activate() | Out-Null',
|
|
168
|
+
' [System.Windows.Forms.Application]::DoEvents() | Out-Null',
|
|
169
|
+
' $owner = $anchor',
|
|
170
|
+
'} catch { $owner = $null }',
|
|
171
|
+
// 对话框的 owner 句柄:有锚点用它的 HWND,没有则传 Zero / 无参重载,两条路都能开窗口。
|
|
172
|
+
'$ownerHandle = if ($owner) { $owner.Handle } else { [IntPtr]::Zero }',
|
|
173
|
+
]
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// 对话框本体 + 输出标记。两个对话框的差别只在中间这段(怎么建、初始目录写进哪个属性、
|
|
177
|
+
// 确定后回吐什么),前置与 BEGIN/END 标记管道完全一致。
|
|
178
|
+
function dialogScript({ body, emit }) {
|
|
179
|
+
return [
|
|
180
|
+
...dialogPrelude(),
|
|
181
|
+
...body,
|
|
182
|
+
"'DSH-PAPER-BEGIN'",
|
|
183
|
+
...emit,
|
|
184
|
+
"'DSH-PAPER-END'",
|
|
185
|
+
].join('\n')
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const FILE_DIALOG = dialogScript({
|
|
189
|
+
body: [
|
|
190
|
+
'$dialog = New-Object System.Windows.Forms.OpenFileDialog',
|
|
191
|
+
"$dialog.Title = '选择 PDF(可按住 Ctrl 多选)'",
|
|
192
|
+
"$dialog.Filter = 'PDF 文件 (*.pdf)|*.pdf|全部文件 (*.*)|*.*'",
|
|
193
|
+
'$dialog.Multiselect = $true',
|
|
194
|
+
'$dialog.CheckFileExists = $true',
|
|
195
|
+
// 初始目录经环境变量读取,脚本完全静态,不拼接任何外部数据。
|
|
196
|
+
'$initial = $env:DSH_PAPER_INITIAL_DIR',
|
|
197
|
+
'if ($initial) { $dialog.InitialDirectory = $initial }',
|
|
198
|
+
// 有锚点窗口时带 owner 打开(浮在最前),锚点建不出来时退回无 owner 重载——两条路都比报错强。
|
|
199
|
+
'if ($owner) { $result = $dialog.ShowDialog($owner) } else { $result = $dialog.ShowDialog() }',
|
|
200
|
+
'if ($result -ne [System.Windows.Forms.DialogResult]::OK) { return }',
|
|
201
|
+
],
|
|
202
|
+
emit: ['$dialog.FileNames'],
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
const FOLDER_TITLE = '选择要扫描 PDF 的文件夹(含其下最多两层子目录)'
|
|
206
|
+
|
|
207
|
+
const FOLDER_DIALOG = dialogScript({
|
|
208
|
+
body: [
|
|
209
|
+
'$initial = $env:DSH_PAPER_INITIAL_DIR',
|
|
210
|
+
'$chosen = $null',
|
|
211
|
+
'$modern = $false',
|
|
212
|
+
// 首选资源管理器风格的 IFileOpenDialog:能定位到初始目录、能直接进任意盘。
|
|
213
|
+
'try { $chosen = [DshPaperFolder]::Pick($ownerHandle, $initial, \'' + FOLDER_TITLE + '\'); $modern = $true } catch { $chosen = $null }',
|
|
214
|
+
// 互操作在个别机器上不可用(COM 被策略拦、shell32 缺符号等)才退回经典树视图,
|
|
215
|
+
// 至少"能选"这条功能不塌;退回时 SelectedPath 可能被无视,属可接受的降级。
|
|
216
|
+
'if (-not $modern) {',
|
|
217
|
+
' $dialog = New-Object System.Windows.Forms.FolderBrowserDialog',
|
|
218
|
+
` $dialog.Description = '${FOLDER_TITLE}'`,
|
|
219
|
+
' $dialog.ShowNewFolderButton = $false',
|
|
220
|
+
' if ($initial -and (Test-Path -LiteralPath $initial -PathType Container)) { $dialog.SelectedPath = $initial }',
|
|
221
|
+
' if ($owner) { $result = $dialog.ShowDialog($owner) } else { $result = $dialog.ShowDialog() }',
|
|
222
|
+
' if ($result -ne [System.Windows.Forms.DialogResult]::OK) { return }',
|
|
223
|
+
' $chosen = $dialog.SelectedPath',
|
|
224
|
+
'}',
|
|
225
|
+
// 取消时 Pick 返回 null;选了 shell 节点(如"此电脑")拿不到文件系统路径,同样按取消处理。
|
|
226
|
+
'if (-not $chosen) { return }',
|
|
227
|
+
],
|
|
228
|
+
emit: ['$chosen'],
|
|
229
|
+
})
|
|
230
|
+
|
|
231
|
+
export function pickerScript() {
|
|
232
|
+
return FILE_DIALOG
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function folderPickerScript() {
|
|
236
|
+
return FOLDER_DIALOG
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export function selectedPaths(stdout) {
|
|
240
|
+
// CLIXML 噪声可能不带换行地与标记同行拼接,按子串定位标记而不是整行匹配。
|
|
241
|
+
const begin = stdout.lastIndexOf('DSH-PAPER-BEGIN')
|
|
242
|
+
const end = stdout.lastIndexOf('DSH-PAPER-END')
|
|
243
|
+
if (begin === -1 || end === -1 || end < begin) return []
|
|
244
|
+
return stdout.slice(begin + 'DSH-PAPER-BEGIN'.length, end).split(/\r?\n/).map(line => line.trim()).filter(Boolean)
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function runDialog(script, { initialDir = '', cacheDir = '', spawnImpl = spawn }, { label, manualHint }) {
|
|
248
|
+
if (platform() !== 'win32') throw pickerError(`系统${label}窗口仅支持 Windows,${manualHint}`)
|
|
249
|
+
// -EncodedCommand 传 UTF-16LE base64,脚本完全静态;初始目录与 DLL 缓存目录经
|
|
250
|
+
// 环境变量字节精确传入,不做任何脚本拼接(PS 单引号转义虽可行,但拼接构造对模板改动脆弱)。
|
|
251
|
+
const encoded = Buffer.from(script, 'utf16le').toString('base64')
|
|
252
|
+
// The dialog process gets the same allowlist as the MinerU SDK bridge: `process.env`
|
|
253
|
+
// holds the MinerU token and whatever else the host was started with, and a spawned
|
|
254
|
+
// process can surface its environment through output, `env`, or a spill file. The two
|
|
255
|
+
// directories this script reads are passed on top of the allowlist, never inherited.
|
|
256
|
+
const env = childEnvironment({
|
|
257
|
+
...(initialDir ? { DSH_PAPER_INITIAL_DIR: initialDir } : {}),
|
|
258
|
+
...(cacheDir ? { DSH_PAPER_CACHE_DIR: cacheDir } : {}),
|
|
259
|
+
}, process.env)
|
|
260
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
261
|
+
const child = spawnImpl('powershell.exe', ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', encoded], {
|
|
262
|
+
windowsHide: true,
|
|
263
|
+
timeout: PICKER_TIMEOUT_MS,
|
|
264
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
265
|
+
env,
|
|
266
|
+
})
|
|
267
|
+
let settled = false
|
|
268
|
+
// 🔴 **先收字节、最后一次性解码**:`stdout += chunk` 会对每个 chunk 各解一次 UTF-8,
|
|
269
|
+
// 一个中文字符刚好跨在两块之间时就被解成两个 U+FFFD —— 路径跟着坏掉,症状是
|
|
270
|
+
// 「文件明明在,却说找不到」。分块边界取决于管道缓冲与路径长度,换台机器/换批文件
|
|
271
|
+
// 就可能复现,所以这里按 Buffer 累积、close 时统一 toString('utf8')。
|
|
272
|
+
const outChunks = []
|
|
273
|
+
const errChunks = []
|
|
274
|
+
const collect = into => chunk => { into.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8')) }
|
|
275
|
+
const fail = error => {
|
|
276
|
+
if (settled) return
|
|
277
|
+
settled = true
|
|
278
|
+
rejectPromise(error)
|
|
279
|
+
}
|
|
280
|
+
child.stdout?.on?.('data', collect(outChunks))
|
|
281
|
+
child.stderr?.on?.('data', collect(errChunks))
|
|
282
|
+
child.on('error', error => fail(new Error(`无法打开系统${label}窗口:${error.message}`)))
|
|
283
|
+
child.on('close', (code, signal) => {
|
|
284
|
+
if (settled) return
|
|
285
|
+
settled = true
|
|
286
|
+
const stdout = Buffer.concat(outChunks).toString('utf8')
|
|
287
|
+
const stderr = Buffer.concat(errChunks).toString('utf8')
|
|
288
|
+
if (signal) return rejectPromise(new Error(`${label}窗口超时未关闭,已终止`))
|
|
289
|
+
if (code !== 0) return rejectPromise(new Error(`无法打开系统${label}窗口:${stderr.trim().split(/\r?\n/).at(-1) || `退出码 ${code}`}`))
|
|
290
|
+
resolvePromise(selectedPaths(stdout))
|
|
291
|
+
})
|
|
292
|
+
})
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export async function pickPdfFiles(options = {}) {
|
|
296
|
+
return runDialog(FILE_DIALOG, options, { label: '文件选择', manualHint: '请手动粘贴 PDF 路径' })
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** 弹出文件夹选择窗口;返回所选文件夹的绝对路径,取消时返回空串。 */
|
|
300
|
+
export async function pickFolder(options = {}) {
|
|
301
|
+
// 非 Windows 上这条没有替代窗口:只能逐篇走「添加并解析」,所以提示写那条路,
|
|
302
|
+
// 而不是让用户去找一个不存在的「粘贴文件夹」入口。
|
|
303
|
+
const [dir] = await runDialog(FOLDER_DIALOG, options, { label: '文件夹选择', manualHint: '请改用「添加并解析」逐篇粘贴 PDF 路径' })
|
|
304
|
+
return dir ?? ''
|
|
305
|
+
}
|