Compare commits

..
13 changed files with 562 additions and 83 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)
+11
View File
@@ -484,6 +484,17 @@ Warning і початковий фокус на No.
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
- **Commands → Quick View** або **Ctrl+Q** вмикає перегляд локального
тексту й Markdown у сусідній панелі. Перегляд слідує за курсором активної
панелі. Повторна команда повертає сусідній каталог, курсор і позначки.
Під час перегляду файлові операції з призначенням у сусідній панелі
пропонують спершу закрити Quick View.
- **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує
останні відвідані локальні папки. Повторний візит підіймає один запис
угору, порядок зберігається після перезапуску. Enter або клік відкриває
шлях у панелі, з якої викликали меню. Delete прибирає вибраний запис.
- У локальному заголовку кнопки ← та → переходять назад і вперед
в історії відповідної панелі. Стрілка ↑, Alt+↑ та рядок `..`
відкривають безпосередню батьківську папку. На корені стрілка вимкнена,
+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;
+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)
+140 -17
View File
@@ -331,6 +331,7 @@ 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"
@@ -359,6 +360,8 @@ bool inLocalBranch(const fs::path &ancestor,fs::path directory)
return false;
}
#include "files_recent_folders.inl"
struct LocalNavigation
{
std::vector<fs::path> history;
@@ -503,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;
@@ -554,7 +561,12 @@ std::vector<size_t> commandAccessPositions;
std::vector<int> commandActions;
int menuIndex{};
bool commandPicker{};
struct FolderPicker { const wchar_t *caption; std::vector<fs::path> paths; };
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;
@@ -1153,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)
@@ -1220,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};
@@ -1277,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);
}
@@ -1314,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);
}
@@ -1363,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]);
@@ -2088,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)
{
@@ -2367,7 +2388,11 @@ 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);
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);
@@ -2460,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()));
@@ -2836,6 +2862,8 @@ 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)
{
@@ -2843,7 +2871,8 @@ bool selectablePickerRow(LRESULT row)
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()
@@ -2877,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);
@@ -2895,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;
@@ -2905,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);
@@ -2989,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);
@@ -3113,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)
@@ -3126,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");
@@ -3236,6 +3299,7 @@ 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);
@@ -3391,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)
@@ -5294,6 +5405,11 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
{
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.");
@@ -6529,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
@@ -6746,6 +6863,7 @@ 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);
@@ -6787,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;
@@ -6998,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);
@@ -7138,7 +7259,8 @@ 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);
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);
@@ -7186,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 && !folderPicker && item.itemID==ftpDriveRow()+1)
if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID==recentDriveRow()+1)
{
auto row=item.rcItem;
FillRect(item.hDC,&row,teal);
@@ -7462,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;
}
@@ -7547,7 +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(handleLocalPathKey(window,message)) continue;
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) &&
+17 -2
View File
@@ -264,13 +264,13 @@ void editPanelPath(Panel &panel)
navigateLocal(panel,prompt.result);
}
void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<fs::path> paths,RECT anchor)
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)};
folderPicker=FolderPicker{caption,std::move(paths),recent};
SendMessageW(picker,LB_RESETCONTENT,0,0);
size_t longest=wcslen(caption);
for(const auto &path:folderPicker->paths)
@@ -295,6 +295,21 @@ void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<fs:
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);
+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)
}
}