Compare commits

..
15 changed files with 1156 additions and 123 deletions

No files matched your search

+5
View File
@@ -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)
+27 -1
View File
@@ -438,6 +438,11 @@ Warning і початковий фокус на No.
Результати відкриваються в тій самій панелі з відносними шляхами.
Enter або подвійний клік відкриває папку й ставить курсор на файл.
Esc у результатах повертає вихідну папку, курсор і позначки.
У результатах F3/F4 відкривають файл, а F5/F6 працюють із позначеними
або поточним файлом, використовуючи папку іншої панелі як призначення.
F8 і Shift+Delete використовують звичайні підтвердження. Успішно
переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
з тією самою маскою й видимістю прихованих файлів.
- Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів
у відкритих локальних папках. Фокус залишається там, де був, а курсор
@@ -479,7 +484,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 поточний шлях відображається по центру верхньої подвійної лінії панелі. Довгий шлях скорочується в межах панелі.
## Спільні елементи діалогів
+12
View File
@@ -420,3 +420,15 @@ BEGIN
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
+4
View File
@@ -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; }
+5 -4
View File
@@ -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;
+10 -4
View File
@@ -54,6 +54,14 @@ INT_PTR CALLBACK findFilesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
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())
@@ -66,10 +74,8 @@ void findLocalFiles(HWND owner,Panel &panel)
setStatus(L"Wait for the current scan to finish.");
return;
}
Panel::FindOptions options;
auto options=panel.findOrigin?panel.findOrigin->options:Panel::FindOptions{};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner,
findFilesDialog,reinterpret_cast<LPARAM>(&options))!=IDOK) return;
cancelFolderSizes(panel);
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)};
startDirectoryScan(panel);
startFileSearch(panel,std::move(options));
}
+4 -11
View File
@@ -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)
+330 -54
View File
@@ -331,12 +331,77 @@ FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDir
}
constexpr auto schemeKey = L"Software\\KSwitcher\\Files";
#include "files_registry_json.inl"
#include "files_ftp.inl"
fs::path panelParentPath(const fs::path &directory,bool local)
{
if(!directory.has_relative_path()) return {};
const auto parent=directory.parent_path();
if(parent==directory) return {};
if(local && directory.root_name().native().starts_with(L"\\\\") && !parent.has_relative_path())
return {}; // A UNC share is a browsing root.
return parent;
}
bool sameLocalFolder(const fs::path &a,const fs::path &b)
{
return CompareStringOrdinal(a.c_str(),-1,b.c_str(),-1,TRUE)==CSTR_EQUAL;
}
bool inLocalBranch(const fs::path &ancestor,fs::path directory)
{
while(!directory.empty())
{
if(sameLocalFolder(ancestor,directory)) return true;
directory=panelParentPath(directory,true);
}
return false;
}
#include "files_recent_folders.inl"
struct LocalNavigation
{
std::vector<fs::path> history;
size_t current{};
fs::path previousBranch;
void opened(const fs::path &directory,std::optional<size_t> position)
{
if(!history.empty())
{
const auto &previous=history[current];
if(sameLocalFolder(previous,directory)) return;
if(inLocalBranch(directory,previous))
{
if(!inLocalBranch(previous,previousBranch)) previousBranch=previous;
}
else if(!inLocalBranch(directory,previousBranch)) previousBranch.clear();
}
if(position && *position<history.size() && sameLocalFolder(history[*position],directory))
{
current=*position;
return;
}
if(!history.empty()) history.erase(history.begin()+current+1,history.end());
history.push_back(directory);
current=history.size()-1;
}
std::optional<size_t> neighbor(int direction) const
{
if(direction<0) return current?std::optional<size_t>(current-1):std::nullopt;
return current+1<history.size()?std::optional<size_t>(current+1):std::nullopt;
}
};
struct Panel
{
HWND path{}, list{}, heading{};
fs::path directory;
LocalNavigation navigation;
std::optional<FilesPeer> peer;
std::optional<FtpProfile> ftp;
struct DirectoryWatch
@@ -370,6 +435,7 @@ struct Panel
struct FindOptions { std::wstring mask=L"*"; bool includeHidden{}; };
struct FindOrigin
{
FindOptions options;
fs::path cursor;
std::set<fs::path> marks;
LRESULT row{}, top{};
@@ -385,6 +451,7 @@ struct Panel
std::shared_ptr<ElevatedHelper> elevated;
std::optional<FtpProfile> ftp;
std::optional<FindOptions> find;
std::optional<size_t> navigationPosition;
};
struct ScanResult
{
@@ -439,6 +506,10 @@ std::wstring panelCaption(const Panel &panel)
}
Panel panels[2];
HWND quickViewWindow{};
int quickViewSource{};
void refreshQuickView(const Panel &panel);
void toggleQuickView(HWND owner);
FilesTerminal terminal;
std::mutex pendingTerminalOutputMutex;
std::string pendingTerminalOutput;
@@ -490,6 +561,13 @@ std::vector<size_t> commandAccessPositions;
std::vector<int> commandActions;
int menuIndex{};
bool commandPicker{};
struct FolderPicker
{
const wchar_t *caption;
std::vector<fs::path> paths;
bool recent{};
};
std::optional<FolderPicker> folderPicker;
constexpr int defaultSizeWidth=6, defaultFontPoints=110;
constexpr bool defaultWide=false, defaultAlignExtensions=true, defaultShowDetails=true, defaultAlignFolders=false;
constexpr DWORD defaultStatusFields=15;
@@ -902,6 +980,7 @@ void showMenu(bool show);
void hidePicker()
{
if (!picker || !IsWindowVisible(picker)) return;
folderPicker.reset();
KillTimer(GetParent(picker),driveQueryTimer);
driveQueries.clear();
ShowWindow(picker,SW_HIDE);
@@ -1086,6 +1165,7 @@ void swapPanels(HWND window)
// Move the controls with their contents to retain the cursor and scroll position.
std::swap(panels[0],panels[1]);
active=1-active;
if(quickViewWindow) quickViewSource=1-quickViewSource;
for(auto &command:terminalCommands)
if(command.panel>=0) command.panel=1-command.panel;
for(int i=0;i<2;++i)
@@ -1153,12 +1233,15 @@ void layout(HWND window,bool activeOnly)
place(panels[i].path, x + 5, 4, std::max(0, end - x - 10), textHeight);
int headingHeight=panels[i].wide?textHeight:0;
const int listWidth=std::max(0,end-x-8-scrollBarWidth(panels[i].list));
const bool panelVisible=!terminalVisible && (!quickViewWindow || i==quickViewSource);
ShowWindow(panels[i].path,panelVisible?SW_SHOWNA:SW_HIDE);
ShowWindow(panels[i].list,panelVisible?SW_SHOWNA:SW_HIDE);
place(panels[i].heading,x+5,textHeight+10,listWidth,headingHeight);
ShowWindow(panels[i].heading,!terminalVisible && panels[i].wide?SW_SHOWNA:SW_HIDE);
ShowWindow(panels[i].heading,panelVisible && panels[i].wide?SW_SHOWNA:SW_HIDE);
place(panels[i].list, x + 5, textHeight+10+headingHeight,listWidth,
std::max(0, panelBottom-textHeight-10-headingHeight));
place(panels[i].selectionSummary,x+8,panelBottom+4,std::max(0,end-x-16),summaryHeight);
ShowWindow(panels[i].selectionSummary,summaryHeight?SW_SHOWNA:SW_HIDE);
ShowWindow(panels[i].selectionSummary,panelVisible && summaryHeight?SW_SHOWNA:SW_HIDE);
}
place(menuBar,0,0,width,textHeight+4);
const int menuEdges[]{0,7,15,27,38,46};
@@ -1210,6 +1293,14 @@ void layout(HWND window,bool activeOnly)
const int right=((i+1)*unit+refreshExtra)*width/total;
place(commands[i],left,height-textHeight,right-left,textHeight);
}
if(quickViewWindow)
{
const int left=quickViewSource==0?middle+2:0;
const int right=quickViewSource==0?width:middle-2;
SetWindowPos(quickViewWindow,nullptr,left+5,4,std::max(0,right-left-10),
std::max(0,panelBottom+summaryHeight+textHeight),SWP_NOZORDER|SWP_NOACTIVATE);
ShowWindow(quickViewWindow,terminalVisible?SW_HIDE:SW_SHOWNA);
}
if(IsWindowVisible(panelSearchPopup)) placePanelSearch(window);
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
}
@@ -1247,11 +1338,6 @@ bool stopDirectoryScan()
void showTerminal(HWND owner,bool show)
{
terminalVisible=show;
for(const auto &panel:panels)
{
ShowWindow(panel.path,show?SW_HIDE:SW_SHOWNA);
ShowWindow(panel.list,show?SW_HIDE:SW_SHOWNA);
}
layout(owner);
SetFocus(terminalInput);
}
@@ -1296,6 +1382,7 @@ void invalidatePanelCursorChange(HWND list,LRESULT previous)
void activatePanel(int index)
{
if(quickViewWindow && index!=quickViewSource) return;
const auto previous=active;
active=index;
showFileDetails(panels[index]);
@@ -1626,12 +1713,15 @@ void copyCommandLineOrPanelNames(HWND owner)
else copyPanelNames(owner);
}
void startFileSearch(Panel &panel,Panel::FindOptions options);
void refreshPanel(Panel &panel)
{
cancelFolderSizes(panel);
panel.folderSizes.clear();
updateSelectionSummary(panel);
open(panel,panel.directory,false);
if(panel.findOrigin) startFileSearch(panel,panel.findOrigin->options);
else open(panel,panel.directory,false);
}
std::wstring powerShellPath(const fs::path &path)
@@ -2018,6 +2108,7 @@ void updateSelectionSummary(const Panel &panel)
void showFileDetails(const Panel &panel)
{
refreshQuickView(panel);
if(&panel==&panels[active] && showDirectoryScanProgress(panels[active])) return;
if(panel.findOrigin)
{
@@ -2276,11 +2367,14 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
if(finding)
{
if(!panel.findOrigin)
panel.findOrigin=Panel::FindOrigin{previousSelection,std::move(markedPaths),previousRow,previousTop};
{
panel.findOrigin=Panel::FindOrigin{*request.find,previousSelection,std::move(markedPaths),previousRow,previousTop};
previousSelection.clear();
previousRow=previousTop=0;
markedPaths.clear();
}
panel.findOrigin->options=std::move(*request.find);
panel.findOrigin->error=error;
previousSelection.clear();
previousRow=previousTop=0;
markedPaths.clear();
}
else if(panel.findOrigin)
{
@@ -2293,6 +2387,12 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
}
panel.findOrigin.reset();
}
if(peer || request.ftp) panel.navigation={};
else if(!finding)
{
panel.navigation.opened(directory,request.navigationPosition);
if(!sameDirectory && !panel.directory.empty() && !partial) updateRecentFolders(directory,true);
}
panel.directory = directory;
panel.peer=std::move(peer);
panel.ftp=std::move(request.ftp);
@@ -2314,7 +2414,8 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
panel.marked.clear();
panel.fileExtensionLength=panel.folderExtensionLength=0;
const bool profiles=ftpProfileList(panel);
const bool hasParent=!finding && directory.has_relative_path();
const auto parent=finding?fs::path{}:panelParentPath(directory,!panel.peer && !panel.ftp);
const bool hasParent=!parent.empty();
const auto rowCount=profiles?ftpProfiles.size():folders.size()+files.size()+hasParent;
panel.rows.reserve(rowCount);
panel.sizes.reserve(rowCount);
@@ -2349,7 +2450,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
}
else
{
if(hasParent) add(directory.parent_path(),L"..",true);
if(hasParent) add(parent,L"..",true);
for(const auto &folder:folders) add(folder,L"["+folder.filename().wstring()+L"]",true);
for(const auto &file:files) add(file,finding?file.lexically_relative(directory).native():file.filename().native(),false);
}
@@ -2384,6 +2485,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
if(visible) SendMessageW(panel.list,WM_SETREDRAW,TRUE,0);
InvalidateRect(panel.list,nullptr,FALSE);
updateSelectionSummary(panel);
refreshQuickView(panel);
if(finding && &panel==&panels[active]) showFileDetails(panel);
else if(partial && &panel==&panels[active])
setStatus(L"Partial: "+std::to_wstring(folders.size()+files.size()));
@@ -2415,13 +2517,14 @@ void startDirectoryScan(Panel &panel)
}
void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional<FilesPeer> peer,
fs::path selection={},fs::path fallback={},std::optional<FtpProfile> ftp={})
fs::path selection={},fs::path fallback={},std::optional<FtpProfile> ftp={},
std::optional<size_t> navigationPosition={})
{
if(directory.empty() && !ftp) return;
if(directory!=panel.directory || !samePanelSource(panel,peer,ftp))
cancelFolderSizes(panel);
panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback),
std::move(peer),offerElevation,statusRevision,{},std::move(ftp)};
std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition};
if(panel.scan.valid())
{
panel.scanSuperseded=true;
@@ -2759,19 +2862,31 @@ void runActivePeerAction(HWND owner,bool update)
}
LRESULT ftpDriveRow() {return static_cast<LRESULT>(drivePaths.size())+1;}
LRESULT recentDriveRow() {return ftpDriveRow()+1;}
void showRecentFolders(int side);
bool selectablePickerRow(LRESULT row)
{
if(row<0) return false;
if(folderPicker) return static_cast<size_t>(row)<folderPicker->paths.size();
if(commandPicker)
return static_cast<size_t>(row)<commandActions.size() && commandActions[row]>=0;
return row<static_cast<LRESULT>(drivePaths.size()) || row==ftpDriveRow() || remoteDriveRows.contains(row);
return row<static_cast<LRESULT>(drivePaths.size()) || row==ftpDriveRow() || row==recentDriveRow() ||
remoteDriveRows.contains(row);
}
void selectDrive()
{
auto row=SendMessageW(picker,LB_GETCURSEL,0,0);
if(!selectablePickerRow(row)) return;
if(folderPicker)
{
const auto path=folderPicker->paths[row];
auto &panel=panels[pickerPanel];
hidePicker();
openOn(panel,path,true,{});
return;
}
if(commandPicker) row=commandActions[row];
const auto remote=remoteDriveRows.find(row);
hidePicker();
@@ -2791,6 +2906,7 @@ void selectDrive()
else if(menuIndex==2 && (row==6 || row==7)) runActivePeerAction(owner,row==7);
else if(menuIndex==2 && row==8) compareSelectedFiles(owner);
else if(menuIndex==2 && row==9) findLocalFiles(owner,panels[active]);
else if(menuIndex==2 && row==10) toggleQuickView(owner);
else
{
const int command=menuIndex==1?113+static_cast<int>(row):110+static_cast<int>(row);
@@ -2809,6 +2925,7 @@ void selectDrive()
}
else setStatus(L"Cannot load saved FTP connections.");
}
else if(row==recentDriveRow()) showRecentFolders(pickerPanel);
else if(remote!=remoteDriveRows.end())
{
const auto &choice=remote->second;
@@ -2819,6 +2936,37 @@ void selectDrive()
LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
{
if(folderPicker && folderPicker->recent && msg==WM_KEYDOWN && wp==VK_DELETE)
{
const auto row=SendMessageW(window,LB_GETCURSEL,0,0);
if(!selectablePickerRow(row)) return 0;
auto &paths=folderPicker->paths;
if(!updateRecentFolders(paths[row],false))
{
setStatus(L"Could not remove the recent folder.");
return 0;
}
paths.erase(paths.begin()+row);
SendMessageW(window,LB_DELETESTRING,row,0);
if(paths.empty())
{
hidePicker();
setStatus(L"No recent local folders.");
}
else SendMessageW(window,LB_SETCURSEL,std::min(row,static_cast<LRESULT>(paths.size()-1)),0);
return 0;
}
if(folderPicker && msg==WM_LBUTTONUP)
{
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
const auto result=DefSubclassProc(window,msg,wp,lp);
if(folderPicker && !HIWORD(hit) && selectablePickerRow(LOWORD(hit)))
{
SendMessageW(window,LB_SETCURSEL,LOWORD(hit),0);
selectDrive();
}
return result;
}
if(msg==WM_KEYDOWN && (wp==VK_UP || wp==VK_DOWN))
{
const auto count=SendMessageW(window,LB_GETCOUNT,0,0);
@@ -2846,7 +2994,7 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT
if(!HIWORD(hit) && !selectablePickerRow(LOWORD(hit))) return 0;
}
if(msg==WM_CAPTURECHANGED) driveWakeAction.cancel();
if(!commandPicker && (msg==WM_LBUTTONDOWN || msg==WM_LBUTTONUP || msg==WM_LBUTTONDBLCLK))
if(!commandPicker && !folderPicker && (msg==WM_LBUTTONDOWN || msg==WM_LBUTTONUP || msg==WM_LBUTTONDBLCLK))
{
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
const int row=HIWORD(hit)?-1:LOWORD(hit);
@@ -2868,7 +3016,7 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT
return 0;
}
}
if(!commandPicker && msg==WM_CHAR)
if(!commandPicker && !folderPicker && msg==WM_CHAR)
{
const auto key=towupper(static_cast<wchar_t>(wp));
LRESULT row=LB_ERR;
@@ -2892,7 +3040,7 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT
return 0;
}
}
if(!commandPicker && (msg==WM_MOUSEMOVE || msg==WM_MOUSELEAVE))
if(!commandPicker && !folderPicker && (msg==WM_MOUSEMOVE || msg==WM_MOUSELEAVE))
{
int row=-1;
if(msg==WM_MOUSEMOVE)
@@ -2903,7 +3051,7 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT
if(!HIWORD(hit))
{
const auto choice=remoteDriveRows.find(LOWORD(hit));
if(LOWORD(hit)<drivePaths.size() || LOWORD(hit)==ftpDriveRow() ||
if(LOWORD(hit)<drivePaths.size() || LOWORD(hit)==ftpDriveRow() || LOWORD(hit)==recentDriveRow() ||
(choice!=remoteDriveRows.end() && !choice->second.path &&
driveWakeAction.hit(window,LOWORD(hit),lp,cellWidth)))
row=LOWORD(hit);
@@ -3027,7 +3175,7 @@ void showRemoteDrives(bool focus=false,int initialRow=0)
auto selection=SendMessageW(picker,LB_GETCURSEL,0,0);
std::optional<DriveChoice> previous;
if(auto row=remoteDriveRows.find(selection);row!=remoteDriveRows.end()) previous=row->second;
if(selection>ftpDriveRow()) selection=-1;
if(selection>recentDriveRow()) selection=-1;
if(focus) selection=initialRow;
const auto top=SendMessageW(picker,LB_GETTOPINDEX,0,0);
for(auto count=SendMessageW(picker,LB_GETCOUNT,0,0);count>static_cast<LRESULT>(drivePaths.size());--count)
@@ -3040,6 +3188,7 @@ void showRemoteDrives(bool focus=false,int initialRow=0)
};
add(L"");
add(L"FTP");
add(L"Recent folders");
add(L"KSwitcher LAN");
if(!drivePeerLookupError.empty()) add(L" "+drivePeerLookupError);
else if(driveQueries.empty()) add(L" No paired computers");
@@ -3082,7 +3231,7 @@ void showRemoteDrives(bool focus=false,int initialRow=0)
void pollDriveQueries(HWND owner)
{
if(commandPicker || !IsWindowVisible(picker))
if(commandPicker || folderPicker || !IsWindowVisible(picker))
{
KillTimer(owner,driveQueryTimer);
driveQueries.clear();
@@ -3150,6 +3299,8 @@ void pollDriveQueries(HWND owner)
void chooseDrive(int index,bool fromMenu)
{
if(quickViewWindow && index!=quickViewSource) toggleQuickView(GetParent(picker));
folderPicker.reset();
commandPicker=false;
if (!fromMenu) showMenu(false);
pickerPanel=index;
@@ -3304,6 +3455,53 @@ ks::files::TextDialogs textWindowDialogs()
},chooseTextSaveOptions};
}
void refreshQuickView(const Panel &panel)
{
if(!quickViewWindow || &panel!=&panels[quickViewSource]) return;
const auto row=currentPanelRow(panel);
const bool file=!panel.peer && !panel.ftp && row!=LB_ERR &&
panel.sizes[row]!=L"Folder" && panel.sizes[row]!=L"Up";
ks::files::previewQuickViewFile(quickViewWindow,file?panel.rows[row]:fs::path{});
}
void toggleQuickView(HWND owner)
{
if(quickViewWindow)
{
DestroyWindow(std::exchange(quickViewWindow,nullptr));
layout(owner);
restoreCommandFocus();
return;
}
const auto &panel=panels[active];
if(panel.peer || panel.ftp || terminalVisible)
{
setStatus(L"Quick View requires a visible local file pane.");
return;
}
try {quickViewWindow=ks::files::createQuickView(owner,textWindowDialogs());}
catch(const std::exception &) {}
if(!quickViewWindow)
{
setStatus(L"Could not open Quick View.");
return;
}
quickViewSource=active;
refreshQuickView(panel);
layout(owner);
}
bool handleQuickViewKey(HWND window,const MSG &message)
{
if(message.message!=WM_KEYDOWN || message.wParam!='Q' || terminalVisible ||
!commandLineAvailable(window) ||
!(GetKeyState(VK_CONTROL)&0x8000) ||
((GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
return false;
if(!(message.lParam&(1LL<<30))) toggleQuickView(window);
return true;
}
ks::files::RemoteTextSource ftpTextSource(const FtpProfile &profile);
void openSelectedText(const Panel &panel, bool edit, bool external)
@@ -3994,10 +4192,14 @@ CopyDestination validateCopyDestination(CopyRequest request,const std::wstring &
throw std::runtime_error(ks::utf8(L"The destination folder is unavailable."));
const bool sameHost=(!peer && !request.sourcePeer) ||
(peer && request.sourcePeer && peer->id==request.sourcePeer->id);
const bool sameFolder=sameHost && (peer?
CompareStringOrdinal(destination.c_str(),-1,sourceDirectory.c_str(),-1,TRUE)==CSTR_EQUAL:
fs::equivalent(destination,sourceDirectory,error));
if(request.newName.empty() && sameFolder)
const bool containsDestination=sameHost && request.newName.empty() &&
std::any_of(request.sources.begin(),request.sources.end(),[&](const auto &path)
{
const auto parent=path.parent_path();
return peer?CompareStringOrdinal(destination.c_str(),-1,parent.c_str(),-1,TRUE)==CSTR_EQUAL:
fs::equivalent(destination,parent,error);
});
if(containsDestination)
throw std::runtime_error(ks::utf8(L"Open a different folder in the other panel, or enter a new name for a single item."));
return {std::move(request.destination),std::move(request.newName),useSourcePeer};
}
@@ -4233,7 +4435,7 @@ struct CopyProgress
HWND window{};
std::atomic_bool canceled{};
bool closeOwner{};
bool move{};
bool move{}, fileSourcesOnly{};
int conflictChoice{};
ConflictMode conflictMode{};
bool askReadOnly=true;
@@ -4979,6 +5181,8 @@ bool countCopy(CopyHost &host,const fs::path &path,CopyProgress &progress)
const auto info=host.stat(path,progress.canceled);
if(!info || (info->attributes&FILE_ATTRIBUTE_REPARSE_POINT))
throw std::system_error(info?ERROR_NOT_SUPPORTED:ERROR_FILE_NOT_FOUND,std::system_category());
if(progress.fileSourcesOnly && (info->attributes&FILE_ATTRIBUTE_DIRECTORY))
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
if(!(info->attributes&FILE_ATTRIBUTE_DIRECTORY))
{
++progress.totalFiles;
@@ -5045,6 +5249,8 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
const auto incoming=hosts.source.stat(from,progress.canceled);
if(!incoming || (incoming->attributes&FILE_ATTRIBUTE_REPARSE_POINT))
throw std::system_error(incoming?ERROR_NOT_SUPPORTED:ERROR_FILE_NOT_FOUND,std::system_category());
if(progress.fileSourcesOnly && (incoming->attributes&FILE_ATTRIBUTE_DIRECTORY))
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
const auto moveOnHost=[&](const fs::path &target,bool replace)
{
@@ -5168,15 +5374,53 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
return transfer(to,true,mode==ConflictMode::append);
}
void pruneSearchResults(Panel &panel,const std::set<fs::path> &removed)
{
if(!panel.findOrigin || removed.empty()) return;
const bool visible=IsWindowVisible(panel.list);
if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0);
const auto cursor=currentPanelRow(panel);
LRESULT next=cursor;
for(size_t row=panel.rows.size();row>0;)
{
--row;
const auto &path=panel.rows[row];
if(!removed.contains(path)) continue;
panel.timestamps.erase(path);
SendMessageW(panel.list,LB_DELETESTRING,row,0);
panel.rows.erase(panel.rows.begin()+row);
panel.sizes.erase(panel.sizes.begin()+row);
panel.dimmed.erase(panel.dimmed.begin()+row);
panel.marked.erase(panel.marked.begin()+row);
if(static_cast<LRESULT>(row)<cursor) --next;
}
if(cursor!=LB_ERR && !panel.rows.empty())
SendMessageW(panel.list,LB_SETCURSEL,std::min(next,static_cast<LRESULT>(panel.rows.size()-1)),0);
if(visible) SendMessageW(panel.list,WM_SETREDRAW,TRUE,0);
InvalidateRect(panel.list,nullptr,FALSE);
updateSelectionSummary(panel);
}
void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
{
if(source.findOrigin || destination.findOrigin)
{
setStatus(L"Open the folder before copying or moving files.");
return;
}
const auto sourceFtp=source.ftp;
const bool ftpRename=move && sourceFtp && !ftpProfileList(source);
if(quickViewWindow && &destination!=&panels[quickViewSource] && !ftpRename)
{
setStatus(L"Close Quick View to use the destination pane.");
return;
}
if(destination.findOrigin && !ftpRename)
{
setStatus(L"Open a destination folder in the other panel before copying or moving files.");
return;
}
if(source.findOrigin && source.scanRequest)
{
setStatus(L"Wait for the search to finish.");
return;
}
const bool fromSearch=source.findOrigin.has_value();
const auto destinationFtp=ftpRename?sourceFtp:destination.ftp;
const bool ftp=sourceFtp || destinationFtp;
if(ftp && !ftpRename && (move || (sourceFtp && destinationFtp) || source.peer || destination.peer ||
@@ -5221,6 +5465,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
const bool sameHost=!ftp && peerId(request.sourcePeer)==peerId(targetPeer);
CopyProgress progress;
progress.move=move;
progress.fileSourcesOnly=fromSearch;
progress.conflictMode=request.conflictMode;
progress.askReadOnly=request.askReadOnly;
FilesModalDialog progressDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(103),owner,
@@ -5238,7 +5483,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
progressDialog.show();
bool failed=false, skipped=false;
size_t copied=0;
std::set<fs::path> results;
std::set<fs::path> results, removed;
std::wstring failure;
std::vector<fs::path> lockPaths;
try
@@ -5303,6 +5548,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
if(outcome==CopyResult::failed) { failed=true; break; }
if(outcome==CopyResult::skipped) { skipped=true; continue; }
++copied;
if(move && fromSearch) removed.insert(path);
results.insert(progress.renamedTarget.empty()?to:progress.renamedTarget);
progress.ui.invoke([&] {
const auto row=std::find(source.rows.begin(),source.rows.end(),path);
@@ -5341,9 +5587,10 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
}
if(move)
{
open(source,source.directory);
if(fromSearch) pruneSearchResults(source,removed);
else open(source,source.directory);
if(!ftpRename) open(destination,destination.directory);
if(renamed && copied && (sameHost || ftpRename))
if(!fromSearch && renamed && copied && (sameHost || ftpRename))
{
const auto renamedPath=progress.renamedTarget.empty()?
targetDirectory/request.newName:progress.renamedTarget;
@@ -5353,7 +5600,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
else
{
auto &updated=renameInSource?source:destination;
if(updated.directory==targetDirectory)
if(!updated.findOrigin && updated.directory==targetDirectory)
open(updated,updated.directory);
}
if(!results.empty())
@@ -5532,9 +5779,10 @@ INT_PTR CALLBACK deleteProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM
void deleteSelection(HWND owner,Panel &panel,bool permanent)
{
if(panel.findOrigin)
const bool fromSearch=panel.findOrigin.has_value();
if(fromSearch && panel.scanRequest)
{
setStatus(L"Open the folder before making changes.");
setStatus(L"Wait for the search to finish.");
return;
}
if(ftpProfileList(panel)) return;
@@ -5548,7 +5796,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
for(size_t i=0;i<shown;++i)
{
if(i) entries+=L"\r\n";
entries+=paths[i].filename().wstring();
entries+=fromSearch?paths[i].lexically_relative(panel.directory).native():paths[i].filename().native();
}
if(shown<paths.size()) entries+=L"\r\n…and "+std::to_wstring(paths.size()-shown)+L" more";
const auto instance=GetModuleHandleW(nullptr);
@@ -5587,7 +5835,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
int readOnlyChoice=0;
std::vector<std::vector<fs::path>> groups;
std::wstring failure, sharingFailure;
std::set<fs::path> lockPaths;
std::set<fs::path> lockPaths, removed;
const auto recordFailure=[&](const std::system_error &error,const fs::path &path)
{
++failed;
@@ -5617,7 +5865,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
{
if(canceled) break;
auto &group=groups.emplace_back(1,path);
if(permanent)
if(permanent && !fromSearch)
{
try
{
@@ -5679,7 +5927,9 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
bool readOnly=false;
try
{
const auto info=permanent?host.stat(current,canceled):std::optional<FileInfo>{};
const auto info=(permanent || fromSearch)?host.stat(current,canceled):std::optional<FileInfo>{};
if(fromSearch && info && (info->attributes&FILE_ATTRIBUTE_DIRECTORY))
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
const auto attributes=info?info->attributes:INVALID_FILE_ATTRIBUTES;
if(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_READONLY) &&
!(attributes&FILE_ATTRIBUTE_DIRECTORY))
@@ -5724,6 +5974,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
}
else host.remove(current,permanent,attributes,readOnly);
++done;
if(!panel.peer && !ftp) removed.insert(current);
}
catch(const std::system_error &e)
{
@@ -5742,7 +5993,10 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
progressDialog.close();
for(auto &visible:panels)
if(!visible.directory.empty()) open(visible,visible.directory);
{
if(visible.findOrigin) pruneSearchResults(visible,removed);
else if(!visible.directory.empty()) open(visible,visible.directory);
}
SetFocus(panel.list);
const auto summary=(canceled?L"Deletion canceled. ":L"Deletion finished. ")+
std::to_wstring(done)+(permanent?L" deleted, ":L" moved to Recycle Bin, ")+
@@ -6374,6 +6628,7 @@ void openMenu(HWND window, int index)
return;
}
menuIndex=index;
folderPicker.reset();
commandPicker=true;
SendMessageW(picker,LB_RESETCONTENT,0,0);
std::vector<std::wstring> rows;
@@ -6390,13 +6645,14 @@ void openMenu(HWND window, int index)
rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts",
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4",
L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(),
L"Find files\tAlt+F7"};
L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q"};
}
commandActions.clear();
if(index==2)
{
commandActions={0,3,-1,1,2,4,5,8};
if(!panels[active].peer && !panels[active].ftp) commandActions.insert(commandActions.begin()+1,9);
if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10);
if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7});
}
else
@@ -6601,10 +6857,13 @@ void submitTerminalReturn(HWND owner,bool shift)
handleFilesReturn(shift);
}
#include "files_path_navigation.inl"
LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
{
if(message==filesPreferencesChanged)
{
if(quickViewWindow) SendNotifyMessageW(quickViewWindow,message,wp,lp);
if(reinterpret_cast<HWND>(wp)!=window)
{
loadFilesPreferences(window);
@@ -6646,6 +6905,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
drivePeerReplyReceived=true;
return TRUE;
}
case ks::files::quickViewToggleMessage:
if(quickViewWindow && !copyInProgress && !FilesModalDialog::activeFor(window)) toggleQuickView(window);
return 0;
case directoryScanReady:
if(!FilesModalDialog::activeFor(window)) collectDirectoryScans();
return 0;
@@ -6737,7 +6999,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
for (int i = 0; i < 2; ++i)
{
auto &panel = panels[i];
panel.path = CreateWindowW(L"STATIC", L"", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | SS_OWNERDRAW,
panel.path = CreateWindowW(L"STATIC", L"", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | SS_OWNERDRAW | SS_NOTIFY,
0, 0, 0, 0, window, reinterpret_cast<HMENU>(142 + static_cast<INT_PTR>(i)), instance, nullptr);
panel.list = CreateWindowExW(0, L"LISTBOX", L"",
WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS,
@@ -6757,6 +7019,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
openOn(panel,saved.is_absolute()?saved:root,false,{},savedPanelPath(panelCursorKeys[i]),
saved.is_absolute() && saved!=root?root:fs::path{});
SetWindowSubclass(panel.list, panelKeys, 1, 0);
SetWindowSubclass(panel.path,pathBarInput,1,0);
installScrollBar(panel.list,window,firstPanelScrollBar+i);
}
SetFocus(panels[0].list);
@@ -6856,7 +7119,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
const RECT divider{box.left+1,box.bottom-2,box.right-1,box.bottom-1};
box.bottom=std::max(box.bottom,details.bottom+6);
FrameRect(dc,&box,border);
paintScrollPosition(window,dc,panel.list,colors[PanelBlue]);
if(IsWindowVisible(panel.list)) paintScrollPosition(window,dc,panel.list,colors[PanelBlue]);
InflateRect(&box,-3,-3);
FrameRect(dc,&box,border);
FillRect(dc,&divider,border);
@@ -6929,6 +7192,12 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
RECT column{x,middle,x+1,bounds.bottom};
FillRect(item.hDC,&column,lineBrush);
}
const bool highlighted=static_cast<int>(item.CtlID)-142==active;
if(localNavigationAvailable(panel))
{
paintLocalPath(item.hDC,bounds,panel,highlighted);
return TRUE;
}
if(path.empty()) return TRUE;
const int saved=SaveDC(item.hDC);
SelectObject(item.hDC,mono);
@@ -6937,7 +7206,6 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
const auto width=std::min(bounds.right-bounds.left,text.cx+2L*cellWidth);
bounds.left+=(bounds.right-bounds.left-width)/2;
bounds.right=bounds.left+width;
const bool highlighted=static_cast<int>(item.CtlID)-142==active;
FillRect(item.hDC,&bounds,highlighted?teal:blue);
const auto padding=std::min(static_cast<LONG>(cellWidth),width/4);
InflateRect(&bounds,-padding,0);
@@ -6967,7 +7235,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
if(item.hwndItem==pickerFrame || item.hwndItem==completionFrame)
{
const bool driveFrame=item.hwndItem==pickerFrame && !commandPicker;
const bool driveFrame=item.hwndItem==pickerFrame && !commandPicker && !folderPicker;
auto border=CreateSolidBrush(driveFrame?RGB(255,255,255):colors[Frame]);
const auto box=paintDialogFrame(item.hDC,item.rcItem,
dialogFrameMetrics(GetDpiForWindow(window)),teal,border);
@@ -6990,6 +7258,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
paintDialogFrameCaptions(item.hDC,item.rcItem,box,L"Change drive",teal,colors[Text],mono);
}
if(item.hwndItem==pickerFrame && folderPicker)
paintDialogFrameCaptions(item.hDC,item.rcItem,box,folderPicker->caption,teal,colors[Text],mono,
folderPicker->recent?L"Del Remove":nullptr);
const auto list=item.hwndItem==pickerFrame?picker:completionList;
paintScrollPosition(item.hwndItem,item.hDC,list,colors[Dialog]);
DeleteObject(border);
@@ -7027,7 +7298,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
const bool popupRow=item.hwndItem==picker || item.hwndItem==completionList;
auto background=item.CtlType==ODT_BUTTON?Footer:popupRow?Dialog:PanelBlue;
auto foreground=colors[Text];
if(item.hwndItem==picker && ((commandPicker && item.itemID<commandActions.size() && commandActions[item.itemID]<0) ||
if(item.hwndItem==picker && !folderPicker && ((commandPicker && item.itemID<commandActions.size() && commandActions[item.itemID]<0) ||
(!commandPicker && item.itemID==drivePaths.size())))
{
FillRect(item.hDC,&item.rcItem,teal);
@@ -7037,7 +7308,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
FillRect(item.hDC,&line,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
return TRUE;
}
if(item.hwndItem==picker && !commandPicker && item.itemID==ftpDriveRow()+1)
if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID==recentDriveRow()+1)
{
auto row=item.rcItem;
FillRect(item.hDC,&row,teal);
@@ -7080,7 +7351,10 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
}
auto shortcut=text.find(L'\t');
if(item.hwndItem==picker && commandPicker && item.itemID<commandAccessPositions.size())
if(item.hwndItem==picker && folderPicker)
paintDialogListRow(item.hDC,item.rcItem,text.c_str(),mono,foreground,rowBackground,
dialogRowTextInset(cellWidth),DT_PATH_ELLIPSIS|DT_END_ELLIPSIS);
else if(item.hwndItem==picker && commandPicker && item.itemID<commandAccessPositions.size())
{
auto labelRect=item.rcItem, keyRect=item.rcItem;
SelectObject(item.hDC,mono);
@@ -7096,7 +7370,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
paintMenuLabel(item.hDC,labelRect,text.substr(0,shortcut),commandAccessPositions[item.itemID],
colors[Text],colors[background]);
}
else if(item.hwndItem==picker && !commandPicker && item.itemID<drivePaths.size())
else if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID<drivePaths.size())
{
SelectObject(item.hDC,mono);
SetTextColor(item.hDC,foreground);
@@ -7136,7 +7410,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
SetBkMode(item.hDC,OPAQUE);
}
else if(item.hwndItem==picker && !commandPicker && item.itemID>=drivePaths.size())
else if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID>=drivePaths.size())
{
auto bounds=item.rcItem;
RECT button{};
@@ -7310,6 +7584,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
remoteCommandThread.request_stop();
remoteCommandThread.join();
}
if(quickViewWindow) DestroyWindow(std::exchange(quickViewWindow,nullptr));
ks::files::textWindowOwnerClosed();
return 0;
}
@@ -7395,6 +7670,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
if(message.hwnd==window && message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST &&
GetFocus()==terminalInput)
message.hwnd=terminalInput;
if(handleQuickViewKey(window,message) || handleLocalPathKey(window,message)) continue;
if(message.hwnd==terminalInput && message.message==WM_KEYDOWN &&
!(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_SHIFT)&0x8000) &&
!(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) &&
+383
View File
@@ -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;
}
+41
View File
@@ -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;
}
+25
View File
@@ -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
View File
@@ -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 &notice)
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();
+4
View File
@@ -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={});
+6 -3
View File
@@ -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 {
+101
View File
@@ -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)
}
}