Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a4df70079 | ||
|
|
e986dd90e5 | ||
|
|
3dd4edeb2c | ||
|
|
edb259e6bb | ||
|
|
9e287c3a1d | ||
|
|
5eda68a7a2 | ||
|
|
6cbb0639a1 | ||
|
|
2a6f9c7841 | ||
|
|
94b22fdd52 | ||
|
|
0d293429df | ||
|
|
83a099ab25 |
No files matched your search
@@ -26,6 +26,11 @@ add_custom_target(check-files-search-arrow
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>"
|
||||
DEPENDS KSwitcherFiles
|
||||
VERBATIM)
|
||||
add_custom_target(check-files-quick-view
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_quick_view.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>"
|
||||
DEPENDS KSwitcherFiles
|
||||
VERBATIM)
|
||||
target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
|
||||
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet)
|
||||
if(MSVC)
|
||||
|
||||
+41
-1
@@ -204,6 +204,10 @@ Warning і початковий фокус на No.
|
||||
Незбережені зміни у примусово закритих вікнах втрачаються.
|
||||
Закриття процесів і результат записуються до `kswitcher.log`.
|
||||
|
||||
- **Commands → Copy full path** або **Ctrl+Shift+C** копіює повний шлях
|
||||
файла чи папки під курсором як текст. У LAN- і FTP-панелях текст включає
|
||||
адресу віддаленого джерела. Для рядка `..` команда не змінює буфер.
|
||||
|
||||
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
|
||||
курсора командного рядка або замінює виділення. Подвійні лапки додаються
|
||||
лише до шляхів із пробілами. На рядку `..` вставляється шлях папки,
|
||||
@@ -429,6 +433,21 @@ Warning і початковий фокус на No.
|
||||
|
||||
## Панелі
|
||||
|
||||
- **F9 → Commands → Find files** або **Alt+F7** запускає фоновий пошук
|
||||
файлів у поточній локальній папці та її підпапках. Поле приймає повне
|
||||
ім’я або маску без урахування регістру. `*` відповідає довільній
|
||||
послідовності символів, `?` — одному символу. Приховані та системні
|
||||
елементи можна включити прапорцем. Пошук не обходить junction та інші
|
||||
посилання на каталоги. Esc під час пошуку зупиняє обхід і показує знайдене.
|
||||
Результати відкриваються в тій самій панелі з відносними шляхами.
|
||||
Enter або подвійний клік відкриває папку й ставить курсор на файл.
|
||||
Esc у результатах повертає вихідну папку, курсор і позначки.
|
||||
У результатах F3/F4 відкривають файл, а F5/F6 працюють із позначеними
|
||||
або поточним файлом, використовуючи папку іншої панелі як призначення.
|
||||
F8 і Shift+Delete використовують звичайні підтвердження. Успішно
|
||||
переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
|
||||
з тією самою маскою й видимістю прихованих файлів.
|
||||
|
||||
- Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів
|
||||
у відкритих локальних папках. Фокус залишається там, де був, а курсор
|
||||
лишається на поточному елементі, якщо той ще існує.
|
||||
@@ -469,7 +488,28 @@ Warning і початковий фокус на No.
|
||||
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
|
||||
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
|
||||
|
||||
- Поточний шлях відображається по центру верхньої подвійної лінії панелі. Лінію видно з обох боків напису. Бірюзове тло активної панелі охоплює лише напис шляху з невеликими відступами. Довгий шлях скорочується в межах панелі.
|
||||
- **Commands → Quick View** або **Ctrl+Q** вмикає перегляд локального
|
||||
тексту й Markdown у сусідній панелі. Перегляд слідує за курсором активної
|
||||
панелі. Повторна команда повертає сусідній каталог, курсор і позначки.
|
||||
Під час перегляду файлові операції з призначенням у сусідній панелі
|
||||
пропонують спершу закрити Quick View.
|
||||
|
||||
- **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує
|
||||
останні відвідані локальні папки. Повторний візит підіймає один запис
|
||||
угору, порядок зберігається після перезапуску. Enter або клік відкриває
|
||||
шлях у панелі, з якої викликали меню. Delete прибирає вибраний запис.
|
||||
|
||||
- У локальному заголовку кнопки ← та → переходять назад і вперед
|
||||
в історії відповідної панелі. Стрілка ↑, Alt+↑ та рядок `..`
|
||||
відкривають безпосередню батьківську папку. На корені стрілка вимкнена,
|
||||
а рядка немає. Alt+← і Alt+→ працюють з історією активної панелі.
|
||||
- Сегменти шляху відкривають папки. Якщо шлях не вміщується, ліва
|
||||
трикрапка відкриває прихованих предків, а права — приховані папки
|
||||
попередньої гілки. Клік по поточній папці або кнопці редагування та Ctrl+L
|
||||
відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях,
|
||||
а Esc повертає до тих самих панелей і курсора.
|
||||
|
||||
- Для LAN і FTP поточний шлях відображається по центру верхньої подвійної лінії панелі. Довгий шлях скорочується в межах панелі.
|
||||
|
||||
## Спільні елементи діалогів
|
||||
|
||||
|
||||
@@ -407,3 +407,28 @@ BEGIN
|
||||
LTEXT "Reading and comparing files...", -1, 14, 15, 262, 13
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17
|
||||
END
|
||||
|
||||
116 DIALOGEX 0, 0, 300, 98
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Find files"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "File &name or mask", 483, 16, 18, 268, 12
|
||||
FAR_EDIT(480, 0, 16, 32, 268, 15)
|
||||
AUTOCHECKBOX "Include &hidden and system files", 481, 16, 53, 268, 12
|
||||
LTEXT "", 482, 10, 69, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Find", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 68, 73, 80, 17
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 73, 80, 17
|
||||
END
|
||||
|
||||
117 DIALOGEX 0, 0, 290, 83
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Go to folder"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Folder &path (Tab completes)", 486, 16, 18, 258, 12
|
||||
FAR_EDIT(485, 0, 16, 32, 258, 15)
|
||||
LTEXT "", 487, 10, 54, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17
|
||||
END
|
||||
@@ -10,6 +10,10 @@
|
||||
body { max-width: var(--markdown-width, 960px); margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
|
||||
main { font: var(--markdown-font-size, 12pt)/1.55 var(--markdown-font, system-ui, sans-serif); }
|
||||
nav { position: sticky; top: 0; display: flex; flex-wrap: wrap; gap: .4em; padding-block: .25em; background: Canvas; }
|
||||
:root.quick-view body { padding: 8px 12px; }
|
||||
:root.quick-view nav { display: none; }
|
||||
:root.quick-view main > :first-child { margin-block-start: 0; }
|
||||
:root.quick-view h1 { font-size: 1.4em; }
|
||||
nav button { appearance: none; border: 0; background: transparent; color: LinkText;
|
||||
font: 1.35em/1.25 system-ui, sans-serif; min-width: 1.55em; padding: 0; cursor: pointer; }
|
||||
nav button:disabled { color: GrayText; opacity: .6; cursor: default; }
|
||||
|
||||
@@ -247,12 +247,13 @@ searchPrevious.addEventListener('click', () => stepSearch(-1));
|
||||
searchNext.addEventListener('click', () => stepSearch(1));
|
||||
content.addEventListener('toggle', () => { if (!search.hidden) updateSearch(false); }, true);
|
||||
|
||||
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave }) {
|
||||
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave, compact }) {
|
||||
const current = ++generation;
|
||||
if (keepPosition) scroll = window.scrollY;
|
||||
else closeSearch();
|
||||
document.documentElement.classList.remove('rendered');
|
||||
document.title = title;
|
||||
document.documentElement.classList.toggle('quick-view', Boolean(compact));
|
||||
previewRevision = revision;
|
||||
renderContent(text, canSave);
|
||||
const headings = new Set();
|
||||
@@ -264,7 +265,7 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
|
||||
headings.add(id);
|
||||
}
|
||||
images = Array.from(content.querySelectorAll('img[data-path]'));
|
||||
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current }));
|
||||
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current, revision }));
|
||||
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
|
||||
for (const [index, block] of blocks.entries()) {
|
||||
try {
|
||||
@@ -289,7 +290,7 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
|
||||
restorePosition({ fragment, scroll });
|
||||
document.documentElement.classList.add('rendered');
|
||||
if (!search.hidden) updateSearch(false);
|
||||
send('rendered');
|
||||
send('rendered', { revision });
|
||||
}
|
||||
|
||||
content.addEventListener('change', ({ target }) => {
|
||||
@@ -350,7 +351,7 @@ bridge.addEventListener('message', ({ data }) => {
|
||||
document.documentElement.classList.remove('rendered');
|
||||
content.replaceChildren();
|
||||
}
|
||||
if (message.action === 'render') void render(message).catch(() => send('failed'));
|
||||
if (message.action === 'render') void render(message).catch(() => send('failed', { revision: message.revision }));
|
||||
if (message.action === 'task-result' && message.revision === previewRevision && pendingTask) {
|
||||
if (!message.saved) pendingTask.target.checked = !pendingTask.checked;
|
||||
pendingTask = undefined;
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
constexpr int findMask=480, findHidden=481, findFooter=482, findLabel=483;
|
||||
|
||||
INT_PTR CALLBACK findFilesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_DRAWITEM)
|
||||
{
|
||||
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
|
||||
return TRUE;
|
||||
}
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Find files ",false,{findFooter}))
|
||||
return painted;
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
const auto &options=*reinterpret_cast<Panel::FindOptions *>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
layoutDialogContent(dialog,findLabel);
|
||||
for(const auto id:{IDOK,IDCANCEL})
|
||||
{
|
||||
const auto button=GetDlgItem(dialog,id);
|
||||
SetWindowPos(button,nullptr,0,0,farDialogButtonWidth(button),textHeight,
|
||||
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
}
|
||||
layoutDialogButtons(dialog,findFooter,{IDOK,IDCANCEL});
|
||||
installFarCheckbox(GetDlgItem(dialog,findHidden),FarCheckboxSurface::gray);
|
||||
SendDlgItemMessageW(dialog,findMask,EM_SETLIMITTEXT,255,0);
|
||||
SetDlgItemTextW(dialog,findMask,options.mask.c_str());
|
||||
CheckDlgButton(dialog,findHidden,options.includeHidden?BST_CHECKED:BST_UNCHECKED);
|
||||
SetFocus(GetDlgItem(dialog,findMask));
|
||||
SendDlgItemMessageW(dialog,findMask,EM_SETSEL,0,-1);
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
|
||||
{
|
||||
auto &options=*reinterpret_cast<Panel::FindOptions *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
wchar_t mask[256]{};
|
||||
GetDlgItemTextW(dialog,findMask,mask,static_cast<int>(std::size(mask)));
|
||||
if(std::wstring_view(mask).find_first_of(L"/\\:")!=std::wstring_view::npos)
|
||||
{
|
||||
showFilesNotice(dialog,L"Enter a file name or mask without a path.",L"Find files");
|
||||
SetFocus(GetDlgItem(dialog,findMask));
|
||||
return TRUE;
|
||||
}
|
||||
options.mask=*mask?mask:L"*";
|
||||
options.includeHidden=IsDlgButtonChecked(dialog,findHidden)==BST_CHECKED;
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void startFileSearch(Panel &panel,Panel::FindOptions options)
|
||||
{
|
||||
if(panel.scanRequest) return;
|
||||
cancelFolderSizes(panel);
|
||||
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)};
|
||||
startDirectoryScan(panel);
|
||||
}
|
||||
|
||||
void findLocalFiles(HWND owner,Panel &panel)
|
||||
{
|
||||
if(panel.peer || panel.ftp || panel.directory.empty())
|
||||
{
|
||||
setStatus(L"Find files requires a local folder.");
|
||||
return;
|
||||
}
|
||||
if(panel.scanRequest)
|
||||
{
|
||||
setStatus(L"Wait for the current scan to finish.");
|
||||
return;
|
||||
}
|
||||
auto options=panel.findOrigin?panel.findOrigin->options:Panel::FindOptions{};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner,
|
||||
findFilesDialog,reinterpret_cast<LPARAM>(&options))!=IDOK) return;
|
||||
startFileSearch(panel,std::move(options));
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
bool matchesFileMask(std::wstring_view name,std::wstring_view mask)
|
||||
{
|
||||
size_t fileIndex=0, maskIndex=0, star=mask.npos, afterStar=0;
|
||||
while(fileIndex<name.size())
|
||||
{
|
||||
if(maskIndex<mask.size() && mask[maskIndex]==L'*')
|
||||
{
|
||||
star=maskIndex++;
|
||||
afterStar=fileIndex;
|
||||
}
|
||||
else if(maskIndex<mask.size() &&
|
||||
(mask[maskIndex]==L'?' || CompareStringOrdinal(name.data()+fileIndex,1,
|
||||
mask.data()+maskIndex,1,TRUE)==CSTR_EQUAL))
|
||||
{
|
||||
++fileIndex;
|
||||
++maskIndex;
|
||||
}
|
||||
else if(star!=mask.npos)
|
||||
{
|
||||
maskIndex=star+1;
|
||||
fileIndex=++afterStar;
|
||||
}
|
||||
else return false;
|
||||
}
|
||||
return mask.find_first_not_of(L'*',maskIndex)==mask.npos;
|
||||
}
|
||||
|
||||
std::unique_ptr<Panel::ScanResult> scanFileMatches(const Panel::ScanRequest &request,
|
||||
std::atomic_size_t &entriesRead,std::stop_token stop)
|
||||
{
|
||||
auto result=std::make_unique<Panel::ScanResult>();
|
||||
FilesConnection local(nullptr);
|
||||
std::vector<fs::path> pending{request.directory};
|
||||
size_t visited=0;
|
||||
while(!pending.empty() && !stop.stop_requested())
|
||||
{
|
||||
const auto directory=std::move(pending.back());
|
||||
pending.pop_back();
|
||||
try
|
||||
{
|
||||
listFiles(local,directory,[&](const fs::path &path,const FileInfo &entry)
|
||||
{
|
||||
if(stop.stop_requested()) return false;
|
||||
entriesRead.store(++visited,std::memory_order_relaxed);
|
||||
if(!request.find->includeHidden && (entry.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)))
|
||||
return true;
|
||||
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)
|
||||
{
|
||||
if(!(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) pending.push_back(path);
|
||||
}
|
||||
else if(matchesFileMask(path.filename().native(),request.find->mask))
|
||||
{
|
||||
result->files.push_back(path);
|
||||
result->metadata.emplace(path,FolderEntryMetadata{entry.attributes,entry.size});
|
||||
result->timestamps.emplace(path,entry.modified);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
catch(const std::system_error &)
|
||||
{
|
||||
if(directory==request.directory)
|
||||
{
|
||||
result->failure=L"Cannot search folder: "+directory.native();
|
||||
return result;
|
||||
}
|
||||
result->error=ERROR_PARTIAL_COPY;
|
||||
}
|
||||
}
|
||||
if(stop.stop_requested()) result->error=ERROR_CANCELLED;
|
||||
result->opened=true;
|
||||
std::sort(result->files.begin(),result->files.end());
|
||||
return result;
|
||||
}
|
||||
@@ -27,25 +27,18 @@ bool saveFolderShortcuts(const FolderShortcuts &shortcuts)
|
||||
{"name",ks::utf8(entry.peerName)},{"title",ks::utf8(entry.title)}});
|
||||
groups.push_back(std::move(rows));
|
||||
}
|
||||
const auto data=groups.dump();
|
||||
return data.size()<=1024*1024 &&
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
|
||||
return writeFilesJsonPreference(folderShortcutsKey,groups);
|
||||
}
|
||||
catch(const std::exception &){return false;}
|
||||
}
|
||||
|
||||
void loadFolderShortcuts()
|
||||
{
|
||||
DWORD bytes{};
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
|
||||
!bytes || bytes>1024*1024) return;
|
||||
std::string data(bytes,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
|
||||
return;
|
||||
const auto saved=readFilesJsonPreference(folderShortcutsKey);
|
||||
if(!saved) return;
|
||||
try
|
||||
{
|
||||
const auto groups=Json::parse(data.begin(),data.begin()+bytes);
|
||||
const auto &groups=*saved;
|
||||
if(!groups.is_array() || groups.size()!=folderShortcuts.size()) return;
|
||||
FolderShortcuts loaded;
|
||||
for(size_t digit=0;digit<loaded.size();++digit)
|
||||
|
||||
+485
-58
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,383 @@
|
||||
|
||||
bool localNavigationAvailable(const Panel &panel)
|
||||
{
|
||||
return !panel.peer && !panel.ftp && !panel.findOrigin && !panel.directory.empty();
|
||||
}
|
||||
|
||||
enum class PathAction { back, forward, up, edit, ancestors, previous, folder };
|
||||
|
||||
void navigateLocal(Panel &panel,const fs::path &path,std::optional<size_t> position={})
|
||||
{
|
||||
if(path.empty() || sameLocalFolder(path,panel.directory)) return;
|
||||
closePanelSearch();
|
||||
openOn(panel,path,true,{},{},{},{},position);
|
||||
}
|
||||
|
||||
void navigateLocalHistory(Panel &panel,int direction)
|
||||
{
|
||||
if(const auto next=panel.navigation.neighbor(direction))
|
||||
navigateLocal(panel,panel.navigation.history[*next],next);
|
||||
}
|
||||
|
||||
struct PathPart
|
||||
{
|
||||
PathAction action{};
|
||||
std::wstring label;
|
||||
fs::path target;
|
||||
std::vector<fs::path> hidden;
|
||||
RECT rect{};
|
||||
bool current{}, dim{}, enabled=true;
|
||||
};
|
||||
|
||||
std::wstring pathSegmentLabel(const fs::path &path)
|
||||
{
|
||||
return panelParentPath(path,true).empty()?path.native():path.filename().native();
|
||||
}
|
||||
|
||||
LONG segmentWidth(const fs::path &path)
|
||||
{
|
||||
return static_cast<LONG>(pathSegmentLabel(path).size()+2)*cellWidth;
|
||||
}
|
||||
|
||||
std::vector<PathPart> localPathParts(const Panel &panel,RECT bounds)
|
||||
{
|
||||
const LONG total=bounds.right-bounds.left;
|
||||
if(total<=0) return {};
|
||||
const LONG width=std::max(1L,std::min(2L*cellWidth,total/7));
|
||||
std::vector<PathPart> parts;
|
||||
const auto add=[&](PathPart part,LONG length)
|
||||
{
|
||||
if(length<=0 || bounds.left>=bounds.right) return;
|
||||
part.rect={bounds.left,bounds.top,std::min(bounds.right,bounds.left+length),bounds.bottom};
|
||||
bounds.left=part.rect.right;
|
||||
parts.push_back(std::move(part));
|
||||
};
|
||||
const auto parent=panelParentPath(panel.directory,true);
|
||||
add({.action=PathAction::back,.label=L"←",.enabled=panel.navigation.neighbor(-1).has_value()},width);
|
||||
add({.action=PathAction::forward,.label=L"→",.enabled=panel.navigation.neighbor(1).has_value()},width);
|
||||
add({.action=PathAction::up,.label=L"↑",.target=parent,.enabled=!parent.empty()},width);
|
||||
add({.action=PathAction::edit,.label=L"✎"},width);
|
||||
|
||||
std::vector<fs::path> ancestors, previous;
|
||||
for(auto path=parent;!path.empty();path=panelParentPath(path,true)) ancestors.push_back(path);
|
||||
std::reverse(ancestors.begin(),ancestors.end());
|
||||
if(inLocalBranch(panel.directory,panel.navigation.previousBranch))
|
||||
{
|
||||
for(auto path=panel.navigation.previousBranch;!sameLocalFolder(path,panel.directory);
|
||||
path=panelParentPath(path,true))
|
||||
previous.push_back(path);
|
||||
std::reverse(previous.begin(),previous.end());
|
||||
}
|
||||
|
||||
const LONG room=bounds.right-bounds.left;
|
||||
LONG required=segmentWidth(panel.directory);
|
||||
for(const auto &path:ancestors) required+=segmentWidth(path);
|
||||
for(const auto &path:previous) required+=segmentWidth(path);
|
||||
size_t firstAncestor=0,visiblePrevious=previous.size();
|
||||
LONG currentWidth=segmentWidth(panel.directory);
|
||||
if(required>room)
|
||||
{
|
||||
const LONG reserved=(!ancestors.empty()?width:0)+(!previous.empty()?width:0);
|
||||
currentWidth=std::min(currentWidth,std::max(1L,room-reserved));
|
||||
LONG remaining=room-currentWidth-reserved;
|
||||
firstAncestor=ancestors.size();
|
||||
while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1]))
|
||||
remaining-=segmentWidth(ancestors[--firstAncestor]);
|
||||
visiblePrevious=0;
|
||||
while(visiblePrevious<previous.size() && remaining>=segmentWidth(previous[visiblePrevious]))
|
||||
remaining-=segmentWidth(previous[visiblePrevious++]);
|
||||
}
|
||||
|
||||
if(firstAncestor)
|
||||
add({.action=PathAction::ancestors,.label=L"…",
|
||||
.hidden={ancestors.begin(),ancestors.begin()+firstAncestor}},width);
|
||||
for(size_t i=firstAncestor;i<ancestors.size();++i)
|
||||
add({.action=PathAction::folder,.label=pathSegmentLabel(ancestors[i]),.target=ancestors[i]},
|
||||
segmentWidth(ancestors[i]));
|
||||
add({.action=PathAction::edit,.label=pathSegmentLabel(panel.directory),.current=true},currentWidth);
|
||||
for(size_t i=0;i<visiblePrevious;++i)
|
||||
add({.action=PathAction::folder,.label=pathSegmentLabel(previous[i]),.target=previous[i],.dim=true},
|
||||
segmentWidth(previous[i]));
|
||||
if(visiblePrevious<previous.size())
|
||||
add({.action=PathAction::previous,.label=L"…",
|
||||
.hidden={previous.begin()+visiblePrevious,previous.end()},.dim=true},width);
|
||||
return parts;
|
||||
}
|
||||
|
||||
void paintLocalPath(HDC dc,RECT bounds,const Panel &panel,bool activePanel)
|
||||
{
|
||||
const int saved=SaveDC(dc);
|
||||
SelectObject(dc,mono);
|
||||
SetBkMode(dc,TRANSPARENT);
|
||||
for(const auto &part:localPathParts(panel,bounds))
|
||||
{
|
||||
const bool current=activePanel && part.current;
|
||||
FillRect(dc,&part.rect,current?teal:blue);
|
||||
SetTextColor(dc,!part.enabled || part.dim?RGB(160,170,190):colors[current?Text:Frame]);
|
||||
auto text=part.rect;
|
||||
DrawTextW(dc,part.label.c_str(),static_cast<int>(part.label.size()),&text,
|
||||
DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||||
}
|
||||
if(saved) RestoreDC(dc,saved);
|
||||
}
|
||||
|
||||
constexpr int addressField=485,addressLabel=486,addressFooter=487;
|
||||
|
||||
struct PathPrompt
|
||||
{
|
||||
fs::path base, result;
|
||||
std::wstring completionInput;
|
||||
std::future<std::wstring> completion;
|
||||
};
|
||||
|
||||
constexpr UINT addressComplete=WM_APP+29;
|
||||
constexpr UINT_PTR addressCompletionTimer=1;
|
||||
|
||||
fs::path enteredPanelPath(const fs::path &base,std::wstring text)
|
||||
{
|
||||
if(text.size()>=2 && text.front()==L'"' && text.back()==L'"')
|
||||
text=text.substr(1,text.size()-2);
|
||||
return fs::path(text).is_absolute()?fs::path(std::move(text)):base/fs::path(std::move(text));
|
||||
}
|
||||
|
||||
std::wstring panelPathCompletion(const fs::path &base,const std::wstring &text)
|
||||
{
|
||||
const auto path=enteredPanelPath(base,text);
|
||||
const auto directory=path.has_filename()?path.parent_path():path;
|
||||
const auto prefix=path.filename().native();
|
||||
fs::path best;
|
||||
std::error_code error;
|
||||
for(fs::directory_iterator it(directory,error),end;!error && it!=end;it.increment(error))
|
||||
{
|
||||
const auto name=it->path().filename().native();
|
||||
if(name.size()<prefix.size() || (!prefix.empty() && CompareStringOrdinal(name.data(),
|
||||
static_cast<int>(prefix.size()),prefix.data(),static_cast<int>(prefix.size()),TRUE)!=CSTR_EQUAL))
|
||||
continue;
|
||||
std::error_code typeError;
|
||||
if(it->is_directory(typeError) && (best.empty() || it->path()<best)) best=it->path();
|
||||
}
|
||||
return best.empty()?std::wstring{}:best.native()+L"\\";
|
||||
}
|
||||
|
||||
LRESULT CALLBACK addressFieldKeys(HWND field,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_GETDLGCODE)
|
||||
{
|
||||
const auto *key=reinterpret_cast<const MSG *>(lp);
|
||||
if(key && key->wParam==VK_TAB && !(GetKeyState(VK_SHIFT)&0x8000))
|
||||
return DefSubclassProc(field,message,wp,lp)|DLGC_WANTTAB;
|
||||
}
|
||||
if(message==WM_KEYDOWN && wp==VK_TAB && !(GetKeyState(VK_SHIFT)&0x8000))
|
||||
{
|
||||
SendMessageW(GetParent(field),addressComplete,0,0);
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_CHAR && wp==VK_TAB) return 0;
|
||||
return DefSubclassProc(field,message,wp,lp);
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_DRAWITEM)
|
||||
{
|
||||
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
|
||||
return TRUE;
|
||||
}
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Go to folder ",false,{addressFooter}))
|
||||
return painted;
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &prompt=*reinterpret_cast<PathPrompt *>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
layoutDialogContent(dialog,addressLabel);
|
||||
layoutDialogButtons(dialog,addressFooter,{IDOK,IDCANCEL});
|
||||
const auto field=GetDlgItem(dialog,addressField);
|
||||
SendMessageW(field,EM_SETLIMITTEXT,32767,0);
|
||||
SetWindowTextW(field,(prompt.base/fs::path{}).c_str());
|
||||
SetWindowSubclass(field,addressFieldKeys,4,0);
|
||||
SetFocus(field);
|
||||
SendMessageW(field,EM_SETSEL,0,-1);
|
||||
return FALSE;
|
||||
}
|
||||
if(message==addressComplete)
|
||||
{
|
||||
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(prompt.completion.valid()) return TRUE;
|
||||
prompt.completionInput=shortcutField(dialog,addressField);
|
||||
std::packaged_task<std::wstring()> task([base=prompt.base,text=prompt.completionInput]
|
||||
{
|
||||
return panelPathCompletion(base,text);
|
||||
});
|
||||
if(!SetTimer(dialog,addressCompletionTimer,30,nullptr)) return TRUE;
|
||||
prompt.completion=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_TIMER && wp==addressCompletionTimer)
|
||||
{
|
||||
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!prompt.completion.valid() ||
|
||||
prompt.completion.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return TRUE;
|
||||
KillTimer(dialog,addressCompletionTimer);
|
||||
try
|
||||
{
|
||||
const auto value=prompt.completion.get();
|
||||
if(!value.empty() && shortcutField(dialog,addressField)==prompt.completionInput)
|
||||
{
|
||||
const auto field=GetDlgItem(dialog,addressField);
|
||||
SetWindowTextW(field,value.c_str());
|
||||
SendMessageW(field,EM_SETSEL,value.size(),value.size());
|
||||
SendMessageW(field,EM_SCROLLCARET,0,0);
|
||||
}
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
|
||||
{
|
||||
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
auto path=enteredPanelPath(prompt.base,shortcutField(dialog,addressField)).lexically_normal();
|
||||
if(!path.is_absolute())
|
||||
{
|
||||
showFilesNotice(dialog,L"Enter a folder path.",L"Go to folder");
|
||||
return TRUE;
|
||||
}
|
||||
if(!path.has_filename() && path.has_relative_path()) path=path.parent_path();
|
||||
prompt.result=std::move(path);
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void editPanelPath(Panel &panel)
|
||||
{
|
||||
PathPrompt prompt{panel.directory};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(117),GetParent(panel.list),
|
||||
editPathDialog,reinterpret_cast<LPARAM>(&prompt))==IDOK)
|
||||
navigateLocal(panel,prompt.result);
|
||||
}
|
||||
|
||||
void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<fs::path> paths,RECT anchor,bool recent=false)
|
||||
{
|
||||
hidePicker();
|
||||
showMenu(false);
|
||||
commandPicker=false;
|
||||
pickerPanel=side;
|
||||
folderPicker=FolderPicker{caption,std::move(paths),recent};
|
||||
SendMessageW(picker,LB_RESETCONTENT,0,0);
|
||||
size_t longest=wcslen(caption);
|
||||
for(const auto &path:folderPicker->paths)
|
||||
{
|
||||
longest=std::max(longest,path.native().size());
|
||||
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(path.c_str()));
|
||||
}
|
||||
RECT client{};
|
||||
GetClientRect(owner,&client);
|
||||
const int inset=dialogFrameMetrics(GetDpiForWindow(owner)).content();
|
||||
const int width=std::max(1,std::min(static_cast<int>(client.right)-2*inset,static_cast<int>(longest+3)*cellWidth));
|
||||
const int x=std::clamp(static_cast<int>(anchor.left),inset,std::max(inset,static_cast<int>(client.right)-width-inset));
|
||||
const int y=anchor.bottom+inset;
|
||||
const int row=std::max(1,static_cast<int>(SendMessageW(picker,LB_GETITEMHEIGHT,0,0)));
|
||||
RECT input{};
|
||||
GetWindowRect(terminalInput,&input);
|
||||
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT *>(&input),2);
|
||||
const int bottom=std::min(client.bottom,input.top);
|
||||
const int shown=std::clamp((bottom-y-inset)/row,1,static_cast<int>(folderPicker->paths.size()));
|
||||
showFramedList(picker,pickerFrame,x,y,width,row*shown,inset);
|
||||
SendMessageW(picker,LB_SETCURSEL,0,0);
|
||||
SetFocus(picker);
|
||||
}
|
||||
|
||||
void showRecentFolders(int side)
|
||||
{
|
||||
auto paths=readRecentFolders();
|
||||
if(paths.empty())
|
||||
{
|
||||
setStatus(L"No recent local folders.");
|
||||
return;
|
||||
}
|
||||
const auto owner=GetParent(picker);
|
||||
RECT anchor{};
|
||||
GetWindowRect(panels[side].path,&anchor);
|
||||
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT *>(&anchor),2);
|
||||
showFolderPicker(owner,side,L"Recent folders",std::move(paths),anchor,true);
|
||||
}
|
||||
|
||||
void showHiddenPathParts(HWND window,int side,const PathPart &part)
|
||||
{
|
||||
const auto owner=GetParent(window);
|
||||
auto anchor=part.rect;
|
||||
MapWindowPoints(window,owner,reinterpret_cast<POINT*>(&anchor),2);
|
||||
showFolderPicker(owner,side,part.action==PathAction::ancestors?L"Parent folders":L"Previous path",
|
||||
part.hidden,anchor);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_LBUTTONDOWN)
|
||||
{
|
||||
SetCapture(window);
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_LBUTTONUP && GetCapture()==window)
|
||||
{
|
||||
ReleaseCapture();
|
||||
const int index=GetDlgCtrlID(window)-142;
|
||||
if(index<0 || index>=2) return 0;
|
||||
auto &panel=panels[index];
|
||||
if(!localNavigationAvailable(panel))
|
||||
{
|
||||
selectPanelEdge(panel,true);
|
||||
return 0;
|
||||
}
|
||||
activatePanel(index);
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
const POINT mouse{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
const auto parts=localPathParts(panel,bounds);
|
||||
for(const auto &part:parts)
|
||||
{
|
||||
if(!part.enabled || !PtInRect(&part.rect,mouse)) continue;
|
||||
switch(part.action)
|
||||
{
|
||||
case PathAction::back: navigateLocalHistory(panel,-1); break;
|
||||
case PathAction::forward: navigateLocalHistory(panel,1); break;
|
||||
case PathAction::up: case PathAction::folder: navigateLocal(panel,part.target); break;
|
||||
case PathAction::edit: editPanelPath(panel); break;
|
||||
case PathAction::ancestors: case PathAction::previous: showHiddenPathParts(window,index,part); break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return DefSubclassProc(window,message,wp,lp);
|
||||
}
|
||||
|
||||
bool handleLocalPathKey(HWND owner,const MSG &message)
|
||||
{
|
||||
if(!commandLineAvailable(owner) || terminalVisible || !localNavigationAvailable(panels[active]) ||
|
||||
(message.hwnd!=terminalInput && message.hwnd!=panels[active].list) ||
|
||||
((GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) return false;
|
||||
auto &panel=panels[active];
|
||||
if(message.message==WM_KEYDOWN && message.wParam=='L' &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000))
|
||||
{
|
||||
if(!(message.lParam&(1LL<<30))) editPanelPath(panel);
|
||||
return true;
|
||||
}
|
||||
if(message.message!=WM_SYSKEYDOWN || !(message.lParam&(1LL<<29)) ||
|
||||
(GetKeyState(VK_CONTROL)&0x8000)) return false;
|
||||
if(message.wParam==VK_UP)
|
||||
navigateLocal(panel,panelParentPath(panel.directory,true));
|
||||
else if(message.wParam==VK_LEFT || message.wParam==VK_RIGHT)
|
||||
navigateLocalHistory(panel,message.wParam==VK_LEFT?-1:1);
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
constexpr wchar_t recentFoldersKey[]=L"RecentFolders";
|
||||
constexpr size_t recentFoldersLimit=100;
|
||||
|
||||
std::vector<fs::path> readRecentFolders()
|
||||
{
|
||||
const auto saved=readFilesJsonPreference(recentFoldersKey);
|
||||
std::vector<fs::path> folders;
|
||||
if(!saved || !saved->is_array()) return folders;
|
||||
for(const auto &entry:*saved)
|
||||
{
|
||||
if(!entry.is_string()) continue;
|
||||
const auto path=filePath(entry);
|
||||
if(!path.is_absolute() || path.native().find(L'\0')!=std::wstring::npos) continue;
|
||||
if(std::none_of(folders.begin(),folders.end(),[&](const auto &known){return sameLocalFolder(path,known);}))
|
||||
folders.push_back(path);
|
||||
if(folders.size()==recentFoldersLimit) break;
|
||||
}
|
||||
return folders;
|
||||
}
|
||||
|
||||
bool updateRecentFolders(const fs::path &path,bool remember)
|
||||
{
|
||||
const Handle lock{CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.RecentFolders")};
|
||||
if(!lock.value) return false;
|
||||
const auto wait=WaitForSingleObject(lock.value,100);
|
||||
if(wait!=WAIT_OBJECT_0 && wait!=WAIT_ABANDONED) return false;
|
||||
bool saved=false;
|
||||
try
|
||||
{
|
||||
auto folders=readRecentFolders();
|
||||
std::erase_if(folders,[&](const auto &known){return sameLocalFolder(path,known);});
|
||||
if(remember) folders.insert(folders.begin(),path);
|
||||
if(folders.size()>recentFoldersLimit) folders.resize(recentFoldersLimit);
|
||||
auto data=Json::array();
|
||||
for(const auto &folder:folders) data.push_back(ks::utf8(folder.native()));
|
||||
saved=writeFilesJsonPreference(recentFoldersKey,data);
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
ReleaseMutex(lock.value);
|
||||
return saved;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
constexpr DWORD maxFilesJsonBytes=1024*1024;
|
||||
|
||||
std::optional<Json> readFilesJsonPreference(const wchar_t *key)
|
||||
{
|
||||
DWORD bytes{};
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,key,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
|
||||
!bytes || bytes>maxFilesJsonBytes) return {};
|
||||
std::string data(bytes,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,key,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
|
||||
return {};
|
||||
try {return Json::parse(data.begin(),data.begin()+bytes);}
|
||||
catch(const std::exception &) {return {};}
|
||||
}
|
||||
|
||||
bool writeFilesJsonPreference(const wchar_t *key,const Json &value)
|
||||
{
|
||||
try
|
||||
{
|
||||
const auto data=value.dump();
|
||||
return data.size()<=maxFilesJsonBytes &&
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,key,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
|
||||
}
|
||||
catch(const std::exception &) {return false;}
|
||||
}
|
||||
+199
-46
@@ -740,13 +740,13 @@ class TextWindow
|
||||
{
|
||||
public:
|
||||
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const RemoteTextSource *backend,
|
||||
std::string_view fragment,TextOpenOptions options)
|
||||
std::string_view fragment,TextOpenOptions options,bool quickView=false)
|
||||
: original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()),
|
||||
edit(editable), draft(options.draft), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
edit(editable), draft(options.draft), embedded(quickView), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
search{dialogs}, previewFragment(fragment)
|
||||
{
|
||||
if (backend) remote=std::make_unique<RemoteTextFile>(*backend,original);
|
||||
else document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
|
||||
else if(!embedded) document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
|
||||
if(options.encoding!=TextEncoding::automatic)
|
||||
{
|
||||
newFormat.encoding=options.encoding;
|
||||
@@ -772,6 +772,7 @@ public:
|
||||
HWND window{}, editor{};
|
||||
bool handleKey(const MSG &message);
|
||||
void goToFragment(std::string_view fragment);
|
||||
void previewFile(const std::filesystem::path &path);
|
||||
std::filesystem::path original;
|
||||
const std::string peerId;
|
||||
|
||||
@@ -780,7 +781,7 @@ private:
|
||||
std::unique_ptr<TextDocument> document;
|
||||
std::wstring filename;
|
||||
bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{};
|
||||
bool draft{};
|
||||
bool draft{}, embedded{};
|
||||
TextSaveFormat newFormat;
|
||||
std::filesystem::path pendingSavePath;
|
||||
HICON smallIcon{},largeIcon{};
|
||||
@@ -862,6 +863,20 @@ private:
|
||||
static constexpr UINT_PTR openTimer = 2;
|
||||
static constexpr UINT_PTR previewTimer = 3;
|
||||
static constexpr UINT_PTR navigationTimer = 4;
|
||||
static constexpr UINT_PTR quickViewTimer = 5;
|
||||
struct QuickDocument
|
||||
{
|
||||
std::unique_ptr<TextDocument> document;
|
||||
std::string firstPage;
|
||||
std::optional<std::string> markdown;
|
||||
};
|
||||
std::future<QuickDocument> quickLoading;
|
||||
std::filesystem::path quickPath;
|
||||
uint64_t quickRequest{}, quickReading{};
|
||||
ULONGLONG quickReadyAt{};
|
||||
std::wstring quickError;
|
||||
std::optional<std::string> quickMarkdown;
|
||||
void pollQuickView();
|
||||
static constexpr UINT trimUndo = WM_APP + 1;
|
||||
static constexpr UINT previewFailed = WM_APP + 2;
|
||||
static constexpr UINT openPreviewLink = WM_APP + 3;
|
||||
@@ -890,7 +905,7 @@ private:
|
||||
void invalidateStatus() const;
|
||||
void invalidateHints() const;
|
||||
|
||||
void initializeDocument();
|
||||
void initializeDocument(std::optional<std::string> firstPage={});
|
||||
void finishOpen();
|
||||
void createMenu();
|
||||
void releaseMenu();
|
||||
@@ -906,7 +921,7 @@ private:
|
||||
void updateLineNumberMargin();
|
||||
void applyLineEnding();
|
||||
void installLexer();
|
||||
void loadPage(uint64_t index);
|
||||
void loadPage(uint64_t index,std::optional<std::string> cached={});
|
||||
void stagePage();
|
||||
void go(uint64_t index);
|
||||
void saveFile(bool closeWhenDone);
|
||||
@@ -1206,7 +1221,7 @@ void TextWindow::reloadPreferences()
|
||||
if (!fontChanged && profile == prefs) return;
|
||||
prefs = std::move(profile);
|
||||
filesFont = font;
|
||||
if (fontChanged)
|
||||
if (fontChanged && !embedded)
|
||||
{
|
||||
releaseMenu();
|
||||
createMenu();
|
||||
@@ -1294,9 +1309,9 @@ void TextWindow::applyLineEnding()
|
||||
send(SCI_SETEOLMODE, choices[prefs.lineEnding]);
|
||||
}
|
||||
|
||||
void TextWindow::loadPage(uint64_t index)
|
||||
void TextWindow::loadPage(uint64_t index,std::optional<std::string> cached)
|
||||
{
|
||||
auto data = document->readPage(index);
|
||||
auto data=cached?std::move(*cached):document->readPage(index);
|
||||
const auto offset = document->boundary(index);
|
||||
page = index;
|
||||
pageOffset = offset;
|
||||
@@ -1344,19 +1359,99 @@ void TextWindow::go(uint64_t index)
|
||||
loadPage(index);
|
||||
}
|
||||
|
||||
void TextWindow::initializeDocument()
|
||||
void TextWindow::initializeDocument(std::optional<std::string> firstPage)
|
||||
{
|
||||
automatic=detectLanguage(original,document->readPage(0));
|
||||
if(!firstPage) firstPage=document->readPage(0);
|
||||
automatic=detectLanguage(original,*firstPage);
|
||||
language=automatic;
|
||||
if(canPreview()) ShowWindow(editor,SW_HIDE);
|
||||
releaseMenu();
|
||||
createMenu();
|
||||
if(!embedded)
|
||||
{
|
||||
releaseMenu();
|
||||
createMenu();
|
||||
if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment});
|
||||
}
|
||||
installLexer();
|
||||
loadPage(0);
|
||||
if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment});
|
||||
loadPage(0,std::move(firstPage));
|
||||
updatePreview();
|
||||
}
|
||||
|
||||
std::string readMarkdownDocument(TextDocument &document)
|
||||
{
|
||||
std::string text;
|
||||
for(uint64_t index=0;index<document.pages();++index) text+=document.readPage(index);
|
||||
return text;
|
||||
}
|
||||
|
||||
void TextWindow::previewFile(const std::filesystem::path &path)
|
||||
{
|
||||
if(path==quickPath) return;
|
||||
quickPath=path;
|
||||
++quickRequest;
|
||||
quickReadyAt=GetTickCount64()+80;
|
||||
stopPreview(false,true);
|
||||
document.reset();
|
||||
quickMarkdown.reset();
|
||||
quickError.clear();
|
||||
layout();
|
||||
SetTimer(window,quickViewTimer,30,nullptr);
|
||||
}
|
||||
|
||||
void TextWindow::pollQuickView()
|
||||
{
|
||||
if(quickLoading.valid())
|
||||
{
|
||||
if(quickLoading.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
|
||||
const bool current=quickRequest==quickReading;
|
||||
try
|
||||
{
|
||||
auto loaded=quickLoading.get();
|
||||
if(current)
|
||||
{
|
||||
original=quickPath;
|
||||
filename=original.filename().wstring();
|
||||
document=std::move(loaded.document);
|
||||
quickMarkdown=std::move(loaded.markdown);
|
||||
initializeDocument(std::move(loaded.firstPage));
|
||||
}
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(current)
|
||||
{
|
||||
quickError=wide(error.what());
|
||||
document.reset();
|
||||
layout();
|
||||
}
|
||||
}
|
||||
if(current)
|
||||
{
|
||||
KillTimer(window,quickViewTimer);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if(quickPath.empty())
|
||||
{
|
||||
KillTimer(window,quickViewTimer);
|
||||
return;
|
||||
}
|
||||
if(GetTickCount64()<quickReadyAt) return;
|
||||
quickReading=quickRequest;
|
||||
std::packaged_task<QuickDocument()> task([path=quickPath] {
|
||||
auto source=std::make_unique<TextDocument>(path,false);
|
||||
auto first=source->readPage(0);
|
||||
if(first.find('\0')!=std::string::npos)
|
||||
throw std::runtime_error("Binary preview is unavailable.");
|
||||
std::optional<std::string> markdown;
|
||||
if(source->size()<=TextDocument::editLimit && detectLanguage(path,first).lexer=="markdown")
|
||||
markdown=readMarkdownDocument(*source);
|
||||
source->releaseReadHandle();
|
||||
return QuickDocument{std::move(source),std::move(first),std::move(markdown)};
|
||||
});
|
||||
quickLoading=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
}
|
||||
|
||||
void TextWindow::finishOpen()
|
||||
{
|
||||
if(!opening.valid() || opening.wait_for(std::chrono::milliseconds(0))!=std::future_status::ready) return;
|
||||
@@ -1602,6 +1697,12 @@ bool TextWindow::startPreviewBrowser()
|
||||
{
|
||||
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
|
||||
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
|
||||
if(embedded)
|
||||
{
|
||||
if(!ctrl || alt || key!='Q') return false;
|
||||
PostMessageW(GetParent(window),quickViewToggleMessage,0,0);
|
||||
return true;
|
||||
}
|
||||
if(!alt && ((ctrl && key=='F') || key==VK_F3))
|
||||
{
|
||||
const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0;
|
||||
@@ -1684,12 +1785,10 @@ void TextWindow::renderPreview(bool keepPosition)
|
||||
{
|
||||
applyMarkdownPreferences(loadTextPreferences().markdown);
|
||||
previewDeadline=GetTickCount64()+30000;
|
||||
previewText.clear();
|
||||
for(uint64_t index=0;index<document->pages();++index)
|
||||
previewText+=document->readPage(index);
|
||||
previewText=quickMarkdown?*quickMarkdown:readMarkdownDocument(*document);
|
||||
if(!remote) document->releaseReadHandle();
|
||||
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
|
||||
{"canSave",!remote || remote->revision.editable},
|
||||
{"canSave",!embedded && (!remote || remote->revision.editable)},{"compact",embedded},
|
||||
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
|
||||
{"keepPosition",keepPosition}};
|
||||
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
|
||||
@@ -1706,7 +1805,7 @@ void TextWindow::applyMarkdownPreferences(const MarkdownPreferences &preferences
|
||||
|
||||
void TextWindow::refreshPreview()
|
||||
{
|
||||
if(remote || !previewVisible || navigation.valid() || busy() || pendingTask || GetTickCount64()<nextFileCheck) return;
|
||||
if(embedded || remote || !previewVisible || navigation.valid() || busy() || pendingTask || GetTickCount64()<nextFileCheck) return;
|
||||
nextFileCheck=GetTickCount64()+350;
|
||||
const auto stamp=previewFileStamp();
|
||||
if(!stamp || stamp==previewStamp) return;
|
||||
@@ -1862,14 +1961,17 @@ void TextWindow::previewMessage(const std::wstring &value)
|
||||
PostMessageW(window,cycleWindow,message.value("reverse",false),0);
|
||||
return;
|
||||
}
|
||||
if(embedded && action!="image" && action!="rendered" && action!="failed") return;
|
||||
const auto revision=message.value("revision",previewRevision);
|
||||
if(embedded && revision!=previewRevision) return;
|
||||
if(action=="failed")
|
||||
{
|
||||
PostMessageW(window,previewFailed,0,0);
|
||||
PostMessageW(window,previewFailed,static_cast<WPARAM>(revision),0);
|
||||
return;
|
||||
}
|
||||
if(action=="rendered")
|
||||
{
|
||||
PostMessageW(window,previewRendered,0,0);
|
||||
PostMessageW(window,previewRendered,static_cast<WPARAM>(revision),0);
|
||||
return;
|
||||
}
|
||||
if(action=="save-task")
|
||||
@@ -2054,8 +2156,10 @@ void TextWindow::layout()
|
||||
RECT area{};
|
||||
GetClientRect(window, &area);
|
||||
const auto row = chromeHeight();
|
||||
MoveWindow(editor, 0, 2 * row, area.right, std::max(0L, area.bottom - 3 * row), TRUE);
|
||||
preview.layout({0,2*row,area.right,std::max<LONG>(2*row,area.bottom-row)},previewWanted);
|
||||
const int top=embedded?row:2*row;
|
||||
const LONG bottom=std::max<LONG>(top,area.bottom-(embedded?0:row));
|
||||
MoveWindow(editor,0,top,area.right,bottom-top,TRUE);
|
||||
preview.layout({0,top,area.right,bottom},previewWanted && (!embedded || previewVisible));
|
||||
ShowWindow(editor,document && !previewWanted?SW_SHOWNA:SW_HIDE);
|
||||
invalidate();
|
||||
}
|
||||
@@ -2121,6 +2225,24 @@ void TextWindow::paint()
|
||||
const auto row = chromeHeight();
|
||||
const auto brush = static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||||
SetDCBrushColor(dc, color(TextColor::background));
|
||||
if(embedded)
|
||||
{
|
||||
FillRect(dc,&client,brush);
|
||||
auto font=filesFont.font;
|
||||
font.lfHeight=-MulDiv(filesFont.tenthsOfPoint,GetDpiForWindow(window),720);
|
||||
const auto chromeFont=CreateFontIndirectW(&font);
|
||||
std::wstring label=L"Quick View";
|
||||
if(!quickPath.empty()) label+=L" · "+quickPath.filename().native();
|
||||
if(!quickError.empty()) label+=L" · "+quickError;
|
||||
else if(quickPath.empty()) label+=L" · Select a local text file";
|
||||
else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…";
|
||||
else if(!previewVisible && pageTotal>1) label+=L" · First page";
|
||||
drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg),
|
||||
color(TextColor::chrome),scale(6),label);
|
||||
if(chromeFont) DeleteObject(chromeFont);
|
||||
EndPaint(window,&paint);
|
||||
return;
|
||||
}
|
||||
const RECT body{0,2*row,client.right,std::max<LONG>(2*row,client.bottom-row)};
|
||||
FillRect(dc, &body, brush);
|
||||
SetDCBrushColor(dc, color(TextColor::chromebg));
|
||||
@@ -2339,6 +2461,7 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
|
||||
bool TextWindow::handleKey(const MSG &message)
|
||||
{
|
||||
if(embedded) return false;
|
||||
const auto key = message.wParam;
|
||||
if (message.hwnd != editor) return false;
|
||||
if (message.message == WM_SYSKEYDOWN && (message.lParam & (1LL << 29)))
|
||||
@@ -2387,7 +2510,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
const auto &state=*static_cast<const std::shared_ptr<TextWindow> *>(create->lpCreateParams);
|
||||
state->window=window;
|
||||
textWindows.emplace(window,state);
|
||||
textWindowOrder.push_back(window);
|
||||
if(!state->embedded) textWindowOrder.push_back(window);
|
||||
}
|
||||
const auto found=textWindows.find(window);
|
||||
if(found==textWindows.end()) return DefWindowProcW(window,message,wparam,lparam);
|
||||
@@ -2428,7 +2551,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
MSG key{child,msg,wp,lp};
|
||||
if(state->handleKey(key)) return 0;
|
||||
}
|
||||
if(msg==WM_XBUTTONUP && !state->edit)
|
||||
if(msg==WM_XBUTTONUP && !state->edit && !state->embedded)
|
||||
{
|
||||
SendMessageW(state->window,WM_COMMAND,
|
||||
GET_XBUTTON_WPARAM(wp)==XBUTTON1?historyBack:historyForward,0);
|
||||
@@ -2447,9 +2570,13 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
state->remote->download(state->edit,[state](uint64_t,uint64_t){return !state->cancelOpen;});
|
||||
});
|
||||
}
|
||||
else if(self->embedded) self->applyPreferences();
|
||||
else self->initializeDocument();
|
||||
self->updateIcons(GetDpiForWindow(window));
|
||||
self->updateTaskbarGroup();
|
||||
if(!self->embedded)
|
||||
{
|
||||
self->updateIcons(GetDpiForWindow(window));
|
||||
self->updateTaskbarGroup();
|
||||
}
|
||||
self->layout();
|
||||
return 0;
|
||||
case WM_ERASEBKGND: return 1;
|
||||
@@ -2465,10 +2592,10 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
self->layout();
|
||||
return 0;
|
||||
}
|
||||
case WM_SETFOCUS: self->focusContent(); return 0;
|
||||
case WM_SETFOCUS: if(!self->embedded) self->focusContent(); return 0;
|
||||
case cycleWindow: cycleTextWindows(window,wparam!=0); return 0;
|
||||
case WM_KEYDOWN:
|
||||
if(self->previewWanted && !self->previewVisible)
|
||||
if(!self->embedded && self->previewWanted && !self->previewVisible)
|
||||
{
|
||||
if(wparam==VK_F6) self->toggleMode();
|
||||
if(wparam==VK_ESCAPE || wparam==VK_F10 ||
|
||||
@@ -2476,13 +2603,15 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
case previewFailed: self->stopPreview(); return 0;
|
||||
case previewFailed:
|
||||
if(!self->embedded || !wparam || wparam==self->previewRevision) self->stopPreview();
|
||||
return 0;
|
||||
case savePreviewTask: self->startMarkdownTask(); return 0;
|
||||
case previewRendered:
|
||||
if(self->previewWanted)
|
||||
if(self->previewWanted && (!self->embedded || wparam==self->previewRevision))
|
||||
{
|
||||
self->previewVisible=true;
|
||||
self->syncNavigation();
|
||||
if(!self->embedded) self->syncNavigation();
|
||||
self->layout();
|
||||
if(GetForegroundWindow()==window) self->focusContent();
|
||||
}
|
||||
@@ -2511,6 +2640,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
return 0;
|
||||
}
|
||||
case WM_COMMAND:
|
||||
if(self->embedded) return 0;
|
||||
if (LOWORD(wparam) >= 600 && LOWORD(wparam) < 605) self->openMenu(LOWORD(wparam) - 600);
|
||||
else self->command(LOWORD(wparam));
|
||||
return 0;
|
||||
@@ -2526,6 +2656,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
if (wparam == openTimer) self->finishOpen();
|
||||
if (wparam == previewTimer) self->pollImages();
|
||||
if (wparam == navigationTimer) self->finishNavigation();
|
||||
if (wparam == quickViewTimer) self->pollQuickView();
|
||||
return 0;
|
||||
case trimUndo:
|
||||
if (self->undoBytes >= 32 * TextDocument::pageBytes)
|
||||
@@ -2538,7 +2669,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
if(self->cancelNavigation) *self->cancelNavigation=true;
|
||||
self->updateTaskbarGroup(true);
|
||||
if(!self->embedded) self->updateTaskbarGroup(true);
|
||||
self->stopPreview(false);
|
||||
self->releaseMenu();
|
||||
return 0;
|
||||
@@ -2552,7 +2683,8 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
self->search.style.message(window, wide(error.what()).c_str());
|
||||
if(self->embedded) self->quickError=wide(error.what());
|
||||
else self->search.style.message(window, wide(error.what()).c_str());
|
||||
self->invalidate();
|
||||
return message == WM_CREATE ? -1 : 0;
|
||||
}
|
||||
@@ -2711,6 +2843,37 @@ HWND findOpenDocument(const std::filesystem::path &path,std::string_view id)
|
||||
return search.match;
|
||||
}
|
||||
|
||||
bool registerTextWindowClass(HINSTANCE instance)
|
||||
{
|
||||
static const bool registered=[instance]
|
||||
{
|
||||
WNDCLASSW type{};
|
||||
type.hInstance=instance;
|
||||
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
|
||||
type.hIcon=LoadIconW(instance,MAKEINTRESOURCEW(1));
|
||||
type.lpfnWndProc=TextWindow::procedure;
|
||||
type.lpszClassName=windowClass;
|
||||
return Scintilla_RegisterClasses(instance) && RegisterClassW(&type);
|
||||
}();
|
||||
return registered;
|
||||
}
|
||||
|
||||
HWND createQuickView(HWND owner,TextDialogs dialogs)
|
||||
{
|
||||
const auto instance=GetModuleHandleW(nullptr);
|
||||
if(!registerTextWindowClass(instance)) return nullptr;
|
||||
auto state=std::make_shared<TextWindow>(std::filesystem::path{},false,dialogs,nullptr,
|
||||
std::string_view{},TextOpenOptions{},true);
|
||||
return CreateWindowExW(0,windowClass,L"Quick View",WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
|
||||
0,0,0,0,owner,reinterpret_cast<HMENU>(158),instance,&state);
|
||||
}
|
||||
|
||||
void previewQuickViewFile(HWND window,const std::filesystem::path &path)
|
||||
{
|
||||
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
|
||||
preview->second->previewFile(path);
|
||||
}
|
||||
|
||||
static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options)
|
||||
{
|
||||
@@ -2733,17 +2896,7 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool
|
||||
}
|
||||
|
||||
const auto instance=GetModuleHandleW(nullptr);
|
||||
static const bool registered=[instance]
|
||||
{
|
||||
WNDCLASSW type{};
|
||||
type.hInstance=instance;
|
||||
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
|
||||
type.hIcon=LoadIconW(instance,MAKEINTRESOURCEW(1));
|
||||
type.lpfnWndProc=TextWindow::procedure;
|
||||
type.lpszClassName=windowClass;
|
||||
return Scintilla_RegisterClasses(instance) && RegisterClassW(&type);
|
||||
}();
|
||||
if(!registered) throw std::runtime_error("Cannot register the text window.");
|
||||
if(!registerTextWindowClass(instance)) throw std::runtime_error("Cannot register the text window.");
|
||||
auto state=std::make_shared<TextWindow>(original,edit,dialogs,backend,fragment,options);
|
||||
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
|
||||
(backend?backend->name+L" · ":std::wstring{})+path.wstring();
|
||||
|
||||
@@ -80,6 +80,10 @@ struct RemoteTextSource
|
||||
const RemoteTextRevision &)> upload;
|
||||
};
|
||||
|
||||
inline constexpr UINT quickViewToggleMessage=WM_APP+31;
|
||||
HWND createQuickView(HWND owner,TextDialogs dialogs);
|
||||
void previewQuickViewFile(HWND window,const std::filesystem::path &path);
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false,
|
||||
TextOpenOptions options={});
|
||||
|
||||
@@ -89,7 +89,8 @@ try {
|
||||
Open-Picker $side
|
||||
$rows = @(Read-Picker)
|
||||
$row = [Array]::IndexOf($rows, 'FTP')
|
||||
if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'KSwitcher LAN') {
|
||||
if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'Recent folders' -or
|
||||
$rows[$row + 2] -cne 'KSwitcher LAN') {
|
||||
throw "Source groups are missing separators in panel $side."
|
||||
}
|
||||
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$row, $null)
|
||||
@@ -98,12 +99,14 @@ try {
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
|
||||
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row }
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
|
||||
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 1 }
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
|
||||
Wait-Until {
|
||||
$selected = [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32()
|
||||
$selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 1)
|
||||
$selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 2)
|
||||
}
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]38, [IntPtr]::Zero)
|
||||
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row }
|
||||
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 1 }
|
||||
[void][FilesDriveShortcutTest]::SendMessage($picker, 407, [IntPtr]($row - 2), $null)
|
||||
$bitmap = Render-Picker
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
param(
|
||||
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe"
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class FilesQuickViewProbe {
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr parent, int id);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
public static bool Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return true;
|
||||
keybd_event(0x12, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(0x12, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
return GetForegroundWindow() == window;
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
function Wait-Until([scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 100; $attempt++) {
|
||||
if (& $Condition) { return }
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
throw "Timed out waiting for: $Condition"
|
||||
}
|
||||
|
||||
$exe = (Resolve-Path $Executable).Path
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$names = 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
|
||||
$saved = @{}
|
||||
foreach ($name in $names) {
|
||||
if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) }
|
||||
}
|
||||
$fixture = [IO.Directory]::CreateTempSubdirectory('ks-files-quick-view-')
|
||||
try {
|
||||
$left = $fixture.CreateSubdirectory('left')
|
||||
$right = $fixture.CreateSubdirectory('right')
|
||||
$document = Join-Path $left.FullName 'preview.txt'
|
||||
[IO.File]::WriteAllText($document, 'Quick View fixture')
|
||||
$key.SetValue('LeftWide', 1, 'DWord')
|
||||
$key.SetValue('RightWide', 1, 'DWord')
|
||||
$key.SetValue('LeftPath', $left.FullName, 'String')
|
||||
$key.SetValue('RightPath', $right.FullName, 'String')
|
||||
$key.SetValue('LeftCursor', $document, 'String')
|
||||
$key.DeleteValue('RightCursor', $false)
|
||||
$key.DeleteValue('WindowPlacement', $false)
|
||||
|
||||
$process = Start-Process -FilePath $exe -PassThru
|
||||
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
|
||||
$window = $process.MainWindowHandle
|
||||
Wait-Until { [FilesQuickViewProbe]::Activate($window) }
|
||||
$keyboard = New-Object -ComObject WScript.Shell
|
||||
$leftList = [FilesQuickViewProbe]::GetDlgItem($window, 102)
|
||||
$rightList = [FilesQuickViewProbe]::GetDlgItem($window, 103)
|
||||
$rightHeading = [FilesQuickViewProbe]::GetDlgItem($window, 141)
|
||||
$rightPath = [FilesQuickViewProbe]::GetDlgItem($window, 143)
|
||||
if (!($leftList -and $rightList -and $rightHeading -and $rightPath)) {
|
||||
throw 'Expected both file panels in the test window.'
|
||||
}
|
||||
Wait-Until { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) }
|
||||
$keyboard.SendKeys('^q')
|
||||
Wait-Until {
|
||||
$hostWindow = [FilesQuickViewProbe]::GetDlgItem($window, 158)
|
||||
$hostWindow -ne [IntPtr]::Zero -and [FilesQuickViewProbe]::IsWindowVisible($hostWindow)
|
||||
}
|
||||
foreach ($control in $rightList, $rightHeading, $rightPath) {
|
||||
if ([FilesQuickViewProbe]::IsWindowVisible($control)) {
|
||||
throw 'A file panel control can draw over the Quick View content.'
|
||||
}
|
||||
}
|
||||
if (![FilesQuickViewProbe]::IsWindowVisible($leftList)) { throw 'Quick View hid the source panel.' }
|
||||
|
||||
$keyboard.SendKeys('^q')
|
||||
Wait-Until { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero }
|
||||
foreach ($control in $rightList, $rightHeading, $rightPath) {
|
||||
if (![FilesQuickViewProbe]::IsWindowVisible($control)) {
|
||||
throw 'A file panel control remained hidden after closing Quick View.'
|
||||
}
|
||||
}
|
||||
'Quick View hides the covered list and chrome, then restores the same controls.'
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) {
|
||||
[void]$process.CloseMainWindow()
|
||||
if (!$process.WaitForExit(3000)) { $process.Kill(); $process.WaitForExit() }
|
||||
}
|
||||
foreach ($name in $names) {
|
||||
if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) }
|
||||
else { $key.DeleteValue($name, $false) }
|
||||
}
|
||||
$key.Dispose()
|
||||
$path = [IO.Path]::GetFullPath($fixture.FullName)
|
||||
if ([IO.Path]::GetDirectoryName($path) -eq [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath()) -and
|
||||
[IO.Path]::GetFileName($path).StartsWith('ks-files-quick-view-')) {
|
||||
[IO.Directory]::Delete($path, $true)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user