Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4992b783bc | ||
|
|
fe1b114b38 | ||
|
|
936c199a43 | ||
|
|
d12273da67 | ||
|
|
1a81075763 | ||
|
|
d5996237c6 | ||
|
|
4ef30ab5e8 | ||
|
|
6279a2ee4f |
No files matched your search
+46
-8
@@ -77,6 +77,32 @@ Warning і початковий фокус на No.
|
||||
Files блокує підключення до передачі пароля або підпису.
|
||||
Для запланованої заміни ключа використовуй **Forget host key**,
|
||||
а тоді **Test connection** зі звіркою нового відбитка.
|
||||
- **Jump via** у SFTP-профілі вибирає попередній збережений SSH-профіль
|
||||
у маршруті. **Direct** підключається напряму. Профіль-посередник може
|
||||
мати власний **Jump via**. Кожен хост має окремий довірений ключ і
|
||||
перевіряється до входу. Маршрут підтримує до восьми хостів і перевіряється
|
||||
на цикли під час збереження. Профіль без доступу до SFTP можна
|
||||
використовувати для пересилання через SSH.
|
||||
- На підключеній SFTP-панелі Ctrl+O відкриває інтерактивну SSH-сесію.
|
||||
Enter після введення команди запускає ту саму сесію з командного рядка.
|
||||
Після `cd` успішно відкритий каталог відображається в панелі.
|
||||
Зміна каталогу в панелі також оновлює робочу папку сесії.
|
||||
Поки команда працює, термінал приймає її інтерактивне введення, зокрема
|
||||
Ctrl+C. При переході до іншої панелі чи джерела сесія від'єднується.
|
||||
Для синхронізації потрібні POSIX-оболонка й утиліта `base64` на сервері.
|
||||
Оболонка та SFTP мають бачити однакові абсолютні шляхи.
|
||||
- **SFTP server for sudo** у профілі приймає абсолютний шлях до
|
||||
серверного OpenSSH `sftp-server`. Після відмови в доступі Viewer і
|
||||
Hex Viewer пропонують один повтор через `sudo` в режимі тільки читання.
|
||||
F2 в Editor після відмови в доступі до запису показує окремий запит.
|
||||
Відмова або Esc під час привілейованого запису залишає чернетку в Editor,
|
||||
якщо заміна файла ще не завершилась. Успішна заміна зберігає POSIX-власника,
|
||||
групу та біти режиму доступу.
|
||||
- Серверний адміністратор має окремо дозволити потрібний варіант команди
|
||||
`sudo -n` для цього облікового запису. Перегляд використовує
|
||||
`sftp-server -R`, а збереження використовує `sftp-server` без цього
|
||||
прапорця. Files закриває привілейоване з'єднання після операції, розриву
|
||||
або тайм-ауту мережевого запиту. Пароль sudo не запитується.
|
||||
- Для SFTP використовуються ключі хоста ECDSA або RSA з підписом SHA‑2.
|
||||
F3 і F4 відкривають Viewer та Editor. F2 в Editor перевіряє розмір і час
|
||||
зміни віддаленого файла перед збереженням. F5 копіює між локальною
|
||||
@@ -226,6 +252,12 @@ Warning і початковий фокус на No.
|
||||
останніх команд з історії, які починаються з набраного тексту.
|
||||
Вибір підставляє всю команду. Підказки з історії доступні й у LAN-панелі.
|
||||
|
||||
- Правий клік по локальному файлу чи папці відкриває системне контекстне
|
||||
меню Windows Shell. Правий клік по вільній області відкриває меню
|
||||
поточної папки. Клавіша Context Menu або Shift+F10 використовує поточний
|
||||
рядок. Команда з меню оновлює панель і зберігає папку, курсор та
|
||||
актуальні позначки. Для LAN, FTP, SFTP, UNC та архівів контекстне меню
|
||||
показує доступні команди Files.
|
||||
- **F8 Delete** у нижньому рядку клавіш викликає той самий діалог видалення,
|
||||
що й клавіша F8.
|
||||
- У нижньому рядку, як у FAR, позначення клавіш сірі на чорному тлі,
|
||||
@@ -519,18 +551,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 перемикає вигляд відповідної
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# Apply the exec-channel variant of SFTP initialization to the pinned library.
|
||||
file(REAL_PATH ".." source_parent)
|
||||
set(patch_file "${CMAKE_CURRENT_BINARY_DIR}/.kswitcher-sftp-command.patch")
|
||||
configure_file("${PATCH}" "${patch_file}" @ONLY NEWLINE_STYLE LF)
|
||||
set(patch_git "${CMAKE_COMMAND}" -E env "GIT_CEILING_DIRECTORIES=${source_parent}" "${GIT}")
|
||||
execute_process(COMMAND ${patch_git} apply --unidiff-zero --check "${patch_file}"
|
||||
RESULT_VARIABLE can_apply ERROR_QUIET)
|
||||
if(can_apply EQUAL 0)
|
||||
execute_process(COMMAND ${patch_git} apply --unidiff-zero "${patch_file}" COMMAND_ERROR_IS_FATAL ANY)
|
||||
else()
|
||||
execute_process(COMMAND ${patch_git} apply --unidiff-zero --reverse --check "${patch_file}"
|
||||
RESULT_VARIABLE already_applied)
|
||||
if(NOT already_applied EQUAL 0)
|
||||
message(FATAL_ERROR "Could not apply the SFTP command patch")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
file(REMOVE "${patch_file}")
|
||||
file(STRINGS "include/libssh2_sftp.h" exec_api REGEX "^libssh2_sftp_init_command")
|
||||
if(NOT exec_api)
|
||||
message(FATAL_ERROR "The SFTP command API is missing after applying the patch")
|
||||
endif()
|
||||
@@ -1,10 +1,16 @@
|
||||
include(FetchContent)
|
||||
find_package(Git REQUIRED)
|
||||
set(kswitcher_ssh_patch "${CMAKE_CURRENT_LIST_DIR}/libssh2-sftp-command.patch")
|
||||
file(SHA256 "${kswitcher_ssh_patch}" kswitcher_ssh_patch_hash)
|
||||
|
||||
# This revision includes the published SFTP security fixes after the 1.11.1 release.
|
||||
FetchContent_Declare(kswitcher_libssh2
|
||||
URL https://codeload.github.com/libssh2/libssh2/tar.gz/dd1546700d0ed8ff7138bc1ccc288286fb3ab2b4
|
||||
URL_HASH SHA256=67d20d434055faef76439c6829ab253c892fcdd68d9a9c86cf5824bd8366e6eb
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP TRUE
|
||||
PATCH_COMMAND "${CMAKE_COMMAND}" "-DGIT=${GIT_EXECUTABLE}"
|
||||
"-DPATCH=${kswitcher_ssh_patch}" "-DPATCH_HASH=${kswitcher_ssh_patch_hash}"
|
||||
-P "${CMAKE_CURRENT_LIST_DIR}/ApplyFilesSshPatch.cmake")
|
||||
|
||||
function(kswitcher_add_ssh_library)
|
||||
set(BUILD_STATIC_LIBS ON)
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
diff --git a/include/libssh2_sftp.h b/include/libssh2_sftp.h
|
||||
--- a/include/libssh2_sftp.h
|
||||
+++ b/include/libssh2_sftp.h
|
||||
@@ -226,0 +227,2 @@
|
||||
+LIBSSH2_API LIBSSH2_SFTP *
|
||||
+libssh2_sftp_init_command(LIBSSH2_SESSION *session, const char *command);
|
||||
diff --git a/src/sftp.c b/src/sftp.c
|
||||
--- a/src/sftp.c
|
||||
+++ b/src/sftp.c
|
||||
@@ -758 +758,2 @@
|
||||
-static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session)
|
||||
+static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session,
|
||||
+ const char *command)
|
||||
@@ -811,3 +812,5 @@
|
||||
- "subsystem",
|
||||
- sizeof("subsystem") - 1,
|
||||
- "sftp", sizeof("sftp") - 1);
|
||||
+ command ? "exec" : "subsystem",
|
||||
+ command ? 4 : 9,
|
||||
+ command ? command : "sftp",
|
||||
+ command ?
|
||||
+ strlen(command) : 4);
|
||||
@@ -1011 +1014,2 @@
|
||||
-LIBSSH2_SFTP *libssh2_sftp_init(LIBSSH2_SESSION *session)
|
||||
+LIBSSH2_SFTP *libssh2_sftp_init_command(LIBSSH2_SESSION *session,
|
||||
+ const char *command)
|
||||
@@ -1024 +1028 @@
|
||||
- BLOCK_ADJUST_ERRNO(ptr, session, sftp_init(session));
|
||||
+ BLOCK_ADJUST_ERRNO(ptr, session, sftp_init(session, command));
|
||||
@@ -1025,0 +1030,5 @@
|
||||
+}
|
||||
+
|
||||
+LIBSSH2_SFTP *libssh2_sftp_init(LIBSSH2_SESSION *session)
|
||||
+{
|
||||
+ return libssh2_sftp_init_command(session, NULL);
|
||||
+7
-3
@@ -575,9 +575,13 @@ BEGIN
|
||||
FAR_EDIT(388, 0, 16, 96, 182, 15)
|
||||
LTEXT "&Password or key passphrase", 389, 210, 83, 194, 12
|
||||
EDITTEXT 390, 210, 96, 194, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL
|
||||
LTEXT "Private &key file (optional)", 562, 16, 117, 388, 12
|
||||
FAR_EDIT(563, 0, 16, 130, 388, 15)
|
||||
LTEXT "", 566, 16, 153, 388, 14, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "Private &key file (optional)", 562, 16, 117, 182, 12
|
||||
FAR_EDIT(563, 0, 16, 130, 182, 15)
|
||||
LTEXT "SFTP ser&ver for sudo (optional)", 569, 210, 117, 194, 12
|
||||
FAR_EDIT(570, 0, 210, 130, 194, 15)
|
||||
LTEXT "", 566, 16, 153, 218, 14, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "&Jump via", 568, 240, 153, 56, 14
|
||||
COMBOBOX 567, 298, 150, 106, 90, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "", 391, 10, 175, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Test connection", 564, "Button", BS_OWNERDRAW | WS_TABSTOP, 20, 183, 128, 17
|
||||
CONTROL "&Forget host key", 565, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 183, 112, 17
|
||||
|
||||
@@ -9,6 +9,10 @@ const terminal = new Terminal({
|
||||
const fit = new FitAddon.FitAddon();
|
||||
terminal.parser.registerOscHandler(633, data => {
|
||||
const prefix = 'ks-directory:';
|
||||
if (data.startsWith('ks-ssh-dir:')) {
|
||||
bridge.postMessage('ssh-directory:' + data.slice(11));
|
||||
return true;
|
||||
}
|
||||
if (!data.startsWith(prefix)) return false;
|
||||
try {
|
||||
bridge.postMessage('directory:' + decodeURIComponent(data.slice(prefix.length)));
|
||||
@@ -22,9 +26,13 @@ const host = document.getElementById('terminal');
|
||||
terminal.open(host);
|
||||
terminal.onSelectionChange(() => bridge.postMessage('selection:' + terminal.getSelection()));
|
||||
const prompt = message => bridge.postMessage('prompt:' + message);
|
||||
host.addEventListener('pointerup', () => prompt('focus-input'), true);
|
||||
let sshInput = false;
|
||||
host.addEventListener('pointerup', () => {
|
||||
if (!sshInput) prompt('focus-input');
|
||||
}, true);
|
||||
terminal.onData(text => {
|
||||
if (!/[\x00-\x1f\x7f]/u.test(text)) prompt('text:' + text);
|
||||
if (sshInput) bridge.postMessage('ssh-input:' + text);
|
||||
else if (!/[\x00-\x1f\x7f]/u.test(text)) prompt('text:' + text);
|
||||
});
|
||||
const screen = host.querySelector('.xterm-screen');
|
||||
let traceEnabled = false;
|
||||
@@ -61,6 +69,14 @@ const promptKeys = new Set([
|
||||
]);
|
||||
terminal.attachCustomKeyEventHandler(event => {
|
||||
if (event.isComposing) return true;
|
||||
if (sshInput) {
|
||||
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.metaKey) return true;
|
||||
const copy = event.code === 'KeyC' && terminal.hasSelection();
|
||||
if (!copy && (event.shiftKey || event.code !== 'KeyO')) return true;
|
||||
event.preventDefault();
|
||||
if (!event.repeat) bridge.postMessage(copy ? 'copy-command-line' : 'toggle');
|
||||
return false;
|
||||
}
|
||||
if (event.type === 'keydown' && promptKeys.has(event.key) &&
|
||||
!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {
|
||||
prompt(event.key);
|
||||
@@ -99,6 +115,21 @@ terminal.onScroll(() => {
|
||||
anchorOutput();
|
||||
});
|
||||
bridge.addEventListener('message', ({ data }) => {
|
||||
if (data === 'ssh-input:on' || data === 'ssh-input:off') {
|
||||
sshInput = data === 'ssh-input:on';
|
||||
terminal.options.cursorBlink = sshInput;
|
||||
terminal.write(sshInput ? '\x1b[?25h' : '\x1b[?25l');
|
||||
return;
|
||||
}
|
||||
if (data === 'ssh-focus') {
|
||||
terminal.focus();
|
||||
return;
|
||||
}
|
||||
if (data === 'ssh-reset') {
|
||||
terminal.reset();
|
||||
terminal.write('\x1b[?25l');
|
||||
return;
|
||||
}
|
||||
if (data === 'clear-selection') {
|
||||
terminal.clearSelection();
|
||||
return;
|
||||
|
||||
+11
-9
@@ -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 ¤t=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");
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
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;
|
||||
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");
|
||||
}
|
||||
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) 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() &&
|
||||
!directory.root_name().native().starts_with(L"\\\\");
|
||||
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
@@ -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)
|
||||
|
||||
+61
-26
@@ -29,45 +29,80 @@ 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);
|
||||
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;
|
||||
}
|
||||
+46
-3
@@ -16,6 +16,8 @@ struct TransferProfile
|
||||
TransferProtocol protocol{};
|
||||
fs::path privateKey;
|
||||
std::string hostFingerprint;
|
||||
std::string jumpProfile;
|
||||
std::wstring sudoSftpServer;
|
||||
};
|
||||
|
||||
struct TransferProfiles
|
||||
@@ -31,6 +33,36 @@ TransferProfiles &transferProfiles(TransferProtocol protocol)
|
||||
return protocol==TransferProtocol::sftp?sftp:ftp;
|
||||
}
|
||||
|
||||
std::atomic<std::shared_ptr<const std::vector<TransferProfile>>> sshProfiles;
|
||||
|
||||
constexpr size_t sshRouteLimit=8;
|
||||
|
||||
std::vector<TransferProfile> sshRoute(const TransferProfile &destination,
|
||||
const std::vector<TransferProfile> &profiles)
|
||||
{
|
||||
std::vector<TransferProfile> route{destination};
|
||||
std::set<std::string> seen{destination.id};
|
||||
while(!route.back().jumpProfile.empty())
|
||||
{
|
||||
const auto &id=route.back().jumpProfile;
|
||||
if(!seen.insert(id).second) throw std::runtime_error("The SSH jump route contains a loop.");
|
||||
if(route.size()>=sshRouteLimit) throw std::runtime_error("An SSH route can contain up to eight hosts.");
|
||||
const auto hop=std::find_if(profiles.begin(),profiles.end(),
|
||||
[&id](const auto &profile){return profile.id==id;});
|
||||
if(hop==profiles.end()) throw std::runtime_error("An SSH jump profile is missing. Edit this connection to update its route.");
|
||||
route.push_back(*hop);
|
||||
}
|
||||
std::reverse(route.begin(),route.end());
|
||||
return route;
|
||||
}
|
||||
|
||||
bool validSudoSftpServer(std::wstring_view path)
|
||||
{
|
||||
constexpr std::wstring_view pathCharacters=L"/-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||
return path.empty() || (path.starts_with(L'/') && path.ends_with(L"/sftp-server") &&
|
||||
path.size()<=255 && path.find_first_not_of(pathCharacters)==path.npos);
|
||||
}
|
||||
|
||||
constexpr DWORD transferProfilesMaxBytes=1024*1024;
|
||||
const fs::path ftpRoot=L"\\";
|
||||
|
||||
@@ -58,13 +90,19 @@ bool saveTransferProfiles(TransferProtocol protocol,const std::vector<TransferPr
|
||||
{
|
||||
row["privateKey"]=ks::utf8(profile.privateKey.native());
|
||||
row["hostFingerprint"]=profile.hostFingerprint;
|
||||
row["jumpProfile"]=profile.jumpProfile;
|
||||
row["sudoSftpServer"]=ks::utf8(profile.sudoSftpServer);
|
||||
}
|
||||
rows.push_back(std::move(row));
|
||||
}
|
||||
const auto data=rows.dump();
|
||||
return data.size()<=transferProfilesMaxBytes &&
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,transferProfiles(protocol).preference,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
|
||||
if(data.size()>transferProfilesMaxBytes) return false;
|
||||
const auto snapshot=protocol==TransferProtocol::sftp?
|
||||
std::make_shared<const std::vector<TransferProfile>>(profiles):nullptr;
|
||||
if(RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,transferProfiles(protocol).preference,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))!=ERROR_SUCCESS) return false;
|
||||
if(snapshot) sshProfiles=snapshot;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool loadTransferProfiles(TransferProtocol protocol=TransferProtocol::ftp)
|
||||
@@ -101,9 +139,14 @@ bool loadTransferProfiles(TransferProtocol protocol=TransferProtocol::ftp)
|
||||
{
|
||||
profile.privateKey=ks::wide(row.value("privateKey",std::string{}));
|
||||
profile.hostFingerprint=row.value("hostFingerprint",std::string{});
|
||||
profile.jumpProfile=row.value("jumpProfile",std::string{});
|
||||
profile.sudoSftpServer=ks::wide(row.value("sudoSftpServer",std::string{}));
|
||||
if(!validSudoSftpServer(profile.sudoSftpServer)) return false;
|
||||
}
|
||||
profiles.push_back(std::move(profile));
|
||||
}
|
||||
if(protocol==TransferProtocol::sftp)
|
||||
sshProfiles=std::make_shared<const std::vector<TransferProfile>>(profiles);
|
||||
settings.rows=std::move(profiles);
|
||||
settings.loaded=true;
|
||||
return true;
|
||||
|
||||
@@ -174,8 +174,11 @@ FileInfo uploadTransferFile(FilesConnection &local,TransferSession &ftp,const fs
|
||||
if(expected && (!existing || existing->size!=expected->size || existing->modified!=expected->modified))
|
||||
throw std::runtime_error("The "+ks::utf8(ftp.label())+" file changed since it was opened. Your edits are still in the editor.");
|
||||
if(existing)
|
||||
{
|
||||
requireFileOperation(replace && !(existing->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
|
||||
ERROR_ALREADY_EXISTS);
|
||||
ftp.prepareReplacement(temporary,target);
|
||||
}
|
||||
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
|
||||
ftp.rename(temporary,target,existing.has_value());
|
||||
return *uploaded;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
namespace transferDialog
|
||||
{
|
||||
constexpr int name=382, host=385, port=386, user=388, password=390, footer=391, legacy=392;
|
||||
constexpr int keyLabel=562,keyFile=563,testConnection=564,forgetKey=565,hostStatus=566;
|
||||
constexpr int keyLabel=562,keyFile=563,testConnection=564,forgetKey=565,hostStatus=566,jumpVia=567,jumpLabel=568;
|
||||
constexpr int sudoLabel=569,sudoServer=570;
|
||||
|
||||
struct Edit
|
||||
{
|
||||
@@ -10,6 +11,7 @@ struct Edit
|
||||
std::wstring pinnedHost;
|
||||
INTERNET_PORT pinnedPort{};
|
||||
std::string pin;
|
||||
std::vector<std::string> jumpChoices;
|
||||
bool testing{};
|
||||
std::atomic_bool canceled{};
|
||||
};
|
||||
@@ -37,6 +39,23 @@ void showHostStatus(HWND dialog,const Edit &edit)
|
||||
EnableWindow(GetDlgItem(dialog,forgetKey),trusted && !edit.testing);
|
||||
}
|
||||
|
||||
void addJumpChoice(HWND dialog,Edit &edit,const std::wstring &label,const std::string &id)
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,jumpVia,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
if(row==CB_ERR || row==CB_ERRSPACE) return;
|
||||
edit.jumpChoices.push_back(id);
|
||||
if(id==edit.profile.jumpProfile) SendDlgItemMessageW(dialog,jumpVia,CB_SETCURSEL,row,0);
|
||||
}
|
||||
|
||||
void populateJumpChoices(HWND dialog,Edit &edit)
|
||||
{
|
||||
addJumpChoice(dialog,edit,L"Direct",{});
|
||||
for(const auto &profile:transferProfiles(TransferProtocol::sftp).rows)
|
||||
if(profile.id!=edit.profile.id) addJumpChoice(dialog,edit,profile.name,profile.id);
|
||||
if(SendDlgItemMessageW(dialog,jumpVia,CB_GETCURSEL,0,0)==CB_ERR)
|
||||
addJumpChoice(dialog,edit,L"Missing profile",edit.profile.jumpProfile);
|
||||
}
|
||||
|
||||
std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
|
||||
{
|
||||
TransferProfile profile;
|
||||
@@ -48,6 +67,7 @@ std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
|
||||
SetFocus(GetDlgItem(dialog,field));
|
||||
return {};
|
||||
};
|
||||
profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16);
|
||||
profile.legacyNames=!sftp && IsDlgButtonChecked(dialog,legacy)==BST_CHECKED;
|
||||
profile.name=trimFilesField(shortcutField(dialog,name));
|
||||
if(profile.name.empty() || profile.name==L".." || profile.name.find_first_of(L"\r\n\t")!=profile.name.npos)
|
||||
@@ -72,6 +92,17 @@ std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
|
||||
if(!profile.privateKey.empty() && !profile.privateKey.is_absolute())
|
||||
return invalid(keyFile,L"Enter the full path of the private key file.");
|
||||
if(sameEndpoint(edit,profile)) profile.hostFingerprint=edit.pin;
|
||||
profile.sudoSftpServer=trimFilesField(shortcutField(dialog,sudoServer));
|
||||
if(!validSudoSftpServer(profile.sudoSftpServer))
|
||||
return invalid(sudoServer,L"Enter the absolute path to sftp-server, for example /usr/lib/openssh/sftp-server.");
|
||||
const auto choice=SendDlgItemMessageW(dialog,jumpVia,CB_GETCURSEL,0,0);
|
||||
if(choice>=0 && static_cast<size_t>(choice)<edit.jumpChoices.size())
|
||||
profile.jumpProfile=edit.jumpChoices[choice];
|
||||
try {sshRoute(profile,profiles);}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
return invalid(jumpVia,ks::wide(error.what()).c_str());
|
||||
}
|
||||
}
|
||||
auto plain=shortcutField(dialog,password);
|
||||
if(!plain.empty())
|
||||
@@ -90,14 +121,13 @@ std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
|
||||
} erase{bytes,plain};
|
||||
profile.secret=ks::protect(bytes);
|
||||
}
|
||||
profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16);
|
||||
return profile;
|
||||
}
|
||||
|
||||
template<class Task>
|
||||
bool runTest(HWND dialog,Edit &edit,const wchar_t *status,Task task)
|
||||
{
|
||||
constexpr int controls[]{name,host,port,user,password,keyFile,testConnection,forgetKey,IDOK};
|
||||
constexpr int controls[]{name,host,port,user,password,keyFile,jumpVia,sudoServer,testConnection,forgetKey,IDOK};
|
||||
edit.testing=true;
|
||||
edit.canceled=false;
|
||||
for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),FALSE);
|
||||
@@ -125,7 +155,7 @@ void testSftp(HWND dialog,Edit &edit,TransferProfile profile)
|
||||
{
|
||||
std::string fingerprint;
|
||||
if(!runTest(dialog,edit,L"Reading the SSH host key…",[&] {
|
||||
const SftpSession probe(profile,true);
|
||||
const SshConnection probe(profile,true);
|
||||
fingerprint=probe.fingerprint();
|
||||
})) return;
|
||||
const auto prompt=profile.host+L":"+std::to_wstring(profile.port)+L"\r\n"+ks::wide(fingerprint)+
|
||||
@@ -136,12 +166,15 @@ void testSftp(HWND dialog,Edit &edit,TransferProfile profile)
|
||||
profile.hostFingerprint=edit.pin=std::move(fingerprint);
|
||||
}
|
||||
fs::path initial;
|
||||
if(runTest(dialog,edit,L"Testing the SFTP login…",[&] {
|
||||
SftpSession session(profile);
|
||||
initial=session.initialDirectory();
|
||||
if(runTest(dialog,edit,L"Testing the SSH login…",[&] {
|
||||
SshConnection connection(profile);
|
||||
const SftpSubsystem sftp(libssh2_sftp_init(connection.session()),libssh2_sftp_shutdown);
|
||||
if(sftp) initial=sftpInitialDirectory(sftp.get());
|
||||
}))
|
||||
{
|
||||
const auto details=L"Connected to "+profile.host+L".\r\n\r\nInitial folder "+ftpPath(initial)+L".";
|
||||
const auto details=L"Connected to "+profile.host+L".\r\n\r\n"+(initial.empty()?
|
||||
L"SFTP is unavailable. This profile can still be used as an SSH jump host.":
|
||||
L"Initial folder "+ftpPath(initial)+L".");
|
||||
showFilesNotice(dialog,details.c_str(),L"SFTP connection test");
|
||||
}
|
||||
}
|
||||
@@ -159,7 +192,7 @@ INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
const auto &profile=edit->profile;
|
||||
prepareCopyDialog(dialog);
|
||||
layoutDialogContent(dialog,381);
|
||||
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL,keyLabel,hostStatus})
|
||||
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL,keyLabel,hostStatus,jumpVia,jumpLabel,sudoLabel})
|
||||
if(const auto control=GetDlgItem(dialog,id)) SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
for(const auto id:{name,host,user,password})
|
||||
SendDlgItemMessageW(dialog,id,EM_SETLIMITTEXT,255,0);
|
||||
@@ -172,6 +205,10 @@ INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
SendDlgItemMessageW(dialog,keyFile,EM_SETLIMITTEXT,32767,0);
|
||||
SetDlgItemTextW(dialog,keyFile,profile.privateKey.c_str());
|
||||
SendDlgItemMessageW(dialog,sudoServer,EM_SETLIMITTEXT,255,0);
|
||||
SetDlgItemTextW(dialog,sudoServer,profile.sudoSftpServer.c_str());
|
||||
populateJumpChoices(dialog,*edit);
|
||||
installFarCombo(GetDlgItem(dialog,jumpVia),GetDlgItem(dialog,keyFile));
|
||||
showHostStatus(dialog,*edit);
|
||||
layoutDialogButtons(dialog,footer,{testConnection,forgetKey,IDOK,IDCANCEL});
|
||||
}
|
||||
|
||||
@@ -34,6 +34,8 @@ struct ImageView
|
||||
std::vector<fs::path> images;
|
||||
size_t position{};
|
||||
ImageLoad load;
|
||||
ImageLoadRetry retry;
|
||||
bool retried{};
|
||||
std::function<void(HWND)> onClose;
|
||||
std::array<HWND,6> buttons{};
|
||||
HFONT font{};
|
||||
@@ -116,6 +118,7 @@ struct ImageView
|
||||
requested=path;
|
||||
++revision;
|
||||
stop.request_stop();
|
||||
retried=false;
|
||||
error.clear();
|
||||
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
|
||||
width=height=0;
|
||||
@@ -154,21 +157,32 @@ struct ImageView
|
||||
if(reading.valid())
|
||||
{
|
||||
if(reading.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
|
||||
const auto current=revision==started;
|
||||
if(current) KillTimer(window,imageTimer);
|
||||
bool retryApproved=false;
|
||||
try
|
||||
{
|
||||
auto image=reading.get();
|
||||
if(revision==started) show(std::move(image));
|
||||
if(current) show(std::move(image));
|
||||
}
|
||||
catch(const std::exception &e)
|
||||
catch(const std::exception &failure)
|
||||
{
|
||||
if(revision==started) error=wide(e.what());
|
||||
if(current)
|
||||
{
|
||||
if(!retried && retry.approve) retryApproved=retry.approve(window,requested,failure);
|
||||
if(!retryApproved) error=wide(failure.what());
|
||||
}
|
||||
}
|
||||
if(revision==started)
|
||||
if(current && !retryApproved)
|
||||
{
|
||||
KillTimer(window,imageTimer);
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
return;
|
||||
}
|
||||
if(retryApproved)
|
||||
{
|
||||
retried=true;
|
||||
SetTimer(window,imageTimer,30,nullptr);
|
||||
}
|
||||
}
|
||||
if(requested.empty())
|
||||
{
|
||||
@@ -177,7 +191,7 @@ struct ImageView
|
||||
}
|
||||
stop=std::stop_source{};
|
||||
started=revision;
|
||||
std::packaged_task<ImageRaster()> task([path=requested,decoder=load,token=stop.get_token()]
|
||||
std::packaged_task<ImageRaster()> task([path=requested,decoder=retried?retry.load:load,token=stop.get_token()]
|
||||
{
|
||||
return decoder?decoder(path,token):decodeImage(path,path,token);
|
||||
});
|
||||
@@ -421,7 +435,7 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
|
||||
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
|
||||
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose)
|
||||
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose,ImageLoadRetry retry)
|
||||
{
|
||||
const auto instance=GetModuleHandleW(nullptr);
|
||||
static const bool registered=[instance]
|
||||
@@ -439,6 +453,7 @@ HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<s
|
||||
state->style=style;
|
||||
state->images=std::move(images);
|
||||
state->load=std::move(load);
|
||||
state->retry=std::move(retry);
|
||||
state->onClose=std::move(onClose);
|
||||
const auto position=std::find(state->images.begin(),state->images.end(),initial);
|
||||
if(position!=state->images.end()) state->position=static_cast<size_t>(position-state->images.begin());
|
||||
|
||||
@@ -3,11 +3,18 @@
|
||||
#include "files_image_decode.h"
|
||||
#include <windows.h>
|
||||
#include <functional>
|
||||
#include <exception>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
using ImageLoad=std::function<ImageRaster(const std::filesystem::path &,std::stop_token)>;
|
||||
|
||||
struct ImageLoadRetry
|
||||
{
|
||||
ImageLoad load;
|
||||
std::function<bool(HWND,const std::filesystem::path &,const std::exception &)> approve;
|
||||
};
|
||||
|
||||
struct ImageViewStyle
|
||||
{
|
||||
LOGFONTW font{};
|
||||
@@ -16,6 +23,6 @@ struct ImageViewStyle
|
||||
};
|
||||
|
||||
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
|
||||
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={});
|
||||
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={},ImageLoadRetry retry={});
|
||||
void showImageViewFile(HWND window,const std::filesystem::path &path);
|
||||
}
|
||||
+276
-67
@@ -373,6 +373,7 @@ constexpr auto schemeKey = L"Software\\KSwitcher\\Files";
|
||||
#include "files_registry_json.inl"
|
||||
#include "files_ftp.inl"
|
||||
#include "files_sftp.inl"
|
||||
#include "files_ssh_terminal.inl"
|
||||
#include "files_transfer.inl"
|
||||
|
||||
|
||||
@@ -714,7 +715,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];
|
||||
@@ -739,7 +741,22 @@ void traceTerminal(const char *event,int a=0,int b=0,int c=0,int d=0,int e=0)
|
||||
++terminalTraceLines;
|
||||
terminalTrace<<GetTickCount64()<<' '<<event<<' '<<a<<' '<<b<<' '<<c<<' '<<d<<' '<<e<<std::endl;
|
||||
}
|
||||
FilesTerminalView terminalView;
|
||||
FilesTerminalView terminalView,sshView;
|
||||
FilesSshTerminal sshTerminal;
|
||||
struct SshPrompt
|
||||
{
|
||||
int panel{};
|
||||
std::string profile,token;
|
||||
fs::path panelDirectory,shellDirectory;
|
||||
std::optional<std::wstring> startupCommand;
|
||||
bool waiting=true;
|
||||
bool raw{},finished{};
|
||||
};
|
||||
std::optional<SshPrompt> sshPrompt;
|
||||
COORD sshSize{80,25};
|
||||
bool sshViewRequested{};
|
||||
|
||||
FilesTerminalView &activeTerminalView(){return sshPrompt?sshView:terminalView;}
|
||||
std::wstring terminalSelection;
|
||||
COORD terminalSize{80,25};
|
||||
bool terminalViewRequested{};
|
||||
@@ -1162,6 +1179,7 @@ bool applyFont(HWND owner, LOGFONTW font, int points)
|
||||
displayFont=font;
|
||||
fontPoints=points;
|
||||
terminalView.setFont(displayFont,fontPoints);
|
||||
sshView.setFont(displayFont,fontPoints);
|
||||
for(auto &panel:panels)
|
||||
{
|
||||
if(panel.path) SendMessageW(panel.path,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
@@ -1533,6 +1551,7 @@ void swapPanels(HWND window)
|
||||
std::swap(panels[0],panels[1]);
|
||||
active=1-active;
|
||||
if(quickViewWindow) quickViewSource=1-quickViewSource;
|
||||
if(sshPrompt) sshPrompt->panel=1-sshPrompt->panel;
|
||||
for(auto &command:terminalCommands)
|
||||
if(command.panel>=0) command.panel=1-command.panel;
|
||||
for(int i=0;i<2;++i)
|
||||
@@ -1652,7 +1671,8 @@ void layout(HWND window,bool activeOnly)
|
||||
if(!showOutput) clearTerminalSelection();
|
||||
ShowWindow(terminalOutput,showOutput?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(status,terminalVisible?SW_HIDE:SW_SHOWNA);
|
||||
terminalView.layout(terminalOutput,showOutput,terminalBottom-4);
|
||||
terminalView.layout(terminalOutput,showOutput && !sshPrompt,terminalBottom-4);
|
||||
sshView.layout(terminalOutput,showOutput && sshPrompt.has_value(),terminalBottom-4);
|
||||
constexpr int refreshExtra=4;
|
||||
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
|
||||
{
|
||||
@@ -1717,7 +1737,12 @@ void showTerminal(HWND owner,bool show)
|
||||
{
|
||||
terminalVisible=show;
|
||||
layout(owner);
|
||||
SetFocus(terminalInput);
|
||||
if(show && sshPrompt && sshPrompt->raw)
|
||||
{
|
||||
sshView.focus();
|
||||
sshView.post(L"ssh-focus");
|
||||
}
|
||||
else SetFocus(terminalInput);
|
||||
}
|
||||
|
||||
void open(Panel &panel,const fs::path &directory,bool offerElevation);
|
||||
@@ -2044,7 +2069,7 @@ void clearTerminalSelection()
|
||||
{
|
||||
if(terminalSelection.empty()) return;
|
||||
terminalSelection.clear();
|
||||
terminalView.post(L"clear-selection");
|
||||
activeTerminalView().post(L"clear-selection");
|
||||
}
|
||||
|
||||
bool copyFilesText(HWND owner,const std::wstring &value,const wchar_t *failure)
|
||||
@@ -2056,6 +2081,8 @@ bool copyFilesText(HWND owner,const std::wstring &value,const wchar_t *failure)
|
||||
|
||||
bool interruptTerminal()
|
||||
{
|
||||
if(sshPrompt)
|
||||
return sshPrompt->raw && sshTerminal.write("\x03");
|
||||
if(remoteCommandRunning)
|
||||
{
|
||||
remoteCommandThread.request_stop();
|
||||
@@ -2111,6 +2138,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];
|
||||
@@ -2260,16 +2318,22 @@ void handleTerminalPromptInput(HWND owner,std::wstring_view action)
|
||||
SendMessageW(terminalInput,character?WM_CHAR:WM_KEYDOWN,key->second,0);
|
||||
}
|
||||
|
||||
bool ensureTerminalView(HWND owner)
|
||||
void acceptSshDirectory(HWND owner,std::wstring_view message);
|
||||
|
||||
bool ensureTerminalView(HWND owner,bool ssh=false)
|
||||
{
|
||||
if(!terminalViewRequested)
|
||||
auto &view=ssh?sshView:terminalView;
|
||||
auto &requested=ssh?sshViewRequested:terminalViewRequested;
|
||||
if(!requested)
|
||||
{
|
||||
terminalViewRequested=terminalView.create(terminalOutput,[owner](const std::wstring &message)
|
||||
requested=view.create(terminalOutput,[owner,ssh](const std::wstring &message)
|
||||
{
|
||||
auto &source=ssh?sshView:terminalView;
|
||||
if(message==L"ready")
|
||||
{
|
||||
terminalView.setFont(displayFont,fontPoints);
|
||||
if(terminalTrace.is_open()) terminalView.enableTrace(traceTerminalOutput);
|
||||
source.setFont(displayFont,fontPoints);
|
||||
if(ssh) source.post(L"ssh-reset");
|
||||
if(terminalTrace.is_open() && !ssh) source.enableTrace(traceTerminalOutput);
|
||||
}
|
||||
else if(traceTerminalOutput && terminalTrace.is_open() && message.starts_with(L"output:"))
|
||||
terminalTrace<<"output "<<ks::utf8(message.substr(7))<<std::endl;
|
||||
@@ -2283,7 +2347,14 @@ bool ensureTerminalView(HWND owner)
|
||||
traceTerminal(events[phase],height,rows,viewport,base,offset);
|
||||
}
|
||||
}
|
||||
else if(message.starts_with(L"directory:"))
|
||||
else if(ssh && message.starts_with(L"ssh-directory:"))
|
||||
acceptSshDirectory(owner,std::wstring_view(message).substr(14));
|
||||
else if(ssh && message.starts_with(L"ssh-input:"))
|
||||
{
|
||||
if(sshPrompt && sshPrompt->raw && GetForegroundWindow()==owner && commandLineAvailable(owner))
|
||||
sshTerminal.write(ks::utf8(message.substr(10)));
|
||||
}
|
||||
else if(!ssh && message.starts_with(L"directory:"))
|
||||
{
|
||||
const auto directory=message.substr(10);
|
||||
if(!terminalCommands.empty())
|
||||
@@ -2302,8 +2373,14 @@ bool ensureTerminalView(HWND owner)
|
||||
}
|
||||
terminalDirectory=directory;
|
||||
}
|
||||
else if(message.starts_with(L"selection:")) terminalSelection=message.substr(10);
|
||||
else if(message.starts_with(L"prompt:")) handleTerminalPromptInput(owner,std::wstring_view(message).substr(7));
|
||||
else if(message.starts_with(L"selection:"))
|
||||
{
|
||||
if(ssh==sshPrompt.has_value()) terminalSelection=message.substr(10);
|
||||
}
|
||||
else if(message.starts_with(L"prompt:"))
|
||||
{
|
||||
if(ssh==sshPrompt.has_value()) handleTerminalPromptInput(owner,std::wstring_view(message).substr(7));
|
||||
}
|
||||
else if(message==L"insert-path") insertCurrentPanelPath();
|
||||
else if(message==L"insert-name") insertCurrentPanelPath(true);
|
||||
else if(message==L"copy-command-line" && GetForegroundWindow()==owner && commandLineAvailable(owner))
|
||||
@@ -2322,16 +2399,24 @@ bool ensureTerminalView(HWND owner)
|
||||
if(swscanf_s(message.c_str()+5,L"%d,%d",&columns,&rows)==2 &&
|
||||
columns>=2 && columns<=32767 && rows>=2 && rows<=32767)
|
||||
{
|
||||
terminalSize={static_cast<SHORT>(columns),static_cast<SHORT>(rows)};
|
||||
terminal.resize(terminalSize);
|
||||
const COORD size{static_cast<SHORT>(columns),static_cast<SHORT>(rows)};
|
||||
if(ssh) {sshSize=size;sshTerminal.resize(size);}
|
||||
else {terminalSize=size;terminal.resize(size);}
|
||||
}
|
||||
}
|
||||
},[owner]
|
||||
},[owner,ssh]
|
||||
{
|
||||
showTerminal(owner,false);
|
||||
if(ssh)
|
||||
{
|
||||
sshTerminal.stop();
|
||||
sshPrompt.reset();
|
||||
sshViewRequested=false;
|
||||
sshView.close();
|
||||
}
|
||||
if(ssh || !sshPrompt) showTerminal(owner,false);
|
||||
setStatus(L"Could not initialize the terminal view.");
|
||||
});
|
||||
if(!terminalViewRequested)
|
||||
},false,{},ssh);
|
||||
if(!requested)
|
||||
{
|
||||
setStatus(L"WebView2 and the local terminal assets are required.");
|
||||
return false;
|
||||
@@ -2340,8 +2425,11 @@ bool ensureTerminalView(HWND owner)
|
||||
return true;
|
||||
}
|
||||
|
||||
#include "files_ssh_prompt.inl"
|
||||
|
||||
bool startTerminal(HWND owner,const fs::path &directory)
|
||||
{
|
||||
closeSshPrompt(owner);
|
||||
if(terminal.alive()) return true;
|
||||
if(!ensureTerminalView(owner)) return false;
|
||||
if(terminal.start(directory.c_str(),terminalSize))
|
||||
@@ -2356,12 +2444,16 @@ bool startTerminal(HWND owner,const fs::path &directory)
|
||||
|
||||
bool showCommandOutput(HWND owner,const Panel &panel)
|
||||
{
|
||||
if(panel.ftp && panel.ftp->protocol==TransferProtocol::sftp && !panel.ftp->id.empty())
|
||||
return startSshTerminal(owner,panel);
|
||||
closeSshPrompt(owner);
|
||||
if(panel.archive) return startTerminal(owner,panel.archive->file.parent_path());
|
||||
return panel.peer || panel.ftp?ensureTerminalView(owner):startTerminal(owner,panel.directory);
|
||||
}
|
||||
|
||||
void updateTerminalOutput()
|
||||
void updateTerminalOutput(HWND owner)
|
||||
{
|
||||
updateSshTerminal(owner);
|
||||
if(!terminalView.initialized()) return;
|
||||
const auto bytes=terminal.takeOutput();
|
||||
if(!bytes.empty()) terminalView.send(bytes);
|
||||
@@ -2396,9 +2488,12 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
|
||||
}
|
||||
if(panel.ftp)
|
||||
{
|
||||
setStatus(std::wstring(L"Shell commands are unavailable in ")+transferProtocolName(panel.ftp->protocol)+L" panels.");
|
||||
if(panel.ftp->protocol==TransferProtocol::sftp && !panel.ftp->id.empty())
|
||||
return submitSshCommand(owner,panel,value);
|
||||
setStatus(L"Shell commands require a connected SFTP, LAN or local folder.");
|
||||
return false;
|
||||
}
|
||||
closeSshPrompt(owner);
|
||||
if(remoteCommandRunning)
|
||||
{
|
||||
constexpr auto busy=L"A remote command is running. Clear the command line and press Escape to cancel it.";
|
||||
@@ -2476,7 +2571,7 @@ void runCommandLine()
|
||||
{
|
||||
const auto value=terminalInputText();
|
||||
if(!submitTerminalCommand(panels[active],value)) return;
|
||||
terminalView.post(L"scroll-bottom");
|
||||
activeTerminalView().post(L"scroll-bottom");
|
||||
if(value.find_first_not_of(L" \t\r\n")!=value.npos)
|
||||
{
|
||||
rememberCommand(value);
|
||||
@@ -2565,6 +2660,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;
|
||||
@@ -2652,6 +2749,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)
|
||||
{
|
||||
@@ -2661,7 +2760,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;
|
||||
@@ -2897,6 +3000,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);
|
||||
@@ -3048,7 +3159,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
|
||||
{
|
||||
@@ -3144,7 +3259,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),
|
||||
@@ -3184,7 +3300,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},
|
||||
@@ -3570,7 +3686,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);
|
||||
@@ -3730,7 +3846,7 @@ 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]);
|
||||
@@ -4464,7 +4580,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;
|
||||
@@ -4927,12 +5044,17 @@ LRESULT CALLBACK paintFarCombo(HWND control,UINT message,WPARAM wp,LPARAM lp,UIN
|
||||
const auto dc=message==WM_PAINT?BeginPaint(control,&paint):reinterpret_cast<HDC>(wp);
|
||||
RECT bounds{};
|
||||
GetClientRect(control,&bounds);
|
||||
wchar_t label[64]{};
|
||||
std::wstring label;
|
||||
const auto selected=SendMessageW(control,CB_GETCURSEL,0,0);
|
||||
if(selected!=CB_ERR) SendMessageW(control,CB_GETLBTEXT,selected,reinterpret_cast<LPARAM>(label));
|
||||
const auto length=selected==CB_ERR?CB_ERR:SendMessageW(control,CB_GETLBTEXTLEN,selected,0);
|
||||
if(length>=0)
|
||||
{
|
||||
label.resize(static_cast<size_t>(length)+1);
|
||||
SendMessageW(control,CB_GETLBTEXT,selected,reinterpret_cast<LPARAM>(label.data()));
|
||||
}
|
||||
const auto parts=farDropDownBounds(bounds);
|
||||
const bool enabled=IsWindowEnabled(control)!=FALSE;
|
||||
paintFarDropDownText(dc,parts.field,label,enabled);
|
||||
paintFarDropDownText(dc,parts.field,label.c_str(),enabled);
|
||||
ks::files::paintFarFieldArrow(dc,parts.arrow,enabled,GetDpiForWindow(control));
|
||||
if(GetFocus()==control) DrawFocusRect(dc,&parts.field);
|
||||
if(message==WM_PAINT) EndPaint(control,&paint);
|
||||
@@ -6072,33 +6194,59 @@ ks::files::RemoteTextSource transferTextSource(const TransferProfile &profile)
|
||||
{
|
||||
auto identity=Json::array({ks::utf8(transferProtocolName(profile.protocol)),ks::utf8(ks::lower(profile.host)),
|
||||
profile.port,ks::utf8(profile.user)}).dump();
|
||||
return {std::move(identity),profile.name,
|
||||
[profile](const fs::path &path,const fs::path &cache,bool edit,
|
||||
const auto reader=[profile](SftpAccess access) -> ks::files::RemoteTextSource::Download
|
||||
{
|
||||
return [profile,access](const fs::path &path,const fs::path &cache,bool edit,
|
||||
const ks::files::RemoteTextSource::Progress &progress,uint64_t limit)
|
||||
{
|
||||
requireFileOperation(!progress || progress(0,0),ERROR_CANCELLED);
|
||||
TransferSession ftp(profile);
|
||||
TransferSession ftp(profile,access);
|
||||
const auto info=transferEntry(transferChildren(ftp,path.parent_path()),path);
|
||||
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
|
||||
requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
|
||||
ERROR_NOT_SUPPORTED);
|
||||
const bool editable=!(info->attributes&FILE_ATTRIBUTE_READONLY);
|
||||
const bool editable=access!=SftpAccess::sudoRead && !(info->attributes&FILE_ATTRIBUTE_READONLY);
|
||||
if(edit && !editable) throw std::runtime_error("The "+ks::utf8(transferProtocolName(profile.protocol))+" file is read-only.");
|
||||
if(info->size>limit) throw std::system_error(ERROR_FILE_TOO_LARGE,std::system_category());
|
||||
FilesConnection local;
|
||||
downloadTransferFile(ftp,local,path,cache,*info,false,progress);
|
||||
return ks::files::RemoteTextRevision{info->size,info->modified,editable};
|
||||
},
|
||||
[profile](const fs::path &path,const fs::path &cache,const ks::files::RemoteTextRevision &expected)
|
||||
};
|
||||
};
|
||||
const auto write=[profile](SftpAccess access,const fs::path &path,const fs::path &cache,
|
||||
const ks::files::RemoteTextRevision &expected,const ks::files::RemoteTextSource::Progress &progress)
|
||||
{
|
||||
requireFileOperation(!progress || progress(0,0),ERROR_CANCELLED);
|
||||
FilesConnection local;
|
||||
const auto info=statFile(local,cache);
|
||||
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
|
||||
TransferSession ftp(profile,access);
|
||||
requireFileOperation(!progress || progress(0,0),ERROR_CANCELLED);
|
||||
const auto result=uploadTransferFile(local,ftp,cache,path,*info,true,progress,&expected);
|
||||
return ks::files::RemoteTextRevision{result.size,result.modified,expected.editable};
|
||||
};
|
||||
ks::files::RemoteTextSource source{std::move(identity),profile.name,reader(SftpAccess::normal),
|
||||
[write](const auto &path,const auto &cache,const auto &expected)
|
||||
{
|
||||
FilesConnection local;
|
||||
const auto info=statFile(local,cache);
|
||||
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
|
||||
TransferSession ftp(profile);
|
||||
const auto result=uploadTransferFile(local,ftp,cache,path,*info,true,
|
||||
[](uint64_t,uint64_t){return true;},&expected);
|
||||
return ks::files::RemoteTextRevision{result.size,result.modified,expected.editable};
|
||||
return write(SftpAccess::normal,path,cache,expected,{});
|
||||
}};
|
||||
if(profile.protocol==TransferProtocol::sftp && !profile.sudoSftpServer.empty())
|
||||
{
|
||||
source.elevation=ks::files::RemoteTextSource::Elevation{reader(SftpAccess::sudoRead),
|
||||
[write](const auto &path,const auto &cache,const auto &expected,const auto &progress)
|
||||
{
|
||||
return write(SftpAccess::sudoWrite,path,cache,expected,progress);
|
||||
},[name=profile.name](HWND owner,const fs::path &path,bool write)
|
||||
{
|
||||
const auto action=write?L"Retry this save with temporary sudo write access?":
|
||||
L"Open this file with temporary read-only sudo access?";
|
||||
const auto message=std::wstring(L"The SFTP server denied access.\r\n\r\n")+action+
|
||||
L"\r\n\r\n"+name+L" · "+ftpPath(path);
|
||||
return showFilesNotice(owner,message.c_str(),write?L"SFTP save with sudo":L"SFTP read with sudo",
|
||||
{.confirm=true})==IDYES;
|
||||
}};
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
bool countCopy(CopyHost &host,const fs::path &path,CopyProgress &progress)
|
||||
@@ -6350,20 +6498,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;
|
||||
@@ -6377,7 +6525,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))
|
||||
@@ -6403,7 +6551,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)
|
||||
{
|
||||
@@ -6413,12 +6561,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));
|
||||
@@ -6492,6 +6644,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;
|
||||
@@ -6969,7 +7122,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)
|
||||
{
|
||||
@@ -6989,8 +7142,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);
|
||||
@@ -7452,12 +7609,25 @@ void openOrCreateText(HWND owner,const Panel &panel)
|
||||
void editTransferProfile(Panel &panel,bool create);
|
||||
|
||||
#include "files_drag_drop.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);
|
||||
@@ -7740,14 +7910,37 @@ void openMenu(HWND window, int index)
|
||||
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…"};
|
||||
}
|
||||
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);
|
||||
}
|
||||
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 && 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});
|
||||
@@ -8020,7 +8213,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
if(pendingPeerAction.valid() &&
|
||||
pendingPeerAction.wait_for(std::chrono::seconds(0))==std::future_status::ready)
|
||||
setStatus(pendingPeerAction.get());
|
||||
updateTerminalOutput();
|
||||
updateTerminalOutput(window);
|
||||
updateCompletion(window);
|
||||
return 0;
|
||||
}
|
||||
@@ -8397,6 +8590,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);
|
||||
@@ -8405,7 +8600,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;
|
||||
@@ -8690,7 +8886,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]);
|
||||
@@ -8741,6 +8938,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
stopTreeBranches(panel);
|
||||
panel.watch.reset();
|
||||
}
|
||||
sshTerminal.stop();
|
||||
sshView.close();
|
||||
terminalView.close();
|
||||
terminal.close();
|
||||
if(remoteCommandThread.joinable())
|
||||
@@ -8839,6 +9038,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) &&
|
||||
@@ -8872,7 +9081,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)
|
||||
@@ -8896,7 +9105,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;
|
||||
}
|
||||
|
||||
+217
-39
@@ -6,7 +6,7 @@ void initializeSsh()
|
||||
if(initialized) throw std::runtime_error("Could not initialize the SSH client.");
|
||||
}
|
||||
|
||||
void connectSftpSocket(ks::lan::WinSocket &connection,const TransferProfile &profile)
|
||||
void connectSshSocket(ks::lan::WinSocket &connection,const TransferProfile &profile)
|
||||
{
|
||||
ADDRINFOW query{};
|
||||
query.ai_socktype=SOCK_STREAM;
|
||||
@@ -53,28 +53,66 @@ void connectSftpSocket(ks::lan::WinSocket &connection,const TransferProfile &pro
|
||||
throw std::system_error(lastError,std::system_category());
|
||||
}
|
||||
|
||||
struct SftpFile
|
||||
{
|
||||
LIBSSH2_SFTP_HANDLE *handle{};
|
||||
explicit SftpFile(LIBSSH2_SFTP_HANDLE *value):handle(value){}
|
||||
SftpFile(const SftpFile &)=delete;
|
||||
SftpFile(SftpFile &&other) noexcept:handle(std::exchange(other.handle,nullptr)){}
|
||||
~SftpFile(){if(handle) libssh2_sftp_close_handle(handle);}
|
||||
};
|
||||
using SshChannel=std::unique_ptr<LIBSSH2_CHANNEL,decltype(&libssh2_channel_free)>;
|
||||
|
||||
class SftpSession
|
||||
class SshConnection
|
||||
{
|
||||
struct Tunnel
|
||||
{
|
||||
SshChannel channel;
|
||||
LIBSSH2_SESSION *parent;
|
||||
|
||||
struct Nonblocking
|
||||
{
|
||||
LIBSSH2_SESSION *parent;
|
||||
int previous;
|
||||
explicit Nonblocking(LIBSSH2_SESSION *session):
|
||||
parent(session),previous(libssh2_session_get_blocking(parent))
|
||||
{
|
||||
libssh2_session_set_blocking(parent,0);
|
||||
}
|
||||
~Nonblocking(){libssh2_session_set_blocking(parent,previous);}
|
||||
};
|
||||
};
|
||||
|
||||
struct Hop
|
||||
{
|
||||
std::unique_ptr<Tunnel> tunnel;
|
||||
std::unique_ptr<LIBSSH2_SESSION,decltype(&libssh2_session_free)> session{nullptr,libssh2_session_free};
|
||||
};
|
||||
|
||||
ks::lan::Network network_;
|
||||
ks::lan::WinSocket socket_;
|
||||
std::unique_ptr<LIBSSH2_SESSION,decltype(&libssh2_session_free)> session_{nullptr,libssh2_session_free};
|
||||
std::unique_ptr<LIBSSH2_SFTP,decltype(&libssh2_sftp_shutdown)> sftp_{nullptr,libssh2_sftp_shutdown};
|
||||
std::optional<std::stop_callback<std::function<void()>>> stopConnection_;
|
||||
std::vector<Hop> hops_;
|
||||
std::string fingerprint_;
|
||||
|
||||
static LIBSSH2_SEND_FUNC(sendThroughJump)
|
||||
{
|
||||
const auto &tunnel=*static_cast<Tunnel*>(*abstract);
|
||||
// Channel writes drain incoming packets first. A nested transport must
|
||||
// report when that drain would block so it can still send its own data.
|
||||
const Tunnel::Nonblocking nonblocking(tunnel.parent);
|
||||
const auto result=libssh2_channel_write(tunnel.channel.get(),static_cast<const char*>(buffer),length);
|
||||
return result>=0?result:result==LIBSSH2_ERROR_EAGAIN?-EAGAIN:-EIO;
|
||||
}
|
||||
|
||||
static LIBSSH2_RECV_FUNC(receiveThroughJump)
|
||||
{
|
||||
const auto &tunnel=*static_cast<Tunnel*>(*abstract);
|
||||
const Tunnel::Nonblocking nonblocking(tunnel.parent);
|
||||
auto *channel=tunnel.channel.get();
|
||||
const auto result=libssh2_channel_read(channel,static_cast<char*>(buffer),length);
|
||||
if(result>0) return result;
|
||||
if(result==0 && libssh2_channel_eof(channel)) return 0;
|
||||
return result==0 || result==LIBSSH2_ERROR_EAGAIN?-EAGAIN:-EIO;
|
||||
}
|
||||
|
||||
[[noreturn]] void sshError(const char *operation) const
|
||||
{
|
||||
char *message{};
|
||||
int length{};
|
||||
libssh2_session_last_error(session_.get(),&message,&length,0);
|
||||
libssh2_session_last_error(session(),&message,&length,0);
|
||||
throw std::runtime_error(std::string(operation)+(message && length>0?": "+std::string(message,length):""));
|
||||
}
|
||||
|
||||
@@ -95,7 +133,7 @@ class SftpSession
|
||||
const auto user=ks::utf8(profile.user);
|
||||
int result{};
|
||||
if(profile.privateKey.empty())
|
||||
result=libssh2_userauth_password_ex(session_.get(),user.c_str(),static_cast<unsigned>(user.size()),
|
||||
result=libssh2_userauth_password_ex(session(),user.c_str(),static_cast<unsigned>(user.size()),
|
||||
secret.c_str(),static_cast<unsigned>(secret.size()),nullptr);
|
||||
else
|
||||
{
|
||||
@@ -111,7 +149,7 @@ class SftpSession
|
||||
ks::Bytes publicKey;
|
||||
std::error_code error;
|
||||
if(fs::exists(publicPath,error)) publicKey=ks::readFile(publicPath,64*1024);
|
||||
result=libssh2_userauth_publickey_frommemory(session_.get(),user.c_str(),user.size(),
|
||||
result=libssh2_userauth_publickey_frommemory(session(),user.c_str(),user.size(),
|
||||
publicKey.empty()?nullptr:reinterpret_cast<const char*>(publicKey.data()),publicKey.size(),
|
||||
reinterpret_cast<const char*>(key.data()),key.size(),secret.c_str());
|
||||
}
|
||||
@@ -119,24 +157,40 @@ class SftpSession
|
||||
"SFTP key authentication failed (use RSA PEM without a passphrase, or ECDSA OpenSSH with its .pub file)");
|
||||
}
|
||||
|
||||
static std::string encode(const fs::path &path) {return ks::utf8(ftpPath(path));}
|
||||
|
||||
public:
|
||||
explicit SftpSession(const TransferProfile &profile,bool probeOnly=false)
|
||||
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.");
|
||||
initializeSsh();
|
||||
connectSftpSocket(socket_,profile);
|
||||
session_.reset(libssh2_session_init());
|
||||
if(!session_) throw std::runtime_error("Could not create an SSH session.");
|
||||
libssh2_session_set_timeout(session_.get(),sftpTimeoutMs);
|
||||
libssh2_session_set_read_timeout(session_.get(),sftpTimeoutMs/1000);
|
||||
if(libssh2_session_method_pref(session_.get(),LIBSSH2_METHOD_HOSTKEY,
|
||||
Hop hop;
|
||||
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);
|
||||
SshChannel channel(libssh2_channel_direct_tcpip(session(),host.c_str(),profile.port),libssh2_channel_free);
|
||||
if(!channel) sshError("Could not open an SSH jump tunnel");
|
||||
hop.tunnel=std::make_unique<Tunnel>(Tunnel{std::move(channel),session()});
|
||||
}
|
||||
hop.session.reset(libssh2_session_init_ex(nullptr,nullptr,nullptr,hop.tunnel.get()));
|
||||
if(!hop.session) throw std::runtime_error("Could not create an SSH session.");
|
||||
hops_.push_back(std::move(hop));
|
||||
if(hops_.back().tunnel)
|
||||
{
|
||||
libssh2_session_callback_set2(session(),LIBSSH2_CALLBACK_SEND,
|
||||
reinterpret_cast<libssh2_cb_generic*>(sendThroughJump));
|
||||
libssh2_session_callback_set2(session(),LIBSSH2_CALLBACK_RECV,
|
||||
reinterpret_cast<libssh2_cb_generic*>(receiveThroughJump));
|
||||
}
|
||||
libssh2_session_set_timeout(session(),sftpTimeoutMs);
|
||||
libssh2_session_set_read_timeout(session(),sftpTimeoutMs/1000);
|
||||
if(libssh2_session_method_pref(session(),LIBSSH2_METHOD_HOSTKEY,
|
||||
"ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,rsa-sha2-512,rsa-sha2-256") ||
|
||||
libssh2_session_handshake(session_.get(),socket_.value))
|
||||
libssh2_session_handshake(session(),socket_.value))
|
||||
sshError("Could not negotiate an SSH connection");
|
||||
const auto digest=reinterpret_cast<const BYTE*>(libssh2_hostkey_hash(session_.get(),LIBSSH2_HOSTKEY_HASH_SHA256));
|
||||
const auto digest=reinterpret_cast<const BYTE*>(libssh2_hostkey_hash(session(),LIBSSH2_HOSTKEY_HASH_SHA256));
|
||||
if(!digest) throw std::runtime_error("The server did not provide a verifiable SSH host key.");
|
||||
char fingerprint[64]{};
|
||||
DWORD length=static_cast<DWORD>(std::size(fingerprint));
|
||||
@@ -148,19 +202,117 @@ public:
|
||||
if(!ks::lan::equal(fingerprint_,profile.hostFingerprint))
|
||||
throw std::runtime_error("The SFTP host key changed. Connection blocked before authentication. Received "+fingerprint_+".");
|
||||
authenticate(profile);
|
||||
sftp_.reset(libssh2_sftp_init(session_.get()));
|
||||
if(!sftp_) sshError("Could not start the SFTP subsystem");
|
||||
}
|
||||
|
||||
void close() noexcept
|
||||
{
|
||||
if(socket_.value!=INVALID_SOCKET) shutdown(socket_.value,SD_BOTH);
|
||||
while(!hops_.empty())
|
||||
{
|
||||
auto &hop=hops_.back();
|
||||
libssh2_session_set_blocking(hop.session.get(),1);
|
||||
hop.session.reset();
|
||||
hops_.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
explicit SshConnection(const TransferProfile &destination,bool probeOnly=false,std::stop_token stop={})
|
||||
{
|
||||
initializeSsh();
|
||||
const auto profiles=sshProfiles.load();
|
||||
static const std::vector<TransferProfile> empty;
|
||||
const auto route=sshRoute(destination,profiles?*profiles:empty);
|
||||
try
|
||||
{
|
||||
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(),stop);}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(route.size()==1) throw;
|
||||
throw std::runtime_error(ks::utf8(profile.name)+": "+error.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(...) {close();throw;}
|
||||
}
|
||||
|
||||
~SshConnection(){close();}
|
||||
LIBSSH2_SESSION *session() const {return hops_.back().session.get();}
|
||||
const std::string &fingerprint() const {return fingerprint_;}
|
||||
|
||||
void nonblocking()
|
||||
{
|
||||
for(const auto &hop:hops_) libssh2_session_set_blocking(hop.session.get(),0);
|
||||
}
|
||||
|
||||
[[noreturn]] void operationError(const char *operation) const {sshError(operation);}
|
||||
};
|
||||
|
||||
struct SftpFile
|
||||
{
|
||||
LIBSSH2_SFTP_HANDLE *handle{};
|
||||
explicit SftpFile(LIBSSH2_SFTP_HANDLE *value):handle(value){}
|
||||
SftpFile(const SftpFile &)=delete;
|
||||
SftpFile(SftpFile &&other) noexcept:handle(std::exchange(other.handle,nullptr)){}
|
||||
~SftpFile(){if(handle) libssh2_sftp_close_handle(handle);}
|
||||
};
|
||||
|
||||
using SftpSubsystem=std::unique_ptr<LIBSSH2_SFTP,decltype(&libssh2_sftp_shutdown)>;
|
||||
|
||||
fs::path sftpInitialDirectory(LIBSSH2_SFTP *sftp)
|
||||
{
|
||||
std::array<char,32768> path{};
|
||||
const auto length=libssh2_sftp_realpath(sftp,".",path.data(),path.size());
|
||||
if(length<=0) return {};
|
||||
auto value=fs::path(ks::wide(std::string(path.data(),length))).lexically_normal();
|
||||
if(!isFtpFolderPath(value)) throw std::runtime_error("The server returned an invalid SFTP folder path.");
|
||||
return value;
|
||||
}
|
||||
|
||||
enum class SftpAccess { normal, sudoRead, sudoWrite };
|
||||
|
||||
class SftpSession
|
||||
{
|
||||
SshConnection connection_;
|
||||
const SftpAccess access_;
|
||||
SftpSubsystem sftp_{nullptr,libssh2_sftp_shutdown};
|
||||
|
||||
static std::string encode(const fs::path &path) {return ks::utf8(ftpPath(path));}
|
||||
|
||||
void requireWriteAccess() const
|
||||
{
|
||||
if(access_==SftpAccess::sudoRead)
|
||||
throw std::system_error(ERROR_ACCESS_DENIED,std::system_category(),"The sudo SFTP session is read-only");
|
||||
}
|
||||
|
||||
public:
|
||||
explicit SftpSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal,
|
||||
std::stop_token stop={}):connection_(profile,false,stop),access_(access)
|
||||
{
|
||||
if(access==SftpAccess::normal)
|
||||
{
|
||||
sftp_.reset(libssh2_sftp_init(connection_.session()));
|
||||
if(!sftp_) connection_.operationError("Could not start the SFTP subsystem");
|
||||
return;
|
||||
}
|
||||
if(profile.sudoSftpServer.empty() || !validSudoSftpServer(profile.sudoSftpServer))
|
||||
throw std::runtime_error("Configure the absolute sftp-server path for sudo in this SFTP profile.");
|
||||
const auto command="sudo -n -- "+ks::utf8(profile.sudoSftpServer)+(access==SftpAccess::sudoRead?" -R":"");
|
||||
sftp_.reset(libssh2_sftp_init_command(connection_.session(),command.c_str()));
|
||||
if(!sftp_) connection_.operationError("Could not start sudo SFTP. Verify the sftp-server path and the server's sudo authorization");
|
||||
}
|
||||
|
||||
[[noreturn]] void operationError(const char *operation) const
|
||||
{
|
||||
if(libssh2_session_last_errno(session_.get())==LIBSSH2_ERROR_SFTP_PROTOCOL)
|
||||
if(libssh2_session_last_errno(connection_.session())==LIBSSH2_ERROR_SFTP_PROTOCOL)
|
||||
{
|
||||
const auto status=libssh2_sftp_last_error(sftp_.get());
|
||||
if(status==LIBSSH2_FX_PERMISSION_DENIED)
|
||||
throw std::system_error(ERROR_ACCESS_DENIED,std::system_category(),operation);
|
||||
throw ks::files::RemoteAccessDenied(operation);
|
||||
if(status==LIBSSH2_FX_NO_SUCH_FILE || status==LIBSSH2_FX_NO_SUCH_PATH)
|
||||
throw std::system_error(ERROR_FILE_NOT_FOUND,std::system_category(),operation);
|
||||
if(status==LIBSSH2_FX_FILE_ALREADY_EXISTS)
|
||||
@@ -168,17 +320,14 @@ public:
|
||||
if(status==LIBSSH2_FX_OP_UNSUPPORTED)
|
||||
throw std::system_error(ERROR_NOT_SUPPORTED,std::system_category(),operation);
|
||||
}
|
||||
sshError(operation);
|
||||
connection_.operationError(operation);
|
||||
}
|
||||
|
||||
fs::path initialDirectory() const
|
||||
{
|
||||
std::array<char,32768> path{};
|
||||
const auto length=libssh2_sftp_realpath(sftp_.get(),".",path.data(),path.size());
|
||||
if(length<=0) operationError("Could not resolve the initial SFTP folder");
|
||||
auto value=fs::path(ks::wide(std::string(path.data(),length))).lexically_normal();
|
||||
if(!isFtpFolderPath(value)) throw std::runtime_error("The server returned an invalid SFTP folder path.");
|
||||
return value;
|
||||
auto path=sftpInitialDirectory(sftp_.get());
|
||||
if(path.empty()) operationError("Could not resolve the initial SFTP folder");
|
||||
return path;
|
||||
}
|
||||
|
||||
DWORD list(const fs::path &directory,const FileVisitor &visit,std::stop_token stop={}) const
|
||||
@@ -214,6 +363,7 @@ public:
|
||||
|
||||
SftpFile open(const fs::path &path,bool write) const
|
||||
{
|
||||
if(write) requireWriteAccess();
|
||||
const auto name=encode(path);
|
||||
const auto flags=write?LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_EXCL:LIBSSH2_FXF_READ;
|
||||
SftpFile file(libssh2_sftp_open_ex(sftp_.get(),name.c_str(),static_cast<unsigned>(name.size()),
|
||||
@@ -224,19 +374,47 @@ public:
|
||||
|
||||
void makeDirectory(const fs::path &path) const
|
||||
{
|
||||
requireWriteAccess();
|
||||
const auto name=encode(path);
|
||||
if(libssh2_sftp_mkdir(sftp_.get(),name.c_str(),0755)) operationError("Could not create the SFTP folder");
|
||||
}
|
||||
|
||||
void remove(const fs::path &path,bool directory) const
|
||||
{
|
||||
requireWriteAccess();
|
||||
const auto name=encode(path);
|
||||
const auto result=directory?libssh2_sftp_rmdir(sftp_.get(),name.c_str()):libssh2_sftp_unlink(sftp_.get(),name.c_str());
|
||||
if(result) operationError("Could not remove the SFTP entry");
|
||||
}
|
||||
|
||||
void prepareReplacement(const fs::path &staged,const fs::path &existing) const
|
||||
{
|
||||
if(access_!=SftpAccess::sudoWrite) return;
|
||||
const auto source=encode(existing),target=encode(staged);
|
||||
LIBSSH2_SFTP_ATTRIBUTES attributes{};
|
||||
if(libssh2_sftp_lstat(sftp_.get(),source.c_str(),&attributes))
|
||||
operationError("Could not read the file ownership and permissions");
|
||||
constexpr auto metadata=LIBSSH2_SFTP_ATTR_UIDGID|LIBSSH2_SFTP_ATTR_PERMISSIONS;
|
||||
if((attributes.flags&metadata)!=metadata || !LIBSSH2_SFTP_S_ISREG(attributes.permissions))
|
||||
throw std::runtime_error("The server did not supply the file ownership and permissions. The original was kept.");
|
||||
const auto original=attributes;
|
||||
attributes.flags=LIBSSH2_SFTP_ATTR_UIDGID;
|
||||
if(libssh2_sftp_setstat(sftp_.get(),target.c_str(),&attributes))
|
||||
operationError("Could not preserve the file ownership");
|
||||
attributes.flags=LIBSSH2_SFTP_ATTR_PERMISSIONS;
|
||||
attributes.permissions=original.permissions&07777;
|
||||
if(libssh2_sftp_setstat(sftp_.get(),target.c_str(),&attributes))
|
||||
operationError("Could not preserve the file permissions");
|
||||
if(libssh2_sftp_lstat(sftp_.get(),target.c_str(),&attributes))
|
||||
operationError("Could not verify the staged file permissions");
|
||||
if((attributes.flags&metadata)!=metadata || attributes.uid!=original.uid ||
|
||||
attributes.gid!=original.gid || (attributes.permissions&07777)!=(original.permissions&07777))
|
||||
throw std::runtime_error("The server did not preserve ownership and permissions. The original was kept.");
|
||||
}
|
||||
|
||||
void rename(const fs::path &from,const fs::path &to,bool replace) const
|
||||
{
|
||||
requireWriteAccess();
|
||||
const auto source=encode(from),target=encode(to);
|
||||
if(replace)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
bool panelMatchesSshPrompt()
|
||||
{
|
||||
const auto &panel=panels[active];
|
||||
return sshPrompt && sshPrompt->panel==active && panel.ftp &&
|
||||
panel.ftp->protocol==TransferProtocol::sftp && panel.ftp->id==sshPrompt->profile;
|
||||
}
|
||||
|
||||
void closeSshPrompt(HWND owner)
|
||||
{
|
||||
if(!sshPrompt) return;
|
||||
clearTerminalSelection();
|
||||
sshPrompt.reset();
|
||||
sshTerminal.stop();
|
||||
sshView.post(L"ssh-input:off");
|
||||
layout(owner);
|
||||
}
|
||||
|
||||
bool startSshTerminal(HWND owner,const Panel &panel)
|
||||
{
|
||||
if(panelMatchesSshPrompt() && !sshPrompt->finished) return true;
|
||||
if(sshTerminal.running())
|
||||
{
|
||||
setStatus(L"The previous SSH session is closing. Try again when it has disconnected.");
|
||||
return false;
|
||||
}
|
||||
if(!ensureTerminalView(owner,true)) return false;
|
||||
try
|
||||
{
|
||||
auto token=ks::lan::randomHex(16);
|
||||
sshTerminal.start(*panel.ftp,panel.directory,token,sshSize);
|
||||
clearTerminalSelection();
|
||||
sshPrompt=SshPrompt{active,panel.ftp->id,std::move(token),panel.directory};
|
||||
}
|
||||
catch(const std::exception &error) {setStatus(ks::wide(error.what()));return false;}
|
||||
sshView.post(L"ssh-reset");
|
||||
if(!terminalVisible) terminalRows=std::max(terminalRows,5);
|
||||
layout(owner);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool sendSshCommand(HWND owner,const fs::path &directory,const std::wstring &value)
|
||||
{
|
||||
const auto text=ks::utf8(value);
|
||||
const auto command=directory==sshPrompt->shellDirectory?text:
|
||||
"if "+sshChangeDirectory(directory)+"; then eval "+sshShellQuote(text)+"; fi";
|
||||
if(!sshTerminal.write(command+"\r"))
|
||||
{
|
||||
setStatus(L"Could not send input to the SSH terminal.");
|
||||
return false;
|
||||
}
|
||||
sshPrompt->panelDirectory=directory;
|
||||
sshPrompt->waiting=true;
|
||||
sshPrompt->raw=true;
|
||||
sshView.post(L"ssh-input:on");
|
||||
if(GetForegroundWindow()==owner)
|
||||
{
|
||||
sshView.focus();
|
||||
sshView.post(L"ssh-focus");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool submitSshCommand(HWND owner,const Panel &panel,const std::wstring &value)
|
||||
{
|
||||
if(!startSshTerminal(owner,panel)) return false;
|
||||
if(!sshPrompt->waiting) return sendSshCommand(owner,panel.directory,value);
|
||||
if(sshPrompt->shellDirectory.empty() && !sshPrompt->startupCommand)
|
||||
{
|
||||
sshPrompt->startupCommand=value;
|
||||
return true;
|
||||
}
|
||||
setStatus(L"The SSH prompt is busy.");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::optional<fs::path> sshReportedDirectory(std::wstring_view encoded)
|
||||
{
|
||||
if(encoded.empty() || encoded.size()>49152) return {};
|
||||
DWORD length{};
|
||||
if(!CryptStringToBinaryW(encoded.data(),static_cast<DWORD>(encoded.size()),CRYPT_STRING_BASE64|CRYPT_STRING_STRICT,
|
||||
nullptr,&length,nullptr,nullptr) || !length) return {};
|
||||
auto bytes=std::string(length,'\0');
|
||||
if(!CryptStringToBinaryW(encoded.data(),static_cast<DWORD>(encoded.size()),CRYPT_STRING_BASE64|CRYPT_STRING_STRICT,
|
||||
reinterpret_cast<BYTE*>(bytes.data()),&length,nullptr,nullptr) || bytes.front()!='/' ||
|
||||
bytes.find_first_of("\\:\r\n")!=bytes.npos || bytes.find('\0')!=bytes.npos) return {};
|
||||
auto path=fs::path(ks::wide(bytes)).lexically_normal();
|
||||
return isFtpFolderPath(path)?std::optional(std::move(path)):std::nullopt;
|
||||
}
|
||||
|
||||
void acceptSshDirectory(HWND owner,std::wstring_view message)
|
||||
{
|
||||
if(!panelMatchesSshPrompt() || sshPrompt->finished || message.size()<33 || message[32]!=L':' ||
|
||||
message.substr(0,32)!=ks::wide(sshPrompt->token)) return;
|
||||
const auto reported=sshReportedDirectory(message.substr(33));
|
||||
if(!reported) return;
|
||||
auto &panel=panels[active];
|
||||
auto &prompt=*sshPrompt;
|
||||
const bool initial=prompt.shellDirectory.empty();
|
||||
const bool command=std::exchange(prompt.raw,false);
|
||||
prompt.shellDirectory=*reported;
|
||||
prompt.waiting=false;
|
||||
if(command)
|
||||
{
|
||||
sshView.post(L"ssh-input:off");
|
||||
if(GetForegroundWindow()==owner) restoreCommandFocus();
|
||||
}
|
||||
if(prompt.startupCommand)
|
||||
{
|
||||
const auto pending=std::exchange(prompt.startupCommand,{});
|
||||
if(!sendSshCommand(owner,prompt.panelDirectory,*pending) && !GetWindowTextLengthW(terminalInput))
|
||||
SetWindowTextW(terminalInput,pending->c_str());
|
||||
return;
|
||||
}
|
||||
if(panel.scan.valid() || panel.directory!=prompt.panelDirectory || panel.directory==*reported) return;
|
||||
if(initial || command)
|
||||
{
|
||||
prompt.panelDirectory=*reported;
|
||||
open(panel,*reported,false);
|
||||
}
|
||||
else setStatus(L"The SSH shell could not enter the panel folder.");
|
||||
}
|
||||
|
||||
void updateSshTerminal(HWND owner)
|
||||
{
|
||||
if(!sshPrompt) return;
|
||||
if(!panelMatchesSshPrompt()) {closeSshPrompt(owner);return;}
|
||||
if(!sshView.initialized()) return;
|
||||
const auto output=sshTerminal.takeOutput();
|
||||
if(!output.empty()) sshView.send(output);
|
||||
auto &prompt=*sshPrompt;
|
||||
if(!sshTerminal.running() && !prompt.finished)
|
||||
{
|
||||
auto reason=sshTerminal.takeError();
|
||||
if(reason.empty()) reason=L"SSH session disconnected.";
|
||||
sshView.send(ks::utf8(L"\r\n["+reason+L"]\r\n"));
|
||||
if(prompt.startupCommand && !GetWindowTextLengthW(terminalInput))
|
||||
SetWindowTextW(terminalInput,prompt.startupCommand->c_str());
|
||||
prompt.finished=true;
|
||||
prompt.raw=false;
|
||||
sshView.post(L"ssh-input:off");
|
||||
setStatus(reason);
|
||||
if(GetForegroundWindow()==owner) restoreCommandFocus();
|
||||
return;
|
||||
}
|
||||
const auto &panel=panels[active];
|
||||
if(prompt.finished || prompt.waiting || panel.scan.valid() || panel.directory==prompt.panelDirectory) return;
|
||||
prompt.panelDirectory=panel.directory;
|
||||
if(panel.directory!=prompt.shellDirectory && sshTerminal.write(sshChangeDirectory(panel.directory)+"\r"))
|
||||
prompt.waiting=true;
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
std::string sshShellQuote(std::string_view text)
|
||||
{
|
||||
std::string quoted="'";
|
||||
for(const auto character:text)
|
||||
if(character=='\'') quoted+="'\\''";
|
||||
else quoted+=character;
|
||||
return quoted+"'";
|
||||
}
|
||||
|
||||
std::string sshChangeDirectory(const fs::path &path)
|
||||
{
|
||||
return "cd "+sshShellQuote(ks::utf8(ftpPath(path)));
|
||||
}
|
||||
|
||||
class FilesSshTerminal
|
||||
{
|
||||
std::mutex mutex_;
|
||||
std::string input_,output_;
|
||||
std::wstring error_;
|
||||
COORD size_{};
|
||||
std::atomic_bool running_{};
|
||||
std::jthread worker_;
|
||||
|
||||
void run(const TransferProfile &profile,const fs::path &directory,const std::string &token,
|
||||
COORD terminalSize,std::stop_token stop)
|
||||
{
|
||||
SshConnection connection(profile);
|
||||
if(stop.stop_requested()) return;
|
||||
SshChannel channel(libssh2_channel_open_session(connection.session()),libssh2_channel_free);
|
||||
if(!channel) connection.operationError("Could not open the SSH terminal");
|
||||
if(libssh2_channel_request_pty_ex(channel.get(),"xterm-256color",14,nullptr,0,
|
||||
terminalSize.X,terminalSize.Y,0,0)) connection.operationError("Could not allocate the SSH terminal");
|
||||
|
||||
// Expand the prompt after every command so panel navigation can follow even scripted directory changes.
|
||||
const auto report="printf '\\033]633;ks-ssh-dir:"+token+
|
||||
":%s\\007' \"$(printf '%s' \"$(pwd -P)\" | base64 | tr -d '\\r\\n')\"";
|
||||
const auto command=sshChangeDirectory(directory)+
|
||||
" || exit; command -v base64 >/dev/null 2>&1 || { echo 'SSH directory sync requires base64.'; exit 1; }; "
|
||||
"if command -v bash >/dev/null 2>&1; then exec env PS1='' PS2='> ' PROMPT_COMMAND="+
|
||||
sshShellQuote(report)+" bash --noprofile --norc -i; else exec env ENV=/dev/null PS2='> ' PS1="+
|
||||
sshShellQuote("$("+report+")")+" /bin/sh -i; fi";
|
||||
if(libssh2_channel_exec(channel.get(),command.c_str()))
|
||||
connection.operationError("Could not start the SSH shell");
|
||||
|
||||
connection.nonblocking();
|
||||
auto buffer=std::array<char,32768>{};
|
||||
std::string pending;
|
||||
size_t offset{};
|
||||
std::optional<COORD> resize;
|
||||
while(!stop.stop_requested())
|
||||
{
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
if(pending.empty()) pending.swap(input_);
|
||||
if(!resize && (terminalSize.X!=size_.X || terminalSize.Y!=size_.Y)) resize=size_;
|
||||
}
|
||||
bool progressed=false;
|
||||
if(resize)
|
||||
{
|
||||
const auto result=libssh2_channel_request_pty_size(channel.get(),resize->X,resize->Y);
|
||||
if(result!=LIBSSH2_ERROR_EAGAIN)
|
||||
{
|
||||
terminalSize=*resize;
|
||||
resize.reset();
|
||||
}
|
||||
}
|
||||
if(!pending.empty())
|
||||
{
|
||||
const auto count=libssh2_channel_write(channel.get(),pending.data()+offset,pending.size()-offset);
|
||||
if(count<0 && count!=LIBSSH2_ERROR_EAGAIN) connection.operationError("Could not send SSH terminal input");
|
||||
if(count>0)
|
||||
{
|
||||
offset+=count;
|
||||
if(offset==pending.size()) {pending.clear();offset=0;}
|
||||
progressed=true;
|
||||
}
|
||||
}
|
||||
for(int stream:{0,SSH_EXTENDED_DATA_STDERR})
|
||||
{
|
||||
const auto count=libssh2_channel_read_ex(channel.get(),stream,buffer.data(),buffer.size());
|
||||
if(count<0 && count!=LIBSSH2_ERROR_EAGAIN) connection.operationError("Could not read SSH terminal output");
|
||||
if(count>0)
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
output_.append(buffer.data(),count);
|
||||
constexpr size_t limit=1024*1024;
|
||||
if(output_.size()>limit) output_.erase(0,output_.size()-limit);
|
||||
progressed=true;
|
||||
}
|
||||
}
|
||||
if(!progressed)
|
||||
{
|
||||
if(libssh2_channel_eof(channel.get())) break;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
}
|
||||
// The connection owns all channels. Its teardown also handles a channel blocked in a nonblocking request.
|
||||
channel.release();
|
||||
}
|
||||
|
||||
public:
|
||||
bool running() const {return running_;}
|
||||
|
||||
void start(TransferProfile profile,fs::path directory,std::string token,COORD size)
|
||||
{
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
input_.clear();
|
||||
output_.clear();
|
||||
error_.clear();
|
||||
size_=size;
|
||||
}
|
||||
running_=true;
|
||||
try
|
||||
{
|
||||
worker_=std::jthread([this,profile=std::move(profile),directory=std::move(directory),
|
||||
token=std::move(token),size](std::stop_token stop)
|
||||
{
|
||||
try {run(profile,directory,token,size,stop);}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
error_=ks::wide(error.what());
|
||||
}
|
||||
running_=false;
|
||||
});
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
running_=false;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void stop() {worker_.request_stop();}
|
||||
|
||||
bool write(std::string_view input)
|
||||
{
|
||||
if(!running_) return false;
|
||||
const std::lock_guard lock(mutex_);
|
||||
constexpr size_t limit=256*1024;
|
||||
if(input.size()>limit-input_.size()) return false;
|
||||
input_+=input;
|
||||
return true;
|
||||
}
|
||||
|
||||
void resize(COORD size)
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
size_=size;
|
||||
}
|
||||
|
||||
std::string takeOutput()
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
return std::exchange(output_,{});
|
||||
}
|
||||
|
||||
std::wstring takeError()
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
return std::exchange(error_,{});
|
||||
}
|
||||
};
|
||||
@@ -127,7 +127,7 @@ public:
|
||||
return SUCCEEDED(web->PostWebMessageAsString(message.c_str()));
|
||||
}
|
||||
bool create(HWND host,std::function<void(const std::wstring&)> receive,std::function<void()> failed,
|
||||
bool markdown=false,std::function<bool(UINT)> handleKey={})
|
||||
bool markdown=false,std::function<bool(UINT)> handleKey={},bool ssh=false)
|
||||
{
|
||||
wchar_t exe[MAX_PATH]{};
|
||||
if(!GetModuleFileNameW(nullptr,exe,MAX_PATH)) return false;
|
||||
@@ -144,7 +144,7 @@ public:
|
||||
if(!length || length>=MAX_PATH) return false;
|
||||
const auto profile=std::filesystem::path(local)/L"KSwitcher"/(markdown?L"MarkdownWebView":L"TerminalWebView");
|
||||
const auto origin=markdown?L"kswitcher-markdown.invalid":L"kswitcher-terminal.invalid";
|
||||
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
|
||||
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":ssh?L"/index.html?ssh":L"/index.html");
|
||||
const auto assets=folder/L"terminal";
|
||||
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
|
||||
waitForReady=!markdown;
|
||||
|
||||
+103
-31
@@ -647,22 +647,26 @@ struct RemoteTextFile
|
||||
std::filesystem::remove(cache.parent_path(),ignored);
|
||||
}
|
||||
|
||||
void download(bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit=UINT64_MAX)
|
||||
void download(bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit=UINT64_MAX,bool elevated=false)
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t name[40]{};
|
||||
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
|
||||
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
|
||||
const auto directory=std::filesystem::temp_directory_path()/(L"ks-files-edit-"+std::wstring(name));
|
||||
if(!std::filesystem::create_directory(directory))
|
||||
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
|
||||
cache=directory/L"content";
|
||||
revision=source.download(original,cache,edit,progress,sizeLimit);
|
||||
if(cache.empty())
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t name[40]{};
|
||||
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
|
||||
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
|
||||
const auto directory=std::filesystem::temp_directory_path()/(L"ks-files-edit-"+std::wstring(name));
|
||||
if(!std::filesystem::create_directory(directory))
|
||||
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
|
||||
cache=directory/L"content";
|
||||
}
|
||||
const auto &read=elevated?source.elevation->download:source.download;
|
||||
revision=read(original,cache,edit,progress,sizeLimit);
|
||||
}
|
||||
|
||||
void upload()
|
||||
void upload(const RemoteTextSource::Progress &cancel)
|
||||
{
|
||||
revision=source.upload(original,cache,revision);
|
||||
revision=cancel?source.elevation->upload(original,cache,revision,cancel):source.upload(original,cache,revision);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -902,9 +906,10 @@ private:
|
||||
std::future<std::string> image;
|
||||
ImageRequest activeImage;
|
||||
std::shared_ptr<std::atomic<bool>> cancelImages;
|
||||
std::atomic<bool> cancelOpen{};
|
||||
std::atomic<bool> cancelOpen{},cancelElevatedSave{};
|
||||
std::future<void> opening;
|
||||
std::future<bool> saving;
|
||||
bool elevatedOpen{},elevatedSave{};
|
||||
static constexpr UINT_PTR saveTimer = 1;
|
||||
static constexpr UINT_PTR openTimer = 2;
|
||||
static constexpr UINT_PTR previewTimer = 3;
|
||||
@@ -964,6 +969,7 @@ private:
|
||||
void invalidateHints() const;
|
||||
|
||||
void initializeDocument(std::optional<std::string> firstPage={});
|
||||
void startRemoteOpen(bool elevated=false);
|
||||
void finishOpen();
|
||||
void createMenu();
|
||||
void releaseMenu();
|
||||
@@ -986,7 +992,7 @@ private:
|
||||
void pickBookmark(bool currentFile);
|
||||
void stagePage();
|
||||
void go(uint64_t index);
|
||||
void saveFile(bool closeWhenDone);
|
||||
void saveFile(bool closeWhenDone,bool elevated=false);
|
||||
void finishSave();
|
||||
void requestClose();
|
||||
void toggleMode();
|
||||
@@ -1677,6 +1683,24 @@ void TextWindow::pollQuickView()
|
||||
std::thread(std::move(task)).detach();
|
||||
}
|
||||
|
||||
void TextWindow::startRemoteOpen(bool elevated)
|
||||
{
|
||||
elevatedOpen=elevated;
|
||||
if(!SetTimer(window,openTimer,75,nullptr)) throw std::runtime_error("Cannot start the remote file timer.");
|
||||
try
|
||||
{
|
||||
opening=std::async(std::launch::async,[this,elevated]
|
||||
{
|
||||
remote->download(edit,[this](uint64_t,uint64_t){return !cancelOpen;},UINT64_MAX,elevated);
|
||||
});
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
KillTimer(window,openTimer);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void TextWindow::finishOpen()
|
||||
{
|
||||
if(!opening.valid() || opening.wait_for(std::chrono::milliseconds(0))!=std::future_status::ready) return;
|
||||
@@ -1689,6 +1713,18 @@ void TextWindow::finishOpen()
|
||||
initializeDocument();
|
||||
invalidate();
|
||||
}
|
||||
catch(const RemoteAccessDenied &error)
|
||||
{
|
||||
if(!cancelOpen && !edit && !elevatedOpen && remote->source.elevation)
|
||||
{
|
||||
if(remote->source.elevation->approve(window,original,false))
|
||||
startRemoteOpen(true);
|
||||
else DestroyWindow(window);
|
||||
return;
|
||||
}
|
||||
if(!cancelOpen) search.style.message(window,wide(error.what()).c_str());
|
||||
DestroyWindow(window);
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(!cancelOpen) search.style.message(window,wide(error.what()).c_str());
|
||||
@@ -1696,7 +1732,7 @@ void TextWindow::finishOpen()
|
||||
}
|
||||
}
|
||||
|
||||
void TextWindow::saveFile(bool closeWhenDone)
|
||||
void TextWindow::saveFile(bool closeWhenDone,bool elevated)
|
||||
{
|
||||
if (busy() || savedViewerLoad.valid() || !edit) return;
|
||||
auto destination=original;
|
||||
@@ -1710,17 +1746,22 @@ void TextWindow::saveFile(bool closeWhenDone)
|
||||
pendingCaret = send(SCI_GETCURRENTPOS);
|
||||
if(draft) pendingSavePath=destination;
|
||||
closeAfterSave = closeWhenDone;
|
||||
elevatedSave=elevated;
|
||||
cancelElevatedSave=false;
|
||||
if (!SetTimer(window, saveTimer, 75, nullptr)) throw std::runtime_error("Cannot start the save timer.");
|
||||
send(SCI_SETREADONLY, TRUE);
|
||||
try
|
||||
{
|
||||
saving=std::async(std::launch::async,[this,destination=std::move(destination)]
|
||||
saving=std::async(std::launch::async,[this,destination=std::move(destination),elevated]
|
||||
{
|
||||
const auto reopened=draft?document->saveNew(destination,newFormat):document->save();
|
||||
if(remote)
|
||||
{
|
||||
uploadPending=true;
|
||||
remote->upload();
|
||||
const auto progress=elevated?RemoteTextSource::Progress([this](uint64_t,uint64_t) {
|
||||
return !cancelElevatedSave;
|
||||
}):RemoteTextSource::Progress{};
|
||||
remote->upload(progress);
|
||||
uploadPending=false;
|
||||
}
|
||||
return reopened;
|
||||
@@ -1745,7 +1786,22 @@ void TextWindow::finishSave()
|
||||
return;
|
||||
}
|
||||
send(SCI_SETREADONLY, !edit);
|
||||
const auto reopened = saving.get();
|
||||
bool reopened{};
|
||||
try {reopened=saving.get();}
|
||||
catch(const RemoteAccessDenied &)
|
||||
{
|
||||
if(!remote || elevatedSave || !remote->source.elevation) throw;
|
||||
if(remote->source.elevation->approve(window,original,true)) saveFile(closeAfterSave,true);
|
||||
else {closeAfterSave=false;invalidate();}
|
||||
return;
|
||||
}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
if(!elevatedSave || error.code().value()!=ERROR_CANCELLED) throw;
|
||||
closeAfterSave=false;
|
||||
invalidate();
|
||||
return;
|
||||
}
|
||||
stagedDirty = false;
|
||||
const bool created=std::exchange(draft,false);
|
||||
if(created)
|
||||
@@ -1781,7 +1837,11 @@ void TextWindow::finishSave()
|
||||
void TextWindow::requestClose()
|
||||
{
|
||||
if (opening.valid()) { cancelOpen=true; return; }
|
||||
if (busy()) return;
|
||||
if (busy())
|
||||
{
|
||||
if(elevatedSave) cancelElevatedSave=true;
|
||||
return;
|
||||
}
|
||||
cancelSavedViewerLoad();
|
||||
if (needsSave())
|
||||
{
|
||||
@@ -2651,7 +2711,7 @@ void TextWindow::find(bool down, DWORD flags)
|
||||
void TextWindow::command(UINT id)
|
||||
{
|
||||
if(!document && id!=close) return;
|
||||
if (busy()) return;
|
||||
if (busy() && id!=close) return;
|
||||
if(hex && (id==switchMode || id==historyBack || id==historyForward || id==findText || id==findNext ||
|
||||
id==findPrevious || id==lexerAuto || id==lexerPlain || id>=lexerStart)) return;
|
||||
switch (id)
|
||||
@@ -2877,12 +2937,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
{
|
||||
self->applyPreferences();
|
||||
self->send(SCI_SETREADONLY,TRUE);
|
||||
if(!SetTimer(window,openTimer,75,nullptr))
|
||||
throw std::runtime_error("Cannot start the remote file timer.");
|
||||
self->opening=std::async(std::launch::async,[state=self.get()]
|
||||
{
|
||||
state->remote->download(state->edit,[state](uint64_t,uint64_t){return !state->cancelOpen;});
|
||||
});
|
||||
self->startRemoteOpen();
|
||||
}
|
||||
else if(self->embedded) self->applyPreferences();
|
||||
else self->initializeDocument();
|
||||
@@ -3228,18 +3283,35 @@ void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const
|
||||
{
|
||||
const auto backend=source?std::optional(*source):peer?std::optional(lanTextSource(*peer)):std::nullopt;
|
||||
ImageLoad load;
|
||||
ImageLoadRetry retry;
|
||||
if(backend)
|
||||
load=[backend=*backend](const std::filesystem::path &original,std::stop_token stop) {
|
||||
RemoteTextFile file(backend,original);
|
||||
file.download(false,[&](uint64_t,uint64_t){return !stop.stop_requested();},imageSourceLimit);
|
||||
return decodeImage(file.cache,original,stop);
|
||||
{
|
||||
const auto reader=[&](bool elevated) -> ImageLoad
|
||||
{
|
||||
return [backend=*backend,elevated](const std::filesystem::path &original,std::stop_token stop)
|
||||
{
|
||||
RemoteTextFile file(backend,original);
|
||||
file.download(false,[&](uint64_t,uint64_t){return !stop.stop_requested();},imageSourceLimit,elevated);
|
||||
return decodeImage(file.cache,original,stop);
|
||||
};
|
||||
};
|
||||
load=reader(false);
|
||||
if(backend->elevation)
|
||||
{
|
||||
retry.load=reader(true);
|
||||
retry.approve=[approve=backend->elevation->approve](HWND window,
|
||||
const std::filesystem::path &file,const std::exception &failure)
|
||||
{
|
||||
return dynamic_cast<const RemoteAccessDenied*>(&failure) && approve(window,file,false);
|
||||
};
|
||||
}
|
||||
}
|
||||
if(!textWindows.contains(owner)) filesOwner=owner;
|
||||
const auto window=createImageView(owner,false,imageViewStyle(dialogs),std::move(images),path,std::move(load),
|
||||
[](HWND closed) {
|
||||
std::erase(textWindowOrder,closed);
|
||||
quitWhenFilesWindowsClose();
|
||||
});
|
||||
},std::move(retry));
|
||||
if(!window) throw std::runtime_error("Could not open the image viewer.");
|
||||
textWindowOrder.push_back(window);
|
||||
const auto instance=GetModuleHandleW(nullptr);
|
||||
|
||||
+24
-4
@@ -3,6 +3,8 @@
|
||||
#include <windows.h>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <system_error>
|
||||
#include <cstdint>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
@@ -71,15 +73,33 @@ struct RemoteTextRevision
|
||||
bool editable{};
|
||||
};
|
||||
|
||||
struct RemoteAccessDenied : std::system_error
|
||||
{
|
||||
explicit RemoteAccessDenied(const char *operation):
|
||||
std::system_error(ERROR_ACCESS_DENIED,std::system_category(),operation) {}
|
||||
};
|
||||
|
||||
struct RemoteTextSource
|
||||
{
|
||||
using Progress=std::function<bool(uint64_t,uint64_t)>;
|
||||
using Download=std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
|
||||
bool,const Progress &,uint64_t)>;
|
||||
using Upload=std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
|
||||
const RemoteTextRevision &)>;
|
||||
|
||||
struct Elevation
|
||||
{
|
||||
Download download;
|
||||
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
|
||||
const RemoteTextRevision &,const Progress &)> upload;
|
||||
std::function<bool(HWND,const std::filesystem::path &,bool)> approve;
|
||||
};
|
||||
|
||||
std::string id;
|
||||
std::wstring name;
|
||||
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
|
||||
bool,const Progress &,uint64_t)> download;
|
||||
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
|
||||
const RemoteTextRevision &)> upload;
|
||||
Download download;
|
||||
Upload upload;
|
||||
std::optional<Elevation> elevation;
|
||||
};
|
||||
RemoteTextSource createLanTextSource(const lan::FilesPeer &peer);
|
||||
|
||||
|
||||
@@ -59,9 +59,10 @@ class TransferSession
|
||||
std::optional<SftpSession> sftp_;
|
||||
|
||||
public:
|
||||
explicit TransferSession(const TransferProfile &profile)
|
||||
explicit TransferSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal,
|
||||
std::stop_token stop={})
|
||||
{
|
||||
if(profile.protocol==TransferProtocol::sftp) sftp_.emplace(profile);
|
||||
if(profile.protocol==TransferProtocol::sftp) sftp_.emplace(profile,access,stop);
|
||||
else ftp_.emplace(profile);
|
||||
}
|
||||
|
||||
@@ -101,6 +102,11 @@ public:
|
||||
FtpDeleteFileA(ftp_->handle(),name.c_str()));
|
||||
}
|
||||
|
||||
void prepareReplacement(const fs::path &staged,const fs::path &existing)
|
||||
{
|
||||
if(sftp_) sftp_->prepareReplacement(staged,existing);
|
||||
}
|
||||
|
||||
void rename(const fs::path &from,const fs::path &to,bool replace=false)
|
||||
{
|
||||
if(sftp_) {sftp_->rename(from,to,replace);return;}
|
||||
|
||||
+30
-11
@@ -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
@@ -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 = {});
|
||||
};
|
||||
|
||||
@@ -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"}};
|
||||
|
||||
Reference in new issue
Block a user