Compare commits

...
10 changed files with 660 additions and 75 deletions

No files matched your search

+13
View File
@@ -836,6 +836,11 @@ Warning і початковий фокус на No.
- Секції поточного файла й загального прогресу мають однаковий вертикальний відступ від вмісту до верхньої та нижньої ліній. Cancel стоїть по центру спільної нижньої секції.
- Обидві шкали займають усю ширину вмісту. Відсотки показуються по центру шкали, а її висота враховує поточний шрифт.
- **Options** у Copy/Move задає маску імен файлів із символами `*` і `?`. Порожня маска або `*` копіює всі файли й порожні папки. З іншою маскою Files зберігає структуру папок із відповідними файлами. У Move файли поза маскою залишаються в джерелі.
- Додаткові папки вводяться абсолютними шляхами, по одному на рядок, на тому самому комп’ютері або підключенні, що й основне призначення. Однакові папки обробляються один раз. У Move джерело видаляється після успішного копіювання елемента в усі вибрані папки. У разі пропуску або збою вже записані копії зберігаються. Підсумок показує кількість повністю скопійованих елементів по всіх призначеннях і загальну кількість записаних файлів.
- **Preserve modification time** зберігає час зміни там, де ціль підтримує його встановлення. Збереження часу підтримують Windows і SFTP. FTP-призначення використовує час сервера. **Preserve Windows permissions** переносить DACL між файловими системами Windows, які підтримують цей тип прав. Наявні папки, у які додаються файли, зберігають власні права й час.
- Оцінка залишку часу в прогресі з’являється після кількох вимірювань швидкості. Довга пауза скидає оцінку. Скасування й конфлікти використовують спільні діалоги.
## Попередження про конфлікт
- Для однойменних файлів Warning показує точний розмір у байтах із розділенням тисяч і місцевий
@@ -853,6 +858,14 @@ Warning і початковий фокус на No.
- F8 переміщує підтверджені елементи в кошик Windows. Shift+Delete видаляє підтверджене дерево від вкладених елементів до батьківської папки. Прогрес і підсумок окремо показують успішні, пропущені й невдалі дії.
- Cancel і Esc у вікні прогресу відкривають спільне червоне підтвердження скасування. Yes зупиняє операцію, а No або Esc у підтвердженні повертає до прогресу. Початковий фокус стоїть на No.
## Обмін і компонування панелей
- **Commands → Swap panels** або **Ctrl+U** міняє панелі місцями. Активна панель, шлях, курсор, прокручування, позначки, поточний режим і Quick View переходять разом.
- **Options → File panel modes → Panel layout** містить незалежні параметри для правої кнопки, кнопок дисків і компактного компонування. За замовчуванням ці параметри вимкнені.
- **Mark items with the right mouse button** перемикає позначку рядка. **Shift+права кнопка**, **Shift+F10** і клавіша **Menu** відкривають контекстне меню. Права кнопка на порожньому місці також відкриває контекстне меню панелі.
- **Show drive buttons** додає наявні локальні диски над панелями. Кнопка відкриває корінь диска в активній панелі. Якщо всі диски не поміщаються, **…** відкриває Change drive.
- **Compact commander layout** скорочує проміжки між шляхом, рядками та станом, зберігаючи розмір шрифту, командний рядок і клавіші дій.
## Перевірка змін
Відкрий Copy і Warning в одній збірці та порівняй висоту нижніх секцій, центрування, повноту підписів і видимість фокуса. Перевір Tab, стрілки й Esc. Після узгодження нового правила онови відповідний розділ цього документа.
+24 -2
View File
@@ -169,6 +169,10 @@ BEGIN
COMBOBOX 273, 132, 40, 108, 74, CBS_DROPDOWNLIST | WS_TABSTOP
LTEXT "&Right panel", 507, 251, 27, 117, 11
COMBOBOX 274, 251, 40, 117, 74, CBS_DROPDOWNLIST | WS_TABSTOP
AUTOCHECKBOX "Mark items with the right mouse button", 520, 132, 64, 245, 13
AUTOCHECKBOX "Show drive buttons", 521, 132, 81, 245, 13
AUTOCHECKBOX "Compact commander layout", 522, 132, 98, 245, 13
LTEXT "Shift+right-click opens the Windows context menu.", 523, 132, 115, 245, 13
GROUPBOX "Wide panel columns", 275, 129, 27, 259, 59
LTEXT "Size column &width (6–16 characters)", 276, 138, 44, 175, 10
EDITTEXT 201, 335, 41, 43, 14, ES_NUMBER | ES_AUTOHSCROLL
@@ -262,8 +266,9 @@ BEGIN
LTEXT "Existing files:", 212, 14, 57, 122, 14, SS_CENTERIMAGE
COMBOBOX 213, 140, 57, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
AUTOCHECKBOX "Also ask on read-only files", 214, 14, 77, 322, 14
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 92, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 92, 86, 18
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 42, 92, 86, 18
CONTROL "&Options...", 215, "Button", BS_OWNERDRAW | WS_TABSTOP, 132, 92, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 222, 92, 86, 18
END
103 DIALOGEX 0, 0, 460, 126
@@ -671,3 +676,20 @@ BEGIN
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 100, 78, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 186, 100, 78, 16
END
129 DIALOGEX 0, 0, 388, 177
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Copy/Move options"
FONT 10, "Consolas"
BEGIN
LTEXT "File &mask", 645, 14, 15, 360, 13
FAR_EDIT(640, 0, 14, 28, 360, 17)
LTEXT "Additional &folders on this computer (one absolute path per line)", 646, 14, 53, 360, 13
EDITTEXT 641, 14, 67, 360, 40, ES_MULTILINE | ES_WANTRETURN | ES_AUTOVSCROLL | WS_VSCROLL
AUTOCHECKBOX "Preserve modification &time", 642, 14, 112, 360, 14
AUTOCHECKBOX "Preserve Windows &permissions", 643, 14, 127, 360, 14
LTEXT "Extra folders use the same destination computer or connection.", 647, 14, 143, 360, 13
LTEXT "", 644, 10, 159, 1, 1, NOT WS_VISIBLE
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 161, 86, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 200, 161, 86, 16
END
+97
View File
@@ -0,0 +1,97 @@
struct CopyOptionsPrompt
{
CopyOptions value;
bool permissions{}, move{}, unixDest{};
};
INT_PTR CALLBACK copyOptionsDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int mask=640, paths=641, time=642, permissions=643, footer=644, folderLabel=646, hint=647;
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(window,message,wp,lp,L" Copy/Move options ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
{
const auto &prompt=*reinterpret_cast<const CopyOptionsPrompt*>(lp);
SetWindowLongPtrW(window,DWLP_USER,lp);
prepareCopyDialog(window);
layoutDialogContent(window,645);
fitFarEditToLine(GetDlgItem(window,mask));
installFarCheckbox(GetDlgItem(window,time),FarCheckboxSurface::gray);
installFarCheckbox(GetDlgItem(window,permissions),FarCheckboxSurface::gray);
for(const auto id:{time,permissions})
SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
layoutDialogButtons(window,footer,{IDOK,IDCANCEL});
CheckDlgButton(window,time,prompt.value.preserveTime?BST_CHECKED:BST_UNCHECKED);
CheckDlgButton(window,permissions,prompt.value.preservePermissions?BST_CHECKED:BST_UNCHECKED);
EnableWindow(GetDlgItem(window,permissions),prompt.permissions);
SetDlgItemTextW(window,mask,prompt.value.mask.c_str());
SendDlgItemMessageW(window,mask,EM_SETLIMITTEXT,255,0);
SendDlgItemMessageW(window,paths,EM_SETLIMITTEXT,32767,0);
std::wstring lines;
for(const auto &path:prompt.value.additional)
{
if(!lines.empty()) lines+=L"\r\n";
lines+=path.native();
}
SetDlgItemTextW(window,paths,lines.c_str());
if(prompt.unixDest) SetDlgItemTextW(window,folderLabel,L"Additional &folders on this server (one absolute path per line)");
if(prompt.move) SetDlgItemTextW(window,hint,L"Move keeps the source until every requested copy succeeds.");
SetFocus(GetDlgItem(window,mask));
SendDlgItemMessageW(window,mask,EM_SETSEL,0,-1);
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(window,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &prompt=*reinterpret_cast<CopyOptionsPrompt*>(GetWindowLongPtrW(window,DWLP_USER));
const auto text=[&](int id) {
auto control=GetDlgItem(window,id);
std::wstring value(GetWindowTextLengthW(control)+1,L'\0');
value.resize(GetWindowTextW(control,value.data(),static_cast<int>(value.size())));
return value;
};
auto pattern=text(mask);
if(pattern.find_first_of(L"/\\:")!=pattern.npos)
{
showFilesNotice(window,L"Enter a file name or mask without a path.",L"Copy/Move options");
SetFocus(GetDlgItem(window,mask));
return TRUE;
}
const auto entered=text(paths);
std::vector<fs::path> folders;
for(size_t start=0;start<entered.size();)
{
const auto end=entered.find(L'\n',start);
auto line=std::wstring_view(entered).substr(start,end==entered.npos?end:end-start);
if(!line.empty() && line.back()==L'\r') line.remove_suffix(1);
if(!line.empty())
{
auto path=fs::path(line);
const bool unc=!prompt.unixDest && (line.starts_with(L"\\\\") || line.starts_with(L"//"));
const bool absolute=prompt.unixDest?line.front()==L'/':path.is_absolute() || unc;
if(!absolute || line.find_first_of(L"<>|?*")!=line.npos || line.starts_with(L"\\\\.\\"))
{
showFilesNotice(window,L"Enter one absolute destination folder per line.",L"Copy/Move options");
SetFocus(GetDlgItem(window,paths));
return TRUE;
}
if(!unc) path=path.lexically_normal();
folders.push_back(folderPathWithoutSeparator(std::move(path)));
}
if(end==entered.npos) break;
start=end+1;
}
prompt.value={pattern.empty()?L"*":std::move(pattern),std::move(folders),
IsDlgButtonChecked(window,time)==BST_CHECKED,
prompt.permissions && IsDlgButtonChecked(window,permissions)==BST_CHECKED};
FilesModalDialog::finish(window,IDOK);
return TRUE;
}
+14 -1
View File
@@ -25,6 +25,7 @@ struct CopyHost
FileOperationElevation *elevation{};
fs::path listedDirectory;
FileEntries listedEntries;
std::optional<bool> copyMetadataSupport;
CopyHost(const FilesPeer *peer,const std::optional<TransferProfile> &profile,FileOperationElevation *admin=nullptr)
{
@@ -67,6 +68,17 @@ struct CopyHost
return entries;
}
bool supportsCopyMetadata()
{
if(!copyMetadataSupport)
{
const auto reply=request(fileRequest("fileCapabilities",L"C:\\"));
if(reply.at("error")!=ERROR_INVALID_FUNCTION) checkFileReply(reply);
copyMetadataSupport=reply.value("copyMetadata",false);
}
return *copyMetadataSupport;
}
void makeDirectory(const fs::path &path)
{
if(!ftp)
@@ -131,7 +143,7 @@ void downloadTransferFile(TransferSession &ftp,FilesConnection &local,const fs::
FileInfo uploadTransferFile(FilesConnection &local,TransferSession &ftp,const fs::path &source,const fs::path &target,
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress,
const ks::files::RemoteTextRevision *expected=nullptr)
const ks::files::RemoteTextRevision *expected=nullptr,bool preserveTime=false)
{
const auto directory=target.parent_path();
const auto temporary=directory/ks::wide("kswitcher-"+ks::lan::randomHex(16)+".partial");
@@ -179,6 +191,7 @@ FileInfo uploadTransferFile(FilesConnection &local,TransferSession &ftp,const fs
ERROR_ALREADY_EXISTS);
ftp.prepareReplacement(temporary,target);
}
if(preserveTime) ftp.preserveModificationTime(temporary,info.modified);
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
ftp.rename(temporary,target,existing.has_value());
return *uploaded;
+376 -69
View File
@@ -834,6 +834,11 @@ constexpr DWORD defaultStatusFields=15;
int sizeWidth=defaultSizeWidth;
bool alignExtensions=defaultAlignExtensions, showDetails=defaultShowDetails;
bool alignFolders=defaultAlignFolders;
bool rightClickMarks{}, showDriveButtons{}, compactLayout{};
constexpr wchar_t rightClickMarksKey[]=L"RightClickMarks", driveButtonsKey[]=L"ShowDriveButtons",
compactLayoutKey[]=L"CompactPanelLayout";
constexpr int firstDriveButton=660, moreDriveButton=firstDriveButton+26;
std::array<HWND,27> driveButtons{};
DWORD statusFields=defaultStatusFields;
std::vector<fs::path> drivePaths;
bool lanDrivePicker{};
@@ -1594,6 +1599,8 @@ void swapPanels(HWND window)
}
notifyFilesPreferences(window);
layout(window);
showFileDetails(panels[active]);
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
}
bool hasSelectionSummary()
@@ -1631,7 +1638,12 @@ void layout(HWND window,bool activeOnly)
const bool gitMode=showingGitChanges();
const int terminalBottom=std::max(4,inputTop);
const int summaryHeight=!terminalVisible && hasSelectionSummary()?textHeight:0;
const int detailsHeight=terminalVisible?0:textHeight+12+summaryHeight;
const int detailsInset=compactLayout?2:4;
const int detailsHeight=terminalVisible?0:textHeight+(compactLayout?4:12)+summaryHeight;
const DWORD driveMask=showDriveButtons && !terminalVisible && !gitMode?GetLogicalDrives():0;
const int driveHeight=driveMask?textHeight+2:0;
const int panelMargin=compactLayout?4:5;
const int pathTop=driveHeight+(compactLayout?1:4);
const int terminalTop=terminalVisible?4:std::max(4,terminalBottom-
std::min(terminalRows,std::max(0,(terminalBottom-detailsHeight)/textHeight-4))*textHeight);
const int panelBottom=terminalTop-detailsHeight;
@@ -1645,21 +1657,41 @@ void layout(HWND window,bool activeOnly)
};
if(!activeOnly)
{
const int buttonWidth=std::max(4*cellWidth,32);
const int maxButtons=std::max(1,(width-8)/buttonWidth);
int drives=0;
for(int letter=0;letter<26;++letter) if(driveMask&(1UL<<letter)) ++drives;
const int visibleDrives=drives>maxButtons?maxButtons-1:drives;
int slot=0;
for(int letter=0;letter<26;++letter)
{
const auto button=driveButtons[letter];
if(!button) continue;
const bool visible=(driveMask&(1UL<<letter)) && slot<visibleDrives;
if(visible) place(button,4+slot++*buttonWidth,0,buttonWidth,textHeight);
ShowWindow(button,visible?SW_SHOWNA:SW_HIDE);
}
if(const auto more=driveButtons.back())
{
place(more,4+slot*buttonWidth,0,buttonWidth,textHeight);
ShowWindow(more,drives>maxButtons?SW_SHOWNA:SW_HIDE);
}
const int headingTop=pathTop+textHeight+(compactLayout?2:6);
for (int i = 0; i < 2; ++i)
{
int x = i ? middle + 2 : 0;
int end = i ? width : middle - 2;
place(panels[i].path, x + 5, 4, std::max(0, end - x - 10), textHeight);
place(panels[i].path, x+panelMargin,pathTop,std::max(0,end-x-2*panelMargin),textHeight);
int headingHeight=detailedPanel(panels[i])?textHeight:0;
const int listWidth=std::max(0,end-x-8-scrollBarWidth(panels[i].list));
const int listWidth=std::max(0,end-x-panelMargin-3-scrollBarWidth(panels[i].list));
const bool panelVisible=!gitMode && !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);
place(panels[i].heading,x+panelMargin,headingTop,listWidth,headingHeight);
ShowWindow(panels[i].heading,panelVisible && detailedPanel(panels[i])?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);
place(panels[i].list,x+panelMargin,headingTop+headingHeight,listWidth,
std::max(0,panelBottom-headingTop-headingHeight));
place(panels[i].selectionSummary,x+8,panelBottom+detailsInset,std::max(0,end-x-16),summaryHeight);
ShowWindow(panels[i].selectionSummary,panelVisible && summaryHeight?SW_SHOWNA:SW_HIDE);
}
place(menuBar,0,0,width,textHeight+4);
@@ -1669,7 +1701,7 @@ void layout(HWND window,bool activeOnly)
}
const int detailsLeft=active?middle+2:0;
const int detailsRight=active?width:middle-2;
place(status,detailsLeft+8,panelBottom+4+summaryHeight,std::max(0,detailsRight-detailsLeft-16),textHeight);
place(status,detailsLeft+8,panelBottom+detailsInset+summaryHeight,std::max(0,detailsRight-detailsLeft-16),textHeight);
const auto &current=panels[active];
const auto prompt=panelLocation(current)+(terminalVisible?L"> ":L">");
SetWindowTextW(terminalPrompt,prompt.c_str());
@@ -1686,7 +1718,13 @@ void layout(HWND window,bool activeOnly)
place(terminalInput,4+promptWidth,inputTop,std::max(0,width-8-promptWidth),textHeight);
if(activeOnly)
{
const RECT details{0,panelBottom+4+summaryHeight,width,panelBottom+4+summaryHeight+textHeight};
const RECT details{0,panelBottom+detailsInset+summaryHeight,width,
panelBottom+detailsInset+summaryHeight+textHeight};
if(driveHeight)
{
const RECT drives{0,0,width,driveHeight};
RedrawWindow(window,&drives,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
}
const RECT commandLine{0,inputTop,width,inputTop+textHeight};
if(!terminalVisible) RedrawWindow(window,&details,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
RedrawWindow(window,&commandLine,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
@@ -1723,8 +1761,9 @@ void layout(HWND window,bool activeOnly)
for(const auto preview:{quickViewWindow,quickImageWindow})
{
if(!preview) continue;
SetWindowPos(preview,nullptr,left+5,4,std::max(0,right-left-10),
std::max(0,panelBottom+summaryHeight+textHeight),SWP_NOZORDER|SWP_NOACTIVATE);
const int bottom=panelBottom+summaryHeight+textHeight+detailsInset;
SetWindowPos(preview,nullptr,left+panelMargin,pathTop,std::max(0,right-left-2*panelMargin),
std::max(0,bottom-pathTop),SWP_NOZORDER|SWP_NOACTIVATE);
const bool current=quickViewDisplaysImage==(preview==quickImageWindow);
ShowWindow(preview,!gitMode && !terminalVisible && current?SW_SHOWNA:SW_HIDE);
}
@@ -3900,6 +3939,7 @@ void selectDrive()
else if(menuIndex==2 && row==15) showProcesses(owner);
else if(menuIndex==2 && row==16) openGitChanges(owner,panels[active]);
else if(menuIndex==2 && row==17) showEnvironmentPanel(owner);
else if(menuIndex==2 && row==18) swapPanels(owner);
else if(menuIndex==1 && row==4) createArchive(owner,panels[active]);
else if(menuIndex==1 && row==5) showPanelItemProperties(owner,panels[active]);
else if(menuIndex==1 && row==6) showPanelLockProcesses(owner,panels[active]);
@@ -4651,6 +4691,13 @@ struct CopyDestination
bool useSourcePeer{};
};
struct CopyOptions
{
std::wstring mask=L"*";
std::vector<fs::path> additional;
bool preserveTime=true, preservePermissions{};
};
struct CopyRequest
{
std::vector<fs::path> sources;
@@ -4665,6 +4712,7 @@ struct CopyRequest
std::wstring ftpDestination;
bool upload{};
bool ftpRename{}, externalSources{}, archiveSource{};
CopyOptions options;
};
bool directoryExists(const FilesPeer *peer,const fs::path &path)
@@ -5292,6 +5340,8 @@ CopyDestination validateCopyDestination(CopyRequest request,const std::wstring &
return {std::move(request.destination),std::move(request.newName),useSourcePeer};
}
#include "files_copy_options.inl"
INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
{
constexpr int summary=210, pathField=211, conflicts=212;
@@ -5347,7 +5397,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
SendDlgItemMessageW(dialog,pathField,EM_SETREADONLY,!single && !request.move,0);
if(request.move) SetDlgItemTextW(dialog,IDOK,request.externalSources?L"&Move":L"&Rename");
fitFarEditToLine(GetDlgItem(dialog,pathField));
layoutDialogButtons(dialog,214,{IDOK,IDCANCEL});
layoutDialogButtons(dialog,214,{IDOK,215,IDCANCEL});
installFarCheckbox(GetDlgItem(dialog,214),FarCheckboxSurface::gray);
CheckDlgButton(dialog,214,request.askReadOnly?BST_CHECKED:BST_UNCHECKED);
SendDlgItemMessageW(dialog,summary,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
@@ -5385,7 +5435,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
if(!request.validation.valid() ||
request.validation.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return TRUE;
KillTimer(dialog,validationTimer);
for(const auto control:{pathField,213,214,IDOK}) EnableWindow(GetDlgItem(dialog,control),TRUE);
for(const auto control:{pathField,213,214,215,IDOK}) EnableWindow(GetDlgItem(dialog,control),TRUE);
try
{
auto result=request.validation.get();
@@ -5403,6 +5453,14 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
InvalidateRect(GetDlgItem(dialog,213),nullptr,FALSE);
return FALSE;
}
if(LOWORD(wp)==215)
{
CopyOptionsPrompt options{request.options, request.ftpDestination.empty() && !request.archiveSource, request.move,
request.upload};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(129),dialog,copyOptionsDialog,
reinterpret_cast<LPARAM>(&options))==IDOK) request.options=std::move(options.value);
return TRUE;
}
if(LOWORD(wp)!=IDOK) return FALSE;
if(request.validation.valid()) return TRUE;
try
@@ -5446,7 +5504,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
std::thread(std::move(validation)).detach();
request.validation=std::move(ready);
SetFocus(GetDlgItem(dialog,IDCANCEL));
for(const auto control:{pathField,213,214,IDOK}) EnableWindow(GetDlgItem(dialog,control),FALSE);
for(const auto control:{pathField,213,214,215,IDOK}) EnableWindow(GetDlgItem(dialog,control),FALSE);
}
catch(const std::exception &e)
{
@@ -5526,14 +5584,17 @@ struct CopyProgress
std::atomic_bool canceled{};
bool closeOwner{};
bool move{}, fileSourcesOnly{};
bool writingArchive{};
bool writingArchive{}, deferRemoval{};
CopyOptions options;
int conflictChoice{};
ConflictMode conflictMode{};
bool askReadOnly=true;
uint64_t files{}, totalFiles{}, bytes{}, totalBytes{};
uint64_t skippedFiles{}, skippedBytes{};
const wchar_t *lastSkipReason=L"";
ULONGLONG lastPaint{};
ULONGLONG lastPaint{}, sampleStart{}, lastSample{};
uint64_t sampleBytes{}, lastBytes{};
unsigned samples{};
fs::path from,to,renamedTarget;
fs::path localLockSource,localLockTarget;
};
@@ -5599,8 +5660,30 @@ void updateCopyProgress(CopyProgress &progress,uint64_t current,uint64_t fileSiz
SetDlgItemTextW(progress.window,224,(L"Files: "+std::to_wstring(progress.files)+L" / "+
std::to_wstring(progress.totalFiles)+(progress.skippedFiles?
L" Skipped: "+std::to_wstring(progress.skippedFiles)+L" ("+progress.lastSkipReason+L")":L"")).c_str());
SetDlgItemTextW(progress.window,225,(L"Size: "+formatSize(bytes)+L" / "+
formatSize(progress.totalBytes)).c_str());
auto sizeText=L"Size: "+formatSize(bytes)+L" / "+formatSize(progress.totalBytes);
if(!progress.sampleStart || progress.lastPaint-progress.lastSample>1500 || bytes<progress.lastBytes)
{
progress.sampleStart=progress.lastSample=progress.lastPaint;
progress.sampleBytes=progress.lastBytes=bytes;
progress.samples=0;
}
else if(bytes>progress.lastBytes && progress.lastPaint-progress.lastSample>=200)
{
progress.lastSample=progress.lastPaint;
progress.lastBytes=bytes;
++progress.samples;
}
const auto elapsed=progress.lastSample-progress.sampleStart;
const auto accounted=std::min(progress.totalBytes,bytes+progress.skippedBytes);
if(progress.samples>=3 && elapsed>=1200 && bytes>progress.sampleBytes && accounted<progress.totalBytes)
{
const auto estimate=std::ceil((progress.totalBytes-accounted)*(elapsed/1000.0)/(bytes-progress.sampleBytes));
const auto seconds=static_cast<uint64_t>(std::min(estimate,360000000.0));
sizeText+=L" Remaining: "+std::to_wstring(seconds/3600)+L":"+
(seconds%3600/60<10?L"0":L"")+std::to_wstring(seconds%3600/60)+L":"+
(seconds%60<10?L"0":L"")+std::to_wstring(seconds%60);
}
SetDlgItemTextW(progress.window,225,sizeText.c_str());
}
void reportCopyProgress(CopyProgress &progress,uint64_t current,uint64_t fileSize,bool force=false)
@@ -6299,23 +6382,69 @@ ks::files::RemoteTextSource transferTextSource(const TransferProfile &profile)
return source;
}
bool countCopy(CopyHost &host,const fs::path &path,CopyProgress &progress)
struct CopyNode
{
if(progress.canceled) return false;
fs::path path;
FileInfo info;
std::vector<CopyNode> children;
bool whole=true;
};
std::optional<CopyNode> planCopy(CopyHost &host,const fs::path &path,CopyProgress &progress)
{
if(progress.canceled) throw std::system_error(ERROR_CANCELLED,std::system_category());
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))
if(!info) throw std::system_error(ERROR_FILE_NOT_FOUND,std::system_category());
const bool directory=info->attributes&FILE_ATTRIBUTE_DIRECTORY;
if(!directory && !matchesFileMask(path.filename().native(),progress.options.mask)) return {};
if(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT)
throw std::system_error(ERROR_NOT_SUPPORTED,std::system_category());
if(progress.fileSourcesOnly && directory)
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
if(!(info->attributes&FILE_ATTRIBUTE_DIRECTORY))
CopyNode node{path,*info,{}};
if(!directory)
{
++progress.totalFiles;
progress.totalBytes+=info->size;
return true;
}
for(const auto &[child,entry]:host.children(path,progress.canceled))
if(!countCopy(host,child,progress)) return false;
return true;
else
{
for(const auto &[child,entry]:host.children(path,progress.canceled))
{
auto item=planCopy(host,child,progress);
node.whole=node.whole && item && item->whole;
if(item) node.children.push_back(std::move(*item));
}
if(node.children.empty() && progress.options.mask!=L"*") return {};
}
return node;
}
void verifyCopyPlan(CopyHost &source,const CopyNode &node,const std::atomic_bool &canceled)
{
if(canceled) throw std::system_error(ERROR_CANCELLED,std::system_category());
const auto current=source.stat(node.path,canceled);
if(!current || current->size!=node.info.size || current->modified!=node.info.modified ||
((current->attributes^node.info.attributes)&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)))
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
for(const auto &child:node.children) verifyCopyPlan(source,child,canceled);
}
void removeCopiedPlan(CopyHost &source,const CopyNode &node,CopyProgress &progress,bool local)
{
if(progress.canceled) throw std::system_error(ERROR_CANCELLED,std::system_category());
const bool directory=node.info.attributes&FILE_ATTRIBUTE_DIRECTORY;
for(const auto &child:node.children) removeCopiedPlan(source,child,progress,local);
if(directory && !node.whole) return;
progress.localLockSource=local?node.path:fs::path{};
progress.localLockTarget.clear();
auto action=fileRequest(directory?"rmdir":"remove",node.path);
if(!directory)
{
action["size"]=node.info.size;
action["modified"]=node.info.modified;
}
checkFileReply(source.request(action));
}
enum class CopyResult { complete, skipped, failed };
@@ -6343,7 +6472,7 @@ void transferFile(const CopyEndpoints &hosts,const fs::path &from,const fs::path
}
if(hosts.target.ftp)
{
uploadTransferFile(*hosts.source.files,*hosts.target.ftp,from,to,info,replace,update);
uploadTransferFile(*hosts.source.files,*hosts.target.ftp,from,to,info,replace,update,nullptr,progress.options.preserveTime);
hosts.target.listedDirectory.clear();
return;
}
@@ -6362,9 +6491,27 @@ void transferFile(const CopyEndpoints &hosts,const fs::path &from,const fs::path
info.size,info.modified,replace,append,update);
}
CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::path &to,CopyProgress &progress,
void applyCopyMetadata(const CopyEndpoints &hosts,const fs::path &to,const FileInfo &info,
const CopyOptions &options,const Json &permissions,bool directory)
{
if(hosts.target.ftp)
{
if(directory && options.preserveTime) hosts.target.ftp->preserveModificationTime(to,info.modified);
return;
}
auto request=fileRequest("applyCopyMetadata",to);
if(directory && options.preserveTime && info.modified && hosts.target.supportsCopyMetadata())
request["modified"]=info.modified;
else if(!directory && !options.preserveTime)
request["modified"]=uint64_t{};
if(!permissions.is_null()) request["permissions"]=permissions;
if(request.size()>2) checkFileReply(hosts.target.request(request));
}
CopyResult copyItem(const CopyEndpoints &hosts,const CopyNode &node,const fs::path &to,CopyProgress &progress,
bool topLevel=false,bool singleItem=false)
{
const auto &from=node.path;
if(progress.canceled) return CopyResult::failed;
if((hosts.source.ftp || hosts.target.ftp) && !validFtpCopyName(to.filename().native(),hosts.target.ftp.has_value()))
throw std::system_error(ERROR_INVALID_NAME,std::system_category());
@@ -6373,12 +6520,21 @@ 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))
if(((incoming->attributes^node.info.attributes)&FILE_ATTRIBUTE_DIRECTORY) ||
(!(incoming->attributes&FILE_ATTRIBUTE_DIRECTORY) &&
(incoming->size!=node.info.size || incoming->modified!=node.info.modified)))
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
const auto readPermissions=[&] {
if(!progress.options.preservePermissions) return Json(nullptr);
const auto reply=hosts.source.request(fileRequest("copyPermissions",from));
checkFileReply(reply);
return Json(reply.at("permissions"));
};
const auto removeImmediately=progress.move && !progress.deferRemoval;
const auto moveOnHost=[&](const fs::path &target,bool replace)
{
if(!progress.move || !hosts.sameHost) return false;
if(!removeImmediately || !hosts.sameHost) return false;
auto request=fileRequest("move",from);
request["target"]=ks::utf8(target.native());
request["replace"]=replace;
@@ -6399,15 +6555,17 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
progress.bytes=progress.totalBytes;
return CopyResult::complete;
}
const auto permissions=existing?Json(nullptr):readPermissions();
if(!existing) hosts.target.makeDirectory(to);
auto result=CopyResult::complete;
for(const auto &[child,entry]:hosts.source.children(from,progress.canceled))
for(const auto &child:node.children)
{
const auto outcome=copyItem(hosts,child,to/child.filename(),progress);
const auto outcome=copyItem(hosts,child,to/child.path.filename(),progress);
if(outcome==CopyResult::failed) return outcome;
if(outcome==CopyResult::skipped) result=outcome;
}
if(progress.move && result==CopyResult::complete)
if(!existing) applyCopyMetadata(hosts,to,*incoming,progress.options,permissions,true);
if(removeImmediately && result==CopyResult::complete)
{
progress.localLockSource=hosts.sourceLocal?from:fs::path{};
progress.localLockTarget.clear();
@@ -6424,8 +6582,10 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
if(hosts.targetLocal) progress.localLockTarget=target;
if(!moveOnHost(target,replace))
{
const auto permissions=readPermissions();
transferFile(hosts,from,target,*incoming,replace,append,progress);
if(progress.move)
applyCopyMetadata(hosts,target,*incoming,progress.options,permissions,false);
if(removeImmediately)
{
auto remove=fileRequest("remove",from);
remove["size"]=incoming->size;
@@ -6638,6 +6798,9 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
progress.fileSourcesOnly=fromSearch;
progress.conflictMode=request.conflictMode;
progress.askReadOnly=request.askReadOnly;
progress.options=std::move(request.options);
progress.deferRemoval=move && (progress.options.mask!=L"*" || !progress.options.additional.empty() ||
progress.options.preservePermissions || !progress.options.preserveTime);
FilesModalDialog progressDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(103),owner,
copyProgressDialog,reinterpret_cast<LPARAM>(&progress));
progress.window=progressDialog.window();
@@ -6652,8 +6815,11 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
for(const auto command:commands) EnableWindow(command,FALSE);
progressDialog.show();
bool failed=false, skipped=false;
size_t copied=0;
size_t copied=0, completedCopies=0, requestedCopies=0;
const bool multiple=!progress.options.additional.empty();
bool noMatchingFiles=false;
std::set<fs::path> results, removed;
fs::path failedDestination;
std::wstring failure;
std::vector<fs::path> lockPaths;
try
@@ -6706,43 +6872,103 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
const CopyEndpoints hosts{sourceHost,otherHost?*otherHost:sourceHost,sameHost,
request.sourcePeer?request.sourcePeer->id:"local",!request.sourcePeer && !sourceFtp,
!targetPeer && !destinationFtp};
for(const auto &path:sources)
if(!countCopy(sourceHost,path,progress)) { failed=true; break; }
reportCopyProgress(progress,0,0,true);
std::vector<std::pair<size_t,CopyNode>> plans;
for(size_t i=0;i<sources.size();++i)
if(auto plan=planCopy(sourceHost,sources[i],progress)) plans.emplace_back(i,std::move(*plan));
if(plans.empty()) { noMatchingFiles=true; return; }
const auto canonical=[&](const fs::path &name) {
const auto reply=hosts.target.request(fileRequest("canonical",name));
checkFileReply(reply);
return filePath(reply.at("path"));
};
const auto equalPath=[&](const fs::path &first,const fs::path &second) {
return destinationFtp?first==second:
CompareStringOrdinal(first.c_str(),-1,second.c_str(),-1,TRUE)==CSTR_EQUAL;
};
std::vector<fs::path> folders{targetDirectory};
std::vector<fs::path> locations{destinationFtp?targetDirectory:canonical(targetDirectory)};
for(const auto &folder:progress.options.additional)
{
if(failed) break;
const auto &path=sources[i];
const auto to=targetDirectory/(renamed?request.newName:path.filename());
if(sameHost)
const auto location=destinationFtp?folder:canonical(folder);
if(std::any_of(locations.begin(),locations.end(),[&](const auto &known) {return equalPath(known,location);}))
continue;
const auto info=folder==folder.root_path() && destinationFtp?std::optional<FileInfo>{
FileInfo{FILE_ATTRIBUTE_DIRECTORY,0,0}}:hosts.target.stat(folder,progress.canceled);
if(!info || !(info->attributes&FILE_ATTRIBUTE_DIRECTORY))
{
const auto canonical=[&](const fs::path &name)
failedDestination=folder;
throw std::system_error(ERROR_PATH_NOT_FOUND,std::system_category());
}
folders.push_back(folder);
locations.push_back(location);
}
requestedCopies=plans.size()*folders.size();
progress.totalFiles*=folders.size();
progress.totalBytes*=folders.size();
if(progress.options.preservePermissions &&
(!hosts.source.supportsCopyMetadata() || !hosts.target.supportsCopyMetadata()))
throw std::runtime_error("Update both KSwitcher computers to preserve Windows permissions.");
if(!progress.options.preserveTime && !destinationFtp && !hosts.target.supportsCopyMetadata())
throw std::runtime_error("Update KSwitcher on the destination to set a new modification time.");
if(sameHost)
{
for(const auto &[index,plan]:plans)
{
const auto canonicalSource=canonical(plan.path);
for(const auto &folder:folders)
{
const auto reply=sourceHost.request(fileRequest("canonical",name));
checkFileReply(reply);
return filePath(reply.at("path"));
};
const auto canonicalSource=canonical(path);
const auto canonicalTarget=canonical(to);
for(auto ancestor=canonicalTarget;;ancestor=ancestor.parent_path())
{
if(CompareStringOrdinal(ancestor.c_str(),-1,canonicalSource.c_str(),-1,TRUE)==CSTR_EQUAL)
const auto target=folder/(renamed?request.newName:plan.path.filename());
const auto canonicalTarget=canonical(target);
for(auto ancestor=canonicalTarget;;ancestor=ancestor.parent_path())
{
throw std::system_error(ERROR_INVALID_PARAMETER,std::system_category());
if(equalPath(ancestor,canonicalSource))
{
failedDestination=target;
throw std::system_error(ERROR_INVALID_PARAMETER,std::system_category());
}
if(!ancestor.has_relative_path()) break;
}
if(!ancestor.has_relative_path()) break;
}
}
if(failed) break;
progress.renamedTarget.clear();
const auto outcome=copyItem(hosts,path,to,progress,true,sources.size()==1);
if(outcome==CopyResult::failed) { failed=true; break; }
if(outcome==CopyResult::skipped) { skipped=true; continue; }
}
reportCopyProgress(progress,0,0,true);
for(const auto &[index,plan]:plans)
{
const auto &path=plan.path;
bool allDestinations=true;
fs::path primaryResult;
for(size_t destinationIndex=0;destinationIndex<folders.size();++destinationIndex)
{
if(progress.canceled) return;
const auto to=folders[destinationIndex]/(renamed?request.newName:path.filename());
failedDestination=to;
progress.renamedTarget.clear();
const auto outcome=copyItem(hosts,plan,to,progress,true,plans.size()==1 && folders.size()==1);
if(outcome==CopyResult::failed) { failed=true; return; }
if(outcome==CopyResult::skipped) { skipped=true; allDestinations=false; continue; }
++completedCopies;
if(destinationIndex==0)
{
primaryResult=progress.renamedTarget.empty()?to:progress.renamedTarget;
results.insert(primaryResult);
}
}
if(!allDestinations) continue;
failedDestination.clear();
if(progress.deferRemoval)
{
verifyCopyPlan(sourceHost,plan,progress.canceled);
removeCopiedPlan(sourceHost,plan,progress,hosts.sourceLocal);
if(!plan.whole) skipped=true;
}
if(!primaryResult.empty() && primaryResult.filename()!=path.filename())
progress.renamedTarget=primaryResult;
++copied;
if(move && fromSearch) removed.insert(path);
results.insert(progress.renamedTarget.empty()?to:progress.renamedTarget);
if(!request.externalSources) progress.ui.invoke([&] {
const auto row=std::find(source.rows.begin(),source.rows.end(),request.sources[i]);
if(move && plan.whole && (fromSearch || treePanelActive(source))) removed.insert(path);
if(!request.externalSources && plan.whole) progress.ui.invoke([&] {
const auto row=std::find(source.rows.begin(),source.rows.end(),request.sources[index]);
if(row!=source.rows.end()) markPanelRow(source,row-source.rows.begin(),false);
else if(treePanelActive(source)) source.tree.marks.erase(path);
InvalidateRect(source.list,nullptr,FALSE);
@@ -6764,7 +6990,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
catch(const std::exception &e)
{
failed=true;
failure=archive.empty()?L"File connection interrupted.":ks::wide(e.what());
failure=ks::wide(e.what());
}
const auto targetId=peerId(targetPeer);
const bool restoreFocus=GetForegroundWindow()==progress.window;
@@ -6824,9 +7050,24 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
SetForegroundWindow(owner);
SetFocus(panels[active].list);
}
const auto outcomeText=[&] {
auto text=std::to_wstring(completedCopies)+L" of "+std::to_wstring(requestedCopies)+
L" item copies completed across the requested folders. "+std::to_wstring(progress.files)+L" files copied.";
if(move) text+=L" Sources were removed only after their requested copies completed.";
return text;
};
if(failed && !progress.canceled)
{
if(failure.empty()) failure=L"Could not complete the operation.";
if(!failedDestination.empty()) failure+=L"\r\n\r\nDestination: "+failedDestination.native();
if(multiple && requestedCopies) failure+=L"\r\n\r\n"+outcomeText();
showFileOperationError(owner,ftpRename?L"Rename failed":move?L"Move failed":L"Copy failed",
failure.empty()?L"Could not complete the operation.":failure,std::move(lockPaths));
failure,std::move(lockPaths));
}
else if(noMatchingFiles)
setStatus(L"No files match the copy mask.");
else if(multiple)
setStatus((progress.canceled?L"Canceled. ":skipped?L"Finished with skipped copies. ":L"")+outcomeText());
else if(ftpRename)
setStatus(copied?L"Rename complete.":L"Rename canceled.");
else if(move)
@@ -7675,6 +7916,27 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
if(message==WM_RBUTTONUP)
{
POINT screen{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
if(rightClickMarks && !(wp&MK_SHIFT) && commandLineAvailable(GetParent(window)))
{
auto &panel=panels[index];
const auto row=panelRowAt(window,screen,SendMessageW(window,LB_GETTOPINDEX,0,0),panel.rows.size());
if(row!=LB_ERR && panel.sizes[row]!=L"Up" && !transferProfileList(panel))
{
closePanelSearch();
SetFocus(window);
activatePanel(index);
panelClipboardContext=true;
clearTerminalSelection();
const auto previous=currentPanelRow(panel);
SendMessageW(window,LB_SETCURSEL,row,0);
markPanelRow(panel,row,!panel.marked[row]);
invalidatePanelRow(window,row);
if(previous!=row) invalidatePanelRow(window,previous);
updateSelectionSummary(panel);
showFileDetails(panel);
return 0;
}
}
ClientToScreen(window,&screen);
showPanelContextMenu(window,MAKELPARAM(screen.x,screen.y));
return 0;
@@ -7897,6 +8159,9 @@ bool loadFilesPreferences(HWND window)
alignExtensions=preference(L"AlignExtensions",defaultAlignExtensions)!=0;
showDetails=preference(L"ShowDetails",defaultShowDetails)!=0;
alignFolders=preference(L"AlignFolders",defaultAlignFolders)!=0;
rightClickMarks=preference(rightClickMarksKey,0)!=0;
showDriveButtons=preference(driveButtonsKey,0)!=0;
compactLayout=preference(compactLayoutKey,0)!=0;
statusFields=preference(L"StatusFields",defaultStatusFields)&15;
loadCommandHistoryKeys();
loadComparisonShortcut();
@@ -7962,7 +8227,7 @@ void openMenu(HWND window, int index)
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"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…",L"Processes…",
L"Git Changes…",L"Environment Variables…"};
L"Git Changes…",L"Environment Variables…",L"Swap panels\tCtrl+U"};
}
const auto &panel=panels[active];
const bool remoteResults=remoteSearchResults(panel);
@@ -7988,6 +8253,7 @@ void openMenu(HWND window, int index)
else if(index==2)
{
commandActions={0,3,11,-1,1,13,14,2,4,5,8};
if(!terminalVisible) commandActions.insert(commandActions.begin()+1,18);
if(!terminalVisible) commandActions.push_back(15);
if(gitChangesAvailable(panel)) commandActions.push_back(16);
if(!terminalVisible) commandActions.push_back(17);
@@ -8366,6 +8632,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
commands[i] = CreateWindowW(L"BUTTON", keyBar[i].label, WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
0, 0, 0, 0, window, reinterpret_cast<HMENU>(static_cast<INT_PTR>(keyBar[i].id)), instance, nullptr);
for(int i=0;i<static_cast<int>(driveButtons.size());++i)
{
const wchar_t letter[]{static_cast<wchar_t>(L'A'+i),L':',0};
driveButtons[i]=CreateWindowW(L"BUTTON",i==26?L"…":letter,WS_CHILD|BS_OWNERDRAW|WS_CLIPSIBLINGS,
0,0,0,0,window,reinterpret_cast<HMENU>(static_cast<INT_PTR>(firstDriveButton+i)),instance,nullptr);
if(!driveButtons[i]) return -1;
}
for (int i = 0; i < 2; ++i)
{
auto &panel = panels[i];
@@ -8409,6 +8682,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
return 0;
}
case WM_DEVICECHANGE:
if(showDriveButtons)
{
layout(window);
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
}
break;
case WM_SIZE:
hideCompletion();
hidePicker();
@@ -8489,7 +8769,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
GetWindowRect(status,&details);
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&details),2);
const RECT divider{box.left+1,box.bottom-2,box.right-1,box.bottom-1};
box.bottom=std::max(box.bottom,details.bottom+6);
box.bottom=std::max(box.bottom,details.bottom+(compactLayout?2:6));
FrameRect(dc,&box,border);
if(IsWindowVisible(panel.list)) paintScrollPosition(window,dc,panel.list,colors[PanelBlue]);
InflateRect(&box,-3,-3);
@@ -8661,6 +8941,21 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
GetWindowTextW(item.hwndItem,label,64);
text=label;
}
if(item.CtlID>=firstDriveButton && item.CtlID<=moreDriveButton)
{
const auto &panel=panels[active];
const auto drive=panel.directory.root_name().native();
const bool selected=item.CtlID!=moreDriveButton && !panel.peer && !panel.ftp && !panel.archive &&
drive.size()==2 && towupper(drive.front())==L'A'+item.CtlID-firstDriveButton;
auto bounds=item.rcItem;
FillRect(item.hDC,&bounds,selected?teal:blue);
SelectObject(item.hDC,mono);
SetBkMode(item.hDC,TRANSPARENT);
SetTextColor(item.hDC,colors[selected?Text:Frame]);
DrawTextW(item.hDC,text.c_str(),-1,&bounds,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX);
if(item.itemState&ODS_FOCUS) DrawFocusRect(item.hDC,&bounds);
return TRUE;
}
if(std::find(std::begin(commands),std::end(commands),item.hwndItem)!=std::end(commands))
{
if(item.CtlID==114 && remoteSearchResults(panels[active]) && panels[active].ftp)
@@ -8950,6 +9245,18 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
return 0;
}
if(HIWORD(wp)==BN_CLICKED && LOWORD(wp)>=firstDriveButton && LOWORD(wp)<=moreDriveButton)
{
const auto id=LOWORD(wp);
if(id==moreDriveButton) chooseDrive(active);
else
{
const wchar_t root[]{static_cast<wchar_t>(L'A'+id-firstDriveButton),L':',L'\\',0};
openOn(panels[active],root,false,{});
restoreCommandFocus();
}
return 0;
}
if(LOWORD(wp)==121 && HIWORD(wp)==LBN_DBLCLK) selectDrive();
if(LOWORD(wp)>=130 && LOWORD(wp)<=134 && HIWORD(wp)==BN_CLICKED)
{
+19 -2
View File
@@ -11,7 +11,8 @@ constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Pop
L"Menu selection",L"Command bar",L"File cursor"};
enum PanelSection { PanelLayout, WideColumns, StatusColumns };
constexpr const wchar_t *panelSectionNames[]{L"Panel layout",L"Wide panel columns",L"Status line columns"};
constexpr int panelLayoutControls[]{506,273,507,274};
constexpr int rightClickMarksControl=520, driveButtonsControl=521, compactLayoutControl=522;
constexpr int panelLayoutControls[]{506,273,507,274,rightClickMarksControl,driveButtonsControl,compactLayoutControl,523};
constexpr int wideColumnControls[]{275,276,201,202,204};
constexpr int statusColumnControls[]{277,203,205,206,207,208};
constexpr int colorOptionControls[]{279,280};
@@ -67,6 +68,9 @@ struct PanelProperty
};
constexpr PanelProperty panelProperties[]{
{PanelLayout,273,L"Left panel mode",defaultWide?1u:0u},{PanelLayout,274,L"Right panel mode",defaultWide?1u:0u},
{PanelLayout,rightClickMarksControl,L"Mark items with the right mouse button",0},
{PanelLayout,driveButtonsControl,L"Show drive buttons",0},
{PanelLayout,compactLayoutControl,L"Compact commander layout",0},
{WideColumns,201,L"Size column width",defaultSizeWidth},
{WideColumns,202,L"Align file extensions",defaultAlignExtensions},
{WideColumns,204,L"Align folder extensions",defaultAlignFolders},
@@ -107,6 +111,7 @@ struct OptionsBaseline
bool remoteUpdate=ks::lan::remoteUpdateAllowed();
DWORD width=static_cast<DWORD>(sizeWidth), fields=statusFields;
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
bool mouseMarks=rightClickMarks, drives=showDriveButtons, compact=compactLayout;
std::array<PanelMode,2> modes{panels[0].mode,panels[1].mode};
ks::files::TextSettings text=ks::files::loadTextPreferences();
ComparisonAppearance comparison=readComparisonAppearance();
@@ -181,6 +186,8 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
const bool dirty=!valid || draft.markdownError || width!=base.width ||
panelModeOption(dialog,0)!=base.modes[0] || panelModeOption(dialog,1)!=base.modes[1] ||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
checked(rightClickMarksControl)!=base.mouseMarks || checked(driveButtonsControl)!=base.drives ||
checked(compactLayoutControl)!=base.compact ||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
@@ -679,6 +686,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
showPanelModeOptions(dialog);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
@@ -898,7 +908,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
case 201:
case 202: case 203: case 204: case 205: case 206: case 207: case 208:
case 273: case 274: case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
case 273: case 274: case rightClickMarksControl: case driveButtonsControl: case compactLayoutControl:
case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
updateOptionsApply(dialog,*draft);
return TRUE;
case 321: case 323: case comparisonShortcutControl:
@@ -1050,6 +1061,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
saveChanged(L"AlignExtensions",checked(202),base.extensions);
saveChanged(L"AlignFolders",checked(204),base.folders);
saveChanged(L"ShowDetails",checked(203),base.details);
saveChanged(rightClickMarksKey,checked(rightClickMarksControl),base.mouseMarks);
saveChanged(driveButtonsKey,checked(driveButtonsControl),base.drives);
saveChanged(compactLayoutKey,checked(compactLayoutControl),base.compact);
DWORD fields=preference(L"StatusFields",defaultStatusFields)&15;
const auto initialFields=fields;
for(int i=0;i<4;++i)
@@ -1092,6 +1106,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
showPanelModeOptions(dialog);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
+18
View File
@@ -388,6 +388,24 @@ public:
if(libssh2_sftp_mkdir(sftp_.get(),name.c_str(),0755)) operationError("Could not create the SFTP folder");
}
void preserveModificationTime(const fs::path &path,uint64_t modified) const
{
constexpr uint64_t ticks=10000000, windowsEpoch=11644473600;
if(modified/ticks<windowsEpoch || modified/ticks-windowsEpoch>UINT32_MAX) return;
requireWriteAccess();
const auto name=encode(path);
LIBSSH2_SFTP_ATTRIBUTES attributes{};
if(libssh2_sftp_lstat(sftp_.get(),name.c_str(),&attributes))
operationError("Could not read the staged file timestamps");
const auto seconds=static_cast<unsigned long>(modified/ticks-windowsEpoch);
if(!(attributes.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)) attributes.atime=seconds;
attributes.flags=LIBSSH2_SFTP_ATTR_ACMODTIME;
attributes.mtime=seconds;
if(libssh2_sftp_setstat(sftp_.get(),name.c_str(),&attributes) &&
libssh2_sftp_last_error(sftp_.get())!=LIBSSH2_FX_OP_UNSUPPORTED)
operationError("Could not preserve the SFTP modification time");
}
void remove(const fs::path &path,bool directory) const
{
requireWriteAccess();
+5
View File
@@ -102,6 +102,11 @@ public:
FtpDeleteFileA(ftp_->handle(),name.c_str()));
}
void preserveModificationTime(const fs::path &path,uint64_t modified)
{
if(sftp_ && modified) sftp_->preserveModificationTime(path,modified);
}
void prepareReplacement(const fs::path &staged,const fs::path &existing)
{
if(sftp_) sftp_->prepareReplacement(staged,existing);
+63 -1
View File
@@ -8,6 +8,7 @@
#include <bcrypt.h>
#include <wincrypt.h>
#include <sddl.h>
#include <aclapi.h>
#include <winsafer.h>
#include <cstring>
#include <mutex>
@@ -679,7 +680,7 @@ public:
}
return reply;
}
if(action=="fileCapabilities") return {{"error",0},{"revision",1}};
if(action=="fileCapabilities") return {{"error",0},{"revision",1},{"copyMetadata",true}};
if(action=="listNext") return listNext();
if(action=="read")
{
@@ -770,6 +771,67 @@ public:
const auto canonical=fs::weakly_canonical(name,error);
return error?failure(error.value()):Json{{"error",0},{"path",utf8(canonical.native())}};
}
if(action=="copyPermissions")
{
DWORD size{};
GetFileSecurityW(name.c_str(),DACL_SECURITY_INFORMATION,nullptr,0,&size);
if(!size || GetLastError()!=ERROR_INSUFFICIENT_BUFFER) return failure();
Bytes descriptor(size);
if(!GetFileSecurityW(name.c_str(),DACL_SECURITY_INFORMATION,descriptor.data(),size,&size)) return failure();
LPWSTR sddl{};
if(!ConvertSecurityDescriptorToStringSecurityDescriptorW(descriptor.data(),SDDL_REVISION_1,
DACL_SECURITY_INFORMATION,&sddl,nullptr)) return failure();
const auto value=utf8(sddl);
LocalFree(sddl);
return {{"error",0},{"permissions",value}};
}
if(action=="applyCopyMetadata")
{
if(request.contains("modified"))
{
FileHandle file{CreateFileW(name.c_str(),FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return failure();
BY_HANDLE_FILE_INFORMATION info{};
if(!GetFileInformationByHandle(file.value,&info)) return failure();
if(info.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT) return failure(ERROR_NOT_SUPPORTED);
auto stamp=request.at("modified").get<uint64_t>();
FILETIME time{static_cast<DWORD>(stamp),static_cast<DWORD>(stamp>>32)};
if(!stamp) GetSystemTimeAsFileTime(&time);
if(!SetFileTime(file.value,nullptr,nullptr,&time)) return failure();
}
if(request.contains("permissions"))
{
FileHandle file{CreateFileW(name.c_str(),FILE_READ_ATTRIBUTES|READ_CONTROL|WRITE_DAC,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return failure();
BY_HANDLE_FILE_INFORMATION info{};
if(!GetFileInformationByHandle(file.value,&info)) return failure();
if(info.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT) return failure(ERROR_NOT_SUPPORTED);
PSECURITY_DESCRIPTOR descriptor{};
const auto sddl=wide(request.at("permissions").get<std::string>());
if(!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(),SDDL_REVISION_1,
&descriptor,nullptr)) return failure();
SECURITY_DESCRIPTOR_CONTROL control{};
DWORD revision{};
BOOL present{}, defaulted{};
PACL acl{};
auto error=DWORD(ERROR_SUCCESS);
if(!GetSecurityDescriptorDacl(descriptor,&present,&acl,&defaulted) || !present ||
!GetSecurityDescriptorControl(descriptor,&control,&revision)) error=ERROR_INVALID_DATA;
else
{
auto security=DACL_SECURITY_INFORMATION|((control&SE_DACL_PROTECTED)?
PROTECTED_DACL_SECURITY_INFORMATION:UNPROTECTED_DACL_SECURITY_INFORMATION);
error=SetSecurityInfo(file.value,SE_FILE_OBJECT,security,nullptr,nullptr,acl,nullptr);
}
LocalFree(descriptor);
if(error) return failure(error);
}
return ok();
}
if(action=="mkdir") return CreateDirectoryW(name.c_str(),nullptr)?ok():failure();
if(action=="mkdir-link")
{
+31
View File
@@ -200,6 +200,37 @@ int main()
catch(const std::system_error &){}
verifyConnectionCancellation(client,key);
FilesConnection host(one,client,key);
{
const auto source=root/L"acl-source.txt", copied=root/L"acl-target.txt";
save(source,"source");
save(copied,"target");
auto get=fileRequest("copyPermissions",source);
const auto inherited=host.call(get);
checkFileReply(inherited);
auto acl=inherited.at("permissions").get<std::string>();
if(!acl.starts_with("D:P")) acl.insert(2,"P");
auto protect=fileRequest("applyCopyMetadata",source);
protect["permissions"]=acl;
const auto protectedSource=host.call(protect);
require(protectedSource.at("error")==ERROR_SUCCESS, "could not set a protected source DACL");
const auto permissions=host.call(get);
checkFileReply(permissions);
require(permissions.at("permissions").get<std::string>().starts_with("D:P"),
"copy permission action did not protect the Windows DACL");
auto apply=fileRequest("applyCopyMetadata",copied);
constexpr uint64_t modified=132537600000000000ULL;
apply["permissions"]=permissions.at("permissions");
apply["modified"]=modified;
const auto applied=host.call(apply);
require(applied.at("error")==ERROR_SUCCESS, "could not copy Windows metadata to the target");
auto result=host.call(fileRequest("copyPermissions",copied));
checkFileReply(result);
require(result.at("permissions")==permissions.at("permissions"),
"Windows permissions did not survive LAN metadata copy");
result=host.call(fileRequest("stat",copied));
checkFileReply(result);
require(result.at("modified")==modified,"LAN copy metadata lost the file modification time");
}
{
const Json hibernate={{"action","hibernate"}};
FilesConnection target(two,client,key);