-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfolder_picker_win.cpp
More file actions
550 lines (483 loc) · 18.8 KB
/
Copy pathfolder_picker_win.cpp
File metadata and controls
550 lines (483 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
#include "folder_picker.hpp"
#include "strings.hpp"
#ifdef _WIN32
#include "../utils/logger.hpp"
#include "../utils/encoding.hpp"
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# ifndef NOMINMAX
# define NOMINMAX
# endif
#include <windows.h>
#include <shobjidl.h>
#include <shlobj.h>
#include <atomic>
#include <chrono>
#include <cwchar>
#include <exception>
#include <string>
#include <thread>
namespace acecode::desktop {
namespace {
std::wstring folder_picker_title() {
return acecode::utf8_to_wide(
std::string(native_string(DesktopStringId::FolderPickerTitle)));
}
std::wstring session_export_save_title() {
return acecode::utf8_to_wide(
std::string(native_string(DesktopStringId::SessionExportSaveTitle)));
}
// UTF-16 → UTF-8。基础实现,夹带不可解码字节直接落空(MVP 容忍,实际选目录路径都是
// 系统合法 UTF-16)。
std::string wide_to_utf8(const std::wstring& w) {
if (w.empty()) return {};
int len = ::WideCharToMultiByte(CP_UTF8, 0, w.data(), static_cast<int>(w.size()),
nullptr, 0, nullptr, nullptr);
if (len <= 0) return {};
std::string out(static_cast<size_t>(len), '\0');
::WideCharToMultiByte(CP_UTF8, 0, w.data(), static_cast<int>(w.size()),
out.data(), len, nullptr, nullptr);
return out;
}
bool is_usable_owner_window(HWND hwnd) {
if (!hwnd || !::IsWindow(hwnd) || !::IsWindowVisible(hwnd)) return false;
LONG_PTR style = ::GetWindowLongPtrW(hwnd, GWL_STYLE);
return (style & WS_VISIBLE) != 0;
}
HWND resolve_dialog_owner(HWND requested_parent) {
HWND owner = requested_parent;
if (!owner) {
// Edge app compatibility mode calls the daemon endpoint, so the daemon
// has no WebView HWND. The user's click still leaves the Edge app as the
// foreground window; using it as owner keeps the dialog above that app.
owner = ::GetForegroundWindow();
}
if (owner) {
if (HWND root = ::GetAncestor(owner, GA_ROOT); root) {
owner = root;
}
}
return is_usable_owner_window(owner) ? owner : nullptr;
}
struct DialogForegroundState {
DWORD pid = 0;
bool found = false;
};
// 既认标题也认窗口类:IFileDialog 的顶层窗口类固定是 #32770(通用对话框),
// SetTitle 之后标题应当匹配,但个别 Windows 版本上标题落地有时序窗口,曾导致
// 仅按标题精确匹配的脉冲整轮扫不到对话框(webapp 模式下对话框永远垫底)。
// daemon 进程没有其它可见顶层窗口,pid + #32770 足够准确。
bool is_folder_picker_window(HWND hwnd) {
wchar_t title[128] = {0};
::GetWindowTextW(hwnd, title, static_cast<int>(sizeof(title) / sizeof(title[0])));
const std::wstring expected_title = folder_picker_title();
if (std::wcscmp(title, expected_title.c_str()) == 0) return true;
wchar_t cls[64] = {0};
::GetClassNameW(hwnd, cls, static_cast<int>(sizeof(cls) / sizeof(cls[0])));
return std::wcscmp(cls, L"#32770") == 0;
}
// 后台进程直接 SetForegroundWindow 大概率被拒(foreground lock)。经典缓解是把
// 当前线程的输入队列 attach 到前台线程后再调用 —— 此时系统认为调用方"参与"了
// 前台输入,放行率显著更高(AutoHotkey / 各类 launcher 的常用组合)。失败再退回
// 裸调用,保底仍有下方的 TOPMOST 脉冲保证 z-order 可见。
void force_foreground(HWND hwnd) {
const DWORD my_tid = ::GetCurrentThreadId();
const DWORD fg_tid = ::GetWindowThreadProcessId(::GetForegroundWindow(), nullptr);
bool attached = false;
if (fg_tid && fg_tid != my_tid) {
attached = ::AttachThreadInput(my_tid, fg_tid, TRUE) != 0;
}
::BringWindowToTop(hwnd);
::SetForegroundWindow(hwnd);
if (attached) {
::AttachThreadInput(my_tid, fg_tid, FALSE);
}
}
BOOL CALLBACK pulse_folder_dialog_proc(HWND hwnd, LPARAM param) {
auto* state = reinterpret_cast<DialogForegroundState*>(param);
if (!state || !hwnd || !::IsWindowVisible(hwnd)) return TRUE;
DWORD pid = 0;
::GetWindowThreadProcessId(hwnd, &pid);
if (pid != state->pid) return TRUE;
if (!is_folder_picker_window(hwnd)) return TRUE;
if (::IsIconic(hwnd)) {
::ShowWindow(hwnd, SW_RESTORE);
} else {
::ShowWindow(hwnd, SW_SHOW);
}
// Windows can deny SetForegroundWindow for background processes. A brief
// topmost pulse still makes the user-initiated dialog visible, then returns
// it to normal z-order so it does not stay globally topmost.
constexpr UINT flags = SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW;
::SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, flags);
::SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, flags);
force_foreground(hwnd);
state->found = true;
return TRUE;
}
class DialogForegroundPulse {
public:
DialogForegroundPulse() = default;
DialogForegroundPulse(const DialogForegroundPulse&) = delete;
DialogForegroundPulse& operator=(const DialogForegroundPulse&) = delete;
~DialogForegroundPulse() { stop(); }
void start() {
stop_.store(false);
try {
worker_ = std::thread([this] {
const DWORD pid = ::GetCurrentProcessId();
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(3);
while (!stop_.load() && std::chrono::steady_clock::now() < deadline) {
DialogForegroundState state;
state.pid = pid;
::EnumWindows(pulse_folder_dialog_proc, reinterpret_cast<LPARAM>(&state));
if (state.found) {
// One or two extra pulses cover the common-dialog activation
// race without fighting the user for focus afterward.
for (int i = 0; i < 2 && !stop_.load(); ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(80));
DialogForegroundState again;
again.pid = pid;
::EnumWindows(pulse_folder_dialog_proc, reinterpret_cast<LPARAM>(&again));
}
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(80));
}
});
} catch (const std::exception& e) {
LOG_WARN(std::string("[folder_picker] foreground pulse unavailable: ") + e.what());
}
}
void stop() {
stop_.store(true);
if (worker_.joinable()) worker_.join();
}
private:
std::atomic<bool> stop_{false};
std::thread worker_;
};
} // namespace
std::optional<std::string> pick_folder(void* parent_hwnd) {
// CoInitializeEx: STA 模式;若已 init 过(webview 内部已初始化 COM)
// 返回 RPC_E_CHANGED_MODE,这种情况直接当 OK 处理 — IFileOpenDialog 在 STA 用得正常。
HRESULT hr_init = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
bool we_init_com = SUCCEEDED(hr_init);
if (!we_init_com && hr_init != RPC_E_CHANGED_MODE && hr_init != S_FALSE) {
LOG_WARN("[folder_picker] CoInitializeEx failed");
return std::nullopt;
}
std::optional<std::string> result;
IFileOpenDialog* dlg = nullptr;
HRESULT hr = ::CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&dlg));
if (SUCCEEDED(hr) && dlg) {
// FOS_PICKFOLDERS: 选目录而不是文件;FOS_FORCEFILESYSTEM: 强制返回真实磁盘路径,
// 排除虚拟 namespace(虚拟回收站之类)。
DWORD opts = 0;
if (SUCCEEDED(dlg->GetOptions(&opts))) {
dlg->SetOptions(opts | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
}
const std::wstring title = folder_picker_title();
dlg->SetTitle(title.c_str());
HWND requested_parent = reinterpret_cast<HWND>(parent_hwnd);
HWND parent = resolve_dialog_owner(requested_parent);
DialogForegroundPulse foreground_pulse;
if (!requested_parent || !parent) {
foreground_pulse.start();
}
hr = dlg->Show(parent);
foreground_pulse.stop();
if (SUCCEEDED(hr)) {
IShellItem* item = nullptr;
if (SUCCEEDED(dlg->GetResult(&item)) && item) {
PWSTR path = nullptr;
if (SUCCEEDED(item->GetDisplayName(SIGDN_FILESYSPATH, &path)) && path) {
result = wide_to_utf8(std::wstring(path));
::CoTaskMemFree(path);
}
item->Release();
}
}
// hr 可能是 HRESULT_FROM_WIN32(ERROR_CANCELLED) — 用户取消,不报错
dlg->Release();
} else {
LOG_WARN("[folder_picker] CoCreateInstance(IFileOpenDialog) failed");
}
if (we_init_com) ::CoUninitialize();
return result;
}
FolderPickOutcome pick_folder_outcome(void* parent_hwnd) {
// Windows:系统对话框必然弹出过,取消与罕见的 COM 失败折叠为 nullopt
// 不影响 UI 反馈,error 恒空。
FolderPickOutcome outcome;
outcome.path = pick_folder(parent_hwnd);
return outcome;
}
SaveFilePickOutcome pick_save_file_outcome(
void* parent_hwnd,
const std::string& suggested_filename) {
SaveFilePickOutcome outcome;
const auto fail = [&outcome](const std::string& stage) {
LOG_WARN("[folder_picker] save dialog failed at " + stage);
outcome.error = std::string(
native_string(DesktopStringId::SessionExportSaveFailed));
};
const HRESULT hr_init = ::CoInitializeEx(
nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
const bool we_init_com = SUCCEEDED(hr_init);
if (!we_init_com && hr_init != RPC_E_CHANGED_MODE && hr_init != S_FALSE) {
fail("CoInitializeEx");
return outcome;
}
IFileSaveDialog* dialog = nullptr;
HRESULT hr = ::CoCreateInstance(
CLSID_FileSaveDialog,
nullptr,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&dialog));
if (FAILED(hr) || !dialog) {
fail("CoCreateInstance(IFileSaveDialog)");
if (we_init_com) ::CoUninitialize();
return outcome;
}
DWORD options = 0;
if (SUCCEEDED(dialog->GetOptions(&options))) {
dialog->SetOptions(options |
FOS_FORCEFILESYSTEM |
FOS_PATHMUSTEXIST |
FOS_OVERWRITEPROMPT |
FOS_NOREADONLYRETURN);
}
const std::wstring title = session_export_save_title();
const std::wstring file_type = acecode::utf8_to_wide(
std::string(native_string(DesktopStringId::SessionExportMarkdownType)));
const std::wstring suggested = acecode::utf8_to_wide(suggested_filename);
const COMDLG_FILTERSPEC filters[] = {
{file_type.c_str(), L"*.md"},
};
dialog->SetTitle(title.c_str());
dialog->SetFileTypes(1, filters);
dialog->SetFileTypeIndex(1);
dialog->SetDefaultExtension(L"md");
if (!suggested.empty()) dialog->SetFileName(suggested.c_str());
HWND requested_parent = reinterpret_cast<HWND>(parent_hwnd);
HWND parent = resolve_dialog_owner(requested_parent);
DialogForegroundPulse foreground_pulse;
if (!requested_parent || !parent) foreground_pulse.start();
hr = dialog->Show(parent);
foreground_pulse.stop();
if (SUCCEEDED(hr)) {
IShellItem* item = nullptr;
if (SUCCEEDED(dialog->GetResult(&item)) && item) {
PWSTR path = nullptr;
if (SUCCEEDED(item->GetDisplayName(SIGDN_FILESYSPATH, &path)) && path) {
const std::string selected = wide_to_utf8(std::wstring(path));
if (!selected.empty()) {
outcome.path = selected;
} else {
fail("UTF-16 path conversion");
}
::CoTaskMemFree(path);
} else {
fail("GetDisplayName");
}
item->Release();
} else {
fail("GetResult");
}
} else if (hr != HRESULT_FROM_WIN32(ERROR_CANCELLED)) {
fail("Show");
}
dialog->Release();
if (we_init_com) ::CoUninitialize();
return outcome;
}
std::optional<std::string> pick_save_file(
void* parent_hwnd,
const std::string& suggested_filename) {
return pick_save_file_outcome(parent_hwnd, suggested_filename).path;
}
} // namespace acecode::desktop
#elif !defined(__APPLE__) // POSIX stub (Linux etc.)
#include "../utils/logger.hpp"
#include <array>
#include <cerrno>
#include <cstring>
#include <optional>
#include <string>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
namespace acecode::desktop {
namespace {
enum class RunStatus {
Picked, // 用户选中,路径有效
Cancelled, // 工具弹出过但用户取消(zenity/kdialog 取消时 exit 1)
ToolMissing, // execvp ENOENT:工具未安装,可以换下一个候选
Failed, // 其他失败(fork/pipe/异常退出码)
};
RunStatus run_folder_picker_command(const std::vector<const char*>& argv,
std::string& out_path) {
out_path.clear();
int pipefd[2] = {-1, -1};
if (::pipe(pipefd) != 0) {
LOG_WARN(std::string("[folder_picker] pipe failed: ") + std::strerror(errno));
return RunStatus::Failed;
}
pid_t pid = ::fork();
if (pid < 0) {
LOG_WARN(std::string("[folder_picker] fork failed: ") + std::strerror(errno));
::close(pipefd[0]);
::close(pipefd[1]);
return RunStatus::Failed;
}
if (pid == 0) {
::close(pipefd[0]);
::dup2(pipefd[1], STDOUT_FILENO);
::close(pipefd[1]);
::execvp(argv[0], const_cast<char* const*>(argv.data()));
::_exit(errno == ENOENT ? 127 : 126);
}
::close(pipefd[1]);
std::string out;
std::array<char, 512> buf{};
while (true) {
ssize_t n = ::read(pipefd[0], buf.data(), buf.size());
if (n > 0) {
out.append(buf.data(), static_cast<size_t>(n));
continue;
}
if (n < 0 && errno == EINTR) continue;
break;
}
::close(pipefd[0]);
int status = 0;
while (::waitpid(pid, &status, 0) < 0) {
if (errno == EINTR) continue;
LOG_WARN(std::string("[folder_picker] waitpid failed: ") + std::strerror(errno));
return RunStatus::Failed;
}
if (!WIFEXITED(status)) return RunStatus::Failed;
const int code = WEXITSTATUS(status);
if (code == 127) {
// execvp ENOENT —— 工具不存在。这必须与"用户取消"区分:取消可以静默,
// 工具缺失必须透传到 UI(否则点"添加项目"毫无反应,用户无从排查;
// UOS/DDE 等发行版默认不带 zenity/kdialog,真实踩过)。
return RunStatus::ToolMissing;
}
if (code != 0) {
// zenity / kdialog 取消都是 exit 1;其他非零也按取消处理(对话框已
// 弹出过,用户有感知,不需要错误提示)。
return RunStatus::Cancelled;
}
while (!out.empty() && (out.back() == '\n' || out.back() == '\r')) {
out.pop_back();
}
if (out.empty()) return RunStatus::Cancelled;
out_path = std::move(out);
return RunStatus::Picked;
}
} // namespace
FolderPickOutcome pick_folder_outcome(void* /*parent*/) {
// Linux best effort without adding a hard GTK dependency to acecode_testable.
// Desktop packages can depend on zenity/kdialog for a native folder dialog.
// 注意:只有 ToolMissing 才落到下一个候选 —— 用户在 zenity 里点了取消,
// 不应再被弹一个 kdialog 对话框。
FolderPickOutcome outcome;
std::string path;
const std::string title = std::string(
native_string(DesktopStringId::FolderPickerTitle));
const std::string zenity_title = "--title=" + title;
auto zenity = run_folder_picker_command({
"zenity",
"--file-selection",
"--directory",
zenity_title.c_str(),
nullptr,
}, path);
if (zenity == RunStatus::Picked) {
outcome.path = path;
return outcome;
}
if (zenity == RunStatus::Cancelled) return outcome;
auto kdialog = run_folder_picker_command({
"kdialog",
"--getexistingdirectory",
".",
"--title",
title.c_str(),
nullptr,
}, path);
if (kdialog == RunStatus::Picked) {
outcome.path = path;
return outcome;
}
if (kdialog == RunStatus::Cancelled) return outcome;
LOG_WARN("[folder_picker] no folder picker tool available (tried zenity, kdialog)");
outcome.error = std::string(
native_string(DesktopStringId::FolderPickerMissing));
return outcome;
}
std::optional<std::string> pick_folder(void* parent) {
return pick_folder_outcome(parent).path;
}
SaveFilePickOutcome pick_save_file_outcome(
void* /*parent*/,
const std::string& suggested_filename) {
SaveFilePickOutcome outcome;
std::string path;
const std::string title = std::string(
native_string(DesktopStringId::SessionExportSaveTitle));
const std::string file_type = std::string(
native_string(DesktopStringId::SessionExportMarkdownType));
const std::string suggestion = suggested_filename.empty()
? std::string("session.md")
: suggested_filename;
const std::string zenity_title = "--title=" + title;
const std::string zenity_filename = "--filename=" + suggestion;
const std::string zenity_filter = "--file-filter=" + file_type + " | *.md";
auto zenity = run_folder_picker_command({
"zenity",
"--file-selection",
"--save",
"--confirm-overwrite",
zenity_title.c_str(),
zenity_filename.c_str(),
zenity_filter.c_str(),
nullptr,
}, path);
if (zenity == RunStatus::Picked) {
outcome.path = path;
return outcome;
}
if (zenity == RunStatus::Cancelled) return outcome;
const std::string initial_path = "./" + suggestion;
const std::string kdialog_filter = "*.md|" + file_type;
auto kdialog = run_folder_picker_command({
"kdialog",
"--getsavefilename",
initial_path.c_str(),
kdialog_filter.c_str(),
"--title",
title.c_str(),
nullptr,
}, path);
if (kdialog == RunStatus::Picked) {
outcome.path = path;
return outcome;
}
if (kdialog == RunStatus::Cancelled) return outcome;
LOG_WARN("[folder_picker] no save-file picker tool available (tried zenity, kdialog)");
outcome.error = std::string(
native_string(DesktopStringId::SessionExportSaveMissing));
return outcome;
}
std::optional<std::string> pick_save_file(
void* parent,
const std::string& suggested_filename) {
return pick_save_file_outcome(parent, suggested_filename).path;
}
} // namespace acecode::desktop
#endif