Compare commits

...
6 changed files with 517 additions and 39 deletions

No files matched your search

+22
View File
@@ -204,6 +204,17 @@ Warning і початковий фокус на No.
Незбережені зміни у примусово закритих вікнах втрачаються.
Закриття процесів і результат записуються до `kswitcher.log`.
- У файловій панелі Ctrl+C копіює позначені або поточний локальний
елемент у файловий буфер Windows. Ctrl+V вставляє файли й папки в
поточний локальний каталог через звичайний діалог Copy і показує
конфлікти та прогрес. Клік або навігація у файловій панелі вибирають
файловий контекст. Клік у командному рядку або введення тексту
повертають текстовий контекст Ctrl+C / Ctrl+V.
- **Commands → Copy full path** або **Ctrl+Shift+C** копіює повний шлях
файла чи папки під курсором як текст. У LAN- і FTP-панелях текст включає
адресу віддаленого джерела. Для рядка `..` команда не змінює буфер.
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
курсора командного рядка або замінює виділення. Подвійні лапки додаються
лише до шляхів із пробілами. На рядку `..` вставляється шлях папки,
@@ -544,6 +555,17 @@ Warning і початковий фокус на No.
- Розкриті списки й історія Far використовують спільний попап із бірюзовим тлом, світлою рамкою та чорним вибраним рядком. Попап прилягає до обох країв бірюзового поля, стрілка лишається праворуч за межами списку. Історія групується за датами. Довгі списки прокручуються, Enter вибирає рядок, Escape закриває список і повертає фокус до поля.
- Повторно використовуй спільне оформлення. Текст, дії та стан операції передавай із коду конкретної операції. Наприклад, Warning повертає відповідь і стан прапорця, а копіювання вирішує, чи застосувати відповідь до наступних конфліктів.
## Перетягування файлів
- Перетягування з Explorer або іншої локальної панелі відкриває діалог
Drop files із повним шляхом призначення та кнопками Copy, Move і Cancel.
Якщо курсор над папкою, призначенням є ця папка. В інших випадках
призначенням є поточна папка панелі. Cancel або Esc скасовує дію.
- Copy і Move відкривають наявний діалог операції з її параметрами,
перевіркою призначення, розв’язанням конфліктів і прогресом. Віддалені
панелі, результати пошуку й віртуальні елементи Explorer без локального
шляху не підтримують перетягування. Files повідомляє причину в рядку стану.
## Діалог Copy
- Вирівнюй підпис Existing files по вертикальному центру списку. Ширше поле списку починається ближче до підпису, а його правий край збігається з правим краєм поля імені.
+239
View File
@@ -0,0 +1,239 @@
constexpr UINT panelDropReady=WM_APP+33;
struct PanelDrop
{
HWND source{}, target{};
fs::path directory, destination;
std::vector<fs::path> paths;
};
std::optional<PanelDrop> pendingPanelDrop;
HWND draggingPanel{};
std::optional<POINT> panelDragStart;
bool localDropPanel(const Panel &panel)
{
return !panel.peer && !panel.ftp && !panel.findOrigin && panel.directory.is_absolute();
}
LRESULT panelRowAt(HWND window,POINT point,LRESULT top,LRESULT count)
{
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,MAKELPARAM(point.x,point.y));
// LB_ITEMFROMPOINT only returns the low 16 bits of the row index.
constexpr LRESULT rowRange=1<<16;
auto row=(top&~(rowRange-1))|LOWORD(hit);
if(row<top) row+=rowRange;
RECT bounds{};
return !HIWORD(hit) && row>=0 && row<count &&
SendMessageW(window,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&bounds))!=LB_ERR &&
PtInRect(&bounds,point)?row:LB_ERR;
}
FORMATETC fileDropFormat()
{
return {CF_HDROP,nullptr,DVASPECT_CONTENT,-1,TYMED_HGLOBAL};
}
template<class Interface,class Derived>
class DragInterface : public Interface
{
public:
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void **out) override
{
if(!out) return E_POINTER;
*out=nullptr;
if(iid!=IID_IUnknown && iid!=__uuidof(Interface)) return E_NOINTERFACE;
*out=static_cast<Interface *>(this);
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE AddRef() override {return ++references;}
ULONG STDMETHODCALLTYPE Release() override
{
const auto count=--references;
if(!count) delete static_cast<Derived *>(this);
return count;
}
private:
ULONG references{1};
};
class PanelDropTarget final : public DragInterface<IDropTarget,PanelDropTarget>
{
public:
explicit PanelDropTarget(HWND window) : target(window) {}
HRESULT STDMETHODCALLTYPE DragEnter(IDataObject *data,DWORD,POINTL,DWORD *effect) override
{
auto format=fileDropFormat();
filesystem=data->QueryGetData(&format)==S_OK;
return updateEffect(effect);
}
HRESULT STDMETHODCALLTYPE DragOver(DWORD,POINTL,DWORD *effect) override
{
return updateEffect(effect);
}
HRESULT STDMETHODCALLTYPE DragLeave() override
{
filesystem=false;
return S_OK;
}
HRESULT STDMETHODCALLTYPE Drop(IDataObject *data,DWORD,POINTL location,DWORD *effect) override
{
updateEffect(effect);
filesystem=false;
if(*effect==DROPEFFECT_NONE) return S_OK;
*effect=DROPEFFECT_NONE;
auto format=fileDropFormat();
STGMEDIUM medium{};
if(FAILED(data->GetData(&format,&medium)))
{
setStatus(L"Could not read local paths from the drop.");
return S_OK;
}
std::vector<fs::path> paths;
try
{
if(medium.tymed==TYMED_HGLOBAL) paths=ks::fileDropPaths(medium.hGlobal);
}
catch(const std::exception &) {}
ReleaseStgMedium(&medium);
if(paths.empty())
{
setStatus(L"The drop contains no usable file or folder paths.");
return S_OK;
}
try
{
const auto &panel=panels[GetDlgCtrlID(target)-102];
POINT point{location.x,location.y};
ScreenToClient(target,&point);
const auto row=panelRowAt(target,point,SendMessageW(target,LB_GETTOPINDEX,0,0),
static_cast<LRESULT>(panel.rows.size()));
const auto &destination=row!=LB_ERR && panel.sizes[row]==L"Folder"?panel.rows[row]:panel.directory;
pendingPanelDrop=PanelDrop{draggingPanel,target,panel.directory,destination,std::move(paths)};
if(PostMessageW(GetParent(target),panelDropReady,0,0))
{
// Files performs the requested move after confirmation.
*effect=DROPEFFECT_COPY;
}
else pendingPanelDrop.reset();
}
catch(const std::exception &)
{
setStatus(L"Could not prepare the drop.");
}
return S_OK;
}
private:
HRESULT updateEffect(DWORD *effect)
{
const auto allowed=*effect;
*effect=DROPEFFECT_NONE;
if(!filesystem || !(allowed&DROPEFFECT_COPY))
setStatus(L"Drag files or folders from a Windows filesystem.");
else if(target==draggingPanel)
setStatus(L"Drop files onto the other panel.");
else if(!localDropPanel(panels[GetDlgCtrlID(target)-102]))
setStatus(L"Open a local folder in the destination panel before dropping files.");
else if(!copyInProgress && !pendingPanelDrop && !FilesModalDialog::activeFor(GetParent(target)))
*effect=DROPEFFECT_COPY;
return S_OK;
}
HWND target;
bool filesystem{};
};
class PanelDragSource final : public DragInterface<IDropSource,PanelDragSource>
{
public:
HRESULT STDMETHODCALLTYPE QueryContinueDrag(BOOL escape,DWORD keys) override
{
if(escape) return DRAGDROP_S_CANCEL;
return keys&MK_LBUTTON?S_OK:DRAGDROP_S_DROP;
}
HRESULT STDMETHODCALLTYPE GiveFeedback(DWORD) override {return DRAGDROP_S_USEDEFAULTCURSORS;}
};
void beginPanelDrag(HWND window)
{
auto &panel=panels[GetDlgCtrlID(window)-102];
if(!localDropPanel(panel))
{
setStatus(L"Drag files or folders from an open local folder.");
return;
}
auto paths=selectedPanelPaths(panel);
if(paths.empty()) return;
std::vector<PCIDLIST_ABSOLUTE> items;
items.reserve(paths.size());
const auto clear=[&](void *){for(auto item:items) CoTaskMemFree(const_cast<PIDLIST_ABSOLUTE>(item));};
const std::unique_ptr<void,decltype(clear)> cleanup(&items,clear);
for(const auto &path:paths)
{
PIDLIST_ABSOLUTE item{};
if(FAILED(SHParseDisplayName(path.c_str(),nullptr,&item,0,nullptr)))
{
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
return;
}
items.push_back(item);
}
IShellItemArray *array{};
if(FAILED(SHCreateShellItemArrayFromIDLists(static_cast<UINT>(items.size()),items.data(),&array)))
{
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
return;
}
IDataObject *data{};
const auto result=array->BindToHandler(nullptr,BHID_DataObject,IID_PPV_ARGS(&data));
array->Release();
if(FAILED(result))
{
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
return;
}
const auto source=new(std::nothrow) PanelDragSource;
if(source)
{
draggingPanel=window;
DWORD effect{};
DoDragDrop(data,source,DROPEFFECT_COPY,&effect);
draggingPanel=nullptr;
source->Release();
}
data->Release();
}
void performPanelDrop(HWND owner)
{
if(!pendingPanelDrop) return;
auto drop=std::move(*pendingPanelDrop);
pendingPanelDrop.reset();
auto index=GetDlgCtrlID(drop.target)-102;
if(index<0 || index>=static_cast<int>(std::size(panels))) return;
auto &panel=panels[index];
if(!localDropPanel(panel) || panel.directory!=drop.directory || !IsWindowVisible(drop.target))
{
setStatus(L"The destination panel changed. Drop the files again.");
return;
}
if(copyInProgress || FilesModalDialog::activeFor(owner))
{
setStatus(L"Finish the current operation before dropping files.");
return;
}
const auto text=L"Destination folder:\r\n"+drop.destination.native();
const auto answer=showFilesNotice(owner,text.c_str(),L"Drop files",
{.tone=FilesNoticeTone::neutral,.chooseTransfer=true});
if(answer!=IDYES && answer!=IDNO) return;
auto &source=drop.source?panels[GetDlgCtrlID(drop.source)-102]:panel;
activatePanel(index);
panelClipboardContext=true;
copySelection(owner,source,panel,answer==IDNO,std::move(drop.paths),std::move(drop.destination));
}
+181 -39
View File
@@ -508,6 +508,7 @@ std::wstring panelCaption(const Panel &panel)
Panel panels[2];
HWND quickViewWindow{};
int quickViewSource{};
bool panelClipboardContext=true;
void refreshQuickView(const Panel &panel);
void toggleQuickView(HWND owner);
FilesTerminal terminal;
@@ -647,7 +648,7 @@ struct FilesNoticeOptions
bool *remember{};
FilesNoticeTone tone{FilesNoticeTone::dialog};
bool processes{};
bool saveChanges{};
bool saveChanges{}, chooseTransfer{};
};
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={});
void openMenu(HWND window, int index);
@@ -1661,12 +1662,18 @@ void clearTerminalSelection()
terminalView.post(L"clear-selection");
}
bool copyFilesText(HWND owner,const std::wstring &value,const wchar_t *failure)
{
try {ks::writeClipboard(owner,ks::textClip(value));}
catch(const std::exception &) {setStatus(failure);return false;}
return true;
}
void copyTerminalText(HWND owner)
{
const auto value=terminalSelection.empty()?terminalInputText():terminalSelection;
if(value.empty()) return;
try { ks::writeClipboard(owner,ks::textClip(value)); }
catch(const std::exception &) { setStatus(L"Could not copy terminal text."); }
copyFilesText(owner,value,L"Could not copy terminal text.");
}
LRESULT currentPanelRow(const Panel &panel)
@@ -1703,8 +1710,46 @@ void copyPanelNames(HWND owner)
names+=path.filename().native();
}
if(names.empty()) return;
try { ks::writeClipboard(owner,ks::textClip(names)); }
catch(const std::exception &) { setStatus(L"Could not copy file names."); }
copyFilesText(owner,names,L"Could not copy file names.");
}
void copyPanelFiles(HWND owner,const Panel &panel)
{
if(panel.peer || panel.ftp)
{
setStatus(L"File clipboard copy requires local files.");
return;
}
const auto paths=selectedPanelPaths(panel);
if(paths.empty()) return;
try
{
ks::writeClipboard(owner,ks::fileDropClip(paths));
setStatus(std::to_wstring(paths.size())+(paths.size()==1?L" item copied":L" items copied")+L" to the file clipboard.");
}
catch(const std::exception &) {setStatus(L"Could not copy files to the clipboard.");}
}
void copyFullPanelPath(HWND owner,const Panel &panel)
{
const auto row=currentPanelRow(panel);
if(row==LB_ERR || panel.sizes[row]==L"Up" || ftpProfileList(panel)) return;
const auto &path=panel.rows[row];
auto value=path.native();
if(panel.ftp)
{
const auto &profile=*panel.ftp;
const auto host=profile.host.find(L':')!=std::wstring::npos && !profile.host.starts_with(L"[")?
L"["+profile.host+L"]":profile.host;
value=L"FTP "+host+L":"+std::to_wstring(profile.port)+L" · "+ftpPath(path);
}
else if(panel.peer)
{
auto host=panel.peer->name;
if(!panel.peer->address.empty()) host+=L" ("+ks::wide(panel.peer->address)+L")";
value=host+L" · "+value;
}
if(copyFilesText(owner,value,L"Could not copy the full path.")) setStatus(L"Full path copied.");
}
void copyCommandLineOrPanelNames(HWND owner)
@@ -1996,6 +2041,7 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U
if(message==WM_KILLFOCUS) resetCompletion();
if(message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN)
{
panelClipboardContext=false;
clearTerminalSelection();
hideCompletion();
}
@@ -2040,7 +2086,11 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U
}
if(message==WM_KEYDOWN && !terminalVisible && wp==VK_TAB)
{
if(plainPanelTab()) activatePanel(1-active);
if(plainPanelTab())
{
panelClipboardContext=true;
activatePanel(1-active);
}
return 0;
}
if(message==WM_KEYDOWN && !terminalVisible &&
@@ -2907,6 +2957,7 @@ void selectDrive()
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 if(menuIndex==2 && row==11) copyFullPanelPath(owner,panels[active]);
else
{
const int command=menuIndex==1?113+static_cast<int>(row):110+static_cast<int>(row);
@@ -3571,7 +3622,7 @@ struct CopyRequest
std::future<CopyDestination> validation;
std::wstring ftpDestination;
bool upload{};
bool ftpRename{};
bool ftpRename{}, externalSources{};
};
bool directoryExists(const FilesPeer *peer,const fs::path &path)
@@ -4185,9 +4236,10 @@ CopyDestination validateCopyDestination(CopyRequest request,const std::wstring &
else request.newName.clear();
}
const auto sourceDirectory=request.sources.front().parent_path();
const auto destination=request.move || request.newName.empty()?request.destination:sourceDirectory;
const bool renameInSource=!request.externalSources && !request.move && !request.newName.empty();
const auto destination=renameInSource?sourceDirectory:request.destination;
std::error_code error;
const auto peer=request.move || request.newName.empty()?request.destinationPeer:request.sourcePeer;
const auto peer=renameInSource?request.sourcePeer:request.destinationPeer;
if(!directoryExists(peer,destination))
throw std::runtime_error(ks::utf8(L"The destination folder is unavailable."));
const bool sameHost=(!peer && !request.sourcePeer) ||
@@ -4257,7 +4309,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
SetDlgItemTextW(dialog,pathField,!single && !request.ftpDestination.empty()?
request.ftpDestination.c_str():fieldText.c_str());
SendDlgItemMessageW(dialog,pathField,EM_SETREADONLY,!single && !request.move,0);
if(request.move) SetDlgItemTextW(dialog,IDOK,L"&Rename");
if(request.move) SetDlgItemTextW(dialog,IDOK,request.externalSources?L"&Move":L"&Rename");
fitFarEditToLine(GetDlgItem(dialog,pathField));
layoutDialogButtons(dialog,214,{IDOK,IDCANCEL});
installFarCheckbox(GetDlgItem(dialog,214),FarCheckboxSurface::gray);
@@ -4345,6 +4397,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
snapshot.move=request.move;
snapshot.ftpDestination=request.ftpDestination;
snapshot.upload=request.upload;
snapshot.externalSources=request.externalSources;
std::packaged_task<CopyDestination()> validation(
[snapshot=std::move(snapshot),value=std::move(value),
source=peer(request.sourcePeer),other=peer(request.otherPeer)]() mutable {
@@ -4784,7 +4837,7 @@ void layoutFilesNotice(HWND dialog)
bottom+=textHeight;
}
place(102,bottom+dialogRowGap()+4,1);
if(notice.options.saveChanges) layoutDialogButtons(dialog,102,{IDYES,IDNO,IDCANCEL});
if(notice.options.saveChanges || notice.options.chooseTransfer) layoutDialogButtons(dialog,102,{IDYES,IDNO,IDCANCEL});
else if(notice.options.confirm) layoutDialogButtons(dialog,102,{IDYES,IDNO});
else if(notice.options.processes) layoutDialogButtons(dialog,102,{showProcessesButton,IDOK});
else layoutDialogButtons(dialog,102,{IDOK});
@@ -4808,7 +4861,7 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
notice.options.tone==FilesNoticeTone::neutral?FarCheckboxSurface::gray:FarCheckboxSurface::dialog);
ShowWindow(checkbox,SW_SHOW);
}
if(notice.options.confirm || notice.options.saveChanges)
if(notice.options.confirm || notice.options.saveChanges || notice.options.chooseTransfer)
{
ShowWindow(GetDlgItem(window,IDOK),SW_HIDE);
ShowWindow(GetDlgItem(window,IDYES),SW_SHOW);
@@ -4820,6 +4873,13 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
SetDlgItemTextW(window,IDNO,L"&Discard");
ShowWindow(GetDlgItem(window,IDCANCEL),SW_SHOW);
}
if(notice.options.chooseTransfer)
{
SetDlgItemTextW(window,IDYES,L"&Copy");
SetDlgItemTextW(window,IDNO,L"&Move");
SetDlgItemTextW(window,IDCANCEL,L"Ca&ncel");
ShowWindow(GetDlgItem(window,IDCANCEL),SW_SHOW);
}
if(notice.options.processes) ShowWindow(GetDlgItem(window,showProcessesButton),SW_SHOW);
RECT caption{},text{};
if(const auto dc=GetDC(window))
@@ -4832,12 +4892,12 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
}
const auto inset=dialogFrameMetrics(GetDpiForWindow(window)).content();
const auto minimum=std::max({24L*cellWidth,caption.right+6*cellWidth,
notice.options.remember || notice.options.processes || notice.options.saveChanges?34L*cellWidth:0L})+2*inset;
notice.options.remember || notice.options.processes || notice.options.saveChanges || notice.options.chooseTransfer?34L*cellWidth:0L})+2*inset;
const auto width=std::clamp(text.right+cellWidth+2*inset,minimum,std::max(minimum,60L*cellWidth+2*inset));
SetWindowPos(window,nullptr,0,0,width,1,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
layoutFilesNotice(window);
FilesModalDialog::fitWidthToOwner(window,minimum,layoutFilesNotice);
const auto defaultButton=notice.options.saveChanges?IDCANCEL:notice.options.confirm?IDNO:IDOK;
const auto defaultButton=(notice.options.saveChanges || notice.options.chooseTransfer)?IDCANCEL:notice.options.confirm?IDNO:IDOK;
SendMessageW(window,DM_SETDEFID,defaultButton,0);
SetFocus(GetDlgItem(window,defaultButton));
return FALSE;
@@ -5401,7 +5461,8 @@ void pruneSearchResults(Panel &panel,const std::set<fs::path> &removed)
updateSelectionSummary(panel);
}
void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::vector<fs::path> external={},
fs::path targetFolder={})
{
const auto sourceFtp=source.ftp;
const bool ftpRename=move && sourceFtp && !ftpProfileList(source);
@@ -5434,18 +5495,20 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
setStatus(L"A copy is already in progress.");
return;
}
CopyRequest request{{},ftpRename?source.directory:destination.directory};
if(targetFolder.empty()) targetFolder=ftpRename?source.directory:destination.directory;
CopyRequest request{{},targetFolder};
request.move=move;
request.ftpRename=ftpRename;
request.externalSources=!external.empty();
if(ftp)
{
request.ftpDestination=panelLocation(destination);
request.upload=destinationFtp.has_value();
}
request.otherDirectory=destination.directory;
request.otherDirectory=ftpRename?destination.directory:targetFolder;
request.sourcePeer=source.peer?&*source.peer:nullptr;
request.otherPeer=request.destinationPeer=destination.peer?&*destination.peer:nullptr;
request.sources=selectedPanelPaths(source);
request.sources=request.externalSources?std::move(external):selectedPanelPaths(source);
if(request.sources.empty()) return;
if(ftpRename && request.sources.size()!=1)
{
@@ -5458,7 +5521,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
if(result!=IDOK) return;
const bool renamed=!request.newName.empty();
const bool renameInSource=renamed && !move && !ftp;
const bool renameInSource=renamed && !move && !ftp && !request.externalSources;
const auto targetDirectory=renameInSource?request.sources.front().parent_path():request.destination;
const auto *targetPeer=renameInSource?request.sourcePeer:request.destinationPeer;
const auto peerId=[](const FilesPeer *peer){return peer?peer->id:std::string{};};
@@ -5550,7 +5613,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
++copied;
if(move && fromSearch) removed.insert(path);
results.insert(progress.renamedTarget.empty()?to:progress.renamedTarget);
progress.ui.invoke([&] {
if(!request.externalSources) progress.ui.invoke([&] {
const auto row=std::find(source.rows.begin(),source.rows.end(),path);
if(row!=source.rows.end()) source.marked[row-source.rows.begin()]=false;
InvalidateRect(source.list,nullptr,FALSE);
@@ -5589,12 +5652,12 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
{
if(fromSearch) pruneSearchResults(source,removed);
else open(source,source.directory);
if(!ftpRename) open(destination,destination.directory);
if(!ftpRename && &source!=&destination) open(destination,destination.directory);
if(!fromSearch && renamed && copied && (sameHost || ftpRename))
{
const auto renamedPath=progress.renamedTarget.empty()?
targetDirectory/request.newName:progress.renamedTarget;
selectPanelPath(source,renamedPath);
selectPanelPath(request.externalSources?destination:source,renamedPath);
}
}
else
@@ -6014,8 +6077,33 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
warningBrush=nullptr;
}
bool pastePanelFiles(HWND owner,Panel &panel)
{
if(!IsClipboardFormatAvailable(CF_HDROP)) return false;
if(panel.peer || panel.ftp || panel.findOrigin)
{
setStatus(L"Open a local folder before pasting files.");
return true;
}
std::vector<fs::path> paths;
try {paths=ks::readClipboardFilePaths(owner);}
catch(const std::exception &)
{
setStatus(L"Could not read file paths from the clipboard.");
return true;
}
if(paths.empty())
{
setStatus(L"The clipboard has no usable file paths.");
return true;
}
copySelection(owner,panel,panel,false,std::move(paths));
return true;
}
void selectPanelEdge(Panel &panel,bool first)
{
panelClipboardContext=true;
activatePanel(static_cast<int>(&panel-panels));
const auto count=SendMessageW(panel.list,LB_GETCOUNT,0,0);
if(count<=0) return;
@@ -6425,13 +6513,33 @@ void openOrCreateText(HWND owner,const Panel &panel)
void editFtpProfile(Panel &panel,bool create);
#include "files_drag_drop.inl"
LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
{
const auto index=GetDlgCtrlID(window)-102;
if(message==WM_NCDESTROY) RevokeDragDrop(window);
if(message==WM_CAPTURECHANGED) panelDragStart.reset();
if(message==WM_MOUSEMOVE && (wp&MK_LBUTTON) && GetCapture()==window && panelDragStart)
{
const auto dpi=GetDpiForWindow(window);
if(std::abs(GET_X_LPARAM(lp)-panelDragStart->x)>=GetSystemMetricsForDpi(SM_CXDRAG,dpi) ||
std::abs(GET_Y_LPARAM(lp)-panelDragStart->y)>=GetSystemMetricsForDpi(SM_CYDRAG,dpi))
{
ReleaseCapture();
beginPanelDrag(window);
restoreCommandFocus();
}
return 0;
}
if(message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK ||
(message==WM_MOUSEMOVE && (wp&MK_LBUTTON) && GetCapture()==window))
{
if(message==WM_LBUTTONDOWN) clearTerminalSelection();
if(message==WM_LBUTTONDOWN)
{
panelClipboardContext=true;
clearTerminalSelection();
}
auto &panel=panels[index];
const auto count=SendMessageW(window,LB_GETCOUNT,0,0);
if(count<=0)
@@ -6440,16 +6548,9 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
return 0;
}
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
// LB_ITEMFROMPOINT only returns the low 16 bits of the row index.
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
const auto top=SendMessageW(window,LB_GETTOPINDEX,0,0);
constexpr LRESULT rowRange=1<<16;
auto row=(top&~(rowRange-1))|LOWORD(hit);
if(row<top) row+=rowRange;
RECT bounds{};
const bool rowHit=!HIWORD(hit) && row<count &&
SendMessageW(window,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&bounds))!=LB_ERR &&
PtInRect(&bounds,point);
const auto row=panelRowAt(window,point,top,count);
const bool rowHit=row!=LB_ERR;
const auto previous=SendMessageW(window,LB_GETCURSEL,0,0);
const auto target=rowHit?row:point.y>=0 && message==WM_LBUTTONDOWN?count-1:previous;
if(target!=previous && index!=active)
@@ -6471,7 +6572,11 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
invalidatePanelCursorChange(window,previous);
}
activatePanel(index);
if(message==WM_LBUTTONDOWN) SetCapture(window);
if(message==WM_LBUTTONDOWN)
{
if(rowHit && panel.sizes[row]!=L"Up") panelDragStart=point;
SetCapture(window);
}
if(message==WM_LBUTTONDBLCLK && rowHit) enter(panel);
return 0;
}
@@ -6484,6 +6589,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
const bool rangeKey=wp==VK_UP || wp==VK_DOWN || wp==VK_LEFT || wp==VK_RIGHT;
if(message==WM_KEYDOWN && (wp==VK_INSERT || (rangeKey && (GetKeyState(VK_SHIFT)&0x8000))))
{
panelClipboardContext=true;
auto &panel=panels[index];
const auto row=SendMessageW(window,LB_GETCURSEL,0,0);
if(row<0 || static_cast<size_t>(row)>=panel.marked.size()) return 0;
@@ -6525,6 +6631,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
{
if(plainPanelTab())
{
panelClipboardContext=true;
activatePanel(1-index);
SetFocus(terminalInput);
}
@@ -6570,7 +6677,11 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
(wp==VK_UP || wp==VK_DOWN || wp==VK_PRIOR || wp==VK_NEXT || wp==VK_HOME || wp==VK_END);
const auto previous=movesCursor?SendMessageW(window,LB_GETCURSEL,0,0):LB_ERR;
auto result=DefSubclassProc(window,message,wp,lp);
if(movesCursor) invalidatePanelCursorChange(window,previous);
if(movesCursor)
{
panelClipboardContext=true;
invalidatePanelCursorChange(window,previous);
}
if(message==WM_LBUTTONUP && GetFocus()==window) restoreCommandFocus();
if(message==WM_PAINT && hasPanelSizeColumn(panels[index]))
{
@@ -6645,12 +6756,13 @@ 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",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q"};
L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q",
L"Copy full path\tCtrl+Shift+C"};
}
commandActions.clear();
if(index==2)
{
commandActions={0,3,-1,1,2,4,5,8};
commandActions={0,3,11,-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});
@@ -6908,6 +7020,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
case ks::files::quickViewToggleMessage:
if(quickViewWindow && !copyInProgress && !FilesModalDialog::activeFor(window)) toggleQuickView(window);
return 0;
case panelDropReady:
performPanelDrop(window);
return 0;
case directoryScanReady:
if(!FilesModalDialog::activeFor(window)) collectDirectoryScans();
return 0;
@@ -7019,6 +7134,11 @@ 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);
if(auto target=new(std::nothrow) PanelDropTarget(panel.list))
{
RegisterDragDrop(panel.list,target);
target->Release();
}
SetWindowSubclass(panel.path,pathBarInput,1,0);
installScrollBar(panel.list,window,firstPanelScrollBar+i);
}
@@ -7516,6 +7636,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
case WM_COMMAND:
if(reinterpret_cast<HWND>(lp)==terminalInput && HIWORD(wp)==EN_CHANGE)
{
panelClipboardContext=false;
clearTerminalSelection();
resetCompletion();
}
@@ -7568,6 +7689,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
DestroyWindow(window);
return 0;
case WM_DESTROY:
pendingPanelDrop.reset();
for(auto &panel:panels)
if(panel.folderSizeJob) panel.folderSizeJob->stop.request_stop();
KillTimer(window,terminalTimer);
@@ -7645,12 +7767,16 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
type.lpszClassName = L"KSwitcher.Files";
if (!registerFarEdit(instance) || !RegisterClassW(&type)) return 1;
const auto com=OleInitialize(nullptr);
auto window = CreateWindowW(type.lpszClassName, L"KSwitcher Files — local prototype",
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 900, 540, nullptr, nullptr, instance, nullptr);
if (!window) return 1;
if(!window)
{
if(SUCCEEDED(com)) OleUninitialize();
return 1;
}
if(!restorePlacement(window)) ShowWindow(window, show);
SetFocus(terminalInput);
const auto com=CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);
MSG message{};
for(;;)
{
@@ -7829,6 +7955,22 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
{
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0;
const bool fileClipboard=!terminalVisible && (panelFocused || panelClipboardContext) &&
commandLineAvailable(window);
if(fileClipboard && ctrl && !shift && (message.wParam=='C' || message.wParam=='V'))
{
if(!(message.lParam&(1LL<<30)))
{
if(message.wParam=='C') copyPanelFiles(window,panels[active]);
else if(!pastePanelFiles(window,panels[active])) SendMessageW(terminalInput,WM_PASTE,0,0);
}
continue;
}
if(ctrl && shift && message.wParam=='C' && !terminalVisible && commandLineAvailable(window))
{
if(!(message.lParam & (1LL<<30))) copyFullPanelPath(window,panels[active]);
continue;
}
if(shift && !ctrl && message.wParam==VK_F4 && !terminalVisible)
{
if(!(message.lParam & (1LL<<30)) && commandLineAvailable(window))
@@ -7948,6 +8090,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
DeleteObject(blue);
DeleteObject(teal);
DeleteObject(terminalBackground);
if(SUCCEEDED(com)) CoUninitialize();
if(SUCCEEDED(com)) OleUninitialize();
return 0;
}
+1
View File
@@ -331,6 +331,7 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_
ReleaseCapture();
const int index=GetDlgCtrlID(window)-142;
if(index<0 || index>=2) return 0;
panelClipboardContext=true;
auto &panel=panels[index];
if(!localNavigationAvailable(panel))
{
+71
View File
@@ -486,6 +486,77 @@ Clip textClip(const std::wstring &text)
memcpy(f.data.data(), text.c_str(), f.data.size());
return Clip{{std::move(f)}};
}
Clip fileDropClip(std::span<const std::filesystem::path> paths)
{
std::wstring names;
for(const auto &path:paths)
{
if(!path.is_absolute() || path.native().find(L'\0')!=std::wstring::npos)
throw std::invalid_argument("A file clipboard path must be absolute and contain no nulls.");
names+=path.native();
names+=L'\0';
}
if(paths.empty()) names+=L'\0';
names+=L'\0';
DROPFILES header{};
header.pFiles=sizeof(header);
header.fWide=TRUE;
Format files{CF_HDROP,{},Bytes(sizeof(header)+names.size()*sizeof(wchar_t))};
memcpy(files.data.data(),&header,sizeof(header));
memcpy(files.data.data()+sizeof(header),names.data(),names.size()*sizeof(wchar_t));
const DWORD effect=DROPEFFECT_COPY;
Format preferred{0,CFSTR_PREFERREDDROPEFFECT,Bytes(sizeof(effect))};
memcpy(preferred.data.data(),&effect,sizeof(effect));
return Clip{{std::move(files),std::move(preferred)}};
}
std::vector<std::filesystem::path> fileDropPaths(HANDLE medium)
{
const auto size=medium?GlobalSize(medium):0;
if(size<sizeof(DROPFILES)) return {};
const auto bytes=static_cast<const unsigned char *>(GlobalLock(medium));
if(!bytes) return {};
DROPFILES header{};
memcpy(&header,bytes,sizeof(header));
bool terminated=false;
if(header.pFiles>=sizeof(header) && header.pFiles<size)
{
const auto start=bytes+header.pFiles;
if(!header.fWide)
terminated=std::search_n(start,bytes+size,2,static_cast<unsigned char>(0))!=bytes+size;
else if(header.pFiles%alignof(wchar_t)==0)
{
const auto names=reinterpret_cast<const wchar_t *>(start);
const auto end=names+(size-header.pFiles)/sizeof(wchar_t);
terminated=std::search_n(names,end,2,L'\0')!=end;
}
}
GlobalUnlock(medium);
if(!terminated) return {};
const auto drop=reinterpret_cast<HDROP>(medium);
const UINT count=DragQueryFileW(drop,UINT(-1),nullptr,0);
std::vector<std::filesystem::path> paths;
std::set<std::filesystem::path> seen;
for(UINT index=0;index<count;++index)
{
const UINT length=DragQueryFileW(drop,index,nullptr,0);
if(!length || length>32767) continue;
std::wstring name(length+1,L'\0');
if(DragQueryFileW(drop,index,name.data(),length+1)!=length) continue;
name.resize(length);
auto path=std::filesystem::path(std::move(name)).lexically_normal();
if(path.is_absolute() && seen.insert(path).second) paths.push_back(std::move(path));
}
return paths;
}
std::vector<std::filesystem::path> readClipboardFilePaths(HWND window)
{
ClipboardLock lock(window);
return fileDropPaths(GetClipboardData(CF_HDROP));
}
std::wstring Clip::text() const
{
for (const auto &f : formats)
+3
View File
@@ -59,6 +59,9 @@ Clip readClipboard(HWND, size_t limit = 32 * 1024 * 1024,
DWORD writeClipboard(HWND, const Clip &);
DWORD writeClipboardGuarded(HWND, const Clip &, std::optional<DWORD> expected);
Clip textClip(const std::wstring &);
Clip fileDropClip(std::span<const std::filesystem::path> paths);
std::vector<std::filesystem::path> fileDropPaths(HANDLE medium);
std::vector<std::filesystem::path> readClipboardFilePaths(HWND window);
bool chord(WORD key, UINT modifiers = 0);
bool chord(std::span<const WORD> keys);
struct SystemVolume