Compare commits

..
19 changed files with 1250 additions and 232 deletions

No files matched your search

+41 -14
View File
@@ -252,6 +252,20 @@ Warning і початковий фокус на No.
останніх команд з історії, які починаються з набраного тексту.
Вибір підставляє всю команду. Підказки з історії доступні й у LAN-панелі.
- Правий клік по локальному файлу чи папці відкриває системне контекстне
меню Windows Shell. Правий клік по вільній області відкриває меню
поточної папки. Клавіша Context Menu або Shift+F10 використовує поточний
рядок. Команда з меню оновлює панель і зберігає папку, курсор та
актуальні позначки. Для LAN, FTP, SFTP, UNC та архівів контекстне меню
показує доступні команди Files.
- **Ctrl+A** або **F9 → Files → Properties** показує властивості поточного
файла чи папки. У локальній панелі можна змінити прапорці **Read-only**,
**Hidden**, **System**, **Archive** та **Not indexed**. **Save** застосовує
лише змінені прапорці й перечитує панель. Помилка Windows з’являється
окремим повідомленням. Прапорці папки застосовуються лише до самої папки.
У LAN, FTP, SFTP, UNC та архіві команда **Properties** також є в
контекстному меню й показує доступні метадані без редагування.
Для SFTP власник відображається як числовий UID, якщо сервер його надає.
- **F8 Delete** у нижньому рядку клавіш викликає той самий діалог видалення,
що й клавіша F8.
- У нижньому рядку, як у FAR, позначення клавіш сірі на чорному тлі,
@@ -545,18 +559,24 @@ Warning і початковий фокус на No.
## Панелі
- **F9 → Commands → Find files** або **Alt+F7** запускає фоновий пошук
файлів у поточній локальній папці та її підпапках. Поле приймає повне
ім’я або маску без урахування регістру. `*` відповідає довільній
файлів у поточній папці та її підпапках. Підтримуються локальні папки,
FTP, SFTP і KSwitcher LAN. Поле приймає повне ім’я або маску без
урахування регістру. `*` відповідає довільній
послідовності символів, `?` — одному символу. Приховані та системні
елементи можна включити прапорцем. Пошук не обходить junction та інші
посилання на каталоги. Esc під час пошуку зупиняє обхід і показує знайдене.
Результати відкриваються в тій самій панелі з відносними шляхами.
елементи можна включити прапорцем. У FTP і SFTP це також стосується
імен із крапкою на початку. Пошук не обходить junction та інші посилання
на каталоги, які джерело позначає як посилання. Esc зупиняє обхід.
При скасуванні або втраті з’єднання знайдені файли залишаються в панелі.
Заголовок віддалених результатів показує джерело і початкову папку,
а рядки показують відносний шлях до кожного файла.
Enter або подвійний клік відкриває папку й ставить курсор на файл.
Esc у результатах повертає вихідну папку, курсор і позначки.
У результатах F3/F4 відкривають файл, а F5/F6 працюють із позначеними
або поточним файлом, використовуючи папку іншої панелі як призначення.
F8 і Shift+Delete використовують звичайні підтвердження. Успішно
переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
або поточним файлом. F5 використовує папку іншої панелі як призначення.
У FTP і SFTP F6 перейменовує один результат у його власній папці.
Меню Files і нижній рядок клавіш враховують джерело, виділення та
можливість копіювання в іншу панель. F8 і Shift+Delete використовують звичайні підтвердження.
Успішно перейменовані, переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
з тією самою маскою й видимістю прихованих файлів.
- **Left/Right → Tree view** або Ctrl+F10 перемикає вигляд відповідної
@@ -726,12 +746,19 @@ Warning і початковий фокус на No.
діалог можна скасувати. Помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху.
- Помилки копіювання, переміщення й видалення показуються в червоному
модальному діалозі Far із причиною помилки та кнопкою OK.
- Якщо локальне перейменування або видалення заблоковане, кнопка Processes… відкриває
список процесів із назвою та PID. Перевірка папки включає вкладені елементи.
End process завершує вибраний процес після окремого підтвердження, після
чого список оновлюється. Якщо Windows обмежила доступ або перевірку
великої папки завершено частково, про це повідомляється в діалозі.
Операцію можна повторити після звільнення файла чи папки.
- **F9 → Commands → Processes** показує локальні процеси, PID, частку
загальної потужності CPU, робочий набір пам’яті та шлях виконуваного файла.
**Filter** шукає за іменем, шляхом або PID. **Sort** змінює порядок,
**Refresh** робить новий вимір. **Go to file** вибирає виконуваний файл
в активній панелі. **End process** завершує процес лише після підтвердження.
- **F9 → Files → Locking processes** перевіряє поточний локальний елемент або
позначені елементи. Кнопка **Processes…** у повідомленні про заблоковане
перейменування або видалення відкриває той самий список із фільтром за
вихідним шляхом. Для папки перевіряються також її вкладені елементи.
**Go to file** у цьому режимі відкриває виконуваний файл у другій панелі
зі збереженням вихідного файла в першій. Після завершення процесу список
перечитується. Якщо Windows обмежила доступ або перевірка великої папки
завершилася частково, діалог повідомляє про це.
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
+38 -7
View File
@@ -124,16 +124,25 @@ BEGIN
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 275, 140, 58, 16
END
609 DIALOGEX 0, 0, 350, 135
609 DIALOGEX 0, 0, 430, 204
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "", 430, 14, 17, 322, 20
LISTBOX 431, 14, 41, 322, 61, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
CONTROL "", 432, "Static", NOT WS_VISIBLE, 14, 108, 1, 1
CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 56, 110, 80, 16
CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 140, 110, 74, 16
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 218, 110, 65, 16
LTEXT "", 430, 16, 15, 398, 13, SS_PATHELLIPSIS | SS_NOPREFIX
LTEXT "&Filter", 440, 16, 33, 38, 13
FAR_EDIT(435, 0, 58, 32, 212, 15)
LTEXT "&Sort", 441, 277, 33, 34, 13
COMBOBOX 436, 312, 32, 102, 92, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
LTEXT "", 439, 17, 51, 397, 13, SS_NOPREFIX
LISTBOX 431, 16, 65, 398, 70, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
LTEXT "E&xecutable", 442, 16, 144, 71, 13
FAR_EDIT(438, ES_READONLY, 89, 143, 325, 15)
LTEXT "", 443, 16, 162, 398, 12, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 432, "Static", NOT WS_VISIBLE, 16, 179, 1, 1
CONTROL "&Go to file", 437, "Button", BS_OWNERDRAW | WS_TABSTOP, 35, 185, 90, 16
CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 130, 185, 90, 16
CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 225, 185, 78, 16
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 308, 185, 72, 16
END
608 DIALOGEX 0, 0, 220, 67
@@ -588,3 +597,25 @@ BEGIN
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 270, 183, 60, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 336, 183, 67, 17
END
125 DIALOGEX 0, 0, 360, 178
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Properties"
FONT 10, "Consolas"
BEGIN
LTEXT "", 580, 16, 15, 328, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 581, 16, 32, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 582, 16, 45, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 583, 16, 58, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 584, 16, 71, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 585, 16, 84, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 586, 16, 99, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
AUTOCHECKBOX "&Read-only", 587, 16, 114, 106, 13
AUTOCHECKBOX "&Hidden", 588, 128, 114, 106, 13
AUTOCHECKBOX "S&ystem", 589, 240, 114, 104, 13
AUTOCHECKBOX "&Archive", 590, 16, 128, 106, 13
AUTOCHECKBOX "Not &indexed", 591, 128, 128, 106, 13
LTEXT "", 592, 10, 146, 1, 1, NOT WS_VISIBLE
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 95, 153, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 185, 153, 80, 17
END
+17 -7
View File
@@ -37,6 +37,13 @@ constexpr std::int64_t archiveEpochOffset=11644473600, archiveTicksPerSecond=100
constexpr char unsafePath[]="The archive contains an unsafe or conflicting path.";
constexpr char encryptedArchive[]="This archive requires a password. Password-protected entries cannot be opened in Files.";
uint64_t archiveTime(bool present,int64_t seconds,long nanos)
{
if(!present || seconds < -archiveEpochOffset || seconds>=INT64_MAX/archiveTicksPerSecond-archiveEpochOffset)
return 0;
return static_cast<uint64_t>((seconds+archiveEpochOffset)*archiveTicksPerSecond+nanos/100);
}
struct ArchiveFileHandle
{
HANDLE value=INVALID_HANDLE_VALUE;
@@ -100,11 +107,15 @@ std::pair<fs::path,ArchiveEntry> decodeEntry(archive_entry *entry)
const auto size=archive_entry_size(entry);
if(size<0 || (!folder && !archive_entry_size_is_set(entry)))
throw std::runtime_error("The archive entry has an invalid size.");
const int64_t seconds=archive_entry_mtime(entry);
const auto modified=archive_entry_mtime_is_set(entry) && seconds>=-archiveEpochOffset &&
seconds<(INT64_MAX/archiveTicksPerSecond-archiveEpochOffset)?
static_cast<uint64_t>((seconds+archiveEpochOffset)*archiveTicksPerSecond+archive_entry_mtime_nsec(entry)/100):0;
return {relative,{static_cast<uint64_t>(size),modified,folder,archive_entry_is_encrypted(entry)!=0}};
ArchiveEntry metadata{
static_cast<uint64_t>(size),
archiveTime(archive_entry_mtime_is_set(entry),archive_entry_mtime(entry),archive_entry_mtime_nsec(entry)),
folder,archive_entry_is_encrypted(entry)!=0};
metadata.created=archiveTime(archive_entry_birthtime_is_set(entry),archive_entry_birthtime(entry),
archive_entry_birthtime_nsec(entry));
metadata.accessed=archiveTime(archive_entry_atime_is_set(entry),archive_entry_atime(entry),archive_entry_atime_nsec(entry));
if(const auto *owner=archive_entry_uname_w(entry)) metadata.owner=owner;
return {relative,std::move(metadata)};
}
void registerEntry(ArchiveEntries &entries,const fs::path &path,const ArchiveEntry &entry)
@@ -240,8 +251,7 @@ uint64_t archiveFileSize(const BY_HANDLE_FILE_INFORMATION &info)
bool sameArchiveFile(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right)
{
return left.dwVolumeSerialNumber==right.dwVolumeSerialNumber && left.nFileIndexHigh==right.nFileIndexHigh &&
left.nFileIndexLow==right.nFileIndexLow && archiveFileSize(left)==archiveFileSize(right) &&
return sameFileIdentity(left,right) && archiveFileSize(left)==archiveFileSize(right) &&
CompareFileTime(&left.ftLastWriteTime,&right.ftLastWriteTime)==0;
}
+3
View File
@@ -5,6 +5,7 @@
#include <functional>
#include <map>
#include <stop_token>
#include <string>
#include <vector>
namespace ks::files
@@ -18,6 +19,8 @@ struct ArchiveEntry
{
uint64_t size{}, modified{};
bool directory{}, encrypted{}, implicit{};
uint64_t created{}, accessed{};
std::wstring owner{};
};
using ArchiveEntries=std::map<std::filesystem::path,ArchiveEntry,ArchiveNameOrder>;
+11 -9
View File
@@ -1242,13 +1242,11 @@ INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPA
return paintTextDialog(dialog,message,wp,lp,L" Compare files ");
}
void compareSelectedFiles(HWND owner)
bool selectedComparisonFiles(CompareFile (&files)[2])
{
auto &current=panels[active],&other=panels[1-active];
const auto selected=selectedPanelPaths(current);
const auto opposite=selectedPanelPaths(other);
auto state=std::make_unique<FileComparison>();
auto &comparison=*state;
const auto pick=[](const Panel &panel,const fs::path &path,CompareFile &file)
{
const auto row=std::find(panel.rows.begin(),panel.rows.end(),path);
@@ -1261,13 +1259,17 @@ void compareSelectedFiles(HWND owner)
file={path,label,panel.peer,panel.ftp};
return true;
};
bool valid=false;
if(selected.size()==2)
valid=pick(current,selected[0],comparison.files[0]) && pick(current,selected[1],comparison.files[1]);
else if(selected.size()==1 && opposite.size()==1)
valid=pick(current,selected.front(),comparison.files[active]) &&
pick(other,opposite.front(),comparison.files[1-active]);
if(!valid)
return pick(current,selected[0],files[0]) && pick(current,selected[1],files[1]);
return selected.size()==1 && opposite.size()==1 && pick(current,selected.front(),files[active]) &&
pick(other,opposite.front(),files[1-active]);
}
void compareSelectedFiles(HWND owner)
{
auto state=std::make_unique<FileComparison>();
auto &comparison=*state;
if(!selectedComparisonFiles(comparison.files))
{
showFilesNotice(owner,L"Mark two text files in the active panel or select one text file in each panel.",
L"Compare files");
+189
View File
@@ -0,0 +1,189 @@
struct ContextPopup
{
HMENU handle=CreatePopupMenu();
~ContextPopup(){if(handle) DestroyMenu(handle);}
};
struct ShellMenuMessages
{
Microsoft::WRL::ComPtr<IContextMenu2> second;
Microsoft::WRL::ComPtr<IContextMenu3> third;
};
LRESULT CALLBACK shellMenuMessage(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR data)
{
if(message==WM_INITMENUPOPUP || message==WM_MENUCHAR ||
((message==WM_DRAWITEM || message==WM_MEASUREITEM) && !wp))
{
const auto &menu=*reinterpret_cast<const ShellMenuMessages*>(data);
LRESULT result{};
if(menu.third && menu.third->HandleMenuMsg2(message,wp,lp,&result)==S_OK) return result;
if(menu.second && message!=WM_MENUCHAR && menu.second->HandleMenuMsg(message,wp,lp)==S_OK)
return message==WM_DRAWITEM || message==WM_MEASUREITEM;
}
return DefSubclassProc(window,message,wp,lp);
}
enum class ShellPanelMenuResult { unavailable, canceled, invoked, rename, failed };
ShellPanelMenuResult showShellPanelMenu(HWND owner,const fs::path &directory,const fs::path &item,POINT screen)
{
const auto &path=item.empty()?directory:item;
PIDLIST_ABSOLUTE raw{};
if(FAILED(SHParseDisplayName(path.c_str(),nullptr,&raw,0,nullptr)) || !raw) return ShellPanelMenuResult::unavailable;
const std::unique_ptr<ITEMIDLIST,decltype(&CoTaskMemFree)> id(raw,CoTaskMemFree);
Microsoft::WRL::ComPtr<IShellFolder> folder;
Microsoft::WRL::ComPtr<IContextMenu> menu;
if(item.empty())
{
Microsoft::WRL::ComPtr<IShellFolder> desktop;
if(FAILED(SHGetDesktopFolder(desktop.GetAddressOf())) ||
FAILED(desktop->BindToObject(id.get(),nullptr,IID_PPV_ARGS(folder.GetAddressOf()))) ||
FAILED(folder->CreateViewObject(owner,IID_PPV_ARGS(menu.GetAddressOf()))))
return ShellPanelMenuResult::unavailable;
}
else
{
PCUITEMID_CHILD child{};
if(FAILED(SHBindToParent(id.get(),IID_PPV_ARGS(folder.GetAddressOf()),&child)) ||
FAILED(folder->GetUIObjectOf(owner,1,&child,IID_IContextMenu,nullptr,
reinterpret_cast<void**>(menu.GetAddressOf()))))
return ShellPanelMenuResult::unavailable;
}
ContextPopup popup;
const auto flags=item.empty()?CMF_NORMAL:CMF_NORMAL|CMF_CANRENAME;
constexpr UINT firstCommand=1,lastCommand=0x7fff;
if(!menu || !popup.handle || FAILED(menu->QueryContextMenu(popup.handle,0,firstCommand,lastCommand,flags)) ||
GetMenuItemCount(popup.handle)<=0) return ShellPanelMenuResult::unavailable;
ShellMenuMessages handler;
if(FAILED(menu.As(&handler.third))) menu.As(&handler.second);
constexpr UINT_PTR subclass=27;
if((handler.third || handler.second) &&
!SetWindowSubclass(owner,shellMenuMessage,subclass,reinterpret_cast<DWORD_PTR>(&handler)))
return ShellPanelMenuResult::unavailable;
const auto choice=static_cast<UINT>(TrackPopupMenuEx(popup.handle,TPM_RETURNCMD|TPM_RIGHTBUTTON,
screen.x,screen.y,owner,nullptr));
RemoveWindowSubclass(owner,shellMenuMessage,subclass);
if(choice<firstCommand || choice>lastCommand) return ShellPanelMenuResult::canceled;
const auto verb=choice-firstCommand;
wchar_t name[64]{};
if(SUCCEEDED(menu->GetCommandString(verb,GCS_VERBW,nullptr,reinterpret_cast<LPSTR>(name),std::size(name))))
{
if(!item.empty() && lstrcmpiW(name,L"rename")==0) return ShellPanelMenuResult::rename;
if(item.empty() && lstrcmpiW(name,L"refresh")==0) return ShellPanelMenuResult::invoked;
}
CMINVOKECOMMANDINFOEX request{sizeof(request)};
request.fMask=CMIC_MASK_UNICODE|CMIC_MASK_NOASYNC|CMIC_MASK_PTINVOKE;
request.hwnd=owner;
request.lpVerb=MAKEINTRESOURCEA(verb);
request.lpVerbW=MAKEINTRESOURCEW(verb);
const auto working=item.empty()?directory:item.parent_path();
request.lpDirectoryW=working.c_str();
request.nShow=SW_SHOWNORMAL;
request.ptInvoke=screen;
const auto result=menu->InvokeCommand(reinterpret_cast<LPCMINVOKECOMMANDINFO>(&request));
if(result==E_ABORT || result==HRESULT_FROM_WIN32(ERROR_CANCELLED)) return ShellPanelMenuResult::canceled;
return SUCCEEDED(result)?ShellPanelMenuResult::invoked:ShellPanelMenuResult::failed;
}
void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen)
{
const auto owner=GetParent(panel.list);
ContextPopup popup;
if(!popup.handle) return;
constexpr UINT openItem=1,findItems=2,newProfile=3,properties=4;
const auto add=[&](UINT id,const wchar_t *label){AppendMenuW(popup.handle,MF_STRING,id,label);};
if(transferProfileList(panel))
{
if(row!=LB_ERR)
{
add(openItem,L"Connect");
add(112,L"Edit connection");
}
add(newProfile,L"New connection");
}
else
{
if(row!=LB_ERR)
{
const bool folder=panel.sizes[row]==L"Folder";
if(folder || panel.findOrigin) add(openItem,folder?L"Open folder":L"Go to file");
if(!folder && remoteSearchActionAvailable(111)) add(111,L"View");
if(!folder && !panel.archive && remoteSearchActionAvailable(112)) add(112,L"Edit");
const auto &other=panels[1-active];
const bool localDestination=!other.peer && !other.ftp && !other.archive && !other.findOrigin;
const bool canCopy=panel.ftp || panel.archive?localDestination:!other.ftp && !other.archive && !other.findOrigin;
if(canCopy && !other.directory.empty() && remoteSearchActionAvailable(113))
add(113,panel.archive?L"Extract":L"Copy");
if(!panel.archive && (panel.ftp || canCopy) && remoteSearchActionAvailable(114))
add(114,panel.ftp?L"Rename":L"Move");
if(!panel.archive && remoteSearchActionAvailable(117)) add(117,L"Delete");
if(panelItemPropertiesAvailable(panel)) add(properties,L"Properties");
}
else if(!panel.findOrigin && !panel.archive && !panel.directory.empty()) add(115,L"Make folder");
if(!panel.archive && !panel.directory.empty()) add(findItems,L"Find files");
add(110,L"Refresh panel");
}
const auto command=static_cast<UINT>(TrackPopupMenuEx(popup.handle,TPM_RETURNCMD|TPM_RIGHTBUTTON,
screen.x,screen.y,owner,nullptr));
if(command==openItem) enter(panel);
else if(command==findItems) findPanelFiles(owner,panel);
else if(command==newProfile) editTransferProfile(panel,true);
else if(command==properties) showPanelItemProperties(owner,panel);
else if(command) SendMessageW(owner,WM_COMMAND,MAKEWPARAM(command,BN_CLICKED),0);
}
void showPanelContextMenu(HWND list,LPARAM position)
{
const auto index=GetDlgCtrlID(list)-102;
if(index<0 || index>=static_cast<int>(std::size(panels)) || terminalVisible || !IsWindowVisible(list)) return;
const auto owner=GetParent(list);
if(!commandLineAvailable(owner)) return;
auto &panel=panels[index];
RECT bounds{};
GetClientRect(list,&bounds);
POINT client{};
LRESULT hit=LB_ERR;
if(position==-1)
{
hit=currentPanelRow(panel);
RECT rowBounds{};
if(hit!=LB_ERR && SendMessageW(list,LB_GETITEMRECT,hit,reinterpret_cast<LPARAM>(&rowBounds))!=LB_ERR)
client.y=std::clamp(rowBounds.bottom,0L,std::max(0L,bounds.bottom-1));
client.x=std::min(2L*cellWidth,std::max(0L,bounds.right-1));
}
else
{
client={GET_X_LPARAM(position),GET_Y_LPARAM(position)};
ScreenToClient(list,&client);
if(!PtInRect(&bounds,client)) return;
hit=panelRowAt(list,client,SendMessageW(list,LB_GETTOPINDEX,0,0),panel.rows.size());
if(hit!=LB_ERR)
{
const auto previous=currentPanelRow(panel);
SendMessageW(list,LB_SETCURSEL,hit,0);
invalidatePanelCursorChange(list,previous);
}
}
activatePanel(index);
closePanelSearch();
panelClipboardContext=true;
clearTerminalSelection();
SetFocus(list);
POINT screen=client;
ClientToScreen(list,&screen);
const auto row=hit!=LB_ERR && panel.sizes[hit]!=L"Up"?hit:LB_ERR;
const auto directory=panel.directory;
const auto item=row==LB_ERR?fs::path{}:panel.rows[row];
const bool shell=!panel.peer && !panel.ftp && !panel.archive && !directory.empty() &&
!windowsNetworkPath(directory);
const auto result=shell?showShellPanelMenu(owner,directory,item,screen):ShellPanelMenuResult::unavailable;
if(result==ShellPanelMenuResult::unavailable) showFilesPanelContext(panel,row,screen);
else if(result==ShellPanelMenuResult::rename)
copySelection(owner,panel,panel,true,{item},item.parent_path(),true);
else if(result==ShellPanelMenuResult::invoked && IsWindow(owner) && panel.directory==directory &&
!panel.peer && !panel.ftp && !panel.archive) refreshPanel(panel);
else if(result==ShellPanelMenuResult::failed) setStatus(L"Windows could not complete the Shell command.");
if(IsWindow(owner)) restoreCommandFocus();
}
+10 -4
View File
@@ -76,15 +76,21 @@ void startFileSearch(Panel &panel,Panel::FindOptions options)
if(panel.scanRequest) return;
cancelFolderSizes(panel);
panel.remoteRetry.reset();
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)};
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.peer=panel.peer,.statusRevision=statusRevision,
.ftp=panel.ftp,.find=std::move(options)};
startDirectoryScan(panel);
}
void findLocalFiles(HWND owner,Panel &panel)
bool canFindFiles(const Panel &panel)
{
if(panel.peer || panel.ftp || panel.archive || panel.directory.empty())
return !panel.archive && !panel.directory.empty() && !transferProfileList(panel);
}
void findPanelFiles(HWND owner,Panel &panel)
{
if(!canFindFiles(panel))
{
setStatus(L"Find files requires a local folder.");
setStatus(L"Find files requires an open folder.");
return;
}
if(panel.scanRequest)
+64 -26
View File
@@ -29,45 +29,83 @@ std::unique_ptr<Panel::ScanResult> scanFileMatches(const Panel::ScanRequest &req
std::atomic_size_t &entriesRead,std::stop_token stop)
{
auto result=std::make_unique<Panel::ScanResult>();
FilesConnection local(nullptr);
std::vector<fs::path> pending{request.directory};
size_t visited=0;
while(!pending.empty() && !stop.stop_requested())
const bool remote=request.peer || request.ftp;
const auto walk=[&](const auto &listDirectory)
{
const auto directory=std::move(pending.back());
pending.pop_back();
try
std::vector<fs::path> pending{request.directory};
size_t visited=0;
while(!pending.empty() && !stop.stop_requested())
{
listFiles(local,directory,[&](const fs::path &path,const FileInfo &entry)
const auto directory=std::move(pending.back());
pending.pop_back();
try
{
if(stop.stop_requested()) return false;
entriesRead.store(++visited,std::memory_order_relaxed);
if(!request.find->includeHidden && (entry.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)))
if(!listDirectory(directory,[&](const fs::path &path,const FileInfo &entry)
{
if(stop.stop_requested()) return false;
if(path.parent_path()!=folderPathWithoutSeparator(directory)) return true;
entriesRead.store(++visited,std::memory_order_relaxed);
const auto name=path.filename().native();
if(!request.find->includeHidden &&
((entry.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)) ||
(request.ftp && name.starts_with(L'.')))) return true;
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)
{
if(!(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) pending.push_back(path);
}
else if((!request.ftp || !(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) &&
matchesFileMask(name,request.find->mask) &&
result->metadata.emplace(path,FolderEntryMetadata{
entry.attributes,entry.size,entry.modified}).second)
{
result->files.push_back(path);
if(entry.transfer) result->columnMetadata[path].transfer=entry.transfer;
}
return true;
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)
})) break;
}
catch(const std::system_error &error)
{
if(stop.stop_requested()) break;
const auto code=error.code().value();
if(remote && code!=ERROR_FILE_NOT_FOUND && code!=ERROR_PATH_NOT_FOUND &&
code!=ERROR_ACCESS_DENIED && code!=ERROR_DIRECTORY)
throw;
if(!remote && directory==request.directory)
{
if(!(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) pending.push_back(path);
}
else if(matchesFileMask(path.filename().native(),request.find->mask))
{
result->files.push_back(path);
result->metadata.emplace(path,FolderEntryMetadata{entry.attributes,entry.size,entry.modified});
result->failure=L"Cannot search folder: "+directory.native();
return;
}
result->error=ERROR_PARTIAL_COPY;
}
}
};
try
{
if(request.ftp)
{
TransferSession connection(*request.ftp,SftpAccess::normal,stop);
walk([&](const fs::path &directory,const FileVisitor &visit)
{
const auto error=connection.list(directory,visit,stop);
if(error==ERROR_CANCELLED) return false;
requireFileOperation(error==ERROR_SUCCESS || error==ERROR_NO_MORE_FILES,error);
return true;
});
}
catch(const std::system_error &)
else
{
if(directory==request.directory)
{
result->failure=L"Cannot search folder: "+directory.native();
return result;
}
result->error=ERROR_PARTIAL_COPY;
FilesConnection connection(request.peer?&*request.peer:nullptr,stop);
walk([&](const fs::path &directory,const FileVisitor &visit){return listFiles(connection,directory,visit);});
}
}
catch(const std::exception &)
{
if(remote) result->error=ERROR_CONNECTION_ABORTED;
else if(!stop.stop_requested()) result->failure=L"Cannot search folder: "+request.directory.native();
}
if(stop.stop_requested()) result->error=ERROR_CANCELLED;
result->opened=true;
result->opened=result->failure.empty();
std::sort(result->files.begin(),result->files.end());
return result;
}
+10 -10
View File
@@ -330,17 +330,17 @@ DWORD listFtpDirectory(FtpSession &session,const fs::path &directory,const FileV
const auto name=session.decodeName(entry.cFileName);
if(name.empty() || name==L"." || name==L".." || name.find_first_of(L"/\\:\r\n")!=name.npos)
continue;
ULARGE_INTEGER modified{}, size{};
FILETIME utc{};
if(LocalFileTimeToFileTime(&entry.ftLastWriteTime,&utc))
const auto ftpTime=[](const FILETIME &local) -> uint64_t
{
modified.HighPart=utc.dwHighDateTime;
modified.LowPart=utc.dwLowDateTime;
}
size.HighPart=entry.nFileSizeHigh;
size.LowPart=entry.nFileSizeLow;
if(!visit(directory/name,{entry.dwFileAttributes,size.QuadPart,modified.QuadPart}))
return ERROR_CANCELLED;
FILETIME utc{};
if((!local.dwLowDateTime && !local.dwHighDateTime) || !LocalFileTimeToFileTime(&local,&utc)) return 0;
return (uint64_t(utc.dwHighDateTime)<<32)|utc.dwLowDateTime;
};
FileInfo info{entry.dwFileAttributes,(uint64_t(entry.nFileSizeHigh)<<32)|entry.nFileSizeLow,
ftpTime(entry.ftLastWriteTime)};
const TransferItemMetadata details{ftpTime(entry.ftCreationTime),ftpTime(entry.ftLastAccessTime)};
if(details.created || details.accessed) info.transfer=details;
if(!visit(directory/name,info)) return ERROR_CANCELLED;
} while(!stop.stop_requested() && InternetFindNextFileA(search.value,&entry));
return stop.stop_requested()?ERROR_CANCELLED:GetLastError();
}
+338 -97
View File
@@ -12,15 +12,9 @@ DWORD probeDeleteAccess(const fs::path &path)
return probe.value==INVALID_HANDLE_VALUE?GetLastError():ERROR_SUCCESS;
}
struct LockProcess
{
DWORD pid;
FILETIME started{};
std::wstring name;
};
struct LockScan
{
std::vector<LockProcess> processes;
std::set<DWORD> pids;
bool incomplete{};
};
@@ -30,7 +24,6 @@ LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token st
const auto query=reinterpret_cast<decltype(&NtQueryInformationFile)>(
GetProcAddress(GetModuleHandleW(L"ntdll.dll"),"NtQueryInformationFile"));
if(!query) { result.incomplete=true; return result; }
std::set<DWORD> pids;
std::vector<ULONG_PTR> buffer(128);
const auto inspect=[&](const fs::path &path) {
const auto error=probeDeleteAccess(path);
@@ -63,7 +56,7 @@ LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token st
}
for(ULONG i=0;i<count;++i)
if(const auto pid=buffer[i+1];pid && pid<=MAXDWORD && pid!=GetCurrentProcessId())
pids.insert(static_cast<DWORD>(pid));
result.pids.insert(static_cast<DWORD>(pid));
};
auto remaining=8192u;
const auto deadline=GetTickCount64()+4000;
@@ -90,162 +83,410 @@ LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token st
}
if(error) result.incomplete=true;
}
for(const auto pid:pids)
return result;
}
struct ProcessIdentity
{
DWORD pid{};
uint64_t started{};
bool operator==(const ProcessIdentity &) const = default;
};
struct ProcessEntry
{
ProcessIdentity identity;
std::wstring name;
fs::path image;
std::optional<uint64_t> workingSet;
std::optional<double> cpu;
};
struct ProcessScan
{
std::vector<ProcessEntry> entries;
bool incomplete{};
};
constexpr uint64_t processTimeTicks(const FILETIME &time)
{
return (uint64_t(time.dwHighDateTime)<<32)|time.dwLowDateTime;
}
struct ProcessTimes
{
uint64_t started, busy;
std::chrono::steady_clock::time_point measured;
};
std::optional<ProcessTimes> readProcessTimes(HANDLE process)
{
FILETIME started{},exited{},kernel{},user{};
if(!GetProcessTimes(process,&started,&exited,&kernel,&user)) return {};
return ProcessTimes{processTimeTicks(started),processTimeTicks(kernel)+processTimeTicks(user),
std::chrono::steady_clock::now()};
}
ProcessScan scanProcesses(const std::vector<fs::path> &files,std::stop_token stop)
{
ProcessScan result;
LockScan locks;
if(!files.empty())
{
Handle process{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,pid)};
LockProcess entry{pid};
if(process.value)
locks=scanLockProcesses(files,stop);
result.incomplete=locks.incomplete;
if(locks.pids.empty() || stop.stop_requested()) return result;
}
const Handle snapshot{CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0)};
if(snapshot.value==INVALID_HANDLE_VALUE)
throw std::system_error(GetLastError(),std::system_category());
PROCESSENTRY32W process{sizeof(PROCESSENTRY32W)};
if(!Process32FirstW(snapshot.value,&process))
throw std::system_error(GetLastError(),std::system_category());
do
{
const auto pid=process.th32ProcessID;
if(files.empty() || locks.pids.contains(pid))
result.entries.push_back({{pid},process.szExeFile});
} while(!stop.stop_requested() && Process32NextW(snapshot.value,&process));
if(!stop.stop_requested() && GetLastError()!=ERROR_NO_MORE_FILES) result.incomplete=true;
std::map<DWORD,ProcessTimes> initial;
for(const auto &entry:result.entries)
{
if(stop.stop_requested()) return {};
const Handle handle{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,entry.identity.pid)};
if(handle.value)
if(const auto time=readProcessTimes(handle.value)) initial.emplace(entry.identity.pid,*time);
}
if(!initial.empty()) std::this_thread::sleep_for(std::chrono::milliseconds(350));
const auto logicalCpus=std::max(1ul,static_cast<unsigned long>(GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)));
std::array<wchar_t,32768> image;
for(auto &entry:result.entries)
{
if(stop.stop_requested()) return {};
const Handle handle{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,entry.identity.pid)};
if(!handle.value) continue;
const auto current=readProcessTimes(handle.value);
const auto before=initial.find(entry.identity.pid);
if(current && before!=initial.end() && current->started!=before->second.started) continue;
if(current)
{
FILETIME exit{},kernel{},user{};
GetProcessTimes(process.value,&entry.started,&exit,&kernel,&user);
wchar_t path[32768];
DWORD count=std::size(path);
if(QueryFullProcessImageNameW(process.value,0,path,&count))
entry.name=fs::path(std::wstring_view(path,count)).filename().wstring();
entry.identity.started=current->started;
if(before!=initial.end() && current->busy>=before->second.busy)
{
const auto elapsed=std::chrono::duration<double>(current->measured-before->second.measured).count();
if(elapsed>0)
entry.cpu=std::clamp((current->busy-before->second.busy)*0.00001/(elapsed*logicalCpus),0.0,100.0);
}
}
if(entry.name.empty()) entry.name=L"Unknown process";
result.processes.push_back(std::move(entry));
DWORD count=image.size();
if(QueryFullProcessImageNameW(handle.value,0,image.data(),&count))
entry.image=std::wstring_view(image.data(),count);
PROCESS_MEMORY_COUNTERS memory{sizeof(memory)};
if(K32GetProcessMemoryInfo(handle.value,&memory,sizeof(memory))) entry.workingSet=memory.WorkingSetSize;
}
return result;
}
struct LockDialog
constexpr int processScope=430,processList=431,processDivider=432,processEnd=433,processRefresh=434,
processFilter=435,processSort=436,processReveal=437,processImage=438,processColumns=439,processStatus=443;
constexpr UINT_PTR processScanTimer=1;
enum class ProcessOrder { pid, cpu, memory, name, image };
struct ProcessDialog
{
std::vector<fs::path> paths;
std::vector<LockProcess> processes;
std::future<LockScan> scan;
std::vector<fs::path> files;
std::vector<ProcessEntry> entries;
std::future<ProcessScan> scan;
std::stop_source stop;
std::wstring failure;
fs::path reveal;
bool incomplete{};
};
constexpr UINT_PTR lockScanTimer=1;
const ProcessEntry *selectedProcess(HWND dialog,const ProcessDialog &state)
{
const auto row=SendDlgItemMessageW(dialog,processList,LB_GETCURSEL,0,0);
if(row==LB_ERR) return nullptr;
const auto index=SendDlgItemMessageW(dialog,processList,LB_GETITEMDATA,row,0);
return index>=0 && size_t(index)<state.entries.size()?&state.entries[index]:nullptr;
}
void refreshLockProcesses(HWND window,LockDialog &state,std::shared_ptr<Handle> terminated={})
bool mayEndProcess(ProcessIdentity identity)
{
return identity.pid && identity.pid!=GetCurrentProcessId() && identity.started;
}
void updateSelectedProcess(HWND dialog,const ProcessDialog &state)
{
const auto *entry=selectedProcess(dialog,state);
const bool hasImage=entry && !entry->image.empty();
SetDlgItemTextW(dialog,processImage,hasImage?entry->image.c_str():entry?L"Unavailable":L"");
EnableWindow(GetDlgItem(dialog,processReveal),!state.scan.valid() && hasImage);
EnableWindow(GetDlgItem(dialog,processEnd),!state.scan.valid() && entry && mayEndProcess(entry->identity));
}
std::wstring processColumnsText(std::wstring_view pid,std::wstring_view cpu,std::wstring_view memory,
std::wstring_view name)
{
std::wostringstream fields;
fields<<std::right<<std::setw(10)<<pid<<L" "<<std::setw(7)<<cpu<<L" "<<std::setw(12)<<memory<<L" "<<name;
return fields.str();
}
int compareProcessNames(const std::wstring &left,const std::wstring &right)
{
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE);
}
void renderProcessList(HWND dialog,const ProcessDialog &state,std::optional<ProcessIdentity> preferred={})
{
const auto field=GetDlgItem(dialog,processFilter);
std::wstring query(GetWindowTextLengthW(field)+1,L'\0');
query.resize(GetWindowTextW(field,query.data(),static_cast<int>(query.size())));
const auto contains=[&](std::wstring_view value)
{
return query.empty() || (!value.empty() && FindNLSStringEx(LOCALE_NAME_INVARIANT,FIND_FROMSTART|NORM_IGNORECASE,
value.data(),static_cast<int>(value.size()),query.c_str(),static_cast<int>(query.size()),nullptr,
nullptr,nullptr,0)>=0);
};
std::vector<size_t> rows;
for(size_t i=0;i<state.entries.size();++i)
{
const auto &entry=state.entries[i];
if(contains(entry.name) || contains(entry.image.native()) || contains(std::to_wstring(entry.identity.pid)))
rows.push_back(i);
}
const auto order=static_cast<ProcessOrder>(SendDlgItemMessageW(dialog,processSort,CB_GETCURSEL,0,0));
std::sort(rows.begin(),rows.end(),[&](size_t a,size_t b)
{
const auto &left=state.entries[a],&right=state.entries[b];
if(order==ProcessOrder::cpu && left.cpu!=right.cpu) return left.cpu>right.cpu;
if(order==ProcessOrder::memory && left.workingSet!=right.workingSet) return left.workingSet>right.workingSet;
if(order==ProcessOrder::name || order==ProcessOrder::image)
{
const auto names=order==ProcessOrder::name?compareProcessNames(left.name,right.name):
compareProcessNames(left.image.native(),right.image.native());
if(names!=CSTR_EQUAL) return names==CSTR_LESS_THAN;
}
return left.identity.pid<right.identity.pid;
});
const auto list=GetDlgItem(dialog,processList);
SendMessageW(list,WM_SETREDRAW,FALSE,0);
SendMessageW(list,LB_RESETCONTENT,0,0);
LRESULT selected=0;
for(const auto index:rows)
{
const auto &entry=state.entries[index];
wchar_t cpu[16]=L"—";
if(entry.cpu) swprintf_s(cpu,L"%.1f%%",*entry.cpu);
const auto text=processColumnsText(std::to_wstring(entry.identity.pid),cpu,
entry.workingSet?formatSize(*entry.workingSet):L"—",entry.name);
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(text.c_str()));
if(row<0) continue;
SendMessageW(list,LB_SETITEMDATA,row,index);
if(preferred==entry.identity) selected=row;
}
if(!rows.empty()) SendMessageW(list,LB_SETCURSEL,selected,0);
SendMessageW(list,WM_SETREDRAW,TRUE,0);
InvalidateRect(list,nullptr,TRUE);
updateSelectedProcess(dialog,state);
std::wstring status;
if(state.scan.valid()) status=state.files.empty()?L"Sampling processes…":L"Checking files for locking processes…";
else if(!state.failure.empty()) status=state.failure;
else if(state.entries.empty()) status=state.files.empty()?L"No processes found.":L"No locking processes found.";
else if(rows.empty()) status=L"No processes match the filter.";
else status=std::to_wstring(rows.size())+(query.empty()?L"":L" of "+std::to_wstring(state.entries.size()))+L" shown";
if(state.incomplete && !state.scan.valid() && state.failure.empty()) status+=L" Some items could not be checked.";
SetDlgItemTextW(dialog,processStatus,status.c_str());
}
void refreshProcesses(HWND dialog,ProcessDialog &state,std::shared_ptr<Handle> ended={})
{
if(state.scan.valid()) return;
state.processes.clear();
SendDlgItemMessageW(window,431,LB_RESETCONTENT,0,0);
EnableWindow(GetDlgItem(window,433),FALSE);
EnableWindow(GetDlgItem(window,434),FALSE);
SetDlgItemTextW(window,430,L"Checking which processes are using the file or folder…");
const auto *entry=selectedProcess(dialog,state);
const auto selected=entry?std::optional(entry->identity):std::nullopt;
state.failure.clear();
try
{
std::packaged_task<LockScan()> task([paths=state.paths,stop=state.stop.get_token(),terminated=std::move(terminated)] {
if(terminated) WaitForSingleObject(terminated->value,2500);
return scanLockProcesses(paths,stop);
std::packaged_task<ProcessScan()> task([files=state.files,stop=state.stop.get_token(),ended=std::move(ended)] {
if(ended) WaitForSingleObject(ended->value,2500);
return scanProcesses(files,stop);
});
auto future=task.get_future();
if(!SetTimer(window,lockScanTimer,50,nullptr))
if(!SetTimer(dialog,processScanTimer,50,nullptr))
throw std::runtime_error("Could not start the process scan.");
std::thread(std::move(task)).detach();
state.scan=std::move(future);
}
catch(const std::exception &)
{
KillTimer(window,lockScanTimer);
EnableWindow(GetDlgItem(window,434),TRUE);
SetDlgItemTextW(window,430,L"Could not start the process scan.");
KillTimer(dialog,processScanTimer);
state.failure=L"Could not start the process scan.";
}
EnableWindow(GetDlgItem(dialog,processRefresh),!state.scan.valid());
renderProcessList(dialog,state,selected);
}
void endLockProcess(HWND window,LockDialog &state)
void endFileProcess(HWND dialog,ProcessDialog &state)
{
const auto index=SendDlgItemMessageW(window,431,LB_GETCURSEL,0,0);
if(index<0 || size_t(index)>=state.processes.size()) return;
const auto &entry=state.processes[index];
auto error=[&](const wchar_t *message) {
showFilesNotice(window,message,L"End process",{.tone=FilesNoticeTone::warning});
const auto *entry=selectedProcess(dialog,state);
if(state.scan.valid() || !entry || !mayEndProcess(entry->identity)) return;
const auto error=[&](const wchar_t *message)
{
showFilesNotice(dialog,message,L"End process",{.tone=FilesNoticeTone::warning});
};
auto process=std::make_shared<Handle>();
process->value=OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,entry.pid);
FILETIME started{},exited{},kernel{},user{};
const auto process=std::make_shared<Handle>();
process->value=OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,entry->identity.pid);
const auto current=process->value?readProcessTimes(process->value):std::nullopt;
BOOL critical{};
if(!process->value || !(entry.started.dwHighDateTime || entry.started.dwLowDateTime) ||
!GetProcessTimes(process->value,&started,&exited,&kernel,&user) ||
CompareFileTime(&started,&entry.started)!=0 || !IsProcessCritical(process->value,&critical) || critical)
if(!current || current->started!=entry->identity.started ||
!IsProcessCritical(process->value,&critical) || critical)
{
error(L"This process has exited, is protected, or cannot be identified.");
return;
}
const auto question=L"End "+entry.name+L" (PID "+std::to_wstring(entry.pid)+
const auto question=L"End "+entry->name+L" (PID "+std::to_wstring(entry->identity.pid)+
L")?\r\nUnsaved work in the process may be lost.";
if(showFilesNotice(window,question.c_str(),L"End process",{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
if(showFilesNotice(dialog,question.c_str(),L"End process",{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
return;
if(WaitForSingleObject(process->value,0)==WAIT_TIMEOUT && !TerminateProcess(process->value,1))
const auto alive=WaitForSingleObject(process->value,0);
if(alive!=WAIT_OBJECT_0 && (alive!=WAIT_TIMEOUT || !TerminateProcess(process->value,1)))
{
const auto message=ks::lastError(L"Could not end the process");
error(message.c_str());
const auto reason=ks::lastError(L"Could not end the process");
error(reason.c_str());
return;
}
refreshLockProcesses(window,state,std::move(process));
refreshProcesses(dialog,state,process);
}
INT_PTR CALLBACK lockProcessesDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
INT_PTR CALLBACK processesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(window,DWLP_USER,lp);
prepareCopyDialog(window);
for(const auto id:{430,431}) SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
const auto list=GetDlgItem(window,431);
RECT bounds{};
GetWindowRect(list,&bounds);
auto &state=*reinterpret_cast<ProcessDialog *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,processScope);
if(state.files.empty()) SetDlgItemTextW(dialog,processScope,L"This PC");
else
{
auto scope=L"Locks for "+state.files.front().native();
if(state.files.size()>1) scope+=L" (+"+std::to_wstring(state.files.size()-1)+L" more)";
SetDlgItemTextW(dialog,processScope,scope.c_str());
}
const auto filterField=GetDlgItem(dialog,processFilter);
SendMessageW(filterField,EM_SETLIMITTEXT,1024,0);
const auto sortField=GetDlgItem(dialog,processSort);
for(const auto name:{L"PID",L"CPU",L"Memory",L"Name",L"Executable"})
SendMessageW(sortField,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
SendMessageW(sortField,CB_SETCURSEL,1,0);
installFarCombo(sortField,filterField);
SetDlgItemTextW(dialog,processColumns,processColumnsText(L"PID",L"CPU",L"Working set",L"Process").c_str());
const auto list=GetDlgItem(dialog,processList);
const auto bounds=dialogControlBounds(dialog,processList);
SetWindowPos(list,nullptr,0,0,std::max(1L,bounds.right-bounds.left-scrollBarWidth(list)),
bounds.bottom-bounds.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
installScrollBar(list,window);
layoutDialogButtons(window,432,{433,434,IDOK});
SendMessageW(window,DM_SETDEFID,IDOK,0);
SetFocus(GetDlgItem(window,IDOK));
refreshLockProcesses(window,*reinterpret_cast<LockDialog *>(lp));
installScrollBar(list,dialog);
layoutDialogButtons(dialog,processDivider,{processReveal,processEnd,processRefresh,IDOK});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(filterField);
refreshProcesses(dialog,state);
return FALSE;
}
auto *data=reinterpret_cast<LockDialog *>(GetWindowLongPtrW(window,DWLP_USER));
auto *data=reinterpret_cast<ProcessDialog *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!data) return FALSE;
auto &state=*data;
if(message==WM_TIMER && wp==lockScanTimer)
if(message==WM_TIMER && wp==processScanTimer)
{
if(!state.scan.valid() || state.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
return TRUE;
KillTimer(window,lockScanTimer);
EnableWindow(GetDlgItem(window,434),TRUE);
KillTimer(dialog,processScanTimer);
EnableWindow(GetDlgItem(dialog,processRefresh),TRUE);
const auto *entry=selectedProcess(dialog,state);
const auto selected=entry?std::optional(entry->identity):std::nullopt;
try
{
auto result=state.scan.get();
for(auto &entry:result.processes)
{
const auto label=entry.name+L" (PID "+std::to_wstring(entry.pid)+L")";
if(SendDlgItemMessageW(window,431,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()))>=0)
state.processes.push_back(std::move(entry));
}
SetDlgItemTextW(window,430,state.processes.empty()?
(result.incomplete?L"No processes found. Some items could not be checked.":L"No locking processes found."):
(result.incomplete?L"Possible locking processes. The scan was incomplete.":L"Processes using locked files or folders."));
if(!state.processes.empty())
{
SendDlgItemMessageW(window,431,LB_SETCURSEL,0,0);
EnableWindow(GetDlgItem(window,433),TRUE);
}
state.entries=std::move(result.entries);
state.incomplete=result.incomplete;
}
catch(const std::exception &) {SetDlgItemTextW(window,430,L"Could not check for locking processes.");}
catch(const std::system_error &e) {state.failure=fileError(e);}
catch(const std::exception &) {state.failure=L"Could not read the process list.";}
renderProcessList(dialog,state,selected);
return TRUE;
}
if(message==WM_DRAWITEM && wp==processSort)
{
drawFarComboRow(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
}
if(message==WM_CTLCOLORLISTBOX && reinterpret_cast<HWND>(lp)!=GetDlgItem(dialog,processList))
{
const auto dc=reinterpret_cast<HDC>(wp);
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[Dialog]);
return reinterpret_cast<INT_PTR>(teal);
}
if(message==WM_COMMAND)
{
switch(LOWORD(wp))
const auto id=LOWORD(wp),notification=HIWORD(wp);
if((id==processFilter && notification==EN_CHANGE) || (id==processSort && notification==CBN_SELCHANGE))
{
case 433: endLockProcess(window,state); return TRUE;
case 434: refreshLockProcesses(window,state); return TRUE;
const auto *entry=selectedProcess(dialog,state);
renderProcessList(dialog,state,entry?std::optional(entry->identity):std::nullopt);
return TRUE;
}
if(id==processList && notification==LBN_SELCHANGE)
{
updateSelectedProcess(dialog,state);
return TRUE;
}
if(id==processReveal || (id==processList && notification==LBN_DBLCLK))
{
const auto *entry=selectedProcess(dialog,state);
if(!state.scan.valid() && entry && !entry->image.empty())
{
state.reveal=entry->image;
FilesModalDialog::finish(dialog,processReveal);
}
return TRUE;
}
switch(id)
{
case processEnd: endFileProcess(dialog,state); return TRUE;
case processRefresh: refreshProcesses(dialog,state); return TRUE;
case IDOK:
case IDCANCEL: FilesModalDialog::finish(window,IDCANCEL); return TRUE;
case IDCANCEL: FilesModalDialog::finish(dialog,IDCANCEL); return TRUE;
}
}
if(message==WM_CLOSE) {FilesModalDialog::finish(window,IDCANCEL);return TRUE;}
return paintCopyDialog(window,message,wp,lp,L" Locking processes ",false,{432},false,GetDlgItem(window,431));
if(message==WM_CLOSE) {FilesModalDialog::finish(dialog,IDCANCEL);return TRUE;}
const auto title=state.files.empty()?L" Processes ":L" Locking processes ";
return paintCopyDialog(dialog,message,wp,lp,title,false,{processDivider},false,GetDlgItem(dialog,processList));
}
void showLockProcesses(HWND owner,std::vector<fs::path> paths)
void showProcesses(HWND owner,std::vector<fs::path> paths)
{
LockDialog state{std::move(paths)};
FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,lockProcessesDialog,
const auto source=active;
ProcessDialog state{std::move(paths)};
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,processesDialog,
reinterpret_cast<LPARAM>(&state));
state.stop.request_stop();
if(result!=processReveal) return;
const auto destination=state.files.empty()?source:1-source;
if(quickViewWindow && destination!=quickViewSource) toggleQuickView(owner);
revealLocalFile(panels[destination],state.reveal);
}
bool panelLockSearchAvailable(const Panel &panel)
{
return !terminalVisible && panelItemPropertiesAvailable(panel) && !panel.ftp && !panel.peer &&
!panel.archive && !windowsNetworkPath(panel.directory);
}
void showPanelLockProcesses(HWND owner,Panel &panel)
{
if(panelLockSearchAvailable(panel)) showProcesses(owner,selectedPanelPaths(panel));
}
+196 -32
View File
@@ -9,6 +9,8 @@
#include <commdlg.h>
#include <aclapi.h>
#include <sddl.h>
#include <tlhelp32.h>
#include <psapi.h>
#include <cmath>
#include <numbers>
#include <algorithm>
@@ -39,6 +41,7 @@
#include "files_compare_text.h"
#include "files_image_decode.h"
#include "files_win32_directory.h"
#include "files_win32_replace.h"
#include "files_command_completion.h"
#include "files_text_window.h"
#include "files_menu_navigation.h"
@@ -67,11 +70,18 @@ using ks::lan::filePath;
using ks::lan::checkFileReply;
using ks::files::validFileName;
struct TransferItemMetadata
{
uint64_t created{}, accessed{};
std::optional<uint32_t> owner, permissions;
};
struct FileInfo
{
DWORD attributes;
uint64_t size, modified;
std::optional<uint64_t> allocated{};
std::optional<TransferItemMetadata> transfer{};
};
FileInfo fileInfo(const Json &row)
{
@@ -383,6 +393,20 @@ fs::path folderPathWithoutSeparator(fs::path path)
return path;
}
bool windowsNetworkPath(const fs::path &path)
{
std::wstring_view name=path.native();
if(name.starts_with(L"\\\\?\\"))
{
name.remove_prefix(4);
if(name.size()>=4 && CompareStringOrdinal(name.data(),4,L"UNC\\",4,TRUE)==CSTR_EQUAL) return true;
return name.size()>=3 && name[1]==L':' && name[2]==L'\\' &&
GetDriveTypeW(std::wstring(name.substr(0,3)).c_str())==DRIVE_REMOTE;
}
return name.starts_with(L"\\\\") || name.starts_with(L"//") ||
GetDriveTypeW(path.root_path().c_str())==DRIVE_REMOTE;
}
fs::path panelParentPath(const fs::path &directory,bool local)
{
if(!directory.has_relative_path()) return {};
@@ -504,6 +528,7 @@ struct ColumnMetadata
std::wstring owner;
std::optional<uint64_t> allocated;
std::optional<DWORD> links;
std::optional<TransferItemMetadata> transfer;
};
using ColumnMetadataMap=std::map<fs::path,ColumnMetadata>;
@@ -715,7 +740,8 @@ std::wstring panelCaption(const Panel &panel)
const auto display=panel.directory.lexically_relative(panel.archive->file.parent_path());
return L"Archive · "+display.native();
}
return panel.findOrigin?L"Search results":panelLocation(panel);
if(!panel.findOrigin) return panelLocation(panel);
return panel.ftp || panel.peer?L"Search results · "+panelLocation(panel):L"Search results";
}
Panel panels[2];
@@ -2137,6 +2163,37 @@ std::vector<fs::path> selectedPanelPaths(const Panel &panel)
return paths;
}
bool remoteSearchResults(const Panel &panel)
{
return panel.findOrigin && (panel.peer || panel.ftp);
}
bool remoteSearchActionAvailable(int command)
{
const auto &panel=panels[active];
if(!remoteSearchResults(panel)) return true;
if(command==110 || command==116) return true;
const auto row=currentPanelRow(panel);
if(row==LB_ERR || panel.scanRequest || command==115) return false;
if(command==112)
{
const auto entry=panel.metadata.find(panel.rows[row]);
return entry!=panel.metadata.end() && !(entry->second.attributes&FILE_ATTRIBUTE_READONLY);
}
if(command==114 && panel.ftp)
{
const auto marked=std::find(panel.marked.begin(),panel.marked.end(),true);
return marked==panel.marked.end() || std::find(std::next(marked),panel.marked.end(),true)==panel.marked.end();
}
if(command==113 || command==114)
{
const auto &destination=panels[1-active];
return !quickViewWindow && !destination.findOrigin && !destination.archive && !destination.ftp &&
(!panel.ftp || !destination.peer) && !destination.directory.empty();
}
return true;
}
void copyPanelNames(HWND owner)
{
const auto &panel=panels[active];
@@ -2628,6 +2685,8 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U
void updateSelectionSummary(const Panel &panel)
{
if(&panel==&panels[active] && remoteSearchResults(panel))
for(const auto key:commands) InvalidateRect(key,nullptr,FALSE);
const bool hadSummary=hasSelectionSummary();
size_t marked=0,unmeasured=0;
uint64_t total=0;
@@ -2715,6 +2774,8 @@ std::wstring folderMeasurementText(const Panel &panel,const fs::path &path,size_
void showFileDetails(const Panel &panel)
{
refreshQuickView(panel);
if(&panel==&panels[active])
for(const auto key:commands) InvalidateRect(key,nullptr,FALSE);
if(&panel==&panels[active] && showDirectoryScanProgress(panels[active])) return;
if(panel.remoteRetry)
{
@@ -2724,7 +2785,11 @@ void showFileDetails(const Panel &panel)
if(panel.findOrigin)
{
const auto error=panel.findOrigin->error;
setStatus(std::to_wstring(panel.rows.size())+(error==ERROR_CANCELLED?L" matches (stopped)":
const auto count=std::to_wstring(panel.rows.size());
if(error==ERROR_CONNECTION_ABORTED)
setStatus(count+(panel.rows.size()==1?L" match":L" matches")+
L" · Connection interrupted · Ctrl+R Retry · Esc Back");
else setStatus(count+(error==ERROR_CANCELLED?L" matches (stopped)":
error?L" matches (some folders could not be read)":L" matches")+
L" · Enter: Go · Esc: Back");
return;
@@ -2841,6 +2906,7 @@ std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &reque
error=ftp.list(directory.empty()?ftpInitialDirectory:directory,[&](const fs::path &path,const FileInfo &info)
{
if(!metadata.emplace(path,FolderEntryMetadata{info.attributes,info.size,info.modified}).second) return true;
if(info.transfer) columnMetadata[path].transfer=info.transfer;
(info.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path);
entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed);
return !stop.stop_requested();
@@ -2960,6 +3026,14 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
const bool sameDirectory=sameFolderPath(previousDirectory,directory,provider);
auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=scan;
const bool partial=error==ERROR_CANCELLED;
if(error==ERROR_CONNECTION_ABORTED && request.find && panel.findOrigin && sameDirectory && files.empty() &&
request.find->mask==panel.findOrigin->options.mask &&
request.find->includeHidden==panel.findOrigin->options.includeHidden)
{
panel.findOrigin->error=error;
if(&panel==&panels[active]) showFileDetails(panel);
return true;
}
if(!failure.empty())
{
if((!peer && !request.ftp) || &panel==&panels[active]) setStatus(failure);
@@ -3111,7 +3185,11 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
if(renderTree) appendTreeRows(panel,rows);
else if(finding)
{
for(const auto &file:files) add(file,file.lexically_relative(directory).native(),false);
for(const auto &file:files)
{
const auto relative=file.lexically_relative(directory);
add(file,panel.ftp?ftpPath(relative):relative.native(),false);
}
}
else
{
@@ -3207,7 +3285,8 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti
if(directory.empty() && !ftp) return;
panel.remoteRetry.reset();
if(!panel.view.revealedFile.empty() &&
(peer || ftp || panel.view.revealedFile.parent_path()!=directory)) panel.view.revealedFile.clear();
(panel.view.revealedFile.parent_path()!=folderPathWithoutSeparator(directory) ||
(!samePanelSource(panel,peer,ftp) && panel.view.revealedFile!=selection))) panel.view.revealedFile.clear();
if(directory!=panel.directory || !samePanelSource(panel,peer,ftp))
cancelFolderSizes(panel);
panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback),
@@ -3247,7 +3326,7 @@ void collectDirectoryScans()
try
{
auto result=panel.scan.get();
if(!result->failure.empty() && (request.peer || usesFtp) && !panel.scanStop.stop_requested())
if(!request.find && !result->failure.empty() && (request.peer || usesFtp) && !panel.scanStop.stop_requested())
{
retry=Panel::RemoteRetry{{request.directory,request.selection,usesFtp?request.ftp->id:std::string{},
request.peer,request.navigationPosition,usesFtp?request.ftp->protocol:TransferProtocol::ftp},
@@ -3633,7 +3712,7 @@ void collectFolderSizes(Panel &panel)
void openSelectedText(const Panel &panel, bool edit, bool external,bool hex=false);
ks::files::TextDialogs textWindowDialogs();
void findLocalFiles(HWND owner,Panel &panel);
void findPanelFiles(HWND owner,Panel &panel);
void compareSelectedFiles(HWND owner);
void createArchive(HWND owner,Panel &panel);
void addToArchive(HWND owner,Panel &panel,std::vector<fs::path> sources);
@@ -3753,6 +3832,12 @@ bool driveSourceRow(LRESULT row)
row==sftpDriveRow() || row==smbDriveRow() || row==recentDriveRow());
}
bool panelItemPropertiesAvailable(const Panel &panel);
void showPanelItemProperties(HWND owner,Panel &panel);
bool panelLockSearchAvailable(const Panel &panel);
void showPanelLockProcesses(HWND owner,Panel &panel);
void showProcesses(HWND owner,std::vector<fs::path> paths={});
bool selectablePickerRow(LRESULT row)
{
if(row<0) return false;
@@ -3793,13 +3878,16 @@ void selectDrive()
else if(menuIndex==2 && (row==4 || row==5)) openSelectedText(panels[active],row==5,true);
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==9) findPanelFiles(owner,panels[active]);
else if(menuIndex==2 && row==10) toggleQuickView(owner);
else if(menuIndex==2 && row==11) copyFullPanelPath(owner,panels[active]);
else if(menuIndex==2 && row==12) openSpaceAnalyzer(owner,panels[active]);
else if(menuIndex==2 && row==13) openSelectedText(panels[active],false,false,true);
else if(menuIndex==2 && row==14) ks::files::showAllViewerBookmarks(owner,textWindowDialogs());
else if(menuIndex==2 && row==15) showProcesses(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]);
else
{
const int command=menuIndex==1?113+static_cast<int>(row):110+static_cast<int>(row);
@@ -4527,7 +4615,8 @@ void enter(Panel &panel)
}
if(panel.findOrigin)
{
revealLocalFile(panel,target);
panel.view.revealedFile=target;
openOn(panel,target.parent_path(),false,panel.peer,target,{},panel.ftp);
return;
}
if(panel.sizes[row]==L"Folder" && toggleTreeRow(panel,static_cast<size_t>(row))) return;
@@ -5884,7 +5973,7 @@ void showFileOperationError(HWND owner,const wchar_t *title,const std::wstring &
setStatus(L"");
const auto choice=showFilesNotice(owner,message.c_str(),title,
{.tone=FilesNoticeTone::warning,.processes=!lockPaths.empty()});
if(choice==showProcessesButton) showLockProcesses(owner,std::move(lockPaths));
if(choice==showProcessesButton) showProcesses(owner,std::move(lockPaths));
}
void showTextMessage(HWND owner,const wchar_t *text)
@@ -6444,20 +6533,20 @@ struct ArchiveStaging
}
};
void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::vector<fs::path> external={},
fs::path targetFolder={})
void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::vector<fs::path> explicitItems={},
fs::path targetFolder={},bool renameHere=false)
{
const auto sourceFtp=source.ftp;
const bool ftpRename=move && sourceFtp && !transferProfileList(source);
const auto archive=source.archive?source.archive->file:fs::path{};
auto archiveDirectory=archive.empty()?fs::path{}:source.directory.lexically_relative(archive);
if(archiveDirectory==L".") archiveDirectory.clear();
if(quickViewWindow && &destination!=&panels[quickViewSource] && !ftpRename)
if(quickViewWindow && &destination!=&panels[quickViewSource] && !ftpRename && !renameHere)
{
setStatus(L"Close Quick View to use the destination pane.");
return;
}
if(destination.findOrigin && !ftpRename)
if(destination.findOrigin && !ftpRename && !renameHere)
{
setStatus(L"Open a destination folder in the other panel before copying or moving files.");
return;
@@ -6471,7 +6560,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
{
if(move || source.archive || source.peer || source.ftp)
setStatus(L"Use F5 from a local folder to add files to an archive.");
else addToArchive(owner,destination,external.empty()?selectedPanelPaths(source):std::move(external));
else addToArchive(owner,destination,explicitItems.empty()?selectedPanelPaths(source):std::move(explicitItems));
return;
}
if(!archive.empty() && (move || destination.peer || destination.ftp))
@@ -6497,7 +6586,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
CopyRequest request{{},targetFolder};
request.move=move;
request.ftpRename=ftpRename;
request.externalSources=!external.empty();
request.externalSources=!explicitItems.empty() && !renameHere;
request.archiveSource=!archive.empty();
if(ftp)
{
@@ -6507,12 +6596,16 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
request.otherDirectory=ftpRename?destination.directory:targetFolder;
request.sourcePeer=source.peer?&*source.peer:nullptr;
request.otherPeer=request.destinationPeer=destination.peer?&*destination.peer:nullptr;
request.sources=request.externalSources?std::move(external):selectedPanelPaths(source);
request.sources=explicitItems.empty()?selectedPanelPaths(source):std::move(explicitItems);
if(request.sources.empty()) return;
if(ftpRename && request.sources.size()!=1)
if(ftpRename)
{
setStatus(L"Select one remote file or folder to rename.");
return;
if(request.sources.size()!=1)
{
setStatus(L"Select one remote file or folder to rename.");
return;
}
request.destination=request.sources.front().parent_path();
}
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(ftpRename?113:102),owner,copyDialog,
reinterpret_cast<LPARAM>(&request));
@@ -6586,6 +6679,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
throw std::system_error(ERROR_ALREADY_EXISTS,std::system_category());
if(progress.canceled) return;
sourceHost.ftp->rename(path,target);
if(fromSearch) removed.insert(path);
++copied;
++progress.files;
++progress.totalFiles;
@@ -7063,7 +7157,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
}
else host.remove(current,permanent,attributes,readOnly);
++done;
if(!panel.peer && !ftp) removed.insert(current);
removed.insert(current);
}
catch(const std::system_error &e)
{
@@ -7083,8 +7177,12 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
progressDialog.close();
for(auto &visible:panels)
{
if(treePanelActive(visible) && samePanelSource(panel,visible.peer,visible.ftp)) pruneTreeMarks(visible,removed);
if(visible.findOrigin) pruneSearchResults(visible,removed);
const bool sameSource=samePanelSource(panel,visible.peer,visible.ftp);
if(treePanelActive(visible) && sameSource) pruneTreeMarks(visible,removed);
if(visible.findOrigin)
{
if(sameSource) pruneSearchResults(visible,removed);
}
else if(!visible.directory.empty()) open(visible,visible.directory);
}
SetFocus(panel.list);
@@ -7546,12 +7644,26 @@ void openOrCreateText(HWND owner,const Panel &panel)
void editTransferProfile(Panel &panel,bool create);
#include "files_drag_drop.inl"
#include "files_properties.inl"
#include "files_context_menu.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_CONTEXTMENU)
{
showPanelContextMenu(window,lp);
return 0;
}
if(message==WM_RBUTTONUP)
{
POINT screen{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
ClientToScreen(window,&screen);
showPanelContextMenu(window,MAKELPARAM(screen.x,screen.y));
return 0;
}
if(message==WM_MOUSEMOVE && (wp&MK_LBUTTON) && GetCapture()==window && panelDragStart)
{
const auto dpi=GetDpiForWindow(window);
@@ -7825,23 +7937,55 @@ void openMenu(HWND window, int index)
if(detailedPanel(panel)) rows.push_back(L" Columns…");
}
}
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10",L"Pack files…\tAlt+F5"};
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10",L"Pack files…\tAlt+F5",
L"Properties…\tCtrl+A",L"Locking processes…"};
else if(index==2)
{
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"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…"};
L"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…",L"Processes…"};
}
const auto &panel=panels[active];
const bool remoteResults=remoteSearchResults(panel);
const auto resultRow=remoteResults?currentPanelRow(panel):LB_ERR;
commandActions.clear();
if(index==2)
if(index==1 && remoteResults)
{
if(remoteSearchActionAvailable(113)) commandActions.push_back(0);
if(remoteSearchActionAvailable(114))
{
if(panel.ftp) rows[1]=L"Rename\tF6";
commandActions.push_back(1);
}
commandActions.push_back(3);
if(panelItemPropertiesAvailable(panel)) commandActions.push_back(5);
}
else if(index==1)
{
commandActions={0,1,2,3,4};
if(panelItemPropertiesAvailable(panel)) commandActions.push_back(5);
if(panelLockSearchAvailable(panel)) commandActions.push_back(6);
}
else if(index==2)
{
commandActions={0,3,11,-1,1,13,14,2,4,5,8};
if(!panels[active].peer && !panels[active].ftp)
if(!terminalVisible) commandActions.push_back(15);
if(!terminalVisible && canFindFiles(panels[active])) commandActions.insert(commandActions.begin()+1,9);
if(!terminalVisible && !panels[active].peer && !panels[active].ftp)
commandActions.insert(commandActions.begin()+2,12);
if(remoteResults)
{
commandActions.insert(commandActions.begin()+1,9);
if(!terminalVisible) commandActions.insert(commandActions.begin()+2,12);
CompareFile comparison[2];
const auto view=remoteSearchActionAvailable(111);
const auto edit=remoteSearchActionAvailable(112);
const auto compare=view && selectedComparisonFiles(comparison);
std::erase_if(commandActions,[&](int action)
{
return action==4 || action==5 || (action==2 && !edit) || (action==8 && !compare) ||
(!view && (action==1 || action==13)) || (resultRow==LB_ERR && action==11);
});
}
if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10);
if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7});
@@ -8491,6 +8635,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
if(std::find(std::begin(commands),std::end(commands),item.hwndItem)!=std::end(commands))
{
if(item.CtlID==114 && remoteSearchResults(panels[active]) && panels[active].ftp)
text=L"F6 Rename";
const auto separator=text.find(L' ');
auto key=text.substr(0,separator);
if(key.starts_with(L'F') && key.size()>1) key.erase(0,1);
@@ -8499,7 +8645,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
action.left=shortcut.right;
paintText(item.hDC,shortcut,key.c_str(),RGB(184,184,184),RGB(0,0,0));
if(action.left<action.right)
paintText(item.hDC,action,text.c_str()+separator+1,colors[Selection],colors[Footer]);
paintText(item.hDC,action,remoteSearchActionAvailable(item.CtlID)?text.c_str()+separator+1:L"",
colors[Selection],colors[Footer]);
return TRUE;
}
const bool popupRow=item.hwndItem==picker || item.hwndItem==completionList;
@@ -8784,7 +8931,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
if (HIWORD(wp) == BN_CLICKED)
{
for(const auto &command:keyBar)
if(LOWORD(wp)==command.id) SendMessageW(panels[active].list,WM_KEYDOWN,command.key,0);
if(LOWORD(wp)==command.id && remoteSearchActionAvailable(command.id))
SendMessageW(panels[active].list,WM_KEYDOWN,command.key,0);
}
if (LOWORD(wp) >= 102 && LOWORD(wp) <= 103 && HIWORD(wp) == LBN_DBLCLK)
enter(panels[LOWORD(wp) - 102]);
@@ -8935,6 +9083,16 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
GetFocus()==terminalInput)
message.hwnd=terminalInput;
if(handleQuickViewKey(window,message) || handlePanelPathKey(window,message)) continue;
if((message.message==WM_KEYDOWN || message.message==WM_SYSKEYDOWN) &&
!terminalVisible && commandLineAvailable(window) &&
(message.hwnd==terminalInput || message.hwnd==panels[0].list || message.hwnd==panels[1].list) &&
!(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
(message.wParam==VK_APPS || (message.wParam==VK_F10 && (GetKeyState(VK_SHIFT)&0x8000))))
{
if(!(message.lParam & (1LL<<30))) showPanelContextMenu(
message.hwnd==terminalInput?panels[active].list:message.hwnd,-1);
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) &&
@@ -8968,7 +9126,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
}
if(panel.findOrigin && !panel.scanRequest)
{
openOn(panel,panel.directory,false,{});
open(panel,panel.directory);
continue;
}
if(panel.folderSizeJob)
@@ -8992,7 +9150,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
hidePicker();
showMenu(false);
if(message.wParam==VK_F5) createArchive(window,panels[active]);
else findLocalFiles(window,panels[active]);
else findPanelFiles(window,panels[active]);
}
continue;
}
@@ -9117,6 +9275,12 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
if(!(message.lParam & (1LL<<30))) copyFullPanelPath(window,panels[active]);
continue;
}
if(ctrl && !shift && message.wParam=='A' && !terminalVisible && commandLineAvailable(window) &&
(!GetWindowTextLengthW(terminalInput) || panelFocused) && panelItemPropertiesAvailable(panels[active]))
{
if(!(message.lParam&(1LL<<30))) showPanelItemProperties(window,panels[active]);
continue;
}
if(shift && !ctrl && message.wParam==VK_F4 && !terminalVisible)
{
if(!(message.lParam & (1LL<<30)) && commandLineAvailable(window))
+244
View File
@@ -0,0 +1,244 @@
constexpr int propertiesName=580, propertiesFirstDetail=581, propertiesOtherFlags=586;
constexpr int propertiesFirstFlag=587, propertiesDivider=592;
constexpr DWORD propertyOpenFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT;
constexpr DWORD editablePropertyFlags[]{
FILE_ATTRIBUTE_READONLY,FILE_ATTRIBUTE_HIDDEN,FILE_ATTRIBUTE_SYSTEM,FILE_ATTRIBUTE_ARCHIVE,
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED};
struct FilePropertyFlag
{
DWORD flag;
const wchar_t *name;
};
std::wstring propertyFlagNames(DWORD flags)
{
constexpr FilePropertyFlag names[]{
{FILE_ATTRIBUTE_READONLY,L"Read-only"},{FILE_ATTRIBUTE_HIDDEN,L"Hidden"},
{FILE_ATTRIBUTE_SYSTEM,L"System"},{FILE_ATTRIBUTE_DIRECTORY,L"Directory"},
{FILE_ATTRIBUTE_ARCHIVE,L"Archive"},{FILE_ATTRIBUTE_NORMAL,L"Normal"},
{FILE_ATTRIBUTE_TEMPORARY,L"Temporary"},{FILE_ATTRIBUTE_SPARSE_FILE,L"Sparse"},
{FILE_ATTRIBUTE_REPARSE_POINT,L"Reparse point"},{FILE_ATTRIBUTE_COMPRESSED,L"Compressed"},
{FILE_ATTRIBUTE_OFFLINE,L"Offline"},{FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,L"Not indexed"},
{FILE_ATTRIBUTE_ENCRYPTED,L"Encrypted"},{FILE_ATTRIBUTE_INTEGRITY_STREAM,L"Integrity stream"},
{FILE_ATTRIBUTE_NO_SCRUB_DATA,L"No scrub"},{FILE_ATTRIBUTE_PINNED,L"Pinned"},
{FILE_ATTRIBUTE_UNPINNED,L"Unpinned"}};
std::wstring text;
const auto append=[&](std::wstring_view name)
{
if(!text.empty()) text+=L", ";
text+=name;
};
for(const auto &[flag,name]:names)
if(flags&flag)
{
append(name);
flags&=~flag;
}
if(flags)
{
wchar_t number[16]{};
swprintf_s(number,L"0x%08lX",static_cast<unsigned long>(flags));
append(number);
}
return text.empty()?L"—":text;
}
std::wstring propertyDate(uint64_t ticks)
{
const auto time=localFileTime(ticks);
if(!time) return L"—";
wchar_t label[32]{};
swprintf_s(label,L"%04u-%02u-%02u %02u:%02u:%02u",unsigned(time->wYear),unsigned(time->wMonth),
unsigned(time->wDay),unsigned(time->wHour),unsigned(time->wMinute),unsigned(time->wSecond));
return label;
}
struct ItemProperties
{
std::wstring name, owner;
uint64_t created{}, modified{}, accessed{}, changed{};
DWORD flags{}, requested{};
std::vector<std::wstring> details(bool includeMissing) const
{
std::vector<std::wstring> rows;
if(includeMissing || !owner.empty()) rows.push_back(L"Owner "+(owner.empty()?L"—":owner));
const auto date=[&](const wchar_t *label,uint64_t value)
{
if(includeMissing || value) rows.push_back(label+propertyDate(value));
};
date(L"Created ",created);
date(L"Modified ",modified);
date(L"Accessed ",accessed);
date(L"Changed ",changed);
return rows;
}
};
INT_PTR CALLBACK itemPropertiesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &properties=*reinterpret_cast<ItemProperties*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,propertiesName);
SetDlgItemTextW(dialog,propertiesName,properties.name.c_str());
const auto details=properties.details(true);
for(size_t index=0;index<details.size();++index)
SetDlgItemTextW(dialog,propertiesFirstDetail+static_cast<int>(index),details[index].c_str());
auto other=properties.flags&~FILE_ATTRIBUTE_NORMAL;
for(size_t index=0;index<std::size(editablePropertyFlags);++index)
{
const auto flag=editablePropertyFlags[index];
const auto id=propertiesFirstFlag+static_cast<int>(index);
installFarCheckbox(GetDlgItem(dialog,id),FarCheckboxSurface::gray);
CheckDlgButton(dialog,id,(properties.flags&flag)?BST_CHECKED:BST_UNCHECKED);
other&=~flag;
}
SetDlgItemTextW(dialog,propertiesOtherFlags,(L"Other flags "+propertyFlagNames(other)).c_str());
layoutDialogButtons(dialog,propertiesDivider,{IDOK,IDCANCEL});
return TRUE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
{
auto &properties=*reinterpret_cast<ItemProperties*>(GetWindowLongPtrW(dialog,DWLP_USER));
for(size_t index=0;index<std::size(editablePropertyFlags);++index)
if(IsDlgButtonChecked(dialog,propertiesFirstFlag+static_cast<int>(index))==BST_CHECKED)
properties.requested|=editablePropertyFlags[index];
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
return paintCopyDialog(dialog,message,wp,lp,L" Properties ",false,{propertiesDivider});
}
void showReadOnlyProperties(HWND owner,const ItemProperties &properties,const std::wstring &attributes)
{
auto text=properties.name+L"\r\n\r\n";
for(const auto &line:properties.details(false)) text+=line+L"\r\n";
text+=attributes;
showFilesNotice(owner,text.c_str(),L"Properties",{.tone=FilesNoticeTone::neutral});
}
bool panelItemPropertiesAvailable(const Panel &panel)
{
const auto row=currentPanelRow(panel);
return row!=LB_ERR && panel.sizes[row]!=L"Up" && !transferProfileList(panel);
}
void showSourceItemProperties(HWND owner,const Panel &panel,const fs::path &path,ItemProperties properties)
{
const auto found=panel.metadata.find(path);
if(found==panel.metadata.end()) return;
const auto &entry=found->second;
properties.modified=entry.modified;
if(panel.peer)
{
showReadOnlyProperties(owner,properties,L"Attributes "+propertyFlagNames(entry.attributes));
return;
}
auto attributes=(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)?std::wstring(L"Folder"):
(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)?std::wstring(L"Special file"):std::wstring(L"File");
if(panel.archive && panel.archive->entries)
{
const auto &members=*panel.archive->entries;
if(const auto member=members.find(path.lexically_relative(panel.archive->file));member!=members.end())
{
properties.owner=member->second.owner;
properties.created=member->second.created;
properties.accessed=member->second.accessed;
if(member->second.encrypted) attributes+=L", Encrypted";
}
}
else if(const auto extra=panel.columnMetadata.find(path);
extra!=panel.columnMetadata.end() && extra->second.transfer)
{
const auto &details=*extra->second.transfer;
properties.created=details.created;
properties.accessed=details.accessed;
if(details.owner) properties.owner=L"UID "+std::to_wstring(*details.owner);
if(details.permissions)
{
wchar_t mode[12]{};
swprintf_s(mode,L"%04o",static_cast<unsigned>(*details.permissions));
attributes+=std::wstring(L"\r\nPermissions ")+mode;
}
}
if(panel.ftp && panel.ftp->protocol==TransferProtocol::ftp)
{
const auto flags=entry.attributes&~(FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_DIRECTORY);
if(flags) attributes+=L"\r\nAttributes "+propertyFlagNames(flags);
}
showReadOnlyProperties(owner,properties,L"Type "+attributes);
}
DWORD changeItemProperties(const fs::path &path,HANDLE original,const ItemProperties &properties)
{
DWORD editable{};
for(const auto flag:editablePropertyFlags) editable|=flag;
const DWORD changed=(properties.flags^properties.requested)&editable;
if(!changed) return ERROR_SUCCESS;
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES,columnFileShare,nullptr,
OPEN_EXISTING,propertyOpenFlags,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return GetLastError();
BY_HANDLE_FILE_INFORMATION before{},current{};
if(!GetFileInformationByHandle(original,&before) || !GetFileInformationByHandle(file.value,&current))
return GetLastError();
if(!ks::files::sameFileIdentity(before,current)) return ERROR_FILE_INVALID;
FILE_BASIC_INFO latest{};
if(!GetFileInformationByHandleEx(file.value,FileBasicInfo,&latest,sizeof(latest))) return GetLastError();
if(!((latest.FileAttributes^properties.requested)&changed)) return ERROR_SUCCESS;
FILE_BASIC_INFO update{};
update.FileAttributes=(latest.FileAttributes&~(changed|FILE_ATTRIBUTE_NORMAL))|(properties.requested&changed);
if(!update.FileAttributes) update.FileAttributes=FILE_ATTRIBUTE_NORMAL;
if(!SetFileInformationByHandle(file.value,FileBasicInfo,&update,sizeof(update))) return GetLastError();
return ERROR_SUCCESS;
}
void showPanelItemProperties(HWND owner,Panel &panel)
{
if(!panelItemPropertiesAvailable(panel)) return;
const auto path=panel.rows[currentPanelRow(panel)];
ItemProperties properties{path.filename().native()};
if(panel.ftp || panel.peer || panel.archive)
{
showSourceItemProperties(owner,panel,path,std::move(properties));
return;
}
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,columnFileShare,nullptr,OPEN_EXISTING,
propertyOpenFlags,nullptr)};
FILE_BASIC_INFO info{};
if(file.value==INVALID_HANDLE_VALUE || !GetFileInformationByHandleEx(file.value,FileBasicInfo,&info,sizeof(info)))
{
const auto error=GetLastError();
refreshPanel(panel);
showFileOperationError(owner,L"Could not read properties",fileError({static_cast<int>(error),std::system_category()}));
return;
}
std::map<std::wstring,std::wstring> owners;
properties.owner=localOwnerName(path,owners);
properties.created=info.CreationTime.QuadPart;
properties.modified=info.LastWriteTime.QuadPart;
properties.accessed=info.LastAccessTime.QuadPart;
properties.changed=info.ChangeTime.QuadPart;
properties.flags=info.FileAttributes;
if(windowsNetworkPath(path))
{
showReadOnlyProperties(owner,properties,L"Attributes "+propertyFlagNames(properties.flags));
return;
}
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(125),owner,itemPropertiesDialog,
reinterpret_cast<LPARAM>(&properties))!=IDOK) return;
const auto error=changeItemProperties(path,file.value,properties);
refreshPanel(panel);
if(error!=ERROR_SUCCESS)
showFileOperationError(owner,L"Could not save attributes",error==ERROR_FILE_INVALID?
L"The item was replaced while the properties were open.":
fileError({static_cast<int>(error),std::system_category()}));
}
+24 -9
View File
@@ -83,6 +83,7 @@ class SshConnection
ks::lan::Network network_;
ks::lan::WinSocket socket_;
std::optional<std::stop_callback<std::function<void()>>> stopConnection_;
std::vector<Hop> hops_;
std::string fingerprint_;
@@ -156,12 +157,16 @@ class SshConnection
"SFTP key authentication failed (use RSA PEM without a passphrase, or ECDSA OpenSSH with its .pub file)");
}
void connectHop(const TransferProfile &profile,bool probeOnly)
void connectHop(const TransferProfile &profile,bool probeOnly,std::stop_token stop)
{
if(!probeOnly && profile.hostFingerprint.empty())
throw std::runtime_error("The SFTP host key is untrusted. Edit the profile and use Test connection to verify it.");
Hop hop;
if(hops_.empty()) connectSshSocket(socket_,profile);
if(hops_.empty())
{
connectSshSocket(socket_,profile);
if(stop.stop_possible()) stopConnection_.emplace(stop,[handle=socket_.value] {shutdown(handle,SD_BOTH);});
}
else
{
const auto host=ks::utf8(profile.host);
@@ -212,7 +217,7 @@ class SshConnection
}
public:
explicit SshConnection(const TransferProfile &destination,bool probeOnly=false)
explicit SshConnection(const TransferProfile &destination,bool probeOnly=false,std::stop_token stop={})
{
initializeSsh();
const auto profiles=sshProfiles.load();
@@ -222,8 +227,9 @@ public:
{
for(size_t i=0;i<route.size();++i)
{
requireFileOperation(!stop.stop_requested(),ERROR_CANCELLED);
const auto &profile=route[i];
try {connectHop(profile,probeOnly && i+1==route.size());}
try {connectHop(profile,probeOnly && i+1==route.size(),stop);}
catch(const std::exception &error)
{
if(route.size()==1) throw;
@@ -284,8 +290,8 @@ class SftpSession
}
public:
explicit SftpSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal):
connection_(profile),access_(access)
explicit SftpSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal,
std::stop_token stop={}):connection_(profile,false,stop),access_(access)
{
if(access==SftpAccess::normal)
{
@@ -348,9 +354,18 @@ public:
else if(!LIBSSH2_SFTP_S_ISREG(attrs.permissions)) attributes=FILE_ATTRIBUTE_REPARSE_POINT;
if(!(attrs.permissions&0222)) attributes|=FILE_ATTRIBUTE_READONLY;
}
const auto modified=(attrs.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)?
(uint64_t(attrs.mtime)+11644473600ULL)*10000000ULL:0;
if(!visit(directory/child,{attributes,attrs.filesize,modified})) return ERROR_CANCELLED;
const auto sftpTime=[](unsigned long seconds){return (uint64_t(seconds)+11644473600ULL)*10000000ULL;};
FileInfo info{attributes,attrs.filesize,0};
TransferItemMetadata details;
if(attrs.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)
{
info.modified=sftpTime(attrs.mtime);
details.accessed=sftpTime(attrs.atime);
}
if(attrs.flags&LIBSSH2_SFTP_ATTR_UIDGID) details.owner=attrs.uid;
if(attrs.flags&LIBSSH2_SFTP_ATTR_PERMISSIONS) details.permissions=attrs.permissions&07777;
if(details.accessed || details.owner || details.permissions) info.transfer=details;
if(!visit(directory/child,info)) return ERROR_CANCELLED;
}
return ERROR_CANCELLED;
}
+1 -2
View File
@@ -87,8 +87,7 @@ bool sameFile(HANDLE a, HANDLE b)
BY_HANDLE_FILE_INFORMATION first{}, second{};
if (!GetFileInformationByHandle(a, &first) || !GetFileInformationByHandle(b, &second))
fail("Check file identity");
return first.dwVolumeSerialNumber == second.dwVolumeSerialNumber &&
first.nFileIndexHigh == second.nFileIndexHigh && first.nFileIndexLow == second.nFileIndexLow;
return sameFileIdentity(first,second);
}
std::filesystem::path temporaryPath(const std::filesystem::path &directory)
+3 -2
View File
@@ -59,9 +59,10 @@ class TransferSession
std::optional<SftpSession> sftp_;
public:
explicit TransferSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal)
explicit TransferSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal,
std::stop_token stop={})
{
if(profile.protocol==TransferProtocol::sftp) sftp_.emplace(profile,access);
if(profile.protocol==TransferProtocol::sftp) sftp_.emplace(profile,access,stop);
else ftp_.emplace(profile);
}
+6
View File
@@ -7,6 +7,12 @@
namespace ks::files
{
inline bool sameFileIdentity(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right)
{
return left.dwVolumeSerialNumber==right.dwVolumeSerialNumber && left.nFileIndexHigh==right.nFileIndexHigh &&
left.nFileIndexLow==right.nFileIndexLow;
}
inline DWORD replaceFileWithBackup(const std::filesystem::path &original,const std::filesystem::path &replacement,
const std::filesystem::path &backup)
{
+30 -11
View File
@@ -115,6 +115,7 @@ constexpr DWORD SocketTimeout=5000;
class Wire
{
SOCKET socket;
std::stop_token stop;
std::unique_ptr<InputCipher> tx,rx;
void bytes(void *buffer,size_t size,bool sending)
{
@@ -122,19 +123,36 @@ class Wire
const auto deadline=GetTickCount64()+SocketTimeout;
while(size)
{
if(GetTickCount64()>=deadline)
throw std::system_error(WSAETIMEDOUT,std::system_category());
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
const auto now=GetTickCount64();
if(now>=deadline) throw std::system_error(WSAETIMEDOUT,std::system_category());
if(stop.stop_possible())
{
fd_set ready{};
FD_SET(socket,&ready);
const auto interval=static_cast<long>(std::min<ULONGLONG>(100,deadline-now));
timeval wait{0,interval*1000};
const auto available=select(0,sending?nullptr:&ready,sending?&ready:nullptr,nullptr,&wait);
if(available==SOCKET_ERROR) socketError();
if(!available) continue;
}
const auto n=sending?send(socket,next,static_cast<int>(size),0):
recv(socket,next,static_cast<int>(size),0);
if(n==SOCKET_ERROR) socketError();
if(n==SOCKET_ERROR)
{
if(stop.stop_possible() && WSAGetLastError()==WSAEWOULDBLOCK) continue;
socketError();
}
if(!n) throw std::system_error(WSAECONNRESET,std::system_category());
size-=n;
next+=n;
}
}
public:
explicit Wire(SOCKET socket):socket(socket)
explicit Wire(SOCKET socket,std::stop_token stop={}):socket(socket),stop(stop)
{
u_long nonblocking=1;
if(stop.stop_possible() && ioctlsocket(socket,FIONBIO,&nonblocking)==SOCKET_ERROR) socketError();
if(setsockopt(socket,SOL_SOCKET,SO_RCVTIMEO,reinterpret_cast<const char*>(&SocketTimeout),sizeof(SocketTimeout)) ||
setsockopt(socket,SOL_SOCKET,SO_SNDTIMEO,reinterpret_cast<const char*>(&SocketTimeout),sizeof(SocketTimeout)))
socketError();
@@ -897,7 +915,7 @@ struct FilesConnection::Impl
std::unique_ptr<Wire> wire;
FileOperations local{false};
Impl()=default;
explicit Impl(const FilesPeer *peer)
explicit Impl(const FilesPeer *peer,std::stop_token stop)
{
if(!peer) return;
const auto pairing=Json::parse(unprotect(readFile(dataDirectory()/L"lan-pairing.bin",256*1024)));
@@ -905,15 +923,16 @@ struct FilesConnection::Impl
throw std::system_error(ERROR_ACCESS_DENIED,std::system_category());
const auto id=pairing.at("id").get<std::string>();
const auto key=pairing.at("trusted").at(peer->id).at("key").get<std::string>();
connect(*peer,id,key);
connect(*peer,id,key,stop);
}
void connect(const FilesPeer &peer,const std::string &id,const std::string &key)
void connect(const FilesPeer &peer,const std::string &id,const std::string &key,std::stop_token stop={})
{
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
network.emplace();
socket.value=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(socket.value==INVALID_SOCKET) socketError();
connectPeer(socket.value,peer);
wire=std::make_unique<Wire>(socket.value);
wire=std::make_unique<Wire>(socket.value,stop);
const auto nonce=randomHex(16);
wire->write({{"version",1},{"client",id},{"server",peer.id},{"nonce",nonce}});
const auto challenge=wire->read().at("challenge").get<std::string>();
@@ -929,11 +948,11 @@ DWORD hibernateFromPairedPC()
return requestSystemHibernate();
}
FilesConnection::FilesConnection(const FilesPeer *peer):impl(std::make_unique<Impl>(peer)){}
FilesConnection::FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key):
FilesConnection::FilesConnection(const FilesPeer *peer,std::stop_token stop):impl(std::make_unique<Impl>(peer,stop)){}
FilesConnection::FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key,std::stop_token stop):
impl(std::make_unique<Impl>())
{
impl->connect(peer,local,key);
impl->connect(peer,local,key,stop);
}
FilesConnection::~FilesConnection()=default;
Json FilesConnection::call(const Json &request,const FileProgress &progress)
+2 -2
View File
@@ -23,8 +23,8 @@ class FilesConnection
struct Impl;
std::unique_ptr<Impl> impl;
public:
explicit FilesConnection(const FilesPeer *peer = nullptr);
FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key);
explicit FilesConnection(const FilesPeer *peer = nullptr,std::stop_token stop={});
FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key,std::stop_token stop={});
~FilesConnection();
Json call(const Json &request, const FileProgress &progress = {});
};
+23
View File
@@ -5,6 +5,7 @@
#include <bit>
#include <atomic>
#include <fstream>
#include <future>
#include <iostream>
#include <thread>
@@ -49,6 +50,27 @@ std::string load(const fs::path &path)
return {std::istreambuf_iterator<char>(file),{}};
}
void verifyConnectionCancellation(const std::string &client,const std::string &key)
{
const auto serverId=randomHex(16);
// Keep the server listening while deliberately withholding its handshake response.
FilesListener stalled(serverId,[&](const std::string &id){return id==client?key:std::string{};},0);
require(stalled.port()!=0,"cancellation fixture did not start");
const FilesPeer peer{serverId,"127.0.0.1",L"Stalled peer",stalled.port()};
std::stop_source stop;
auto waiting=std::async(std::launch::async,[&]
{
try {FilesConnection connection(peer,client,key,stop.get_token());}
catch(const std::system_error &error) {return error.code().value();}
return 0;
});
std::this_thread::sleep_for(std::chrono::milliseconds(150));
stop.request_stop();
require(waiting.wait_for(std::chrono::seconds(3))==std::future_status::ready,
"cancellation did not stop the stalled LAN handshake");
require(waiting.get()==ERROR_CANCELLED,"stalled LAN handshake reported the wrong cancellation error");
}
void verifyDirection(const FilesPeer *sourcePeer,const FilesPeer *targetPeer,
const std::string &id,const std::string &key,const fs::path &root)
{
@@ -176,6 +198,7 @@ int main()
require(false,"unpaired client authenticated");
}
catch(const std::system_error &){}
verifyConnectionCancellation(client,key);
FilesConnection host(one,client,key);
{
const Json hibernate={{"action","hibernate"}};