Files
hrynco-kswitcher/src/files_main.cpp
T

10253 lines
422 KiB
C++

#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <commctrl.h>
#include <windowsx.h>
#include <winioctl.h>
#include <shellapi.h>
#include <shlobj.h>
#include <commdlg.h>
#include <dwmapi.h>
#include <aclapi.h>
#include <sddl.h>
#include <tlhelp32.h>
#include <psapi.h>
#include <userenv.h>
#include <cmath>
#include <numbers>
#include <algorithm>
#include <array>
#include <charconv>
#include <atomic>
#include <deque>
#include <filesystem>
#include <fstream>
#include <future>
#include <thread>
#include <iomanip>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include <objbase.h>
#include <winternl.h>
#include <wininet.h>
#include <lm.h>
#include <winnetwk.h>
#include <wincred.h>
#include <wincrypt.h>
#include <libssh2.h>
#include <libssh2_sftp.h>
#include "files_terminal.h"
#include "files_archive.h"
#include "files_git_changes.h"
#include "files_compare_text.h"
#include "files_image_view.h"
#include "files_win32_directory.h"
#include "files_win32_replace.h"
#include "files_command_completion.h"
#include "files_text_window.h"
#include "files_menu_navigation.h"
#include "files_text_preferences.h"
#include "files_appearance.h"
#include "files_help.h"
#include "files_mcp.h"
#include "files_menu_paint.h"
#include "files_dropdown_paint.h"
#include "files_scrollbar.h"
#include "files_inline_action.h"
#include "files_history_date.h"
#include "files_terminal_view.h"
#include "files_lan_ipc.h"
#include "lan_files.h"
#include "lan_network.h"
#include "lan_wake.h"
#include "platform.h"
#include "../resources/resource.h"
namespace
{
namespace fs = std::filesystem;
using ks::lan::FilesConnection;
using ks::lan::FilesPeer;
using ks::lan::Json;
using ks::lan::fileRequest;
using ks::lan::filePath;
using ks::lan::checkFileReply;
using ks::files::validFileName;
struct TransferItemMetadata
{
uint64_t created{}, accessed{};
std::optional<uint32_t> owner, permissions;
};
struct FileInfo
{
DWORD attributes;
uint64_t size, modified;
std::optional<uint64_t> allocated{};
std::optional<TransferItemMetadata> transfer{};
};
FileInfo fileInfo(const Json &row)
{
return {row.at("attributes"),row.at("size"),row.at("modified")};
}
std::optional<FileInfo> statFile(const Json &reply)
{
const auto error=reply.at("error").get<DWORD>();
if(error==ERROR_FILE_NOT_FOUND || error==ERROR_PATH_NOT_FOUND) return {};
checkFileReply(reply);
return fileInfo(reply);
}
std::optional<FileInfo> statFile(FilesConnection &host,const fs::path &path)
{
return statFile(host.call(fileRequest("stat",path)));
}
using FileVisitor=std::function<bool(const fs::path &,const FileInfo &)>;
template<class NextPage>
bool listFilePages(Json page,const fs::path &directory,const FileVisitor &visit,NextPage next)
{
for(;;)
{
checkFileReply(page);
for(const auto &row:page.at("entries"))
if(!visit(directory/filePath(row.at("name")),fileInfo(row))) return false;
if(!page.at("more").get<bool>()) return true;
page=next();
}
}
bool listFiles(FilesConnection &host,const fs::path &directory,const FileVisitor &visit)
{
return listFilePages(host.call(fileRequest("list",directory)),directory,visit,
[&]{return host.call({{"action","listNext"}});});
}
std::wstring fileError(const std::system_error &error)
{
wchar_t *message{};
const DWORD length=FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|
FORMAT_MESSAGE_IGNORE_INSERTS,nullptr,error.code().value(),0,reinterpret_cast<wchar_t*>(&message),0,nullptr);
std::wstring text=length?std::wstring(message,length):L"Windows error "+std::to_wstring(error.code().value());
LocalFree(message);
while(!text.empty() && (text.back()==L'\r' || text.back()==L'\n')) text.pop_back();
return text;
}
std::wstring formatSize(uint64_t bytes,size_t columns=0)
{
constexpr const wchar_t *units[]{L"B",L"KiB",L"MiB",L"GiB",L"TiB",L"PiB",L"EiB"};
constexpr const wchar_t *compact[]{L"",L"K",L"M",L"G",L"T",L"P",L"E"};
if(columns)
{
for(size_t unit=0;;++unit,bytes/=1024)
{
auto label=std::to_wstring(bytes)+compact[unit];
if(label.size()<=columns || unit==std::size(compact)-1) return label;
}
}
size_t unit=0;
double value=static_cast<double>(bytes);
while(value>=1024 && unit+1<std::size(units))
{
value/=1024;
++unit;
}
if(!unit) return std::to_wstring(bytes)+L" B";
std::wostringstream label;
label<<std::fixed<<std::setprecision(2)<<value<<L' '<<units[unit];
return label.str();
}
constexpr wchar_t folderPipePrefix[]=L"\\\\.\\pipe\\KSwitcher.Files.Folder.";
struct Handle
{
HANDLE value;
~Handle(){if(value && value!=INVALID_HANDLE_VALUE) CloseHandle(value);}
};
struct FolderEntryMetadata
{
DWORD attributes;
ULONGLONG size, modified;
};
DWORD enableBackupPrivilege()
{
Handle token{};
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&token.value))
return GetLastError();
TOKEN_PRIVILEGES privileges{};
privileges.PrivilegeCount=1;
privileges.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;
if(!LookupPrivilegeValueW(nullptr,SE_BACKUP_NAME,&privileges.Privileges[0].Luid))
return GetLastError();
AdjustTokenPrivileges(token.value,FALSE,&privileges,0,nullptr,nullptr);
return GetLastError();
}
DWORD listElevatedFolder(const fs::path &directory, const std::wstring &pipeName)
{
if(!IsUserAnAdmin() || !directory.is_absolute() || !pipeName.starts_with(folderPipePrefix))
return ERROR_ACCESS_DENIED;
Handle pipe{CreateFileW(pipeName.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_EXISTING,
SECURITY_SQOS_PRESENT|SECURITY_IDENTIFICATION,nullptr)};
if(pipe.value==INVALID_HANDLE_VALUE) return GetLastError();
// Keep the connection open until the parent verifies the helper's process ID.
char ready{};
DWORD received{};
if(!ReadFile(pipe.value,&ready,sizeof(ready),&received,nullptr)) return GetLastError();
if(received!=sizeof(ready) || ready!=1) return ERROR_INVALID_DATA;
if(const auto error=enableBackupPrivilege();error!=ERROR_SUCCESS)
return error;
Handle folder{CreateFileW(directory.c_str(),FILE_LIST_DIRECTORY,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,nullptr)};
if(folder.value==INVALID_HANDLE_VALUE) return GetLastError();
return ks::files::visitDirectoryRecords(folder.value,[&](const FILE_ID_BOTH_DIR_INFO &entry,std::wstring_view name) {
const FolderEntryMetadata metadata{entry.FileAttributes,static_cast<ULONGLONG>(entry.EndOfFile.QuadPart),
static_cast<ULONGLONG>(entry.LastWriteTime.QuadPart)};
std::wstring row(sizeof(metadata)/sizeof(wchar_t),L'\0');
memcpy(row.data(),&metadata,sizeof(metadata));
row.append(name);
DWORD written{};
if(!WriteFile(pipe.value,row.data(),static_cast<DWORD>(row.size()*sizeof(wchar_t)),&written,nullptr))
return GetLastError();
return static_cast<DWORD>(ERROR_SUCCESS);
});
}
struct ElevatedHelper
{
Handle pipe{}, process{};
};
DWORD launchElevatedHelper(HWND owner,std::wstring_view prefix,const std::wstring &command,
const std::wstring &arguments,ElevatedHelper &session)
{
GUID id{};
wchar_t token[40]{}, executable[32768]{};
auto length=GetModuleFileNameW(nullptr,executable,static_cast<DWORD>(std::size(executable)));
if(!length || length>=std::size(executable) || FAILED(CoCreateGuid(&id)) ||
!StringFromGUID2(id,token,static_cast<int>(std::size(token)))) return ERROR_GEN_FAILURE;
auto name=std::wstring(prefix)+token;
session.pipe.value=CreateNamedPipeW(name.c_str(),PIPE_ACCESS_DUPLEX|FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE|PIPE_NOWAIT|PIPE_REJECT_REMOTE_CLIENTS,1,0,4096,0,nullptr);
if(session.pipe.value==INVALID_HANDLE_VALUE) return GetLastError();
auto parameters=command+L" "+arguments+L" \""+name+L"\"";
SHELLEXECUTEINFOW launch{};
launch.cbSize=sizeof(launch);
launch.fMask=SEE_MASK_NOCLOSEPROCESS|SEE_MASK_NOASYNC;
launch.hwnd=owner;
launch.lpVerb=L"runas";
launch.lpFile=executable;
launch.lpParameters=parameters.c_str();
launch.nShow=SW_HIDE;
if(!ShellExecuteExW(&launch)) return GetLastError();
session.process.value=launch.hProcess;
return ERROR_SUCCESS;
}
DWORD launchElevatedFolder(HWND owner,const fs::path &directory,ElevatedHelper &session)
{
return launchElevatedHelper(owner,folderPipePrefix,L"--list-folder",
L"\""+(directory/L".").wstring()+L"\"",session);
}
DWORD readElevatedFolder(const ElevatedHelper &session,const fs::path &directory,
std::vector<fs::path> &folders,std::vector<fs::path> &files,
std::map<fs::path,FolderEntryMetadata> &metadata,
std::atomic_size_t &entriesRead,std::stop_token stop)
{
bool connected=false;
bool finished=false;
auto deadline=GetTickCount64()+10000;
while(!stop.stop_requested() && GetTickCount64()<deadline)
{
if(!connected)
{
connected=ConnectNamedPipe(session.pipe.value,nullptr) || GetLastError()==ERROR_PIPE_CONNECTED;
if(connected)
{
ULONG client{};
if(!GetNamedPipeClientProcessId(session.pipe.value,&client) || client!=GetProcessId(session.process.value))
return ERROR_ACCESS_DENIED;
const char ready=1;
DWORD written{};
if(!WriteFile(session.pipe.value,&ready,sizeof(ready),&written,nullptr)) return GetLastError();
if(written!=sizeof(ready)) return ERROR_WRITE_FAULT;
}
}
if(connected)
{
wchar_t row[512]{};
DWORD bytes{};
if(ReadFile(session.pipe.value,row,sizeof(row),&bytes,nullptr))
{
FolderEntryMetadata entry{};
if(bytes<=sizeof(entry) || bytes%sizeof(wchar_t)) return ERROR_INVALID_DATA;
memcpy(&entry,row,sizeof(entry));
const std::wstring_view name(row+sizeof(entry)/sizeof(wchar_t),(bytes-sizeof(entry))/sizeof(wchar_t));
if(name.find(L'\0')!=name.npos) return ERROR_INVALID_DATA;
const fs::path child(name);
if(child!=child.filename() || child==L"." || child==L"..") return ERROR_INVALID_DATA;
const auto path=directory/child;
(entry.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path);
metadata.emplace(path,entry);
entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed);
continue;
}
}
if(finished)
{
DWORD result{};
if(!GetExitCodeProcess(session.process.value,&result)) return GetLastError();
return !connected && result==ERROR_SUCCESS ? ERROR_PIPE_NOT_CONNECTED : result;
}
finished=WaitForSingleObject(session.process.value,20)==WAIT_OBJECT_0;
}
return stop.stop_requested()?ERROR_CANCELLED:ERROR_TIMEOUT;
}
struct FolderSize
{
uint64_t bytes{};
bool partial{}, failed{}, previous{};
void add(uint64_t amount)
{
if(amount>UINT64_MAX-bytes) partial=true;
else bytes+=amount;
}
};
using FolderSizes=std::map<fs::path,FolderSize>;
constexpr ULONGLONG folderSpinnerDelay=2000;
constexpr ULONGLONG folderSpinnerInterval=200;
struct FolderSizeJob
{
std::stop_source stop;
std::mutex mutex;
std::deque<fs::path> pending;
std::set<fs::path> requested;
FolderSizes completed;
fs::path current;
ULONGLONG started=GetTickCount64();
bool finished{};
};
using FolderMeasurementObserver=std::function<void(const fs::path &,const FileInfo *)>;
bool listMeasuredDirectory(FilesConnection &host,const fs::path &directory,const FileVisitor &visit,
std::stop_token stop)
{
const auto info=statFile(host,directory);
return info && (info->attributes&FILE_ATTRIBUTE_DIRECTORY) &&
!(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT) && !stop.stop_requested() &&
listFiles(host,directory,visit);
}
template<class ListDirectory>
FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDirectory &listDirectory,
const FolderMeasurementObserver &observe={})
{
FolderSize size;
bool readable=false;
std::vector<fs::path> pending{root};
while(!pending.empty() && !stop.stop_requested())
{
const auto directory=std::move(pending.back());
pending.pop_back();
bool complete=false;
try
{
complete=listDirectory(directory,[&](const fs::path &path,const FileInfo &entry)
{
if(stop.stop_requested()) return false;
readable=true;
if(observe) observe(path,&entry);
if(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT) return true;
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY) pending.push_back(path);
else size.add(entry.size);
return true;
});
}
catch(const std::exception &) {}
readable|=complete;
if(!complete)
{
size.partial=true;
if(observe) observe(directory,nullptr);
}
}
if(stop.stop_requested()) size.partial=true;
size.failed=size.partial && !readable && !stop.stop_requested();
return size;
}
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"
fs::path folderPathWithoutSeparator(fs::path path)
{
if(!path.has_filename() && path.has_relative_path()) return path.parent_path();
return path;
}
bool windowsNetworkPath(const fs::path &path)
{
std::wstring_view name=path.native();
if(name.starts_with(L"\\\\?\\"))
{
name.remove_prefix(4);
if(name.size()>=4 && CompareStringOrdinal(name.data(),4,L"UNC\\",4,TRUE)==CSTR_EQUAL) return true;
return name.size()>=3 && name[1]==L':' && name[2]==L'\\' &&
GetDriveTypeW(std::wstring(name.substr(0,3)).c_str())==DRIVE_REMOTE;
}
return name.starts_with(L"\\\\") || name.starts_with(L"//") ||
GetDriveTypeW(path.root_path().c_str())==DRIVE_REMOTE;
}
fs::path panelParentPath(const fs::path &directory,bool local)
{
if(!directory.has_relative_path()) return {};
const auto parent=directory.parent_path();
if(parent==directory) return {};
if(local && directory.root_name().native().starts_with(L"\\\\") && !parent.has_relative_path())
return {}; // A UNC share is a browsing root.
return parent;
}
enum class FolderProvider { local, ftp, lan, sftp };
bool isTransferFolder(FolderProvider provider)
{
return provider==FolderProvider::ftp || provider==FolderProvider::sftp;
}
FolderProvider transferFolderProvider(TransferProtocol protocol)
{
return protocol==TransferProtocol::sftp?FolderProvider::sftp:FolderProvider::ftp;
}
TransferProtocol folderTransferProtocol(FolderProvider provider)
{
return provider==FolderProvider::sftp?TransferProtocol::sftp:TransferProtocol::ftp;
}
struct FolderLocation
{
fs::path directory;
FolderProvider provider{FolderProvider::local};
std::string id;
std::wstring label;
bool sameSource(const FolderLocation &other) const {return provider==other.provider && id==other.id;}
};
bool sameFolderPath(const fs::path &a,const fs::path &b,FolderProvider provider)
{
return CompareStringOrdinal(a.c_str(),-1,b.c_str(),-1,isTransferFolder(provider)?FALSE:TRUE)==CSTR_EQUAL;
}
bool sameFolderLocation(const FolderLocation &a,const FolderLocation &b)
{
return a.sameSource(b) && sameFolderPath(a.directory,b.directory,a.provider);
}
bool inFolderBranch(const fs::path &ancestor,fs::path directory,FolderProvider provider)
{
while(!directory.empty())
{
if(sameFolderPath(ancestor,directory,provider)) return true;
directory=panelParentPath(directory,provider==FolderProvider::local);
}
return false;
}
#include "files_recent_folders.inl"
struct FolderNavigation
{
std::vector<FolderLocation> history;
size_t current{};
fs::path previousBranch;
void opened(FolderLocation location,std::optional<size_t> position)
{
if(!history.empty())
{
const auto &previous=history[current];
if(sameFolderLocation(previous,location))
{
history[current]=std::move(location);
return;
}
const auto provider=location.provider;
if(!previous.sameSource(location)) previousBranch.clear();
else if(inFolderBranch(location.directory,previous.directory,provider))
{
if(!inFolderBranch(previous.directory,previousBranch,provider)) previousBranch=previous.directory;
}
else if(!inFolderBranch(location.directory,previousBranch,provider)) previousBranch.clear();
}
if(position && *position<history.size() && sameFolderLocation(history[*position],location))
{
history[*position]=std::move(location);
current=*position;
return;
}
if(!history.empty()) history.erase(history.begin()+current+1,history.end());
history.push_back(std::move(location));
current=history.size()-1;
}
std::optional<size_t> neighbor(int direction) const
{
if(direction<0) return current?std::optional<size_t>(current-1):std::nullopt;
return current+1<history.size()?std::optional<size_t>(current+1):std::nullopt;
}
};
enum class PanelMode : DWORD { brief, wide, medium, full };
constexpr const wchar_t *panelModeNames[]{L"Brief",L"Wide",L"Medium",L"Full"};
enum PanelColumn : size_t { nameColumn, extensionColumn, sizeColumn, dateColumn, allocationColumn,
linkColumn, ownerColumn, panelColumnCount };
constexpr const wchar_t *panelColumnNames[]{L"Name",L"Ext",L"Size",L"Modified",L"Allocated",L"Links",L"Owner"};
constexpr DWORD columnMask(PanelColumn column) { return 1u<<column; }
constexpr DWORD extendedColumnMask=columnMask(allocationColumn)|columnMask(linkColumn)|columnMask(ownerColumn);
constexpr DWORD optionalColumnMask=((1u<<panelColumnCount)-1)&~columnMask(nameColumn);
struct ColumnSettings
{
DWORD visibility{};
bool automatic{true}, customized{};
};
struct ColumnMetadata
{
std::wstring owner;
std::optional<uint64_t> allocated;
std::optional<DWORD> links;
std::optional<TransferItemMetadata> transfer;
};
using ColumnMetadataMap=std::map<fs::path,ColumnMetadata>;
DWORD defaultPanelColumns(PanelMode mode)
{
constexpr DWORD medium=columnMask(sizeColumn);
constexpr DWORD wide=medium|columnMask(extensionColumn)|columnMask(dateColumn);
switch(mode)
{
case PanelMode::brief: return 0;
case PanelMode::medium: return medium;
case PanelMode::wide: return wide;
case PanelMode::full: return wide|extendedColumnMask;
}
return 0;
}
enum class PanelSort { name, extension, size, modified };
struct PanelView
{
PanelSort sort{PanelSort::name};
bool descending{}, foldersFirst{true}, showHidden{true}, tree{}, automaticSizes{};
std::wstring mask;
fs::path revealedFile;
};
struct DirectoryRow
{
fs::path path;
uint64_t value{};
bool folder{};
};
struct ArchiveLocation
{
fs::path file;
std::shared_ptr<const ks::files::ArchiveEntries> entries;
};
struct RemotePanelLocation
{
fs::path directory,cursor;
std::string ftpProfile;
std::optional<FilesPeer> peer;
std::optional<size_t> navigationPosition;
TransferProtocol protocol{};
};
namespace smb { struct PendingConnection; }
struct SmbListing
{
std::string serverId;
std::wstring server;
};
struct PanelListing
{
std::optional<SmbListing> smb;
std::vector<FolderLocation> recent;
std::vector<std::pair<fs::path,std::wstring>> rows;
fs::path returnSelection;
};
struct Panel
{
HWND path{}, list{}, heading{};
fs::path directory;
FolderNavigation navigation;
std::optional<FilesPeer> peer;
std::optional<TransferProfile> ftp;
std::optional<PanelListing> listing;
std::shared_ptr<smb::PendingConnection> smbPending;
std::optional<ArchiveLocation> archive;
struct DirectoryWatch
{
HANDLE handle=INVALID_HANDLE_VALUE;
DirectoryWatch()=default;
DirectoryWatch(DirectoryWatch &&other) noexcept {std::swap(handle,other.handle);}
DirectoryWatch &operator=(DirectoryWatch &&other) noexcept
{
if(this!=&other)
{
reset();
std::swap(handle,other.handle);
}
return *this;
}
~DirectoryWatch() { reset(); }
void reset()
{
if(handle!=INVALID_HANDLE_VALUE) FindCloseChangeNotification(handle);
handle=INVALID_HANDLE_VALUE;
}
void start(const fs::path &path)
{
reset();
handle=FindFirstChangeNotificationW(path.c_str(),FALSE,
FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_DIR_NAME|
FILE_NOTIFY_CHANGE_ATTRIBUTES|FILE_NOTIFY_CHANGE_SIZE|FILE_NOTIFY_CHANGE_LAST_WRITE);
}
} watch;
struct FindOptions { std::wstring mask=L"*"; bool includeHidden{}; };
struct FindOrigin
{
FindOptions options;
fs::path cursor;
std::set<fs::path> marks;
LRESULT row{}, top{};
DWORD error{};
};
std::optional<FindOrigin> findOrigin;
PanelView view;
std::set<fs::path> filteredMarks;
struct ScanRequest
{
fs::path directory, selection, fallback;
std::optional<FilesPeer> peer;
bool offerElevation{};
uint64_t statusRevision{};
std::shared_ptr<ElevatedHelper> elevated;
std::optional<TransferProfile> ftp;
std::optional<FindOptions> find;
std::optional<size_t> navigationPosition;
std::optional<ArchiveLocation> archive;
unsigned reconnectAttempt{};
fs::path fallbackSelection;
std::optional<PanelListing> listing;
};
struct RemoteRetry
{
RemotePanelLocation location;
std::wstring failure;
ULONGLONG retryAt{};
unsigned reconnectAttempt{};
};
std::optional<RemoteRetry> remoteRetry;
struct ScanResult
{
DirectoryWatch watch;
std::vector<fs::path> folders, files;
std::map<fs::path,FolderEntryMetadata> metadata;
DWORD error{};
bool opened{};
std::wstring failure;
fs::path ftpInitialDirectory;
std::vector<DirectoryRow> ordered;
ColumnMetadataMap columnMetadata;
std::shared_ptr<const ks::files::ArchiveEntries> archiveEntries;
};
struct TreeBranch
{
std::vector<DirectoryRow> ordered;
std::map<fs::path,FolderEntryMetadata> metadata;
ColumnMetadataMap columnMetadata;
std::future<std::unique_ptr<ScanResult>> scan;
std::stop_source stop;
bool expanded{}, loaded{}, failed{}, needsScan{};
};
struct TreeView
{
fs::path root;
std::map<fs::path,TreeBranch> branches;
std::set<fs::path> marks;
std::map<fs::path,size_t> depths;
} tree;
std::set<fs::path> listReturnMarks;
std::optional<ScanRequest> scanRequest;
std::future<std::unique_ptr<ScanResult>> scan;
std::stop_source scanStop;
std::shared_ptr<std::atomic_size_t> scanEntriesRead;
bool scanSuperseded{};
std::map<fs::path,FolderEntryMetadata> metadata;
std::vector<fs::path> rows;
std::vector<std::wstring> sizes;
std::vector<bool> dimmed;
std::vector<bool> marked;
HWND selectionSummary{};
FolderSizes folderSizes;
std::shared_ptr<FolderSizeJob> folderSizeJob;
std::set<fs::path> folderSizeWaiting;
fs::path folderSpinner;
std::set<fs::path> transferResults;
size_t fileExtensionLength{}, folderExtensionLength{};
PanelMode mode{PanelMode::brief};
std::array<ColumnSettings,std::size(panelModeNames)> columns;
std::array<size_t,panelColumnCount> longestColumn{};
ColumnMetadataMap columnMetadata;
};
bool transferProfileList(const Panel &panel)
{
return panel.ftp && panel.ftp->name.empty();
}
bool recentFolderList(const Panel &panel)
{
return panel.listing && !panel.listing->smb;
}
bool panelListsLocations(const Panel &panel)
{
return panel.listing || transferProfileList(panel);
}
bool samePanelListing(const PanelListing &first,const PanelListing &second)
{
if(first.smb.has_value()!=second.smb.has_value()) return false;
return !first.smb || first.smb->serverId==second.smb->serverId;
}
void showRecentFolders(Panel &panel);
void openRecentFolder(Panel &panel);
void removeRecentFolder(Panel &panel);
void showSmbProfiles(Panel &panel);
void refreshSmbPanel(Panel &panel);
void enterSmbPanel(Panel &panel);
void backSmbPanel(Panel &panel);
void editSmbProfile(Panel &panel,bool create);
void removeSmbProfile(Panel &panel);
void signInSmbProfile(Panel &panel);
void cancelSmbConnection(Panel &panel);
constexpr int smbSignInCommand=547;
FolderLocation folderLocation(const Panel &panel,const fs::path &directory)
{
if(panel.ftp) return {directory,transferFolderProvider(panel.ftp->protocol),panel.ftp->id,panel.ftp->name};
if(panel.peer) return {directory,FolderProvider::lan,panel.peer->id,panel.peer->name};
return {directory};
}
std::wstring panelLocation(const Panel &panel)
{
if(recentFolderList(panel)) return L"Recent folders";
if(panel.listing)
{
const auto &server=panel.listing->smb->server;
return server.empty()?L"SMB":L"SMB · "+server;
}
if(panel.ftp)
return transferProfileList(panel)?transferProtocolName(panel.ftp->protocol):panel.ftp->name+L" · "+ftpPath(panel.directory);
return (panel.peer?panel.peer->name+L" · ":std::wstring{})+panel.directory.native();
}
bool detailedPanel(const Panel &panel) {return panel.mode!=PanelMode::brief;}
DWORD defaultVisibleColumns(PanelMode mode);
DWORD effectivePanelColumns(const Panel &panel)
{
const auto &columns=panel.columns[static_cast<size_t>(panel.mode)];
return detailedPanel(panel)?(columns.customized?columns.visibility:defaultVisibleColumns(panel.mode)):0;
}
bool hasPanelColumns(const Panel &panel)
{
return detailedPanel(panel) && !panel.findOrigin && !panelListsLocations(panel);
}
std::wstring panelCaption(const Panel &panel)
{
if(panel.archive)
{
const auto display=panel.directory.lexically_relative(panel.archive->file.parent_path());
return L"Archive · "+display.native();
}
if(!panel.findOrigin) return panelLocation(panel);
return panel.ftp || panel.peer?L"Search results · "+panelLocation(panel):L"Search results";
}
Panel panels[2];
HWND quickViewWindow{};
HWND quickImageWindow{};
bool quickViewDisplaysImage{};
int quickViewSource{};
bool panelClipboardContext=true;
void refreshQuickView(const Panel &panel);
void toggleQuickView(HWND owner);
FilesTerminal terminal;
std::mutex pendingTerminalOutputMutex;
std::string pendingTerminalOutput;
std::atomic<bool> remoteCommandRunning{};
std::jthread remoteCommandThread;
std::ofstream terminalTrace;
unsigned terminalTraceLines{};
bool traceTerminalOutput{};
void traceTerminal(const char *event,int a=0,int b=0,int c=0,int d=0,int e=0)
{
if(!terminalTrace.is_open() || terminalTraceLines>=4096) return;
++terminalTraceLines;
terminalTrace<<GetTickCount64()<<' '<<event<<' '<<a<<' '<<b<<' '<<c<<' '<<d<<' '<<e<<std::endl;
}
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{};
HWND terminalInput{},terminalOutput{},terminalPrompt{};
constexpr UINT_PTR terminalTimer=2;
constexpr UINT_PTR directoryWatchTimer=4;
bool terminalVisible{};
struct TerminalCommandContext
{
int panel=-1;
fs::path directory;
};
std::deque<TerminalCommandContext> terminalCommands;
std::wstring terminalDirectory;
int terminalRows{};
struct CommandEntry { std::wstring date, command; };
std::vector<CommandEntry> terminalHistory;
size_t terminalHistoryIndex{};
std::wstring terminalHistoryDraft;
constexpr UINT_PTR transferHighlightTimer=1;
unsigned transferHighlightPhase{};
DWORD preference(const wchar_t *name,DWORD fallback);
#include "files_key_schemes.inl"
constexpr struct KeyBarCommand { int id; FilesKey command; const wchar_t *label; } keyBar[]{
{110,FilesKey::Refresh,L"Refresh"}, {111,FilesKey::View,L"View"}, {112,FilesKey::Edit,L"Edit"},
{113,FilesKey::Copy,L"Copy"}, {114,FilesKey::Move,L"Move"}, {115,FilesKey::Mkdir,L"Mkdir"},
{117,FilesKey::Delete,L"Delete"}, {116,FilesKey::Exit,L"Exit"}
};
HWND status{}, commands[std::size(keyBar)]{};
int active{}, split{};
bool dragging{};
bool rememberElevationApproval{};
HWND picker{}, pickerFrame{}, menuBar{};
HWND menuItems[5]{};
constexpr std::wstring_view menuAccessKeys=L"LFCOR";
std::vector<size_t> commandAccessPositions;
std::vector<int> commandActions;
int menuIndex{};
bool commandPicker{};
struct FolderPicker
{
const wchar_t *caption;
std::vector<FolderLocation> locations;
};
std::optional<FolderPicker> folderPicker;
constexpr int defaultSizeWidth=6, defaultFontPoints=110;
constexpr bool defaultWide=false, defaultAlignExtensions=true, defaultShowDetails=true, defaultAlignFolders=false;
constexpr DWORD defaultStatusFields=15;
int sizeWidth=defaultSizeWidth;
bool alignExtensions=defaultAlignExtensions, showDetails=defaultShowDetails;
bool alignFolders=defaultAlignFolders;
bool rightClickMarks{}, showDriveButtons{}, compactLayout{}, restoreDocuments{};
constexpr wchar_t rightClickMarksKey[]=L"RightClickMarks", driveButtonsKey[]=L"ShowDriveButtons",
compactLayoutKey[]=L"CompactPanelLayout",restoreDocumentsKey[]=L"RestoreLocalDocuments";
constexpr int firstDriveButton=660, moreDriveButton=firstDriveButton+26;
std::array<HWND,27> driveButtons{};
DWORD statusFields=defaultStatusFields;
std::vector<fs::path> drivePaths;
bool lanDrivePicker{};
int driveHover=-1;
std::array<LONG,3> driveColumnStarts{};
struct FilesPeerLookup
{
HWND service{};
bool received{};
std::wstring error;
std::vector<FilesPeer> peers;
};
FilesPeerLookup *peerLookupRequest{};
std::wstring drivePeerLookupError;
std::vector<FilesPeer> drivePeers;
std::future<std::wstring> pendingPeerAction;
struct DriveQuery
{
FilesPeer peer;
std::future<Json> pending;
Json drives=Json::array();
std::wstring error;
};
struct DriveChoice { FilesPeer peer; std::optional<fs::path> path; wchar_t digit{}; };
constexpr wchar_t driveWakeLabel[]=L"Wake";
ks::files::InlineListAction driveWakeAction(driveWakeLabel);
std::vector<DriveQuery> driveQueries;
std::map<LRESULT,DriveChoice> remoteDriveRows;
std::map<std::pair<std::string,std::optional<fs::path>>,wchar_t> driveDigits;
constexpr wchar_t ftpDriveDigit=L'1';
constexpr UINT_PTR driveQueryTimer=3;
ULONGLONG nextDriveRefresh{},driveRefreshDeadline{};
int drivePickerWidth{};
int pickerPanel{};
std::wstring panelSearchPrefix;
HWND panelSearchPopup{};
enum Color { PanelBlue, Text, Frame, Dialog, Selection, Footer, PanelCursor, ColorCount };
constexpr std::array<COLORREF,ColorCount> defaultColors{RGB(0,0,128), RGB(230,255,255), RGB(0,255,255),
RGB(0,128,128), RGB(0,0,0), RGB(0,128,128), RGB(0,128,128)};
auto colors=defaultColors;
enum class FilesAppearance : DWORD { Far, Lavender };
constexpr auto filesAppearanceKey=L"AppearanceMode";
FilesAppearance filesAppearance=FilesAppearance::Far;
bool lavenderFiles() { return filesAppearance==FilesAppearance::Lavender; }
constexpr auto placementPreference = L"WindowPlacement";
bool restorePlacement(HWND window)
{
WINDOWPLACEMENT placement{};
DWORD size=sizeof(placement);
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,placementPreference,RRF_RT_REG_BINARY,
nullptr,&placement,&size)!=ERROR_SUCCESS || size!=sizeof(placement) ||
placement.length!=sizeof(placement)) return false;
const auto &rect=placement.rcNormalPosition;
if(static_cast<long long>(rect.right)-rect.left<540 ||
static_cast<long long>(rect.bottom)-rect.top<220) return false;
if(!MonitorFromRect(&rect,MONITOR_DEFAULTTONULL)) return false;
placement.flags=0;
placement.showCmd=placement.showCmd==SW_SHOWMAXIMIZED?SW_SHOWMAXIMIZED:SW_SHOWNORMAL;
if(!SetWindowPlacement(window,&placement)) return false;
ShowWindow(window,static_cast<int>(placement.showCmd));
return true;
}
void savePlacement(HWND window)
{
WINDOWPLACEMENT placement{};
placement.length=sizeof(placement);
if(!GetWindowPlacement(window,&placement)) return;
const bool maximized=IsZoomed(window) ||
(IsIconic(window) && (placement.flags&WPF_RESTORETOMAXIMIZED));
placement.showCmd=maximized?SW_SHOWMAXIMIZED:SW_SHOWNORMAL;
placement.flags=0;
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,placementPreference,REG_BINARY,
&placement,sizeof(placement));
}
void chooseDrive(int index,bool fromMenu=false,bool lanOnly=false);
enum class FilesNoticeTone { dialog, neutral, warning };
struct FilesNoticeOptions
{
bool confirm{};
bool *remember{};
FilesNoticeTone tone{FilesNoticeTone::dialog};
bool processes{};
bool saveChanges{}, chooseTransfer{};
bool fileOperation{};
const wchar_t *accept{}, *decline{};
};
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={});
void openMenu(HWND window, int index);
void openSpaceAnalyzer(HWND owner,Panel &panel);
void showFileDetails(const Panel &panel);
void updateSelectionSummary(const Panel &panel);
void editOptions(HWND owner);
void showFolderShortcuts(Panel &panel,int digit);
void layout(HWND window,bool activeOnly=false);
void clearTerminalSelection();
DWORD preference(const wchar_t *name, DWORD fallback)
{
DWORD value{}, size=sizeof(value);
return RegGetValueW(HKEY_CURRENT_USER,schemeKey,name,RRF_RT_REG_DWORD,nullptr,&value,&size)
== ERROR_SUCCESS ? value : fallback;
}
const UINT filesPreferencesChanged=RegisterWindowMessageW(L"KSwitcher.Files.PreferencesChanged");
void notifyFilesPreferences(HWND source)
{
SendNotifyMessageW(HWND_BROADCAST,filesPreferencesChanged,reinterpret_cast<WPARAM>(source),0);
}
void savePreference(const wchar_t *name, DWORD value)
{
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,name,REG_DWORD,&value,sizeof(value));
}
#include "files_styles.inl"
#include "files_lavender.inl"
FileRowStyle panelRowStyle(const Panel &panel,size_t row,bool cursor,bool activePanel)
{
if(lavenderFiles() && row<panel.rows.size())
{
const bool marked=panel.marked[row];
const bool transferred=transferHighlightPhase%2==0 && panel.transferResults.contains(panel.rows[row]);
const auto foreground=marked?lavender::marked:panel.dimmed[row]?lavender::muted:lavender::ink;
const auto background=cursor?(activePanel?(marked?lavender::markedSelection:lavender::selection):
lavender::idleSelection):transferred?lavender::key:lavender::surface;
return {foreground,background};
}
const bool focused=cursor && activePanel;
const auto foreground=colors[Text],background=colors[focused?PanelCursor:PanelBlue];
if(row>=panel.rows.size() || panel.sizes[row]==L"Up") return {foreground,background};
const bool marked=panel.marked[row];
const bool transferred=transferHighlightPhase%2==0 && panel.transferResults.contains(panel.rows[row]);
const auto state=marked?FileRowState::Marked:!cursor?FileRowState::Normal:
focused?FileRowState::Focused:FileRowState::Unfocused;
return resolveFileStyle(panel.rows[row].extension().native(),panel.sizes[row]!=L"Folder",panel.dimmed[row],
focused || marked || transferred,foreground,background,fileStyles,state,transferred);
}
void setStatus(const std::wstring &message,bool retryAction=false);
void refreshCommandHistory();
std::wstring terminalInputText();
void suppressCurrentCompletion();
#include "files_command_history.inl"
constexpr const wchar_t *panelPathKeys[]{L"LeftPath",L"RightPath"};
constexpr const wchar_t *panelCursorKeys[]{L"LeftCursor",L"RightCursor"};
fs::path savedPanelPath(const wchar_t *key)
{
DWORD size{};
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,key,RRF_RT_REG_SZ,
nullptr,nullptr,&size)!=ERROR_SUCCESS || size<sizeof(wchar_t)) return {};
std::wstring path(size/sizeof(wchar_t),L'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,key,RRF_RT_REG_SZ,
nullptr,path.data(),&size)!=ERROR_SUCCESS) return {};
path.resize(wcslen(path.c_str()));
return path;
}
constexpr const wchar_t *legacyPanelModeKeys[]{L"LeftWide",L"RightWide"};
constexpr const wchar_t *panelModeKeys[]{L"LeftPanelMode",L"RightPanelMode"};
constexpr const wchar_t *panelColumnKeys[2][4]{
{nullptr,L"LeftWideColumns",L"LeftMediumColumns",L"LeftFullColumns"},
{nullptr,L"RightWideColumns",L"RightMediumColumns",L"RightFullColumns"}};
PanelMode readPanelMode(int index)
{
const auto legacy=preference(legacyPanelModeKeys[index],defaultWide)!=0;
const auto stored=preference(panelModeKeys[index],legacy?1:0);
return stored< std::size(panelModeNames)?static_cast<PanelMode>(stored):PanelMode::brief;
}
void savePanelMode(int index,PanelMode mode)
{
savePreference(panelModeKeys[index],static_cast<DWORD>(mode));
savePreference(legacyPanelModeKeys[index],mode!=PanelMode::brief);
}
void loadPanelColumns(int index)
{
auto &panel=panels[index];
for(size_t mode=1;mode<std::size(panelModeNames);++mode)
{
const auto value=preference(panelColumnKeys[index][mode],0);
panel.columns[mode]={value&optionalColumnMask,(value&0x100)==0,(value&0x200)!=0};
}
}
void savePanelColumns(int index,PanelMode mode)
{
const auto slot=static_cast<size_t>(mode);
const auto &settings=panels[index].columns[slot];
savePreference(panelColumnKeys[index][slot],settings.visibility |
(settings.automatic?0:0x100) | (settings.customized?0x200:0));
}
constexpr const wchar_t *panelViewKeys[]{L"LeftViewOrder",L"RightViewOrder"};
void loadPanelView(int index)
{
const auto settings=preference(panelViewKeys[index],0);
auto &view=panels[index].view;
view.sort=static_cast<PanelSort>(settings&3);
view.descending=(settings&4)!=0;
view.foldersFirst=(settings&8)==0;
view.showHidden=(settings&16)==0;
view.tree=(settings&32)!=0;
view.automaticSizes=(settings&64)!=0;
}
void savePanelView(int index)
{
const auto &view=panels[index].view;
savePreference(panelViewKeys[index],static_cast<DWORD>(view.sort) |
(view.descending?4:0) | (view.foldersFirst?0:8) | (view.showHidden?0:16) |
(view.tree?32:0) | (view.automaticSizes?64:0));
}
void refreshPanelColumnData(Panel &panel);
void setMode(int index,PanelMode mode)
{
auto &panel=panels[index];
if(panel.mode==mode) return;
const auto previous=effectivePanelColumns(panel);
panel.mode=mode;
savePanelMode(index,mode);
notifyFilesPreferences(GetParent(panel.list));
layout(GetParent(panel.list));
InvalidateRect(panel.list,nullptr,TRUE);
if((previous^effectivePanelColumns(panel))&extendedColumnMask) refreshPanelColumnData(panel);
showFileDetails(panels[active]);
}
HFONT mono{},terminalFont{};
LOGFONTW displayFont{};
int fontPoints=110;
int textHeight=20, cellWidth=9,terminalTextHeight=20;
using ks::files::AppearanceArea;
constexpr const wchar_t *areaScaleKeys[]{L"PanelScale",L"ViewerScale",L"EditorScale",L"MarkdownScale",
L"TerminalScale",L"ComparisonScale"};
static_assert(std::size(areaScaleKeys)==ks::files::appearanceIndex(AppearanceArea::count));
unsigned readAreaScale(AppearanceArea area)
{
const auto value=preference(areaScaleKeys[ks::files::appearanceIndex(area)],100);
return value>=ks::files::minAppearanceScale && value<=ks::files::maxAppearanceScale?value:100;
}
ks::files::AppearanceScales readAreaScales()
{
auto result=ks::files::defaultAppearanceScales;
for(size_t i=0;i<result.size();++i) result[i]=readAreaScale(static_cast<AppearanceArea>(i));
return result;
}
int areaFontPoints(int points,AppearanceArea area)
{
return ks::files::scaledAppearanceSize(points,readAreaScale(area));
}
using PanelColumnRects=std::array<RECT,panelColumnCount>;
DWORD defaultVisibleColumns(PanelMode mode)
{
auto columns=defaultPanelColumns(mode);
if(mode==PanelMode::wide && !alignExtensions && !alignFolders) columns&=~columnMask(extensionColumn);
return columns;
}
PanelColumnRects panelColumns(const Panel &panel,RECT bounds)
{
PanelColumnRects columns;
columns.fill(bounds);
const auto mask=effectivePanelColumns(panel);
const auto &settings=panel.columns[static_cast<size_t>(panel.mode)];
const auto extensionLength=std::max(alignExtensions || settings.customized || panel.mode==PanelMode::full?
panel.fileExtensionLength:0,alignFolders || settings.customized || panel.mode==PanelMode::full?
panel.folderExtensionLength:0);
const std::array<LONG,panelColumnCount> minimum{10,4,6,11,10,6,7};
const std::array<LONG,panelColumnCount> fixed{10,6,sizeWidth+2L,12,11,7,13};
auto desired=fixed;
if(settings.automatic)
{
desired[extensionColumn]=std::clamp(static_cast<LONG>(extensionLength)+2,4L,14L);
for(const auto column:{sizeColumn,allocationColumn,linkColumn,ownerColumn})
{
const auto limit=column==ownerColumn?20L:16L;
desired[column]=std::max(fixed[column],std::clamp(
static_cast<LONG>(std::min<size_t>(panel.longestColumn[column],limit))+2,minimum[column],limit));
}
}
constexpr std::array widePriority{sizeColumn,dateColumn,extensionColumn,ownerColumn,allocationColumn,linkColumn};
constexpr std::array fullPriority{sizeColumn,allocationColumn,linkColumn,ownerColumn,dateColumn,extensionColumn};
const auto &priority=panel.mode==PanelMode::full?fullPriority:widePriority;
std::array<LONG,panelColumnCount> widths{};
auto available=std::max(0L,bounds.right-bounds.left-minimum[nameColumn]*cellWidth);
for(const auto column:priority)
{
if(!(mask&columnMask(column)) || available<minimum[column]*cellWidth) continue;
widths[column]=minimum[column]*cellWidth;
available-=widths[column];
}
for(const auto column:priority)
{
if(!widths[column]) continue;
const auto extra=std::clamp(desired[column]*cellWidth-widths[column],0L,available);
widths[column]+=extra;
available-=extra;
}
auto edge=bounds.right;
for(size_t index=columns.size();index>1;)
{
--index;
columns[index].right=edge;
edge-=widths[index];
columns[index].left=edge;
}
columns[nameColumn].right=edge;
return columns;
}
std::optional<LONG> firstPanelColumnDivider(const Panel &panel,RECT bounds)
{
if(!hasPanelColumns(panel)) return {};
const auto columns=panelColumns(panel,bounds);
const auto &size=columns[sizeColumn];
if(size.left<size.right) return size.left;
if(columns[nameColumn].right<bounds.right) return columns[nameColumn].right;
return {};
}
void paintPanelColumnLines(HDC dc,const PanelColumnRects &columns)
{
SetDCBrushColor(dc,colors[Frame]);
const auto brush=static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
for(size_t i=1;i<columns.size();++i)
{
const auto &column=columns[i];
if(column.left>=column.right || column.left<=columns[nameColumn].left) continue;
const RECT line{column.left,column.top,column.left+1,column.bottom};
FillRect(dc,&line,brush);
}
}
constexpr UINT refreshProgressLayout=WM_APP+1;
constexpr UINT directoryScanReady=WM_APP+2;
BOOL CALLBACK updateDialogFont(HWND window,LPARAM parameter)
{
const auto old=reinterpret_cast<HFONT>(parameter);
if(reinterpret_cast<HFONT>(SendMessageW(window,WM_GETFONT,0,0))==old)
SendMessageW(window,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
return TRUE;
}
HBRUSH blue{}, teal{}, terminalBackground{};
LOGFONTW defaultFilesFont()
{
LOGFONTW font{};
font.lfWeight=FW_NORMAL;
font.lfCharSet=DEFAULT_CHARSET;
font.lfQuality=CLEARTYPE_QUALITY;
wcscpy_s(font.lfFaceName,L"Consolas");
return font;
}
ks::files::TextWindowFont readFilesFont()
{
LOGFONTW font{};
DWORD bytes=sizeof(font);
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,L"DisplayFont",RRF_RT_REG_BINARY,nullptr,&font,&bytes)
!=ERROR_SUCCESS || bytes!=sizeof(font))
font=defaultFilesFont();
font.lfFaceName[LF_FACESIZE-1]=0;
return {font,static_cast<int>(std::clamp(preference(L"FontPoints",defaultFontPoints),80UL,240UL))};
}
std::array<HFONT,4> fileStyleFonts{};
bool applyFont(HWND owner, LOGFONTW font, int points)
{
const auto dpi=GetDpiForWindow(owner);
font.lfWidth=0;
const int terminalPoints=areaFontPoints(points,AppearanceArea::terminal);
font.lfHeight=-MulDiv(terminalPoints,dpi,720);
const auto nextTerminal=CreateFontIndirectW(&font);
font.lfHeight=-MulDiv(areaFontPoints(points,AppearanceArea::panels),dpi,720);
const auto next=CreateFontIndirectW(&font);
auto dc=GetDC(owner);
if(!next || !nextTerminal || !dc)
{
if(next) DeleteObject(next);
if(nextTerminal) DeleteObject(nextTerminal);
if(dc) ReleaseDC(owner,dc);
return false;
}
const auto previous=SelectObject(dc,next);
TEXTMETRICW metrics{},terminalMetrics{};
GetTextMetricsW(dc,&metrics);
SelectObject(dc,nextTerminal);
GetTextMetricsW(dc,&terminalMetrics);
SelectObject(dc,previous);
ReleaseDC(owner,dc);
textHeight=std::max(static_cast<LONG>(MulDiv(16,dpi,96)),metrics.tmHeight+MulDiv(6,dpi,96));
cellWidth=std::max(1L,metrics.tmAveCharWidth);
terminalTextHeight=std::max(static_cast<LONG>(MulDiv(16,dpi,96)),terminalMetrics.tmHeight+MulDiv(6,dpi,96));
const auto old=mono,oldTerminal=terminalFont;
mono=next;
terminalFont=nextTerminal;
for(unsigned i=1;i<fileStyleFonts.size();++i)
{
if(fileStyleFonts[i]) DeleteObject(fileStyleFonts[i]);
auto decorated=font;
decorated.lfUnderline=(i&1)!=0;
decorated.lfStrikeOut=(i&2)!=0;
fileStyleFonts[i]=CreateFontIndirectW(&decorated);
}
displayFont=font;
displayFont.lfHeight=-MulDiv(points,dpi,720);
fontPoints=points;
terminalView.setFont(displayFont,terminalPoints);
sshView.setFont(displayFont,terminalPoints);
for(auto &panel:panels)
{
if(panel.path) SendMessageW(panel.path,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
if(panel.selectionSummary) SendMessageW(panel.selectionSummary,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
if(panel.list) SendMessageW(panel.list,LB_SETITEMHEIGHT,0,textHeight);
}
if(picker) SendMessageW(picker,LB_SETITEMHEIGHT,0,textHeight);
if(status) SendMessageW(status,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
for(const auto control:{terminalInput,terminalOutput,terminalPrompt})
if(control) SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(terminalFont),FALSE);
if(oldTerminal) DeleteObject(oldTerminal);
if(old)
{
EnumThreadWindows(GetCurrentThreadId(),[](HWND window,LPARAM parameter)->BOOL
{
EnumChildWindows(window,updateDialogFont,parameter);
return TRUE;
},reinterpret_cast<LPARAM>(old));
DeleteObject(old);
}
return true;
}
UINT_PTR CALLBACK lavenderSystemPicker(HWND dialog,UINT message,WPARAM,LPARAM)
{
if(message==WM_INITDIALOG) styleLavenderCaption(dialog,true);
return 0;
}
bool chooseDisplayFont(HWND owner,LOGFONTW &font,int &points,int maximum=24)
{
CHOOSEFONTW dialog{};
dialog.lStructSize=sizeof(dialog);
dialog.hwndOwner=owner;
dialog.lpLogFont=&font;
dialog.iPointSize=points;
dialog.Flags=CF_SCREENFONTS|CF_INITTOLOGFONTSTRUCT|CF_LIMITSIZE;
if(lavenderFiles())
{
dialog.Flags|=CF_ENABLEHOOK;
dialog.lpfnHook=lavenderSystemPicker;
}
dialog.nSizeMin=8;
dialog.nSizeMax=maximum;
if(!ChooseFontW(&dialog)) return false;
points=dialog.iPointSize;
return true;
}
void refreshColors()
{
if (blue) DeleteObject(blue);
if (teal) DeleteObject(teal);
blue = CreateSolidBrush(colors[PanelBlue]);
teal = CreateSolidBrush(colors[Dialog]);
}
void loadColors()
{
for (DWORD i=0; i<ColorCount; ++i)
{
auto name = std::to_wstring(i);
DWORD value{}, size=sizeof(value);
if (RegGetValueW(HKEY_CURRENT_USER, schemeKey, name.c_str(), RRF_RT_REG_DWORD,
nullptr, &value, &size)==ERROR_SUCCESS && value<=0xffffff)
colors[i]=value;
}
refreshColors();
}
bool choosePanelColor(HWND owner,COLORREF &color,COLORREF *custom)
{
CHOOSECOLORW dialog{};
dialog.lStructSize=sizeof(dialog);
dialog.hwndOwner=owner;
dialog.rgbResult=color;
dialog.lpCustColors=custom;
dialog.Flags=CC_RGBINIT | CC_FULLOPEN;
if(lavenderFiles())
{
dialog.Flags|=CC_ENABLEHOOK;
dialog.lpfnHook=lavenderSystemPicker;
}
if(!ChooseColorW(&dialog)) return false;
color=dialog.rgbResult;
return true;
}
void paintText(HDC dc, RECT rect, const wchar_t *text, COLORREF foreground, COLORREF background, bool right=false,HFONT font=nullptr)
{
SetTextColor(dc, foreground);
SetBkColor(dc, background);
SelectObject(dc, font?font:mono);
auto alignment=SetTextAlign(dc,right?TA_RIGHT:TA_LEFT);
ExtTextOutW(dc,right?rect.right-5:rect.left+5,rect.top+3,ETO_OPAQUE|ETO_CLIPPED,&rect,text,lstrlenW(text),nullptr);
SetTextAlign(dc,alignment);
}
void paintMenuLabel(HDC dc,RECT rect,const std::wstring &text,size_t access,COLORREF foreground,COLORREF background,
COLORREF accessInk=RGB(255,255,0),HFONT font=nullptr)
{
paintText(dc,rect,text.c_str(),foreground,background,false,font);
ks::files::paintMenuAccessKey(dc,rect,{rect.left+5,rect.top+3},text,access,accessInk);
}
struct DialogFramePadding
{
DWORD outer,inner,rowText{};
bool operator==(const DialogFramePadding &) const=default;
};
// Delete at 96 DPI: outer line at x=8, inner line at x=10, content at x=25.
constexpr DialogFramePadding defaultDialogFramePadding{8,14};
constexpr DWORD maxDialogFramePadding=24;
constexpr DWORD maxDialogRowTextPadding=4;
constexpr wchar_t dialogFrameOuterKey[]=L"DialogFrameOuterPadding";
constexpr wchar_t dialogFrameInnerKey[]=L"DialogFrameInnerPadding";
constexpr wchar_t dialogRowTextKey[]=L"DialogRowTextPadding";
auto dialogFramePadding=defaultDialogFramePadding;
struct DialogFrameMetrics
{
int outer,gap,inner;
int innerLine() const {return outer+gap;}
int content() const {return innerLine()+1+inner;}
};
DialogFrameMetrics dialogFrameMetrics(UINT dpi,DialogFramePadding padding=dialogFramePadding)
{
return {MulDiv(padding.outer,dpi,96),std::max(2,MulDiv(2,dpi,96)),MulDiv(padding.inner,dpi,96)};
}
void paintDialogCaption(HDC dc,RECT row,const wchar_t *caption,HBRUSH surface,COLORREF ink,HFONT font)
{
const int saved=SaveDC(dc);
SelectObject(dc,font);
SIZE extent{};
GetTextExtentPoint32W(dc,caption,lstrlenW(caption),&extent);
TEXTMETRICW metrics{};
GetTextMetricsW(dc,&metrics);
const LONG width=std::min(row.right-row.left,extent.cx+2*metrics.tmAveCharWidth);
row.left+=(row.right-row.left-width)/2;
row.right=row.left+width;
FillRect(dc,&row,surface);
SetBkMode(dc,TRANSPARENT);
SetTextColor(dc,ink);
DrawTextW(dc,caption,-1,&row,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
if(saved) RestoreDC(dc,saved);
}
RECT paintDialogFrame(HDC dc,RECT bounds,DialogFrameMetrics metrics,HBRUSH surface,HBRUSH border)
{
FillRect(dc,&bounds,surface);
InflateRect(&bounds,-metrics.outer,-metrics.outer);
FrameRect(dc,&bounds,border);
InflateRect(&bounds,-metrics.gap,-metrics.gap);
FrameRect(dc,&bounds,border);
return bounds;
}
void paintDialogFrameCaptions(HDC dc,RECT client,RECT frame,const wchar_t *title,
HBRUSH surface,COLORREF ink,HFONT font,const wchar_t *hints=nullptr)
{
const auto previous=SelectObject(dc,font);
TEXTMETRICW text{};
GetTextMetricsW(dc,&text);
SelectObject(dc,previous);
const auto top=std::max(client.top,frame.top-text.tmHeight/2);
if(title) paintDialogCaption(dc,{frame.left,top,frame.right,top+text.tmHeight},title,surface,ink,font);
const auto bottom=std::min(client.bottom,frame.bottom+(text.tmHeight+1)/2);
if(hints) paintDialogCaption(dc,{frame.left,bottom-text.tmHeight,frame.right,bottom},hints,surface,ink,font);
}
int dialogListInset(DialogFrameMetrics metrics,int fontHeight)
{
return std::max(metrics.content(),metrics.innerLine()+(fontHeight+1)/2);
}
int dialogRowTextInset(int characterWidth,DialogFramePadding padding=dialogFramePadding)
{
return characterWidth*static_cast<int>(padding.rowText);
}
void paintDialogListRow(HDC dc,RECT bounds,std::wstring_view label,HFONT font,
COLORREF foreground,COLORREF background,int inset,UINT ellipsis=DT_PATH_ELLIPSIS)
{
const auto saved=SaveDC(dc);
SetBkColor(dc,background);
ExtTextOutW(dc,0,0,ETO_OPAQUE,&bounds,nullptr,0,nullptr);
SelectObject(dc,font);
SetTextColor(dc,foreground);
SetBkMode(dc,TRANSPARENT);
InflateRect(&bounds,-inset,0);
if(bounds.right>bounds.left)
DrawTextW(dc,label.data(),static_cast<int>(label.size()),&bounds,
DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|ellipsis);
if(saved) RestoreDC(dc,saved);
}
void showMenu(bool show);
void hidePicker()
{
if (!picker || !IsWindowVisible(picker)) return;
folderPicker.reset();
KillTimer(GetParent(picker),driveQueryTimer);
driveQueries.clear();
ShowWindow(picker,SW_HIDE);
ShowWindow(pickerFrame,SW_HIDE);
InvalidateRect(GetParent(picker),nullptr,FALSE);
SetFocus(panels[commandPicker ? active : pickerPanel].list);
if (IsWindowVisible(menuBar)) showMenu(true);
}
void selectDrive();
void showMenu(bool show)
{
if(!show && !IsWindowVisible(menuBar)) return;
if (show) SetWindowPos(menuBar,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW);
for (auto item : menuItems)
{
if (show) SetWindowPos(item,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW);
else ShowWindow(item,SW_HIDE);
if (show) InvalidateRect(item,nullptr,FALSE);
}
if (!show) ShowWindow(menuBar,SW_HIDE);
RedrawWindow(GetParent(menuBar),nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
}
using ks::files::ScrollPosition;
using ks::files::scrollBarWidth;
constexpr UINT_PTR listScrollBar=2, noticeScrollBar=3, firstPanelScrollBar=4;
RECT scrollTrack(HWND host,HWND content)
{
RECT track{};
GetWindowRect(content,&track);
MapWindowPoints(nullptr,host,reinterpret_cast<POINT *>(&track),2);
track.left=track.right;
track.right+=scrollBarWidth(content);
return track;
}
ScrollPosition scrollPosition(HWND content,bool edit)
{
RECT client{};
GetClientRect(content,&client);
int rowHeight{};
if(edit)
{
if(const auto dc=GetDC(content))
{
const auto old=SelectObject(dc,mono);
TEXTMETRICW metrics{};
GetTextMetricsW(dc,&metrics);
rowHeight=metrics.tmHeight;
SelectObject(dc,old);
ReleaseDC(content,dc);
}
}
else rowHeight=static_cast<int>(SendMessageW(content,LB_GETITEMHEIGHT,0,0));
return {
static_cast<int>(SendMessageW(content,edit?EM_GETLINECOUNT:LB_GETCOUNT,0,0)),
std::max(1,static_cast<int>(client.bottom)/std::max(1,rowHeight)),
static_cast<int>(SendMessageW(content,edit?EM_GETFIRSTVISIBLELINE:LB_GETTOPINDEX,0,0))};
}
void paintScrollPosition(HWND host,HDC dc,HWND content,COLORREF background,bool edit=false)
{
if(!IsWindowVisible(content)) return;
const auto position=scrollPosition(content,edit);
if(!edit || position.last())
ks::files::paintScrollBar(dc,scrollTrack(host,content),position,background);
}
void setScrollTop(HWND content,bool edit,ScrollPosition position,int top)
{
top=std::clamp(top,0,position.last());
if(edit) SendMessageW(content,EM_LINESCROLL,0,top-position.top);
else SendMessageW(content,LB_SETTOPINDEX,top,0);
}
LRESULT CALLBACK scrollContentProc(HWND content,UINT message,WPARAM wp,LPARAM lp,UINT_PTR kind,DWORD_PTR target)
{
const bool edit=kind==noticeScrollBar;
const auto host=reinterpret_cast<HWND>(target);
if(message==WM_MOUSEWHEEL)
{
const auto position=scrollPosition(content,edit);
setScrollTop(content,edit,position,position.top-3*(GET_WHEEL_DELTA_WPARAM(wp)/WHEEL_DELTA));
return 0;
}
const auto result=DefSubclassProc(content,message,wp,lp);
switch(message)
{
case LB_DELETESTRING: case LB_RESETCONTENT: case LB_SETCURSEL:
case LB_SETTOPINDEX: case LB_SETITEMHEIGHT: case WM_KEYDOWN: case WM_VSCROLL:
case WM_LBUTTONDOWN: case WM_LBUTTONUP: case EM_LINESCROLL: case WM_SETTEXT:
case WM_WINDOWPOSCHANGED:
{
const auto track=scrollTrack(host,content);
InvalidateRect(host,&track,FALSE);
break;
}
}
return result;
}
LRESULT CALLBACK scrollHostProc(HWND host,UINT message,WPARAM wp,LPARAM lp,UINT_PTR kind,DWORD_PTR target)
{
constexpr auto dragProperty=L"KSwitcher.Files.ScrollDrag";
constexpr auto offsetProperty=L"KSwitcher.Files.ScrollDragOffset";
const bool edit=kind==noticeScrollBar;
const auto content=reinterpret_cast<HWND>(target);
const bool dragging=GetPropW(host,dragProperty)==content;
if(message==WM_CAPTURECHANGED && dragging)
{
RemovePropW(host,dragProperty);
RemovePropW(host,offsetProperty);
}
if(message==WM_LBUTTONUP && dragging && GetCapture()==host)
{
ReleaseCapture();
return 0;
}
if(message==WM_NCHITTEST || message==WM_LBUTTONDOWN ||
(message==WM_MOUSEMOVE && dragging && GetCapture()==host))
{
POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
if(message==WM_NCHITTEST) ScreenToClient(host,&point);
const auto track=scrollTrack(host,content);
if(IsWindowVisible(content) && (PtInRect(&track,point) || message==WM_MOUSEMOVE))
{
const auto position=scrollPosition(content,edit);
if(position.last())
{
if(message==WM_NCHITTEST) return HTCLIENT;
const auto thumb=position.thumb(track);
if(message==WM_MOUSEMOVE)
{
const auto offset=reinterpret_cast<INT_PTR>(GetPropW(host,offsetProperty))-1;
setScrollTop(content,edit,position,position.drag(track,point.y,static_cast<int>(offset)));
}
else if(PtInRect(&thumb,point))
{
SetPropW(host,dragProperty,content);
SetPropW(host,offsetProperty,reinterpret_cast<HANDLE>(
static_cast<INT_PTR>(point.y-thumb.top+1)));
SetCapture(host);
}
else setScrollTop(content,edit,position,position.click(track,point.y));
return 0;
}
}
}
return DefSubclassProc(host,message,wp,lp);
}
void installScrollBar(HWND content,HWND host,UINT_PTR kind=listScrollBar)
{
SetWindowSubclass(content,scrollContentProc,kind,reinterpret_cast<DWORD_PTR>(host));
SetWindowSubclass(host,scrollHostProc,kind,reinterpret_cast<DWORD_PTR>(content));
}
void placePanelSearch(HWND window)
{
RECT panel{};
GetWindowRect(panels[active].list,&panel);
MapWindowPoints(nullptr,window,reinterpret_cast<POINT *>(&panel),2);
const auto frame=dialogFrameMetrics(GetDpiForWindow(window));
const int width=std::min(static_cast<int>(panel.right-panel.left),24*cellWidth+2*frame.content());
const int height=textHeight+2*frame.content();
SetWindowPos(panelSearchPopup,HWND_TOP,(panel.left+panel.right-width)/2,
std::max(panel.top,panel.bottom+textHeight-height),width,height,SWP_NOACTIVATE);
}
void closePanelSearch()
{
panelSearchPrefix.clear();
if(IsWindowVisible(panelSearchPopup)) ShowWindow(panelSearchPopup,SW_HIDE);
}
void swapPanels(HWND window)
{
closePanelSearch();
hidePicker();
showMenu(false);
// Move the controls with their contents to retain the cursor and scroll position.
std::swap(panels[0],panels[1]);
active=1-active;
if(quickViewWindow) quickViewSource=1-quickViewSource;
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)
{
const auto &panel=panels[i];
SetWindowLongPtrW(panel.list,GWLP_ID,102+i);
SetWindowLongPtrW(panel.heading,GWLP_ID,140+i);
SetWindowLongPtrW(panel.path,GWLP_ID,142+i);
SetWindowLongPtrW(panel.selectionSummary,GWLP_ID,154+i);
savePanelMode(i,panel.mode);
for(size_t mode=1;mode<std::size(panelModeNames);++mode) savePanelColumns(i,static_cast<PanelMode>(mode));
savePanelView(i);
}
notifyFilesPreferences(window);
layout(window);
showFileDetails(panels[active]);
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
}
bool hasSelectionSummary()
{
return GetWindowTextLengthW(panels[0].selectionSummary) || GetWindowTextLengthW(panels[1].selectionSummary);
}
int clampPanelDivider(int position,int width)
{
const int panelMinimum=lavenderFiles() && panels[0].list?
LavenderMetrics(GetParent(panels[0].list)).px(135):120;
const int minimum=std::min(width/2,panelMinimum);
return std::clamp(position,minimum,width-minimum);
}
int panelDivider(int width)
{
return clampPanelDivider(split?split:width/2,width);
}
void setPanelDivider(HWND window,int width,int position)
{
const auto next=clampPanelDivider(position,width);
if(next==panelDivider(width)) return;
split=next;
layout(window);
}
void layoutGitChanges(HWND window);
bool showingGitChanges();
void layout(HWND window,bool activeOnly)
{
RECT rect{};
GetClientRect(window, &rect);
int width = rect.right, height = rect.bottom;
const bool lavender=lavenderFiles();
const LavenderMetrics modern(window);
const int commandHeight=lavender?modern.row+modern.px(width<modern.px(680)?22:8):textHeight;
const int inputTop=height-commandHeight-terminalTextHeight;
const bool gitMode=showingGitChanges();
const int terminalBottom=std::max(4,inputTop);
const int summaryHeight=!terminalVisible && hasSelectionSummary()?textHeight:0;
const int detailsGap=lavender?modern.px(6):compactLayout?2:4;
const int detailsHeight=terminalVisible?0:textHeight+(lavender?modern.px(16):compactLayout?4:12)+summaryHeight;
const DWORD driveMask=showDriveButtons && !terminalVisible && !gitMode?GetLogicalDrives():0;
const int driveHeight=driveMask?textHeight+2:0;
const int panelMargin=compactLayout?4:5;
const int pathTop=driveHeight+(compactLayout?1:4);
const int terminalTop=terminalVisible?4:std::max(4,terminalBottom-
std::min(terminalRows,std::max(0,(terminalBottom-detailsHeight)/terminalTextHeight-4))*terminalTextHeight);
const int panelBottom=terminalTop-detailsHeight;
const bool showOutput=!gitMode && terminalTop<terminalBottom;
traceTerminal("layout",terminalRows,terminalTop,terminalBottom,showOutput,terminalVisible);
const int middle=panelDivider(width);
const int inset=lavender?modern.px(14):panelMargin;
const int panelTop=lavender?driveHeight+modern.px(15):pathTop;
const int pathHeight=lavender?modern.row+modern.px(3):textHeight;
const int detailsInset=lavender?inset:8;
const int detailsTop=panelBottom+detailsGap;
auto place=[](HWND control, int x, int y, int width, int height)
{
if(control) SetWindowPos(control,nullptr,x,y,width,height,
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOREDRAW);
};
if(!activeOnly)
{
const int buttonWidth=std::max(4*cellWidth,32);
const int maxButtons=std::max(1,(width-8)/buttonWidth);
int drives=0;
for(int letter=0;letter<26;++letter) if(driveMask&(1UL<<letter)) ++drives;
const int visibleDrives=drives>maxButtons?maxButtons-1:drives;
int slot=0;
for(int letter=0;letter<26;++letter)
{
const auto button=driveButtons[letter];
if(!button) continue;
const bool visible=(driveMask&(1UL<<letter)) && slot<visibleDrives;
if(visible) place(button,4+slot++*buttonWidth,0,buttonWidth,textHeight);
ShowWindow(button,visible?SW_SHOWNA:SW_HIDE);
}
if(const auto more=driveButtons.back())
{
place(more,4+slot*buttonWidth,0,buttonWidth,textHeight);
ShowWindow(more,drives>maxButtons?SW_SHOWNA:SW_HIDE);
}
const int headingTop=panelTop+pathHeight+(lavender?modern.px(7):compactLayout?2:6);
const int rowHeight=lavender?std::max(modern.row,textHeight):textHeight;
const auto panelFont=reinterpret_cast<WPARAM>(lavender?lavender::font:mono);
SendMessageW(status,WM_SETFONT,panelFont,FALSE);
for (int i = 0; i < 2; ++i)
{
int x = i ? middle + 2 : 0;
int end = i ? width : middle - 2;
place(panels[i].path,x+inset,panelTop,std::max(0,end-x-2*inset),pathHeight);
const int headingHeight=detailedPanel(panels[i])?rowHeight:0;
const int listWidth=std::max(0,end-x-(lavender?2*inset:panelMargin+3)-scrollBarWidth(panels[i].list));
const bool panelVisible=!gitMode && !terminalVisible && (!quickViewWindow || i==quickViewSource);
ShowWindow(panels[i].path,panelVisible?SW_SHOWNA:SW_HIDE);
ShowWindow(panels[i].list,panelVisible?SW_SHOWNA:SW_HIDE);
SendMessageW(panels[i].selectionSummary,WM_SETFONT,panelFont,FALSE);
if(SendMessageW(panels[i].list,LB_GETITEMHEIGHT,0,0)!=rowHeight)
SendMessageW(panels[i].list,LB_SETITEMHEIGHT,0,rowHeight);
place(panels[i].heading,x+inset,headingTop,listWidth,headingHeight);
ShowWindow(panels[i].heading,panelVisible && detailedPanel(panels[i])?SW_SHOWNA:SW_HIDE);
place(panels[i].list,x+inset,headingTop+headingHeight,listWidth,
std::max(0,panelBottom-headingTop-headingHeight));
place(panels[i].selectionSummary,x+detailsInset,detailsTop,std::max(0,end-x-2*detailsInset),summaryHeight);
ShowWindow(panels[i].selectionSummary,panelVisible && summaryHeight?SW_SHOWNA:SW_HIDE);
}
place(menuBar,0,0,width,textHeight+4);
const int menuEdges[]{0,7,15,27,38,46};
for(int i=0;i<5;++i)
place(menuItems[i],4+menuEdges[i]*cellWidth,0,(menuEdges[i+1]-menuEdges[i])*cellWidth,textHeight+4);
}
const int detailsLeft=active?middle+2:0;
const int detailsRight=active?width:middle-2;
place(status,detailsLeft+detailsInset,detailsTop+summaryHeight,std::max(0,detailsRight-detailsLeft-2*detailsInset),textHeight);
const auto &current=panels[active];
const auto prompt=panelLocation(current)+(terminalVisible?L"> ":L">");
SetWindowTextW(terminalPrompt,prompt.c_str());
SIZE promptExtent{static_cast<LONG>(prompt.size())*cellWidth,0};
if(const auto dc=GetDC(window))
{
const auto previous=SelectObject(dc,terminalFont);
GetTextExtentPoint32W(dc,prompt.c_str(),static_cast<int>(prompt.size()),&promptExtent);
SelectObject(dc,previous);
ReleaseDC(window,dc);
}
const int promptWidth=std::min(width/2,static_cast<int>(promptExtent.cx));
place(terminalPrompt,4,inputTop,promptWidth,terminalTextHeight);
place(terminalInput,4+promptWidth,inputTop,std::max(0,width-8-promptWidth),terminalTextHeight);
if(activeOnly)
{
const RECT details{0,lavender?driveHeight:detailsTop+summaryHeight,width,
detailsTop+summaryHeight+textHeight+(lavender?modern.px(4):0)};
if(driveHeight)
{
const RECT drives{0,0,width,driveHeight};
RedrawWindow(window,&drives,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
}
const RECT commandLine{0,inputTop,width,inputTop+textHeight};
if(!terminalVisible) RedrawWindow(window,&details,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
RedrawWindow(window,&commandLine,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
return;
}
// Keep the WebView in place while the panels reveal more or less of it.
place(terminalOutput,4,4,std::max(0,width-8),terminalBottom-4);
if(showOutput)
{
const auto region=CreateRectRgn(0,terminalTop-4,std::max(0,width-8),terminalBottom-4);
if(region && !SetWindowRgn(terminalOutput,region,FALSE)) DeleteObject(region);
}
if(!showOutput) clearTerminalSelection();
ShowWindow(terminalOutput,showOutput?SW_SHOWNA:SW_HIDE);
ShowWindow(status,terminalVisible || gitMode?SW_HIDE:SW_SHOWNA);
ShowWindow(terminalPrompt,gitMode?SW_HIDE:SW_SHOWNA);
ShowWindow(terminalInput,gitMode?SW_HIDE:SW_SHOWNA);
terminalView.layout(terminalOutput,showOutput && !sshPrompt,terminalBottom-4);
sshView.layout(terminalOutput,showOutput && sshPrompt.has_value(),terminalBottom-4);
const int gap=modern.px(5);
const int barWidth=std::max(0,std::min(width-gap,modern.px(880)+gap));
constexpr int refreshExtra=4;
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
{
constexpr int unit=10;
const int total=static_cast<int>(std::size(commands))*unit+refreshExtra;
const int available=lavender?barWidth:width;
const int left=i?(i*unit+refreshExtra)*available/total:0;
const int right=((i+1)*unit+refreshExtra)*available/total;
if(lavender) place(commands[i],left+gap,height-commandHeight+gap,
std::max(0,right-left-gap),commandHeight-2*gap);
else place(commands[i],left,height-textHeight,right-left,textHeight);
ShowWindow(commands[i],gitMode?SW_HIDE:SW_SHOWNA);
}
if(quickViewWindow)
{
const int left=quickViewSource==0?middle+2:0;
const int right=quickViewSource==0?width:middle-2;
for(const auto preview:{quickViewWindow,quickImageWindow})
{
if(!preview) continue;
const int bottom=panelBottom+summaryHeight+textHeight+detailsInset;
SetWindowPos(preview,nullptr,left+panelMargin,pathTop,std::max(0,right-left-2*panelMargin),
std::max(0,bottom-pathTop),SWP_NOZORDER|SWP_NOACTIVATE);
const bool current=quickViewDisplaysImage==(preview==quickImageWindow);
ShowWindow(preview,!gitMode && !terminalVisible && current?SW_SHOWNA:SW_HIDE);
}
}
if(IsWindowVisible(panelSearchPopup)) placePanelSearch(window);
layoutGitChanges(window);
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
}
uint64_t statusRevision{};
void setStatus(const std::wstring &message,bool retryAction)
{
++statusRevision;
const auto style=GetWindowLongPtrW(status,GWL_STYLE);
const auto actionStyle=(style&~(SS_ENDELLIPSIS|SS_PATHELLIPSIS|SS_WORDELLIPSIS|SS_NOTIFY)) |
(retryAction?(SS_ENDELLIPSIS|SS_NOTIFY):SS_PATHELLIPSIS);
if(style!=actionStyle) SetWindowLongPtrW(status,GWL_STYLE,actionStyle);
SetWindowTextW(status, message.c_str());
}
bool showDirectoryScanProgress(Panel &panel)
{
if(!panel.scanRequest) return false;
const auto entries=panel.scanEntriesRead ? panel.scanEntriesRead->load(std::memory_order_relaxed) : 0;
auto message=panel.scanSuperseded ? std::wstring(L"Waiting to read…") :
panel.scanStop.stop_requested() ? L"Stopping… "+std::to_wstring(entries) :
(panel.scanRequest->find?L"Searching ":L"Reading ")+std::to_wstring(entries)+L" [Esc]";
wchar_t displayed[96]{};
GetWindowTextW(status,displayed,std::size(displayed));
if(message!=displayed) setStatus(message);
panel.scanRequest->statusRevision=statusRevision;
return true;
}
bool stopDirectoryScan()
{
auto &panel=panels[active];
if(terminalVisible || !panel.scanRequest || panel.scanSuperseded || !panel.scan.valid()) return false;
panel.scanStop.request_stop();
showDirectoryScanProgress(panel);
return true;
}
void showTerminal(HWND owner,bool show)
{
terminalVisible=show;
layout(owner);
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);
void restoreCommandFocus();
void handleFilesReturn(bool shift);
void invalidatePanelRow(HWND list,LRESULT row)
{
RECT bounds{};
if(row!=LB_ERR && SendMessageW(list,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&bounds))!=LB_ERR)
InvalidateRect(list,&bounds,FALSE);
}
void invalidateFolderSizeRow(const Panel &panel,const fs::path &path)
{
if(path.empty()) return;
const auto row=std::find(panel.rows.begin(),panel.rows.end(),path);
if(row!=panel.rows.end()) invalidatePanelRow(panel.list,row-panel.rows.begin());
}
void cancelFolderSizes(Panel &panel)
{
if(panel.folderSizeJob) panel.folderSizeJob->stop.request_stop();
panel.folderSizeJob.reset();
if(!panel.folderSizeWaiting.empty())
{
panel.folderSizeWaiting.clear();
InvalidateRect(panel.list,nullptr,FALSE);
}
invalidateFolderSizeRow(panel,std::exchange(panel.folderSpinner,{}));
}
void invalidatePanelCursorChange(HWND list,LRESULT previous)
{
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
if(current==previous) return;
invalidatePanelRow(list,previous);
invalidatePanelRow(list,current);
}
void activatePanel(int index)
{
if(quickViewWindow && index!=quickViewSource) return;
const auto previous=active;
active=index;
showFileDetails(panels[index]);
if(previous==active) return;
for(const auto &panel:panels)
{
InvalidateRect(panel.path,nullptr,FALSE);
invalidatePanelRow(panel.list,SendMessageW(panel.list,LB_GETCURSEL,0,0));
}
layout(GetParent(panels[index].list),true);
}
bool plainPanelTab()
{
return !((GetKeyState(VK_CONTROL)|GetKeyState(VK_SHIFT)|GetKeyState(VK_MENU)|
GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000);
}
std::wstring terminalInputText()
{
std::wstring value(GetWindowTextLengthW(terminalInput)+1,L'\0');
value.resize(GetWindowTextW(terminalInput,value.data(),static_cast<int>(value.size())));
return value;
}
bool commandLineAvailable(HWND owner);
struct CompletionQuery
{
std::wstring line, directory;
DWORD caret{};
bool operator==(const CompletionQuery &) const = default;
};
struct CompletionItem
{
std::wstring label, text;
size_t index{}, length{};
bool directory{};
};
HWND completionList{}, completionFrame{};
ks::files::CommandCompletion completionWorker;
std::optional<CompletionQuery> completionQuery, pendingCompletion;
std::vector<CompletionItem> completionItems;
ULONGLONG completionDue{};
std::string completionHelpArticle;
bool completionHelpRequested{};
void hideCompletion()
{
ShowWindow(completionList,SW_HIDE);
ShowWindow(completionFrame,SW_HIDE);
completionItems.clear();
completionDue=0;
completionHelpArticle.clear();
completionHelpRequested=false;
}
void resetCompletion()
{
hideCompletion();
completionQuery.reset();
}
std::optional<CompletionQuery> currentCompletionQuery()
{
if(GetFocus()!=terminalInput || GetForegroundWindow()!=GetParent(terminalInput) ||
!commandLineAvailable(GetParent(terminalInput))) return {};
auto line=terminalInputText();
if(line.find_first_not_of(L" \t")==line.npos) return {};
DWORD first{},last{};
SendMessageW(terminalInput,EM_GETSEL,reinterpret_cast<WPARAM>(&first),reinterpret_cast<LPARAM>(&last));
if(!first || first!=last) return {};
std::wstring directory;
if(!panels[active].peer && !panels[active].ftp)
directory=panels[active].directory.native();
return CompletionQuery{std::move(line),std::move(directory),first};
}
void suppressCurrentCompletion()
{
hideCompletion();
completionQuery=currentCompletionQuery();
}
void showFramedList(HWND list,HWND frame,int x,int y,int width,int height,int inset)
{
constexpr UINT flags=SWP_NOACTIVATE|SWP_SHOWWINDOW;
SetWindowPos(frame,HWND_TOP,x-inset,y-inset,width+2*inset,height+2*inset,flags);
SetWindowPos(list,HWND_TOP,x,y,std::max(1,width-scrollBarWidth(list)),height,flags);
}
void appendPowerShellCompletions(const CompletionQuery &query,const Json &reply,
std::set<std::wstring> &seen)
{
if(!reply.is_object() || !reply.contains("matches")) return;
try
{
const auto index=reply.at("index").get<size_t>();
const auto length=reply.at("length").get<size_t>();
if(index>query.caret || length>query.line.size()-index) return;
for(const auto &row:reply.at("matches"))
{
auto value=ks::wide(row.at("text").get<std::string>());
if(value.empty() || query.line.size()-length+value.size()>2048) continue;
auto line=query.line;
line.replace(index,length,value);
if(seen.insert(std::move(line)).second)
completionItems.push_back({ks::wide(row.at("label").get<std::string>()),std::move(value),
index,length,row.at("directory").get<bool>()});
}
}
catch(const Json::exception &) {}
}
void showCompletion(HWND owner,const CompletionQuery &query,const Json &reply={})
{
std::set<std::wstring> seen{query.line};
if(query.caret==query.line.size())
{
for(auto entry=terminalHistory.rbegin();entry!=terminalHistory.rend() && completionItems.size()<5;++entry)
{
const auto &command=entry->command;
if(command.size()>2048 || command.size()<=query.line.size() ||
CompareStringOrdinal(command.data(),static_cast<int>(query.line.size()),query.line.data(),
static_cast<int>(query.line.size()),TRUE)!=CSTR_EQUAL ||
!seen.insert(command).second)
continue;
completionItems.push_back({commandHistoryLabel(command),command,0,query.line.size()});
}
}
appendPowerShellCompletions(query,reply,seen);
if(completionItems.empty()) return;
RECT edit{};
GetWindowRect(terminalInput,&edit);
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT*>(&edit),2);
const int inset=dialogFrameMetrics(GetDpiForWindow(owner)).content();
const int rows=std::min({8,static_cast<int>(completionItems.size()),
(static_cast<int>(edit.top)-2*inset)/textHeight});
int desiredWidth=24*cellWidth;
if(const auto dc=GetDC(completionList))
{
const auto previous=SelectObject(dc,mono);
for(const auto &item:completionItems)
{
SIZE extent{};
GetTextExtentPoint32W(dc,item.label.c_str(),static_cast<int>(item.label.size()),&extent);
desiredWidth=std::max(desiredWidth,static_cast<int>(extent.cx)+2*cellWidth);
}
SelectObject(dc,previous);
ReleaseDC(completionList,dc);
}
if(static_cast<size_t>(rows)<completionItems.size())
desiredWidth+=scrollBarWidth(completionList);
const int width=std::min(desiredWidth,static_cast<int>(edit.right-edit.left)-2*inset);
if(rows<1 || width<1) { hideCompletion(); return; }
SendMessageW(completionList,LB_RESETCONTENT,0,0);
SendMessageW(completionList,LB_SETITEMHEIGHT,0,textHeight);
for(const auto &item:completionItems)
SendMessageW(completionList,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(item.label.c_str()));
const int height=rows*textHeight;
const int y=edit.top-height-inset;
POINT caret{};
const int start=terminalVisible && GetCaretPos(&caret)?
std::clamp<int>(edit.left+caret.x,edit.left+inset,edit.right-width-inset):edit.left+inset;
showFramedList(completionList,completionFrame,start,y,width,height,inset);
}
bool openCompletionHelp(HWND owner)
{
if(completionHelpArticle.empty()) return false;
constexpr auto base=L"https://learn.microsoft.com/windows-server/administration/windows-commands/";
const auto url=base+ks::wide(completionHelpArticle);
if(reinterpret_cast<INT_PTR>(ShellExecuteW(owner,L"open",url.c_str(),nullptr,nullptr,SW_SHOWNORMAL))<=32)
setStatus(L"Could not open Windows command help.");
return true;
}
bool requestCompletionHelp(HWND owner)
{
auto query=currentCompletionQuery();
if(!query || query->directory.empty()) return false;
if(query==completionQuery && openCompletionHelp(owner)) return true;
if(query!=completionQuery || pendingCompletion!=query)
{
hideCompletion();
completionQuery=std::move(query);
}
if(pendingCompletion!=completionQuery) completionDue=GetTickCount64();
completionHelpRequested=true;
return true;
}
void updateCompletion(HWND owner)
{
auto query=currentCompletionQuery();
if(query!=completionQuery)
{
hideCompletion();
completionQuery=std::move(query);
if(completionQuery) completionDue=GetTickCount64()+150;
}
if(pendingCompletion)
{
auto reply=completionWorker.poll();
if(!reply) return;
if(pendingCompletion==completionQuery && !completionDue && completionQuery)
{
if(reply->is_object() && reply->contains("article") && reply->at("article").is_string())
{
const auto &article=reply->at("article").get_ref<const std::string&>();
if(article.size()<128 && std::all_of(article.begin(),article.end(),[](char ch)
{ return (ch>='a' && ch<='z') || (ch>='0' && ch<='9') || ch=='-' || ch=='_'; }))
completionHelpArticle=article;
}
if(!std::exchange(completionHelpRequested,false) || !openCompletionHelp(owner))
showCompletion(owner,*completionQuery,*reply);
}
pendingCompletion.reset();
}
if(completionQuery && completionDue && GetTickCount64()>=completionDue)
{
completionDue=0;
const auto &current=*completionQuery;
if(!current.directory.empty() && completionWorker.request(current.line,current.caret,current.directory))
pendingCompletion=current;
else showCompletion(owner,current);
}
}
bool acceptCompletion(size_t row)
{
if(row>=completionItems.size() || currentCompletionQuery()!=completionQuery) return false;
const auto item=completionItems[row];
SendMessageW(terminalInput,EM_SETSEL,item.index,item.index+item.length);
SendMessageW(terminalInput,EM_REPLACESEL,TRUE,reinterpret_cast<LPARAM>(item.text.c_str()));
if(item.directory && item.text.size()>1 &&
(item.text.front()==L'\'' || item.text.front()==L'"') && item.text.back()==item.text.front())
{
const auto caret=item.index+item.text.size()-1;
SendMessageW(terminalInput,EM_SETSEL,caret,caret);
}
suppressCurrentCompletion();
return true;
}
bool handleCompletionKey(WPARAM key,LPARAM flags)
{
if(key==VK_F1)
return !(flags & (1LL<<30)) && requestCompletionHelp(GetParent(terminalInput));
if(key!=VK_UP && key!=VK_DOWN && key!=VK_RETURN && key!=VK_TAB && key!=VK_ESCAPE) return false;
if(!IsWindowVisible(completionList) || currentCompletionQuery()!=completionQuery) return false;
const auto row=SendMessageW(completionList,LB_GETCURSEL,0,0);
if(key==VK_ESCAPE) { hideCompletion(); return true; }
if(key==VK_TAB || (key==VK_RETURN && row!=LB_ERR))
{
if(!(flags & (1LL<<30))) acceptCompletion(row==LB_ERR?0:static_cast<size_t>(row));
return true;
}
if(key!=VK_UP && key!=VK_DOWN) return false;
const auto count=static_cast<LRESULT>(completionItems.size());
const auto next=key==VK_DOWN?(row+1)%count:(row<=0?count-1:row-1);
SendMessageW(completionList,LB_SETCURSEL,next,0);
return true;
}
LRESULT CALLBACK completionClick(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK)
{
const auto hit=SendMessageW(list,LB_ITEMFROMPOINT,0,lp);
if(!HIWORD(hit)) acceptCompletion(LOWORD(hit));
return 0;
}
return DefSubclassProc(list,message,wp,lp);
}
void clearTerminalSelection()
{
if(terminalSelection.empty()) return;
terminalSelection.clear();
activeTerminalView().post(L"clear-selection");
}
bool copyFilesText(HWND owner,const std::wstring &value,const wchar_t *failure)
{
try {ks::writeClipboard(owner,ks::textClip(value));}
catch(const std::exception &) {setStatus(failure);return false;}
return true;
}
bool interruptTerminal()
{
if(sshPrompt)
return sshPrompt->raw && sshTerminal.write("\x03");
if(remoteCommandRunning)
{
remoteCommandThread.request_stop();
return true;
}
if(!std::any_of(terminalCommands.begin(),terminalCommands.end(),
[](const auto &command){ return command.panel>=0; })) return false;
return terminal.write(L"\x03");
}
void copyOrInterruptTerminal()
{
if(terminalSelection.empty() && (terminalVisible || !GetWindowTextLengthW(terminalInput)) &&
interruptTerminal()) return;
SendMessageW(terminalInput,WM_COPY,0,0);
}
void copyTerminalText(HWND owner)
{
const auto value=terminalSelection.empty()?terminalInputText():terminalSelection;
if(value.empty()) return;
copyFilesText(owner,value,L"Could not copy terminal text.");
}
#include "files_panel_rows.inl"
LRESULT currentPanelRow(const Panel &panel)
{
const auto row=SendMessageW(panel.list,LB_GETCURSEL,0,0);
return row>=0 && static_cast<size_t>(row)<panel.rows.size()?row:LB_ERR;
}
std::vector<fs::path> selectedPanelPaths(const Panel &panel)
{
std::vector<fs::path> paths;
if(panel.listing) return paths;
std::set<fs::path> directories;
visitPanelMarks(panel,[&](const fs::path &path,const FolderEntryMetadata &entry) {
paths.push_back(path);
if(treePanelActive(panel) && (entry.attributes&FILE_ATTRIBUTE_DIRECTORY)) directories.insert(path);
});
if(!directories.empty())
std::erase_if(paths,[&](const auto &path) {
for(auto parent=path.parent_path();parent!=panel.tree.root && parent!=parent.parent_path();
parent=parent.parent_path())
if(directories.contains(parent)) return true;
return false;
});
if(paths.empty())
{
const auto row=currentPanelRow(panel);
if(row!=LB_ERR && panel.sizes[row]!=L"Up") paths.push_back(panel.rows[row]);
}
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];
std::wstring names;
if(transferProfileList(panel))
{
const auto row=currentPanelRow(panel);
const auto &profiles=transferProfiles(panel.ftp->protocol).rows;
if(row>=0 && static_cast<size_t>(row)<profiles.size()) names=profiles[row].name;
}
else for(const auto &path:selectedPanelPaths(panel))
{
if(!names.empty()) names+=L"\r\n";
names+=path.filename().native();
}
if(names.empty()) return;
copyFilesText(owner,names,L"Could not copy file names.");
}
void copyPanelFiles(HWND owner,const Panel &panel)
{
if(panel.peer || panel.ftp || panel.archive || panel.listing)
{
setStatus(L"File clipboard copy requires local files.");
return;
}
const auto paths=selectedPanelPaths(panel);
if(paths.empty()) return;
try
{
ks::writeClipboard(owner,ks::fileDropClip(paths));
setStatus(std::to_wstring(paths.size())+(paths.size()==1?L" item copied":L" items copied")+L" to the file clipboard.");
}
catch(const std::exception &) {setStatus(L"Could not copy files to the clipboard.");}
}
void copyFullPanelPath(HWND owner,const Panel &panel)
{
const auto row=currentPanelRow(panel);
if(row==LB_ERR || panel.sizes[row]==L"Up" || panelListsLocations(panel)) return;
const auto &path=panel.rows[row];
auto value=path.native();
if(panel.ftp)
{
const auto &profile=*panel.ftp;
const auto host=profile.host.find(L':')!=std::wstring::npos && !profile.host.starts_with(L"[")?
L"["+profile.host+L"]":profile.host;
value=std::wstring(transferProtocolName(profile.protocol))+L" "+host+L":"+std::to_wstring(profile.port)+L" · "+ftpPath(path);
}
else if(panel.peer)
{
auto host=panel.peer->name;
if(!panel.peer->address.empty()) host+=L" ("+ks::wide(panel.peer->address)+L")";
value=host+L" · "+value;
}
if(copyFilesText(owner,value,L"Could not copy the full path.")) setStatus(L"Full path copied.");
}
void copyCommandLineOrPanelNames(HWND owner)
{
if(!terminalSelection.empty() || GetWindowTextLengthW(terminalInput)) copyTerminalText(owner);
else copyPanelNames(owner);
}
void startFileSearch(Panel &panel,Panel::FindOptions options);
void refreshArchive(Panel &panel);
bool retryRemotePanel(Panel &panel,bool automatic=false,const fs::path &fallback={});
void refreshPanel(Panel &panel)
{
if(recentFolderList(panel))
{
if(!retryRemotePanel(panel)) showRecentFolders(panel);
return;
}
if(panel.listing) {refreshSmbPanel(panel);return;}
cancelFolderSizes(panel);
if(!panel.view.automaticSizes) panel.folderSizes.clear();
updateSelectionSummary(panel);
if(retryRemotePanel(panel)) return;
if(panel.scanRequest && (panel.scanRequest->peer || panel.scanRequest->ftp)) return;
if(panel.archive) refreshArchive(panel);
else if(panel.findOrigin) startFileSearch(panel,panel.findOrigin->options);
else open(panel,panel.directory,false);
}
std::wstring powerShellPath(const fs::path &path)
{
std::wstring quoted=L"'";
for(const auto character:path.native())
{
// PowerShell recognizes typographic apostrophes as quote delimiters too.
if(character==L'\'' || character==L'\u2018' || character==L'\u2019') quoted+=character;
quoted+=character;
}
return quoted+L"'";
}
void insertCurrentPanelPath(bool nameOnly = false)
{
const auto &panel=panels[active];
if(panel.ftp || panel.listing || panel.archive) return;
const auto row=currentPanelRow(panel);
if(row==LB_ERR) return;
const bool up=panel.sizes[row]==L"Up";
if(nameOnly && up) return;
const auto &item=panel.rows[row];
const auto path=nameOnly?item.filename().native():(up?panel.directory:item).native();
std::wstring quoted;
if(path.find(L' ')!=std::wstring::npos)
{
quoted=L"\"";
for(const auto character:path)
{
if(character==L'`' || character==L'$' || character==L'"' ||
character==L'\u201c' || character==L'\u201d') quoted+=L'`';
quoted+=character;
}
quoted+=L'"';
}
SetFocus(terminalInput);
SendMessageW(terminalInput,EM_REPLACESEL,TRUE,
reinterpret_cast<LPARAM>(quoted.empty()?path.c_str():quoted.c_str()));
}
void handleTerminalPromptInput(HWND owner,std::wstring_view action)
{
if(GetForegroundWindow()!=owner || !commandLineAvailable(owner)) return;
SetFocus(terminalInput);
if(action==L"focus-input") return;
if(action==L"enter" || action==L"shift-enter")
{
const bool shift=action==L"shift-enter";
if(shift || !handleCompletionKey(VK_RETURN,0)) handleFilesReturn(shift);
return;
}
if(action.starts_with(L"text:"))
{
auto text=std::wstring(action.substr(5));
std::erase_if(text,[](wchar_t character){ return character<32 || character==127; });
if(!text.empty()) SendMessageW(terminalInput,EM_REPLACESEL,TRUE,reinterpret_cast<LPARAM>(text.c_str()));
return;
}
constexpr std::pair<std::wstring_view,WPARAM> keys[]{
{L"ArrowLeft",VK_LEFT}, {L"ArrowRight",VK_RIGHT}, {L"ArrowUp",VK_UP}, {L"ArrowDown",VK_DOWN},
{L"Home",VK_HOME}, {L"End",VK_END}, {L"Tab",VK_TAB}, {L"Escape",VK_ESCAPE},
{L"Delete",VK_DELETE}, {L"Backspace",VK_BACK}, {L"F1",VK_F1}};
const auto key=std::find_if(std::begin(keys),std::end(keys),
[action](const auto &binding){ return binding.first==action; });
if(key==std::end(keys) || handleCompletionKey(key->second,0)) return;
if(key->second==VK_F1)
{
PostMessageW(owner,ks::files::filesHelpRequest,0,0);
return;
}
const auto character=key->second==VK_BACK || key->second==VK_ESCAPE;
SendMessageW(terminalInput,character?WM_CHAR:WM_KEYDOWN,key->second,0);
}
void acceptSshDirectory(HWND owner,std::wstring_view message);
bool ensureTerminalView(HWND owner,bool ssh=false)
{
auto &view=ssh?sshView:terminalView;
auto &requested=ssh?sshViewRequested:terminalViewRequested;
if(!requested)
{
requested=view.create(terminalOutput,[owner,ssh](const std::wstring &message)
{
auto &source=ssh?sshView:terminalView;
if(message==L"ready")
{
source.setFont(displayFont,areaFontPoints(fontPoints,AppearanceArea::terminal));
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;
else if(terminalTrace.is_open() && message.starts_with(L"trace:"))
{
int phase{},height{},rows{},viewport{},base{},offset{};
if(swscanf_s(message.c_str()+6,L"%d,%d,%d,%d,%d,%d",
&phase,&height,&rows,&viewport,&base,&offset)==6 && phase>=0 && phase<=3)
{
const char *events[]{"web-before-fit","web-after-fit","web-anchor","web-scroll"};
traceTerminal(events[phase],height,rows,viewport,base,offset);
}
}
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())
{
const auto command=std::move(terminalCommands.front());
terminalCommands.pop_front();
if(command.panel>=0 && !directory.empty() && directory!=command.directory.native())
{
auto &panel=panels[command.panel];
std::error_code error;
if(!panel.peer && !panel.ftp && panel.directory==command.directory &&
(!panel.scanRequest || panel.scanRequest->directory==command.directory) &&
fs::is_directory(directory,error))
open(panel,directory,false);
}
}
terminalDirectory=directory;
}
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))
copyOrInterruptTerminal();
else if(message==L"copy-command-line-or-panel-names") copyCommandLineOrPanelNames(owner);
else if(message==L"refresh-panel") refreshPanel(panels[active]);
else if(message==L"toggle") showTerminal(owner,!terminalVisible);
else if(!terminalVisible && (message==L"grow" || message==L"shrink"))
{
terminalRows=std::max(0,terminalRows+(message==L"grow"?1:-1));
layout(owner);
}
else if(message.starts_with(L"size:"))
{
int columns{},rows{};
if(swscanf_s(message.c_str()+5,L"%d,%d",&columns,&rows)==2 &&
columns>=2 && columns<=32767 && rows>=2 && rows<=32767)
{
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,ssh]
{
if(ssh)
{
sshTerminal.stop();
sshPrompt.reset();
sshViewRequested=false;
sshView.close();
}
if(ssh || !sshPrompt) showTerminal(owner,false);
setStatus(L"Could not initialize the terminal view.");
},false,{},ssh);
if(!requested)
{
setStatus(L"WebView2 and the local terminal assets are required.");
return false;
}
}
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))
{
terminalCommands={{}};
terminalDirectory=directory.native();
return true;
}
setStatus(L"Could not start PowerShell.");
return false;
}
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.listing) return ensureTerminalView(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(HWND owner)
{
updateSshTerminal(owner);
if(!terminalView.initialized()) return;
const auto bytes=terminal.takeOutput();
if(!bytes.empty()) terminalView.send(bytes);
std::string incoming;
{
const std::lock_guard lock(pendingTerminalOutputMutex);
incoming.swap(pendingTerminalOutput);
}
if(!incoming.empty()) terminalView.send(incoming);
}
void appendTerminalOutput(std::string_view output)
{
const std::lock_guard lock(pendingTerminalOutputMutex);
for(const auto character:output)
{
const auto byte=static_cast<unsigned char>(character);
if(byte>=32 || character=='\r' || character=='\n' || character=='\t')
pendingTerminalOutput+=character;
}
constexpr size_t limit=1024*1024;
if(pendingTerminalOutput.size()>limit) pendingTerminalOutput.erase(0,pendingTerminalOutput.size()-limit);
}
bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
{
const auto owner=GetParent(panel.list);
if(panel.archive)
{
setStatus(L"Shell commands require a local or LAN folder.");
return false;
}
if(panel.listing)
{
setStatus(L"Open a folder before running a shell command.");
return false;
}
if(panel.ftp)
{
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.";
setStatus(busy);
if(terminalVisible) appendTerminalOutput(ks::utf8(std::wstring(L"\r\n")+busy+L"\r\n"));
return false;
}
if(panel.peer)
{
if(value.find_first_not_of(L" \t\r\n")==value.npos) return true;
if(!ensureTerminalView(owner)) return false;
terminalRows=std::max(terminalRows,5);
layout(owner);
const auto peer=*panel.peer;
const auto directory=panel.directory;
appendTerminalOutput(ks::utf8(L"\r\n["+peer.name+L" · "+directory.wstring()+L"]> "+value+L"\r\n"));
remoteCommandRunning=true;
try
{
remoteCommandThread=std::jthread([peer,directory,value](std::stop_token stop)
{
try
{
FilesConnection host(&peer);
const auto code=ks::lan::runRemoteCommand(host,directory,value,appendTerminalOutput,stop);
if(code==STATUS_DLL_INIT_FAILED)
appendTerminalOutput("\r\nRemote PowerShell could not start: DLL initialization failed (0xC0000142).\r\n");
else
appendTerminalOutput("\r\n[Remote exit code "+std::to_string(code)+"]\r\n");
}
catch(const std::system_error &error)
{
const auto code=error.code().value();
const auto reason=code==ERROR_ACCESS_DENIED
? L"The remote PC denied this command. Check its Files command-line settings."
: code==ERROR_INVALID_FUNCTION?L"Update KSwitcher on the remote PC."
: code==ERROR_CANCELLED?L"Remote command canceled.":fileError(error);
appendTerminalOutput(ks::utf8(L"\r\n"+std::wstring(reason)+L"\r\n"));
}
catch(const std::exception &)
{
appendTerminalOutput("\r\nThe remote command connection ended.\r\n");
}
remoteCommandRunning=false;
});
}
catch(const std::system_error &error)
{
remoteCommandRunning=false;
setStatus(fileError(error));
return false;
}
return true;
}
if(!startTerminal(owner,panel.directory)) return false;
// Use the directory displayed by the panel at submission time. A queued
// command may change location before PowerShell gets to this input.
const bool hasCommand=value.find_first_not_of(L" \t\r\n")!=value.npos;
std::wstring input;
if(hasCommand && (terminalDirectory!=panel.directory.native() ||
std::any_of(terminalCommands.begin(),terminalCommands.end(),
[](const auto &command){ return command.panel>=0; })))
input=L"try { Microsoft.PowerShell.Management\\Set-Location -LiteralPath "+
powerShellPath(panel.directory)+L" -ErrorAction Stop } catch { Write-Error $_; return }; ";
if(!terminal.write(input+value+L"\r"))
{
setStatus(L"Could not send PowerShell input.");
return false;
}
terminalCommands.push_back({hasCommand?static_cast<int>(&panel-panels):-1,panel.directory});
return true;
}
void runCommandLine()
{
const auto value=terminalInputText();
if(!submitTerminalCommand(panels[active],value)) return;
activeTerminalView().post(L"scroll-bottom");
if(value.find_first_not_of(L" \t\r\n")!=value.npos)
{
rememberCommand(value);
if(!terminalVisible && terminalRows==0)
{
terminalRows=5;
layout(GetParent(terminalInput));
}
}
terminalHistoryIndex=terminalHistory.size();
terminalHistoryDraft.clear();
SetWindowTextW(terminalInput,L"");
}
LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_KILLFOCUS) resetCompletion();
if(message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN)
{
panelClipboardContext=false;
clearTerminalSelection();
hideCompletion();
}
if(message==WM_COPY || (message==WM_CHAR && wp==3))
{
copyTerminalText(GetParent(input));
return 0;
}
if(message==WM_CHAR && wp==VK_TAB && !terminalVisible) return 0;
if(message==WM_CHAR && wp==VK_ESCAPE)
{
if(stopDirectoryScan()) return 0;
if(!GetWindowTextLengthW(input) && (terminalVisible || remoteCommandRunning) &&
interruptTerminal()) return 0;
terminalHistoryDraft.clear();
recallCommand(terminalHistory.size());
return 0;
}
if((message==WM_CHAR && wp==22) ||
(message==WM_KEYDOWN && wp==VK_INSERT && (GetKeyState(VK_SHIFT)&0x8000)))
{
SendMessageW(input,WM_PASTE,0,0);
return 0;
}
// The edit control receives Ctrl+Backspace as DEL.
if(message==WM_CHAR && wp==127)
{
DWORD first{},last{};
SendMessageW(input,EM_GETSEL,reinterpret_cast<WPARAM>(&first),reinterpret_cast<LPARAM>(&last));
if(first==last && first)
{
std::wstring text(GetWindowTextLengthW(input)+1,L'\0');
GetWindowTextW(input,text.data(),static_cast<int>(text.size()));
while(first && iswspace(text[first-1])) --first;
while(first && !iswspace(text[first-1])) --first;
SendMessageW(input,EM_SETSEL,first,last);
}
SendMessageW(input,EM_REPLACESEL,TRUE,reinterpret_cast<LPARAM>(L""));
return 0;
}
if(message==WM_KEYDOWN && !terminalVisible && wp==VK_TAB)
{
if(plainPanelTab())
{
panelClipboardContext=true;
activatePanel(1-active);
}
return 0;
}
if(message==WM_KEYDOWN && !terminalVisible &&
((wp>=VK_F1 && wp<=VK_F12) || wp==VK_UP || wp==VK_DOWN || wp==VK_PRIOR || wp==VK_NEXT ||
(!GetWindowTextLengthW(input) &&
(wp==VK_HOME || wp==VK_END || wp==VK_LEFT || wp==VK_RIGHT || wp==VK_INSERT || wp==VK_DELETE))))
{
SendMessageW(panels[active].list,WM_KEYDOWN,wp,lp);
return 0;
}
if(message==WM_KEYDOWN && wp==VK_UP)
{
recallPreviousCommand();
return 0;
}
return DefSubclassProc(input,message,wp,lp);
}
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;
bool partial=false;
visitPanelMarks(panel,[&](const fs::path &path,const FolderEntryMetadata &entry)
{
++marked;
auto bytes=entry.size;
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)
{
const auto measured=panel.folderSizes.find(path);
if(measured==panel.folderSizes.end() || (measured->second.failed && !measured->second.previous))
{
++unmeasured;
return;
}
bytes=measured->second.bytes;
partial|=measured->second.partial;
}
if(bytes>UINT64_MAX-total)
{
total=UINT64_MAX;
partial=true;
}
else total+=bytes;
});
std::wstring summary;
if(marked)
{
summary=L"Selected: ";
if(partial || unmeasured) summary+=L"≥ ";
summary+=formatSize(total)+L" · "+std::to_wstring(marked)+(marked==1?L" item":L" items");
if(unmeasured) summary+=L" · "+std::to_wstring(unmeasured)+L" to measure";
if(partial) summary+=L" · partial";
}
SetWindowTextW(panel.selectionSummary,summary.c_str());
if(hadSummary!=hasSelectionSummary()) layout(GetParent(panel.list));
}
std::optional<SYSTEMTIME> localFileTime(uint64_t ticks)
{
if(!ticks) return {};
const FILETIME stamp{static_cast<DWORD>(ticks),static_cast<DWORD>(ticks>>32)};
SYSTEMTIME utc{},local{};
if(FileTimeToSystemTime(&stamp,&utc) && SystemTimeToTzSpecificLocalTime(nullptr,&utc,&local)) return local;
return {};
}
std::wstring folderMeasurementText(const Panel &panel,const fs::path &path,size_t columns=0)
{
const bool waiting=panel.folderSizeWaiting.contains(path);
const auto measured=panel.folderSizes.find(path);
if(measured==panel.folderSizes.end())
{
if(path==panel.folderSpinner)
{
constexpr const wchar_t *frames[]{L"|",L"/",L"-",L"\\"};
return frames[(GetTickCount64()/folderSpinnerInterval)%std::size(frames)];
}
return waiting?L"Queued":L"";
}
const auto &size=measured->second;
if(!columns)
{
if(size.failed)
{
auto label=std::wstring(L"size unavailable");
if(size.previous) label+=L" (last known "+formatSize(size.bytes)+L")";
if(waiting) label+=L" (updating)";
return label;
}
auto label=formatSize(size.bytes);
if(size.partial) label+=L" (partial)";
if(waiting) label+=L" (updating)";
return label;
}
if(size.failed && !size.previous) return waiting?L"Error…":L"Error";
std::wstring suffix;
if(size.failed) suffix=L"!";
else if(size.partial) suffix=L"+";
if(waiting) suffix+=L"…";
return formatSize(size.bytes,columns>suffix.size()?columns-suffix.size():1)+suffix;
}
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;
const auto refreshKey=filesKeyHint(FilesKey::Refresh);
if(panel.remoteRetry)
{
setStatus((refreshKey.empty()?L"Refresh to retry":refreshKey+L" to retry")+
L" · "+panel.remoteRetry->failure,true);
return;
}
if(panel.findOrigin)
{
const auto error=panel.findOrigin->error;
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 · "+(refreshKey.empty()?L"Refresh to retry":refreshKey+L" Retry")+L" · 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;
}
if(recentFolderList(panel))
{
setStatus(panel.rows.empty()?L"No recent folders Esc Back":L"Enter Open folder Delete Remove from recent Esc Back");
return;
}
if(panel.listing)
{
if(panel.smbPending) setStatus(L"Connecting to SMB… Esc Cancel");
else if(!panel.listing->smb->server.empty())
setStatus(panel.rows.size()<=1?L"No visible shares Esc Back":L"Enter Open share Esc Back");
else if(panel.rows.empty()) setStatus(L"Shift+F4 New connection Esc Back");
else setStatus(L"Enter Connect Shift+F4 New Right-click for Edit, Remove or Sign in");
return;
}
if(transferProfileList(panel))
{
setStatus(transferProfiles(panel.ftp->protocol).rows.empty()?L"Shift+F4 New connection":
L"Shift+F4 New "+(filesKeyHint(FilesKey::Edit).empty()?L"":filesKeyHint(FilesKey::Edit)+L" Edit ")+
L"Enter Connect");
return;
}
auto row=SendMessageW(panel.list,LB_GETCURSEL,0,0);
if(!detailedPanel(panel) || !showDetails || row<0 || static_cast<size_t>(row)>=panel.rows.size())
{
setStatus(panel.view.mask.empty()?L"":L"Filter: "+panel.view.mask);
return;
}
const auto &path=panel.rows[row];
uint64_t ticks{};
if(const auto found=panel.metadata.find(path); found!=panel.metadata.end()) ticks=found->second.modified;
if(!ticks && !panel.peer && !panel.ftp)
{
WIN32_FILE_ATTRIBUTE_DATA data{};
if(GetFileAttributesExW(path.c_str(),GetFileExInfoStandard,&data))
{
const auto &stamp=data.ftLastWriteTime;
ticks=(uint64_t(stamp.dwHighDateTime)<<32)|stamp.dwLowDateTime;
}
}
wchar_t date[64]{};
if(const auto time=localFileTime(ticks))
swprintf_s(date,L" %04u-%02u-%02u %02u:%02u",unsigned(time->wYear),
unsigned(time->wMonth),unsigned(time->wDay),unsigned(time->wHour),unsigned(time->wMinute));
std::wstring details;
if(statusFields&1) details=path.filename().wstring();
if(statusFields&2)
{
const auto &size=panel.sizes[row];
if(size==L"Folder")
{
const auto measure=folderMeasurementText(panel,path);
details+=L" "+(measure.empty()?size:measure);
}
else details+=L" "+(size==L"Up"?size:formatSize(std::stoull(size)));
}
std::wstring timestamp=date;
if((statusFields&4) && timestamp.size()>=12) details+=timestamp.substr(0,12);
if((statusFields&8) && timestamp.size()>=18) details+=timestamp.substr(12);
if(!panel.view.mask.empty())
{
if(!details.empty()) details+=L" ";
details+=L"Filter: "+panel.view.mask;
}
setStatus(details);
}
#include "files_find_scan.inl"
#include "files_panel_order.inl"
std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &request,
std::atomic_size_t &entriesRead,std::stop_token stop)
{
if(request.find) return scanFileMatches(request,entriesRead,stop);
auto result=std::make_unique<Panel::ScanResult>();
auto &[watch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=*result;
const auto &directory=request.directory;
const auto &peer=request.peer;
if(stop.stop_requested())
{
error=ERROR_CANCELLED;
return result;
}
if(request.archive)
{
try
{
const auto &source=*request.archive;
archiveEntries=source.entries?source.entries:
std::make_shared<const ks::files::ArchiveEntries>(ks::files::readArchive(source.file,stop));
const auto inner=directory.lexically_relative(source.file);
const auto relative=inner==L"."?fs::path{}:inner;
if(!relative.empty())
{
const auto member=archiveEntries->find(relative);
if(member==archiveEntries->end() || !member->second.directory)
throw std::runtime_error("This folder is no longer present in the archive.");
}
for(const auto &[path,entry]:*archiveEntries)
{
if(stop.stop_requested()) {error=ERROR_CANCELLED; return result;}
if(path.parent_path()!=relative) continue;
const auto child=source.file/path;
const DWORD attributes=entry.directory?FILE_ATTRIBUTE_DIRECTORY:FILE_ATTRIBUTE_NORMAL;
metadata.emplace(child,FolderEntryMetadata{attributes,entry.size,entry.modified});
(entry.directory?folders:files).push_back(child);
}
opened=true;
}
catch(const std::system_error &e)
{
if(e.code().value()==ERROR_CANCELLED) error=ERROR_CANCELLED;
else failure=fileError(e);
}
catch(const std::exception &e) {failure=ks::wide(e.what());}
return result;
}
if(request.ftp)
{
if(!request.ftp->name.empty())
{
try
{
TransferSession ftp(*request.ftp);
if(directory.empty()) ftpInitialDirectory=ftp.initialDirectory();
error=ftp.list(directory.empty()?ftpInitialDirectory:directory,[&](const fs::path &path,const FileInfo &info)
{
if(!metadata.emplace(path,FolderEntryMetadata{info.attributes,info.size,info.modified}).second) return true;
if(info.transfer) columnMetadata[path].transfer=info.transfer;
(info.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path);
entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed);
return !stop.stop_requested();
},stop);
if(stop.stop_requested()) error=ERROR_CANCELLED;
if(error!=ERROR_NO_MORE_FILES && error!=ERROR_CANCELLED) requireFileOperation(false,error);
}
catch(const std::system_error &e)
{
error=static_cast<DWORD>(e.code().value());
failure=(request.ftp->protocol==TransferProtocol::sftp?fileError(e):ftpFolderError(e))+L" ("+request.ftp->name+L")";
}
catch(const std::exception &e)
{
failure=request.ftp->name+L": "+ks::wide(e.what());
}
}
opened=failure.empty() && (error!=ERROR_CANCELLED || !metadata.empty());
return result;
}
if(request.elevated)
{
error=readElevatedFolder(*request.elevated,directory,folders,files,metadata,entriesRead,stop);
opened=error==ERROR_SUCCESS || (error==ERROR_CANCELLED && !metadata.empty());
if(opened)
{
if(error==ERROR_SUCCESS) watch.start(directory);
}
else if(error!=ERROR_CANCELLED) failure=error==ERROR_ACCESS_DENIED?L"Windows denied access after elevation: "+directory.wstring():
L"Could not read folder as administrator ("+std::to_wstring(error)+L"): "+directory.wstring();
return result;
}
if(!peer) watch.start(directory);
WIN32_FIND_DATAW data{};
const auto search=peer?INVALID_HANDLE_VALUE:FindFirstFileW((directory/L"*").c_str(),&data);
struct SearchHandle
{
HANDLE handle;
~SearchHandle(){if(handle!=INVALID_HANDLE_VALUE) FindClose(handle);}
} searchHandle{search};
error=search==INVALID_HANDLE_VALUE && !peer ? GetLastError() : ERROR_SUCCESS;
opened=search!=INVALID_HANDLE_VALUE;
if(peer)
{
try
{
FilesConnection host(&*peer);
const bool complete=listFiles(host,directory,[&](const fs::path &path,const FileInfo &info)
{
if(stop.stop_requested()) return false;
(info.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path);
metadata.emplace(path,FolderEntryMetadata{info.attributes,info.size,info.modified});
entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed);
return true;
});
opened=true;
if(!complete) error=ERROR_CANCELLED;
}
catch(const std::system_error &e)
{
error=static_cast<DWORD>(e.code().value());
failure=peer->name+L" — "+fileError(e);
}
catch(const std::exception &){result->failure=L"Cannot open folder on "+peer->name;}
if(!opened && stop.stop_requested())
{
error=ERROR_CANCELLED;
opened=!metadata.empty();
failure.clear();
}
}
if(search!=INVALID_HANDLE_VALUE)
{
do
{
if(stop.stop_requested())
{
error=ERROR_CANCELLED;
break;
}
const std::wstring_view name(data.cFileName);
if(name==L"." || name==L"..") continue;
const auto path=directory/name;
const auto size=(static_cast<ULONGLONG>(data.nFileSizeHigh)<<32)|data.nFileSizeLow;
(data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path);
const auto &stamp=data.ftLastWriteTime;
metadata.emplace(path,FolderEntryMetadata{data.dwFileAttributes,size,
(uint64_t(stamp.dwHighDateTime)<<32)|stamp.dwLowDateTime});
entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed);
} while(FindNextFileW(search,&data));
if(error!=ERROR_CANCELLED) error=GetLastError();
}
else if(!peer && stop.stop_requested()) error=ERROR_CANCELLED;
return result;
}
void startDirectoryScan(Panel &panel);
void queueAutomaticPanelSizes(Panel &panel,bool refresh=false);
void collectTreeBranches();
void stopTreeBranches(Panel &panel);
void refreshTreeBranches(Panel &panel);
void replaceTreeRoot(Panel &panel,Panel::ScanResult &scan,bool sameDirectory,const std::set<fs::path> &marks);
void appendTreeRows(Panel &panel,PanelRowsUpdate &rows);
bool samePanelSource(const Panel &panel,const std::optional<FilesPeer> &peer,const std::optional<TransferProfile> &ftp)
{
return (panel.peer?panel.peer->id:std::string{})==(peer?peer->id:std::string{}) &&
panel.ftp.has_value()==ftp.has_value() && (!panel.ftp || (panel.ftp->protocol==ftp->protocol && panel.ftp->id==ftp->id));
}
bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResult &scan)
{
const auto &directory=scan.ftpInitialDirectory.empty()?request.directory:scan.ftpInitialDirectory;
auto &peer=request.peer;
const auto previousDirectory=samePanelSource(panel,peer,request.ftp)?panel.directory:fs::path{};
const auto provider=peer?FolderProvider::lan:request.ftp?transferFolderProvider(request.ftp->protocol):FolderProvider::local;
const bool sameDirectory=request.listing || panel.listing?
request.listing && panel.listing && samePanelListing(*panel.listing,*request.listing):
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);
return false;
}
if(partial && !opened)
{
if(&panel==&panels[active]) setStatus(L"Reading stopped before the folder opened.");
return false;
}
if (!opened && error!=ERROR_FILE_NOT_FOUND)
{
const bool denied=error==ERROR_ACCESS_DENIED;
setStatus(denied ? L"Access denied: " + directory.wstring() :
L"Cannot open folder: " + directory.wstring());
if(request.offerElevation && denied && !IsUserAnAdmin())
{
auto owner=GetParent(panel.list);
auto path=directory.wstring();
bool remember=false;
const auto question=L"Windows denied access to this folder.\r\n"+path+
L"\r\n\r\nTry opening as administrator? Windows may still ask for UAC.";
if(rememberElevationApproval || showFilesNotice(owner,question.c_str(),
L"KSwitcher Files",{.confirm=true,.remember=&remember})==IDYES)
{
auto elevated=std::make_shared<ElevatedHelper>();
const auto result=launchElevatedFolder(owner,directory,*elevated);
SetForegroundWindow(owner);
SetFocus(panel.list);
if(result!=ERROR_SUCCESS)
{
setStatus(result==ERROR_ACCESS_DENIED ? L"Windows denied access after elevation: "+path :
L"Could not read folder as administrator ("+std::to_wstring(result)+L"): "+path);
return false;
}
rememberElevationApproval=rememberElevationApproval || remember;
request.statusRevision=statusRevision;
request.elevated=std::move(elevated);
panel.scanRequest=std::move(request);
startDirectoryScan(panel);
return true;
}
}
if(error) return false;
}
const bool updateDetails=statusRevision==request.statusRevision;
std::set<fs::path> markedPaths;
fs::path previousSelection;
LRESULT previousRow=0, previousTop=0;
if(sameDirectory)
{
if(!panel.findOrigin) markedPaths=std::move(panel.filteredMarks);
previousRow=SendMessageW(panel.list,LB_GETCURSEL,0,0);
previousTop=SendMessageW(panel.list,LB_GETTOPINDEX,0,0);
if(previousRow>=0 && static_cast<size_t>(previousRow)<panel.rows.size())
previousSelection=panel.rows[previousRow];
for(size_t i=0;i<panel.rows.size();++i)
if(panel.marked[i]) markedPaths.insert(panel.rows[i]);
}
const bool finding=request.find.has_value();
const bool viewChanged=finding!=panel.findOrigin.has_value() || request.listing.has_value()!=panel.listing.has_value();
if(finding)
{
if(!panel.findOrigin)
{
panel.findOrigin=Panel::FindOrigin{*request.find,previousSelection,std::move(markedPaths),previousRow,previousTop};
previousSelection.clear();
previousRow=previousTop=0;
markedPaths.clear();
}
panel.findOrigin->options=std::move(*request.find);
panel.findOrigin->error=error;
}
else if(panel.findOrigin)
{
if(sameDirectory)
{
previousSelection=std::move(panel.findOrigin->cursor);
markedPaths=std::move(panel.findOrigin->marks);
previousRow=panel.findOrigin->row;
previousTop=panel.findOrigin->top;
}
panel.findOrigin.reset();
}
if(!finding && !panel.listReturnMarks.empty())
{
for(const auto &mark:panel.listReturnMarks)
if(mark.parent_path()==folderPathWithoutSeparator(directory)) markedPaths.insert(mark);
panel.listReturnMarks.clear();
}
const bool returningFromListing=panel.listing && request.navigationPosition==panel.navigation.current;
const bool rememberFolder=!sameDirectory && !partial && !returningFromListing &&
(!panel.directory.empty() || panel.listing || peer || request.ftp);
panel.directory = directory;
panel.peer=std::move(peer);
panel.ftp=std::move(request.ftp);
panel.archive=std::move(request.archive);
panel.listing=std::move(request.listing);
if(panel.archive) panel.archive->entries=std::move(archiveEntries);
if(!sameDirectory)
{
cancelFolderSizes(panel);
panel.folderSizes.clear();
}
if(partial || finding || panel.archive || panel.listing) panel.watch.reset();
else if(!sameDirectory || panel.watch.handle==INVALID_HANDLE_VALUE)
{
panel.watch.reset();
std::swap(panel.watch.handle,nextWatch.handle);
}
const bool locationList=panelListsLocations(panel);
if(!finding && !panel.archive && !locationList)
{
auto location=folderLocation(panel,directory);
if(rememberFolder) updateRecentFolders(location,true);
panel.navigation.opened(std::move(location),request.navigationPosition);
}
const bool renderTree=panel.view.tree && !finding && !locationList && !panel.archive;
panel.filteredMarks.clear();
if(renderTree) replaceTreeRoot(panel,scan,sameDirectory,markedPaths);
else
{
if(!finding)
{
stopTreeBranches(panel);
if(!partial) std::erase_if(markedPaths,[&](const auto &path){return !metadata.contains(path);});
panel.filteredMarks=markedPaths;
}
panel.metadata=std::move(metadata);
panel.columnMetadata=std::move(columnMetadata);
}
const auto parent=finding?fs::path{}:panel.archive?directory.parent_path():
panelParentPath(directory,!panel.peer && !panel.ftp);
const bool hasParent=!parent.empty();
const auto rowCount=panel.listing?panel.listing->rows.size():locationList?transferProfiles(panel.ftp->protocol).rows.size():finding?files.size():
renderTree?panel.tree.branches.at(panel.tree.root).ordered.size()+hasParent:ordered.size()+hasParent;
PanelRowsUpdate rows(panel,rowCount);
const auto add=[&](const fs::path &path,const std::wstring &label,bool folder)
{
const bool marked=markedPaths.contains(path);
if(rows.add(path,label,folder,marked) && marked) panel.filteredMarks.erase(path);
};
if(panel.listing)
{
for(const auto &[path,label]:panel.listing->rows) rows.add(path,label,false,false,path==L"..");
}
else if(locationList)
{
const auto &connections=transferProfiles(panel.ftp->protocol).rows;
for(size_t i=0;i<connections.size();++i)
add(ftpRoot/std::to_wstring(i),connections[i].name,false);
}
else
{
if(hasParent) rows.add(parent,L"..",true,false,true);
if(renderTree) appendTreeRows(panel,rows);
else if(finding)
{
for(const auto &file:files)
{
const auto relative=file.lexically_relative(directory);
add(file,panel.ftp?ftpPath(relative):relative.native(),false);
}
}
else
{
for(const auto &entry:ordered)
{
const auto name=entry.path.filename().native();
add(entry.path,entry.folder?L"["+name+L"]":name,entry.folder);
}
}
}
const auto label=panelCaption(panel);
SetWindowTextW(panel.path,label.c_str());
InvalidateRect(panel.path,nullptr,FALSE);
if(viewChanged)
{
InvalidateRect(panel.heading,nullptr,FALSE);
InvalidateRect(GetParent(panel.list),nullptr,FALSE);
}
if(&panel==&panels[active] && !sameDirectory)
layout(GetParent(panel.list),true);
auto selected=std::find(panel.rows.begin(),panel.rows.end(),previousSelection);
if(selected==panel.rows.end() && !panel.rows.empty())
selected=panel.rows.begin()+std::clamp<LRESULT>(previousRow,0,panel.rows.size()-1);
if(!previousDirectory.empty() && previousDirectory.parent_path()==directory)
{
const auto child=std::find(panel.rows.begin(),panel.rows.end(),previousDirectory);
if(child!=panel.rows.end()) selected=child;
}
if(!request.selection.empty())
{
const auto requested=std::find(panel.rows.begin(),panel.rows.end(),request.selection);
if(requested!=panel.rows.end()) selected=requested;
}
if(selected!=panel.rows.end())
{
if(sameDirectory) SendMessageW(panel.list,LB_SETTOPINDEX,previousTop,0);
SendMessageW(panel.list,LB_SETCURSEL,selected-panel.rows.begin(),0);
}
rows.finish();
InvalidateRect(panel.list,nullptr,FALSE);
updateSelectionSummary(panel);
refreshQuickView(panel);
if(finding && &panel==&panels[active]) showFileDetails(panel);
else if(partial && &panel==&panels[active])
setStatus(L"Partial: "+std::to_wstring(folders.size()+files.size()));
else if(!partial && error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND)
setStatus(L"Some entries could not be read.");
else if(updateDetails && &panel==&panels[active]) showFileDetails(panel);
if(!finding && !locationList && !panel.archive) queueAutomaticPanelSizes(panel,true);
return true;
}
#include "files_columns_metadata.inl"
std::future<std::unique_ptr<Panel::ScanResult>> scanDirectoryInBackground(HWND owner,Panel::ScanRequest request,
PanelView view,DWORD columns,std::shared_ptr<std::atomic_size_t> entries,std::stop_token stop)
{
std::packaged_task<std::unique_ptr<Panel::ScanResult>()> task(
[request=std::move(request),view=std::move(view),columns,entries=std::move(entries),stop]
{
if(request.listing)
{
auto result=std::make_unique<Panel::ScanResult>();
result->opened=true;
return result;
}
auto result=scanDirectory(request,*entries,stop);
if(result->opened && !request.find)
{
orderDirectoryRows(*result,view);
if(columns && !request.peer && !request.ftp && !request.archive) readLocalColumnMetadata(*result,columns,stop);
}
return result;
});
auto future=task.get_future();
std::thread([task=std::move(task),owner]() mutable
{
task();
PostMessageW(owner,directoryScanReady,0,0);
}).detach();
return future;
}
void startDirectoryScan(Panel &panel)
{
panel.scanStop=std::stop_source{};
panel.scanEntriesRead=std::make_shared<std::atomic_size_t>(0);
panel.scan=scanDirectoryInBackground(GetParent(panel.list),*panel.scanRequest,panel.view,
effectivePanelColumns(panel)&extendedColumnMask,panel.scanEntriesRead,panel.scanStop.get_token());
panel.scanSuperseded=false;
if(&panel==&panels[active]) showDirectoryScanProgress(panel);
}
void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional<FilesPeer> peer,
fs::path selection={},fs::path fallback={},std::optional<TransferProfile> ftp={},
std::optional<size_t> navigationPosition={},std::optional<ArchiveLocation> archive={},
unsigned reconnectAttempt=0,fs::path fallbackSelection={},std::optional<PanelListing> listing={})
{
if(directory.empty() && !ftp && !listing) return;
cancelSmbConnection(panel);
panel.remoteRetry.reset();
if(!panel.view.revealedFile.empty() &&
(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),
std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition,
std::move(archive),reconnectAttempt,std::move(fallbackSelection),std::move(listing)};
if(panel.scan.valid())
{
panel.scanSuperseded=true;
panel.scanStop.request_stop();
if(&panel==&panels[active]) showDirectoryScanProgress(panel);
}
else startDirectoryScan(panel);
}
#include "files_panel_recovery.inl"
void openPanelListing(Panel &panel,PanelListing listing,fs::path selection={})
{
if(panel.listing) listing.returnSelection=panel.listing->returnSelection;
else if(const auto row=currentPanelRow(panel);row!=LB_ERR) listing.returnSelection=panel.rows[row];
openOn(panel,{},false,{},std::move(selection),{},{},{},{},0,{},std::move(listing));
}
void closePanelListing(Panel &panel)
{
if(panel.navigation.history.empty()) return;
const auto position=panel.navigation.current;
openFolderLocation(panel,panel.navigation.history[position],position,panel.listing->returnSelection);
}
void collectDirectoryScans()
{
for(auto &panel:panels)
{
if(!panel.scan.valid() || panel.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
continue;
if(panel.scanSuperseded)
{
panel.scan={};
startDirectoryScan(panel);
continue;
}
auto request=std::move(*panel.scanRequest);
panel.scanRequest.reset();
panel.scanEntriesRead.reset();
bool applied=false;
auto retry=panel.remoteRetry;
const auto fallback=request.fallback;
const auto fallbackSelection=request.fallbackSelection;
const bool usesFtp=request.ftp && !request.ftp->id.empty();
try
{
auto result=panel.scan.get();
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},
result->failure,0,request.reconnectAttempt};
if(request.peer && transientLanError(result->error) && retry->reconnectAttempt<lanRetryDelays.size())
retry->retryAt=GetTickCount64()+lanRetryDelays[retry->reconnectAttempt];
}
applied=applyDirectoryScan(panel,std::move(request),*result);
if(result->error==ERROR_CANCELLED && fallback.empty()) continue;
}
catch(const std::exception &) {setStatus(L"Could not read the folder.");}
if(!applied && !fallback.empty())
{
const auto root=usesFtp?systemPanelRoot():fs::path{};
openOn(panel,fallback,false,{},fallbackSelection,fallback==root?fs::path{}:root);
}
else if(applied && !panel.scan.valid() && !panel.peer && !panel.ftp &&
panel.watch.handle!=INVALID_HANDLE_VALUE && WaitForSingleObject(panel.watch.handle,0)==WAIT_OBJECT_0)
{
if(!FindNextChangeNotification(panel.watch.handle)) panel.watch.reset();
openOn(panel,panel.directory,false,{});
}
panel.remoteRetry=std::move(retry);
if(panel.remoteRetry && !panel.scan.valid() && &panel==&panels[active]) showFileDetails(panel);
}
}
void open(Panel &panel,const fs::path &directory,bool offerElevation=false)
{
openOn(panel,directory,offerElevation,panel.peer,{},{},panel.ftp,{},panel.archive);
}
void refreshArchive(Panel &panel)
{
openOn(panel,panel.directory,false,{},{},{},{},{},ArchiveLocation{panel.archive->file,{}});
}
void parentArchive(Panel &panel)
{
if(panel.directory==panel.archive->file)
openOn(panel,panel.directory.parent_path(),false,{},panel.archive->file);
else open(panel,panel.directory.parent_path());
}
#include "files_panel_tree.inl"
bool panelViewAvailable(const Panel &panel)
{
return !panel.findOrigin && !transferProfileList(panel) && !panel.directory.empty() &&
(!panel.scanRequest || !panel.scanRequest->find);
}
void updatePanelView(Panel &panel)
{
panel.view.revealedFile.clear();
savePanelView(static_cast<int>(&panel-panels));
InvalidateRect(panel.heading,nullptr,FALSE);
if(panel.scanRequest)
{
panel.scanSuperseded=true;
panel.scanStop.request_stop();
}
else open(panel,panel.directory);
}
void refreshPanelColumnData(Panel &panel)
{
if(panel.directory.empty() || panel.peer || panel.ftp || panel.findOrigin || panel.archive ||
(panel.scanRequest && panel.scanRequest->find)) return;
if(panel.scanRequest)
{
panel.scanSuperseded=true;
panel.scanStop.request_stop();
}
else open(panel,panel.directory);
}
void sortPanel(Panel &panel,PanelSort sort)
{
if(!panelViewAvailable(panel)) return;
if(panel.view.sort==sort) panel.view.descending=!panel.view.descending;
else
{
panel.view.sort=sort;
panel.view.descending=false;
}
updatePanelView(panel);
}
void togglePanelView(Panel &panel,bool foldersFirst)
{
if(!panelViewAvailable(panel)) return;
auto &value=foldersFirst?panel.view.foldersFirst:panel.view.showHidden;
value=!value;
updatePanelView(panel);
}
void editPanelFilter(HWND owner,Panel &panel);
void editPanelColumns(HWND owner,Panel &panel);
void setTreePanelMode(Panel &panel)
{
if(panel.archive || !panelViewAvailable(panel)) return;
if(!panel.view.tree)
{
panel.view.tree=true;
updatePanelView(panel);
return;
}
panel.view.tree=false;
savePanelView(static_cast<int>(&panel-panels));
const auto row=currentPanelRow(panel);
const auto selected=row!=LB_ERR && panel.sizes[row]!=L"Up"?panel.rows[row]:fs::path{};
const auto directory=selected.empty()?panel.directory:selected.parent_path();
panel.listReturnMarks=std::move(panel.tree.marks);
stopTreeBranches(panel);
openOn(panel,directory,false,panel.peer,selected,{},panel.ftp);
}
void toggleAutomaticPanelSizes(Panel &panel)
{
if(panel.archive || !panelViewAvailable(panel)) return;
panel.view.automaticSizes=!panel.view.automaticSizes;
savePanelView(static_cast<int>(&panel-panels));
if(panel.view.automaticSizes) queueAutomaticPanelSizes(panel,true);
else cancelFolderSizes(panel);
}
void panelViewAction(HWND owner,Panel &panel,int action)
{
if(action>=0 && action<4) sortPanel(panel,static_cast<PanelSort>(action));
else if(action==5) editPanelFilter(owner,panel);
else if(action==4 || action==6) togglePanelView(panel,action==4);
else if(action==7) setTreePanelMode(panel);
else if(action==8) toggleAutomaticPanelSizes(panel);
else if(action==9) editPanelColumns(owner,panel);
}
LRESULT CALLBACK panelHeadingInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
const auto index=GetDlgCtrlID(window)-140;
auto &panel=panels[index];
if(message==WM_LBUTTONUP && panelViewAvailable(panel))
{
RECT bounds{};
GetClientRect(window,&bounds);
const auto columns=panelColumns(panel,bounds);
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
for(size_t i=0;i<=dateColumn;++i)
{
if(!PtInRect(&columns[i],point)) continue;
activatePanel(index);
panelClipboardContext=true;
sortPanel(panel,static_cast<PanelSort>(i));
break;
}
return 0;
}
if(message==WM_SETCURSOR && panelViewAvailable(panel))
{
SetCursor(LoadCursorW(nullptr,IDC_HAND));
return TRUE;
}
return DefSubclassProc(window,message,wp,lp);
}
void revealLocalFile(Panel &panel,const fs::path &path)
{
panel.view.revealedFile=path;
openOn(panel,path.parent_path(),false,{},path);
}
void showTransferProfiles(Panel &panel,TransferProtocol protocol,fs::path selection={})
{
TransferProfile root;
root.protocol=protocol;
openOn(panel,ftpRoot,false,{},std::move(selection),{},std::move(root));
}
void selectPanelPath(Panel &panel,const fs::path &path)
{
if(panel.scanRequest && path.parent_path()==panel.scanRequest->directory)
panel.scanRequest->selection=path;
const auto row=std::find(panel.rows.begin(),panel.rows.end(),path);
if(row==panel.rows.end()) return;
SendMessageW(panel.list,LB_SETCURSEL,row-panel.rows.begin(),0);
InvalidateRect(panel.list,nullptr,FALSE);
showFileDetails(panel);
}
void refreshChangedPanels()
{
for(auto &panel:panels)
{
if(panel.scan.valid()) continue;
const auto watch=panel.watch.handle;
if(watch==INVALID_HANDLE_VALUE || WaitForSingleObject(watch,0)!=WAIT_OBJECT_0) continue;
if(!FindNextChangeNotification(watch)) panel.watch.reset();
// Pass a copy because opening the folder rebuilds the panel.
const auto directory=panel.directory;
if(panel.view.automaticSizes) cancelFolderSizes(panel);
auto retry=std::move(panel.remoteRetry);
open(panel,directory);
panel.remoteRetry=std::move(retry);
}
}
void collectFolderSizes(Panel &panel);
bool queueFolderMeasurements(Panel &panel,const std::vector<fs::path> &folders,bool foreground);
bool calculateFolderSizes(Panel &panel,LRESULT current)
{
std::vector<fs::path> folders;
const bool all=panel.sizes[current]==L"Up";
for(size_t i=0;i<panel.rows.size();++i)
if((all || panel.marked[i]) && panel.sizes[i]==L"Folder") folders.push_back(panel.rows[i]);
if(folders.empty())
{
if(all)
{
setStatus(L"No folders to measure.");
return true;
}
if(panel.sizes[current]!=L"Folder") return false;
folders.push_back(panel.rows[current]);
}
return queueFolderMeasurements(panel,folders,true);
}
bool queueFolderMeasurements(Panel &panel,const std::vector<fs::path> &folders,bool foreground)
{
if(folders.empty() || panel.archive) return false;
if(const auto running=panel.folderSizeJob)
{
bool queued=false;
bool added=false;
{
std::lock_guard lock(running->mutex);
if(!running->finished)
{
for(const auto &folder:folders)
if(running->requested.insert(folder).second)
{
running->pending.push_back(folder);
panel.folderSizeWaiting.insert(folder);
added=true;
}
queued=true;
}
}
if(queued)
{
if(added) InvalidateRect(panel.list,nullptr,FALSE);
if(foreground) setStatus(L"Calculating folder sizes... [Esc]");
return true;
}
collectFolderSizes(panel);
}
auto job=std::make_shared<FolderSizeJob>();
job->pending.assign(folders.begin(),folders.end());
job->requested.insert(folders.begin(),folders.end());
job->current=folders.front();
auto task=[peer=panel.peer,ftp=panel.ftp,job]
{
const auto stop=job->stop.get_token();
try
{
const auto measure=[&](const auto &listDirectory)
{
for(;;)
{
fs::path folder;
{
std::lock_guard lock(job->mutex);
if(job->pending.empty() || stop.stop_requested())
{
job->finished=true;
return;
}
folder=std::move(job->pending.front());
job->pending.pop_front();
if(job->current!=folder)
{
job->current=folder;
job->started=GetTickCount64();
}
}
const auto size=measureFolder(folder,stop,listDirectory);
if(stop.stop_requested()) continue;
std::lock_guard lock(job->mutex);
job->completed.emplace(folder,size);
job->current.clear();
}
};
if(ftp)
{
TransferSession host(*ftp);
measure([&](const fs::path &directory,const FileVisitor &visit)
{
return host.list(directory,visit,stop)==ERROR_NO_MORE_FILES;
});
}
else
{
FilesConnection host(peer?&*peer:nullptr);
measure([&](const fs::path &directory,const FileVisitor &visit)
{
return listMeasuredDirectory(host,directory,visit,stop);
});
}
}
catch(const std::exception &)
{
std::lock_guard lock(job->mutex);
if(!job->current.empty()) job->completed.try_emplace(job->current,FolderSize{0,true,true});
for(const auto &folder:job->pending) job->completed.try_emplace(folder,FolderSize{0,true,true});
job->finished=true;
}
};
try {std::thread(std::move(task)).detach();}
catch(const std::system_error &error)
{
setStatus(fileError(error));
return true;
}
panel.folderSizeJob=std::move(job);
panel.folderSizeWaiting.insert(folders.begin(),folders.end());
InvalidateRect(panel.list,nullptr,FALSE);
if(foreground) setStatus(L"Calculating folder sizes... [Esc]");
return true;
}
void queueAutomaticPanelSizes(Panel &panel,bool refresh)
{
if(!panel.view.automaticSizes || panel.findOrigin || transferProfileList(panel)) return;
std::vector<fs::path> folders;
for(size_t i=0;i<panel.rows.size();++i)
{
const auto &path=panel.rows[i];
if(panel.sizes[i]!=L"Folder" || (!refresh && panel.folderSizes.contains(path))) continue;
const auto metadata=panel.metadata.find(path);
if(metadata!=panel.metadata.end() && canExpandTreeEntry(metadata->second)) folders.push_back(path);
}
queueFolderMeasurements(panel,folders,false);
}
void collectFolderSizes(Panel &panel)
{
const auto job=panel.folderSizeJob;
if(!job) return;
FolderSizes completed;
fs::path spinner;
bool finished;
{
std::lock_guard lock(job->mutex);
completed.swap(job->completed);
finished=job->finished;
if(!finished && GetTickCount64()-job->started>=folderSpinnerDelay)
spinner=job->current;
}
if(spinner!=panel.folderSpinner) invalidateFolderSizeRow(panel,panel.folderSpinner);
panel.folderSpinner=std::move(spinner);
invalidateFolderSizeRow(panel,panel.folderSpinner);
for(const auto &[path,size]:completed)
{
panel.folderSizeWaiting.erase(path);
auto reported=size;
if(const auto previous=panel.folderSizes.find(path);
size.failed && previous!=panel.folderSizes.end() && (!previous->second.failed || previous->second.previous))
{
reported.bytes=previous->second.bytes;
reported.previous=true;
}
panel.folderSizes.insert_or_assign(path,reported);
invalidateFolderSizeRow(panel,path);
}
if(finished) cancelFolderSizes(panel);
if(!completed.empty()) updateSelectionSummary(panel);
if((finished || !completed.empty()) && &panel==&panels[active]) showFileDetails(panel);
}
void openSelectedText(const Panel &panel, bool edit, bool external,bool hex=false);
ks::files::ImageEditDialogs imageEditDialogs();
ks::files::TextDialogs textWindowDialogs();
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);
INT_PTR confirmTextSave(HWND owner,bool draft);
bool chooseTextSaveOptions(HWND owner,fs::path &destination,ks::files::TextSaveFormat &format);
INT_PTR paintTextDialog(HWND window, UINT message, WPARAM wp, LPARAM lp, const wchar_t *caption);
INT_PTR paintSearchDialog(HWND window,UINT message,WPARAM wp,LPARAM lp);
ks::files::FarDropDownPalette farDropDownPalette();
void prepareCopyDialog(HWND dialog);
void prepareTextDialog(HWND dialog);
void showTextMessage(HWND owner,const wchar_t *text);
void editFilesAppearance(HWND owner,AppearanceArea area);
void startPeerAction(std::packaged_task<std::wstring()> task,const std::wstring &status)
{
pendingPeerAction=task.get_future();
try {std::thread(std::move(task)).detach();}
catch(const std::system_error &error)
{
pendingPeerAction={};
setStatus(fileError(error));
return;
}
setStatus(status);
}
void wakeRemotePeer(const FilesPeer &peer)
{
if(pendingPeerAction.valid())
{
setStatus(L"A remote PC request is already in progress.");
return;
}
std::packaged_task<std::wstring()> task([peer]
{
try
{
ks::lan::wakeFilesPeer(peer.id);
return peer.name+L": Wake-on-LAN packet sent.";
}
catch(const std::system_error &error)
{
return peer.name+L": Could not send Wake-on-LAN packet. "+fileError(error);
}
catch(const std::exception &error)
{
return peer.name+L": "+ks::wide(error.what());
}
});
startPeerAction(std::move(task),L"Sending Wake-on-LAN packet to "+peer.name+L"...");
}
void runActivePeerAction(HWND owner,bool update)
{
if(!panels[active].peer) return;
if(pendingPeerAction.valid())
{
setStatus(L"A remote PC request is already in progress.");
return;
}
const auto peer=*panels[active].peer;
const auto question=update
? L"Update KSwitcher on "+peer.name+L"? Open KSwitcher windows there will close if an update is available."
: L"Hibernate "+peer.name+L"?";
if(showFilesNotice(owner,question.c_str(),update?L"Update remote KSwitcher":L"Hibernate remote PC",
{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
return;
std::packaged_task<std::wstring()> task([peer,update]
{
const auto prefix=peer.name+L": ";
const auto unconfirmed=prefix+(update?L"Could not confirm receipt of the update request."
:L"Hibernation could not be confirmed.");
try
{
FilesConnection host(&peer);
checkFileReply(host.call({{"action",update?"update":"hibernate"}}));
return prefix+(update?L"Update requested. See the remote KSwitcher log for the result."
:L"Windows accepted the hibernation request.");
}
catch(const std::system_error &error)
{
switch(error.code().value())
{
case ERROR_ACCESS_DENIED:
return prefix+(update?L"Remote updates are disabled. Check Files settings on this PC."
:L"Hibernation is not allowed. Check the remote Files settings.");
case ERROR_INVALID_FUNCTION:
return prefix+(update?L"This version of KSwitcher cannot accept remote update requests."
:L"Update KSwitcher to enable remote hibernation.");
case ERROR_PRIVILEGE_NOT_HELD:
return prefix+L"Windows denied the hibernation privilege.";
default:
return unconfirmed+L" "+fileError(error);
}
}
catch(const std::exception &)
{
return unconfirmed;
}
});
startPeerAction(std::move(task),
(update?L"Requesting a KSwitcher update on ":L"Requesting hibernation for ")+peer.name+L"...");
}
LRESULT ftpDriveRow() {return lanDrivePicker?-1:static_cast<LRESULT>(drivePaths.size())+1;}
LRESULT sftpDriveRow() {return lanDrivePicker?-1:ftpDriveRow()+1;}
LRESULT smbDriveRow() {return lanDrivePicker?-1:sftpDriveRow()+1;}
LRESULT recentDriveRow() {return lanDrivePicker?-1:smbDriveRow()+1;}
LRESULT lanHeaderRow() {return recentDriveRow()+1;}
bool driveSourceRow(LRESULT row)
{
return row>=0 && (row<static_cast<LRESULT>(drivePaths.size()) || row==ftpDriveRow() ||
row==sftpDriveRow() || row==smbDriveRow() || row==recentDriveRow());
}
bool panelItemPropertiesAvailable(const Panel &panel);
void showPanelItemProperties(HWND owner,Panel &panel);
bool panelLockSearchAvailable(const Panel &panel);
void showPanelLockProcesses(HWND owner,Panel &panel);
void showProcesses(HWND owner,std::vector<fs::path> paths={});
bool gitChangesAvailable(const Panel &panel);
void openGitChanges(HWND owner,const Panel &panel);
void showEnvironmentPanel(HWND owner);
void showFilesHelp(HWND owner,ks::files::FilesHelpTopic topic);
void showFilesLog(HWND owner);
void showFilesMcp(HWND owner);
void editFilesKeySchemes(HWND owner,FilesKey initial,FilesKeySettings *pending=nullptr);
void showCommandHistory(HWND owner);
bool selectablePickerRow(LRESULT row)
{
if(row<0) return false;
if(folderPicker) return static_cast<size_t>(row)<folderPicker->locations.size();
if(commandPicker)
return static_cast<size_t>(row)<commandActions.size() && commandActions[row]>=0;
return driveSourceRow(row) || remoteDriveRows.contains(row);
}
void selectDrive()
{
auto row=SendMessageW(picker,LB_GETCURSEL,0,0);
if(!selectablePickerRow(row)) return;
if(folderPicker)
{
const auto location=folderPicker->locations[row];
auto &panel=panels[pickerPanel];
hidePicker();
openFolderLocation(panel,location);
return;
}
if(commandPicker) row=commandActions[row];
const auto remote=remoteDriveRows.find(row);
hidePicker();
showMenu(false);
if(commandPicker)
{
if(row<0) return;
auto owner=GetParent(picker);
if(menuIndex==0 || menuIndex==4)
{
const int index=menuIndex==4;
if(row>4) panelViewAction(owner,panels[index],static_cast<int>(row)-5);
else if(row==4) chooseDrive(index);
else setMode(index,static_cast<PanelMode>(row));
}
else if(menuIndex==2 && row==3) showFolderShortcuts(panels[active],-1);
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) findPanelFiles(owner,panels[active]);
else if(menuIndex==2 && row==10) toggleQuickView(owner);
else if(menuIndex==2 && row==11) copyFullPanelPath(owner,panels[active]);
else if(menuIndex==2 && row==12) openSpaceAnalyzer(owner,panels[active]);
else if(menuIndex==2 && row==13) openSelectedText(panels[active],false,false,true);
else if(menuIndex==2 && row==14) ks::files::showAllViewerBookmarks(owner,textWindowDialogs());
else if(menuIndex==2 && row==15) showProcesses(owner);
else if(menuIndex==2 && row==16) openGitChanges(owner,panels[active]);
else if(menuIndex==2 && row==17) showEnvironmentPanel(owner);
else if(menuIndex==2 && row==18) swapPanels(owner);
else if(menuIndex==2 && row==19) showCommandHistory(owner);
else if(menuIndex==2 && row==20) editFilesKeySchemes(owner,FilesKey::Refresh);
else if(menuIndex==2 && row==21) editFilesAppearance(owner,terminalVisible?AppearanceArea::terminal:AppearanceArea::panels);
else if(menuIndex==2 && row==22) showFilesHelp(owner,terminalVisible?ks::files::FilesHelpTopic::terminal:ks::files::FilesHelpTopic::panels);
else if(menuIndex==2 && row==23) showFilesLog(owner);
else if(menuIndex==2 && row==24) showFilesMcp(owner);
else if(menuIndex==1 && row==4) createArchive(owner,panels[active]);
else if(menuIndex==1 && row==5) showPanelItemProperties(owner,panels[active]);
else if(menuIndex==1 && row==6) showPanelLockProcesses(owner,panels[active]);
else
{
const int command=menuIndex==1?113+static_cast<int>(row):110+static_cast<int>(row);
SendMessageW(owner,WM_COMMAND,MAKEWPARAM(command,BN_CLICKED),0);
}
return;
}
if(row>=0 && static_cast<size_t>(row)<drivePaths.size())
openOn(panels[pickerPanel],drivePaths[row],false,{});
else if(row==ftpDriveRow() || row==sftpDriveRow())
{
const auto protocol=row==sftpDriveRow()?TransferProtocol::sftp:TransferProtocol::ftp;
if(loadTransferProfiles(protocol))
{
activatePanel(pickerPanel);
showTransferProfiles(panels[pickerPanel],protocol);
}
else setStatus(std::wstring(L"Cannot load saved ")+transferProtocolName(protocol)+L" connections.");
}
else if(row==smbDriveRow())
{
activatePanel(pickerPanel);
showSmbProfiles(panels[pickerPanel]);
}
else if(row==recentDriveRow())
{
activatePanel(pickerPanel);
showRecentFolders(panels[pickerPanel]);
}
else if(remote!=remoteDriveRows.end())
{
const auto &choice=remote->second;
if(choice.path) openOn(panels[pickerPanel],*choice.path,false,choice.peer);
else wakeRemotePeer(choice.peer);
}
}
LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
{
if(folderPicker && msg==WM_LBUTTONUP)
{
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
const auto result=DefSubclassProc(window,msg,wp,lp);
if(folderPicker && !HIWORD(hit) && selectablePickerRow(LOWORD(hit)))
{
SendMessageW(window,LB_SETCURSEL,LOWORD(hit),0);
selectDrive();
}
return result;
}
if(msg==WM_KEYDOWN && (wp==VK_UP || wp==VK_DOWN))
{
const auto count=SendMessageW(window,LB_GETCOUNT,0,0);
const auto current=SendMessageW(window,LB_GETCURSEL,0,0);
const auto row=ks::files::adjacentMenuRow(current,count,wp==VK_UP?-1:1,selectablePickerRow);
if(row!=current) SendMessageW(window,LB_SETCURSEL,row,0);
return 0;
}
if(msg==WM_KEYDOWN && (wp==VK_PRIOR || wp==VK_NEXT || wp==VK_HOME || wp==VK_END))
{
const auto result=DefSubclassProc(window,msg,wp,lp);
const auto row=SendMessageW(window,LB_GETCURSEL,0,0);
if(!selectablePickerRow(row))
{
const auto count=SendMessageW(window,LB_GETCOUNT,0,0);
const int direction=(wp==VK_PRIOR || wp==VK_END)?-1:1;
SendMessageW(window,LB_SETCURSEL,
ks::files::adjacentMenuRow(row,count,direction,selectablePickerRow),0);
}
return result;
}
if(msg==WM_LBUTTONDOWN || msg==WM_LBUTTONDBLCLK || (msg==WM_MOUSEMOVE && (wp&MK_LBUTTON)))
{
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
if(!HIWORD(hit) && !selectablePickerRow(LOWORD(hit))) return 0;
}
if(msg==WM_CAPTURECHANGED) driveWakeAction.cancel();
if(!commandPicker && !folderPicker && (msg==WM_LBUTTONDOWN || msg==WM_LBUTTONUP || msg==WM_LBUTTONDBLCLK))
{
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
const int row=HIWORD(hit)?-1:LOWORD(hit);
const auto choice=remoteDriveRows.find(row);
const bool wake=choice!=remoteDriveRows.end() && !choice->second.path;
if(msg==WM_LBUTTONUP && driveWakeAction.pressed())
{
if(driveWakeAction.release(window,row,wake && driveWakeAction.hit(window,row,lp,cellWidth)))
{
SendMessageW(window,LB_SETCURSEL,row,0);
selectDrive();
}
return 0;
}
if(wake && msg!=WM_LBUTTONUP)
{
if(msg==WM_LBUTTONDOWN && driveWakeAction.hit(window,row,lp,cellWidth))
driveWakeAction.press(window,row);
return 0;
}
}
if(!commandPicker && !folderPicker && msg==WM_CHAR)
{
const auto key=towupper(static_cast<wchar_t>(wp));
LRESULT row=LB_ERR;
if(key>=L'A' && key<=L'Z')
{
const auto disk=std::find_if(drivePaths.begin(),drivePaths.end(),[key](const fs::path &path)
{ return path.native().front()==key; });
if(disk!=drivePaths.end()) row=disk-drivePaths.begin();
}
else if(key==ftpDriveDigit) row=ftpDriveRow();
else if(key>=L'0' && key<=L'9')
{
const auto choice=std::find_if(remoteDriveRows.begin(),remoteDriveRows.end(),
[key](const auto &entry){return entry.second.digit==key;});
if(choice!=remoteDriveRows.end()) row=choice->first;
}
if(row!=LB_ERR)
{
SendMessageW(window,LB_SETCURSEL,row,0);
selectDrive();
return 0;
}
}
if(!commandPicker && !folderPicker && (msg==WM_MOUSEMOVE || msg==WM_MOUSELEAVE))
{
int row=-1;
if(msg==WM_MOUSEMOVE)
{
TRACKMOUSEEVENT tracking{sizeof(tracking),TME_LEAVE,window,0};
TrackMouseEvent(&tracking);
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
if(!HIWORD(hit))
{
const auto choice=remoteDriveRows.find(LOWORD(hit));
if(driveSourceRow(LOWORD(hit)) ||
(choice!=remoteDriveRows.end() && !choice->second.path &&
driveWakeAction.hit(window,LOWORD(hit),lp,cellWidth)))
row=LOWORD(hit);
}
}
if(driveHover!=row)
{
driveHover=row;
InvalidateRect(window,nullptr,FALSE);
}
}
if(msg==WM_KEYDOWN && wp==VK_ESCAPE)
{
hidePicker();
return 0;
}
if(msg==WM_KEYDOWN && wp==VK_RETURN){selectDrive();return 0;}
if(msg==WM_KEYDOWN && (wp==VK_LEFT || wp==VK_RIGHT) && IsWindowVisible(menuBar))
{
int next=(menuIndex+(wp==VK_LEFT?4:1))%5;
SendMessageW(GetParent(window),WM_COMMAND,MAKEWPARAM(130+next,BN_CLICKED),0);
return 0;
}
return DefSubclassProc(window,msg,wp,lp);
}
FilesPeerLookup lookupFilesPeers(HWND owner)
{
FilesPeerLookup lookup;
lookup.service=FindWindowW(L"KSwitcher.Main",L"KSwitcher");
if(lookup.service)
{
COPYDATASTRUCT request{FilesLanPeers,0,nullptr};
DWORD_PTR result{};
auto *previous=std::exchange(peerLookupRequest,&lookup);
SetLastError(ERROR_SUCCESS);
const auto delivered=SendMessageTimeoutW(lookup.service,WM_COPYDATA,
reinterpret_cast<WPARAM>(owner),reinterpret_cast<LPARAM>(&request),
SMTO_ABORTIFHUNG|SMTO_ERRORONEXIT,350,&result);
const auto error=GetLastError();
peerLookupRequest=previous;
if(!delivered || result!=1 || !lookup.received)
{
lookup.peers.clear();
if(delivered && result!=1)
lookup.error=L"KSwitcher rejected the peer request";
else if(delivered)
lookup.error=L"Invalid peer list from KSwitcher";
else if(error==ERROR_ACCESS_DENIED)
lookup.error=L"Access denied by Windows";
else if(error==ERROR_TIMEOUT)
lookup.error=L"KSwitcher did not respond in time";
else
lookup.error=L"Peer request failed (Windows code "+std::to_wstring(error)+L")";
ks::log(L"LAN Files peer lookup failed: delivered="+std::to_wstring(delivered!=0)+
L", reply="+std::to_wstring(result)+L", Windows error="+std::to_wstring(error));
}
}
else
{
lookup.error=L"KSwitcher is not running";
ks::log(L"LAN Files peer lookup failed: local KSwitcher window not found");
}
return lookup;
}
void queryDrivePeers()
{
auto lookup=lookupFilesPeers(GetParent(picker));
drivePeers=std::move(lookup.peers);
drivePeerLookupError=std::move(lookup.error);
}
void startDriveQuery(DriveQuery &query)
{
if(query.peer.address.empty()) return;
std::packaged_task<Json()> task([peer=query.peer]
{
FilesConnection host(&peer);
auto reply=host.call({{"action","drives"}});
checkFileReply(reply);
return reply.at("drives");
});
query.pending=task.get_future();
try {std::thread(std::move(task)).detach();}
catch(const std::system_error &e){query.pending={};query.error=fileError(e);}
}
std::array<std::wstring,3> driveLabels(wchar_t letter,UINT type,uint64_t total,uint64_t free)
{
const wchar_t *types[]{L"unknown",L"unavailable",L"removable",L"fixed",L"network",L"CD-ROM",L"RAM disk"};
return {std::wstring(1,letter)+L": "+types[type<std::size(types)?type:0],
total?formatSize(total):L"—",total?formatSize(free):L"—"};
}
void layoutDrivePicker(int selected,bool focus)
{
HWND owner=GetParent(picker);
RECT panel{};
GetWindowRect(panels[pickerPanel].list,&panel);
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT*>(&panel),2);
const int panelWidth=panel.right-panel.left;
const auto frame=dialogFrameMetrics(GetDpiForWindow(owner));
const int inset=frame.content(),vertical=dialogListInset(frame,textHeight);
const int limit=lanDrivePicker?panelWidth:panelWidth*4/5;
const int width=std::clamp(drivePickerWidth,90,std::max(90,limit-2*inset));
const int height=std::min(std::max(1,(static_cast<int>(panel.bottom-panel.top)-2*vertical)/textHeight),
static_cast<int>(SendMessageW(picker,LB_GETCOUNT,0,0)))*textHeight;
const int x=panel.left+(panel.right-panel.left-width)/2;
const int y=panel.top+(panel.bottom-panel.top-height)/2;
constexpr UINT flags=SWP_SHOWWINDOW|SWP_NOACTIVATE|SWP_NOCOPYBITS;
auto layout=BeginDeferWindowPos(2);
if(layout) layout=DeferWindowPos(layout,pickerFrame,HWND_TOP,
x-inset,y-vertical,width+2*inset,height+2*vertical,flags);
if(layout) layout=DeferWindowPos(layout,picker,HWND_TOP,x,y,
std::max(1,width-scrollBarWidth(picker)),height,flags);
if(!layout || !EndDeferWindowPos(layout))
{
SetWindowPos(pickerFrame,HWND_TOP,x-inset,y-vertical,width+2*inset,height+2*vertical,flags);
SetWindowPos(picker,HWND_TOP,x,y,std::max(1,width-scrollBarWidth(picker)),height,flags);
}
RedrawWindow(pickerFrame,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW);
SendMessageW(picker,LB_SETCURSEL,selected,0);
if(focus) SetFocus(picker);
}
void showRemoteDrives(bool focus=false,int initialRow=0)
{
auto selection=SendMessageW(picker,LB_GETCURSEL,0,0);
std::optional<DriveChoice> previous;
if(auto row=remoteDriveRows.find(selection);row!=remoteDriveRows.end()) previous=row->second;
if(selection>=lanHeaderRow()) selection=-1;
if(focus) selection=initialRow;
const auto top=SendMessageW(picker,LB_GETTOPINDEX,0,0);
for(auto count=SendMessageW(picker,LB_GETCOUNT,0,0);count>static_cast<LRESULT>(drivePaths.size());--count)
SendMessageW(picker,LB_DELETESTRING,count-1,0);
remoteDriveRows.clear();
const auto add=[](const std::wstring &label)
{
drivePickerWidth=std::max(drivePickerWidth,static_cast<int>(label.size()+2)*cellWidth);
return SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
};
if(!lanDrivePicker)
{
add(L"");
add(L"FTP");
add(L"SFTP");
add(L"SMB");
add(L"Recent folders");
}
add(L"KSwitcher LAN");
if(!drivePeerLookupError.empty()) add(L" "+drivePeerLookupError);
else if(driveQueries.empty()) add(L" No paired computers");
LRESULT firstDrive=-1,matchingDrive=-1;
const auto &current=panels[pickerPanel];
for(const auto &query:driveQueries)
{
add(query.peer.name);
const auto addChoice=[&](const std::wstring &label,std::optional<fs::path> path)
{
const auto row=add(label);
if(row<0) return;
if(previous && previous->peer.id==query.peer.id && previous->path==path) selection=row;
if(firstDrive<0) firstDrive=row;
if(current.peer && current.peer->id==query.peer.id && path==current.directory.root_path())
matchingDrive=row;
const auto id=std::pair{query.peer.id,path};
constexpr std::wstring_view available=L"234567890";
auto digit=driveDigits.find(id);
if(digit==driveDigits.end() && driveDigits.size()<available.size())
digit=driveDigits.emplace(id,available[driveDigits.size()]).first;
remoteDriveRows.emplace(row,DriveChoice{query.peer,std::move(path),
digit==driveDigits.end()?L'\0':digit->second});
};
if(query.peer.address.empty())
{
const std::wstring status=nextDriveRefresh?L" Looking for PC...":L" Offline";
addChoice(status+L" \t"+driveWakeLabel,std::nullopt);
}
else if(query.pending.valid()) add(L" Loading drives...");
else if(!query.error.empty()) add(L" "+query.error);
else if(query.drives.empty()) add(L" No drives");
for(const auto &entry:query.drives)
{
const auto root=filePath(entry.at("path"));
if(root.native().size()!=3 || root.native().front()<L'A' || root.native().front()>L'Z') continue;
const auto labels=driveLabels(root.native().front(),entry.at("type"),entry.at("total"),entry.at("free"));
addChoice(L" "+labels[0]+L" "+labels[1]+L" "+labels[2],root);
}
}
if(lanDrivePicker && selection<=0) selection=matchingDrive>=0?matchingDrive:firstDrive;
layoutDrivePicker(static_cast<int>(selection),focus);
InvalidateRect(picker,nullptr,FALSE);
if(!focus) SendMessageW(picker,LB_SETTOPINDEX,top,0);
}
void pollDriveQueries(HWND owner)
{
if(commandPicker || folderPicker || !IsWindowVisible(picker))
{
KillTimer(owner,driveQueryTimer);
driveQueries.clear();
return;
}
bool changed=false, pending=false;
const auto now=GetTickCount64();
if(nextDriveRefresh && now>=nextDriveRefresh)
{
nextDriveRefresh=now<driveRefreshDeadline?now+2000:0;
queryDrivePeers();
for(const auto &peer:drivePeers)
{
auto entry=std::find_if(driveQueries.begin(),driveQueries.end(),[&](const DriveQuery &query)
{return query.peer.id==peer.id;});
if(entry==driveQueries.end())
{
auto &query=driveQueries.emplace_back();
query.peer=peer;
startDriveQuery(query);
}
else if(!entry->pending.valid() && (entry->peer.address!=peer.address ||
entry->peer.address.empty() || !entry->error.empty()))
{
entry->peer=peer;
entry->drives=Json::array();
entry->error.clear();
startDriveQuery(*entry);
}
}
changed=true;
}
for(auto &query:driveQueries)
{
if(!query.pending.valid()) continue;
if(query.pending.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
{
pending=true;
continue;
}
try {query.drives=query.pending.get();}
catch(const std::system_error &e)
{
ks::log(L"LAN Files drive query for "+query.peer.name+L" ("+ks::wide(query.peer.address)+
L") failed: Windows error "+std::to_wstring(e.code().value()));
if(e.code()==std::error_code(WSAETIMEDOUT,std::system_category()))
query.error=L"Connection timed out";
else
query.error=query.peer.filesBrowse?fileError(e):L"Check build / TCP 45885";
}
catch(const std::exception &)
{
ks::log(L"LAN Files drive query failed: unexpected error");
query.error=query.peer.filesBrowse?L"Cannot reach TCP 45885":L"Check build / TCP 45885";
}
changed=true;
}
if(!pending && drivePeerLookupError.empty() &&
std::none_of(driveQueries.begin(),driveQueries.end(),[](const DriveQuery &query)
{return query.peer.address.empty() || !query.error.empty();}))
nextDriveRefresh=0;
if(changed) showRemoteDrives();
if(!pending && !nextDriveRefresh) KillTimer(owner,driveQueryTimer);
}
void chooseDrive(int index,bool fromMenu,bool lanOnly)
{
lanDrivePicker=lanOnly;
if(quickViewWindow && index!=quickViewSource) toggleQuickView(GetParent(picker));
folderPicker.reset();
commandPicker=false;
if (!fromMenu) showMenu(false);
pickerPanel=index;
drivePaths.clear();
driveDigits.clear();
driveHover=-1;
SendMessageW(picker,LB_RESETCONTENT,0,0);
queryDrivePeers();
remoteDriveRows.clear();
driveQueries.clear();
for(const auto &peer:drivePeers)
{
auto &query=driveQueries.emplace_back();
query.peer=peer;
startDriveQuery(query);
}
const auto now=GetTickCount64();
nextDriveRefresh=now+500;
driveRefreshDeadline=now+20000;
const DWORD disks=lanOnly?0:GetLogicalDrives();
int selected=0;
int textWidth=0;
auto dc=GetDC(picker);
auto oldFont=dc ? SelectObject(dc,mono) : nullptr;
std::vector<std::array<std::wstring,3>> driveColumns;
std::array<LONG,3> columnWidths{};
SIZE space{cellWidth,0};
if(dc) GetTextExtentPoint32W(dc,L" ",1,&space);
for(int letter=0;letter<26;++letter)
{
if(!(disks & (1UL<<letter))) continue;
wchar_t drive[]{static_cast<wchar_t>(L'A'+letter),L':',L'\\',0};
const auto type=GetDriveTypeW(drive);
ULARGE_INTEGER total{},free{};
if(type==DRIVE_FIXED || type==DRIVE_RAMDISK) GetDiskFreeSpaceExW(drive,nullptr,&total,&free);
driveColumns.push_back(driveLabels(drive[0],type,total.QuadPart,free.QuadPart));
for(size_t i=0;i<columnWidths.size();++i)
{
const auto &value=driveColumns.back()[i];
SIZE extent{static_cast<LONG>(value.size())*cellWidth,0};
if(dc) GetTextExtentPoint32W(dc,value.c_str(),static_cast<int>(value.size()),&extent);
columnWidths[i]=std::max(columnWidths[i],extent.cx);
}
if(fs::path(drive)==panels[index].directory.root_path()) selected=static_cast<int>(drivePaths.size());
drivePaths.emplace_back(drive);
}
LONG edge=0;
for(size_t i=0;i<driveColumnStarts.size();++i)
{
driveColumnStarts[i]=edge+space.cx;
edge=driveColumnStarts[i]+columnWidths[i]+space.cx+1;
}
if(!driveColumns.empty()) textWidth=edge-1;
for(const auto &values:driveColumns)
{
const auto label=values[0]+L"\t"+values[1]+L"\t"+values[2];
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
}
if(const auto &profile=panels[index].ftp) selected=static_cast<int>(
profile->protocol==TransferProtocol::sftp?sftpDriveRow():ftpDriveRow());
if(dc)
{
if(oldFont) SelectObject(dc,oldFont);
ReleaseDC(picker,dc);
}
HWND owner=GetParent(picker);
drivePickerWidth=textWidth;
showRemoteDrives(true,selected);
SetTimer(owner,driveQueryTimer,100,nullptr);
if (fromMenu) showMenu(true);
RedrawWindow(owner,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_UPDATENOW);
}
bool openPanelPathWithSystem(const Panel &panel,const fs::path &path,const wchar_t *verb,
const wchar_t *failureMessage)
{
if (reinterpret_cast<INT_PTR>(ShellExecuteW(GetParent(panel.list), verb, path.c_str(), nullptr,
panel.directory.c_str(), SW_SHOWNORMAL)) > 32) return true;
setStatus(failureMessage);
return false;
}
void openPanelFile(const Panel &panel, const fs::path &file, const wchar_t *verb, const wchar_t *failureMessage)
{
if(panel.peer)
{
setStatus(L"Copy the remote file to a local panel before opening it.");
return;
}
std::error_code error;
if (!fs::is_regular_file(file, error))
{
if(!verb) setStatus(failureMessage);
return;
}
const auto extension=file.extension().wstring();
const auto isExtension=[&](const wchar_t *expected)
{
return CompareStringOrdinal(extension.c_str(),-1,expected,-1,TRUE)==CSTR_EQUAL;
};
if(!verb && (isExtension(L".bat") || isExtension(L".cmd")))
{
const auto command=L"& "+powerShellPath(file);
if(submitTerminalCommand(panel,command) && terminalRows<5)
{
terminalRows=5;
layout(GetParent(panel.list));
}
return;
}
const bool recordOpen=!verb;
if(!verb && isExtension(L".exe")) verb=L"open";
if(!openPanelPathWithSystem(panel,file,verb,failureMessage) || !recordOpen) return;
const auto command=L"start "+powerShellPath(file);
rememberCommand(command);
terminalHistoryIndex=terminalHistory.size();
const auto owner=GetParent(panel.list);
if(!ensureTerminalView(owner)) return;
appendTerminalOutput(ks::utf8(L"\r\n"+file.native()+L"\r\n"));
if(!terminalVisible && terminalRows==0)
{
terminalRows=5;
layout(owner);
}
terminalView.post(L"scroll-bottom");
}
void openSelectedWithSystem(const Panel &panel)
{
if(panel.ftp || panel.listing || panel.archive) return;
const auto row=currentPanelRow(panel);
if(row==LB_ERR) return;
if(panel.peer)
{
setStatus(L"Select a local item before opening it with Windows.");
return;
}
const bool folder=panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up";
openPanelPathWithSystem(panel,panel.rows[row],folder?L"explore":nullptr,
folder?L"Cannot open the selected folder in File Explorer.":L"Cannot open the selected file.");
}
#include "files_lavender_dialogs.inl"
#include "files_dialog_input.inl"
ks::files::TextDialogs textWindowDialogs()
{
return {confirmTextSave,paintTextDialog,paintSearchDialog,prepareTextDialog,editFilesAppearance,showTextMessage,readFilesFont,
farDropDownPalette,FilesModalDialog::run,FilesModalDialog::finish,FilesModalDialog::dismissOwned,
[](HWND owner)
{
return showFilesNotice(owner,L"This file is already open. Switch to its window?",L"Files",
{.confirm=true})==IDYES;
},chooseTextSaveOptions,
[](HWND owner)
{
return showFilesNotice(owner,L"The file changed outside Files. Reload the disk version?",
L"File changed on disk",{.confirm=true,.tone=FilesNoticeTone::warning,
.accept=L"&Reload",.decline=L"&Keep buffer"})==IDYES;
},readAreaScale};
}
void refreshQuickView(const Panel &panel)
{
if(!quickViewWindow || &panel!=&panels[quickViewSource]) return;
const auto row=currentPanelRow(panel);
const bool file=!panel.peer && !panel.ftp && !panel.listing && !panel.archive && row!=LB_ERR &&
panel.sizes[row]!=L"Folder" && panel.sizes[row]!=L"Up";
const auto path=file?panel.rows[row]:fs::path{};
if(file && ks::files::isImagePath(path) && !quickImageWindow)
{
try {quickImageWindow=ks::files::createImageQuickView(GetParent(panel.list),textWindowDialogs());}
catch(const std::exception &) {}
}
const bool image=quickImageWindow && file && ks::files::isImagePath(path);
ks::files::previewQuickViewFile(quickViewWindow,image?fs::path{}:path);
if(quickImageWindow) ks::files::previewImageQuickViewFile(quickImageWindow,image?path:fs::path{});
if(std::exchange(quickViewDisplaysImage,image)!=image) layout(GetParent(panel.list));
}
void closeQuickViews()
{
if(quickImageWindow) DestroyWindow(std::exchange(quickImageWindow,nullptr));
if(quickViewWindow) DestroyWindow(std::exchange(quickViewWindow,nullptr));
quickViewDisplaysImage=false;
}
void toggleQuickView(HWND owner)
{
if(quickViewWindow)
{
closeQuickViews();
layout(owner);
restoreCommandFocus();
return;
}
const auto &panel=panels[active];
if(panel.peer || panel.ftp || panel.archive || terminalVisible)
{
setStatus(L"Quick View requires a visible local file pane.");
return;
}
try {quickViewWindow=ks::files::createQuickView(owner,textWindowDialogs());}
catch(const std::exception &) {}
if(!quickViewWindow)
{
setStatus(L"Could not open Quick View.");
return;
}
quickViewSource=active;
refreshQuickView(panel);
layout(owner);
}
ks::files::RemoteTextSource transferTextSource(const TransferProfile &profile);
void openPanelImage(const Panel &panel,const fs::path &path,const ks::files::RemoteTextSource *source=nullptr)
{
std::vector<fs::path> images;
for(size_t row=0;row<panel.rows.size();++row)
if(panel.sizes[row]!=L"Folder" && panel.sizes[row]!=L"Up" && ks::files::isImagePath(panel.rows[row]))
images.push_back(panel.rows[row]);
ks::files::openImageWindow(GetParent(panel.list),std::move(images),path,textWindowDialogs(),
panel.peer?&*panel.peer:nullptr,source);
}
void openArchiveText(const Panel &panel,const fs::path &path,bool hex=false)
{
const auto file=panel.archive->file;
const auto member=path.lexically_relative(file);
const auto found=panel.archive->entries->find(member);
if(found==panel.archive->entries->end() || found->second.directory) return;
if(found->second.encrypted)
{
setStatus(L"This archive entry requires a password. Password-protected entries cannot be opened in Files.");
return;
}
const ks::files::RemoteTextSource archive{
"archive:"+ks::utf8(file.native()),file.filename().native(),
[file](const fs::path &original,const fs::path &cache,bool,const ks::files::ArchiveProgress &progress,uint64_t limit)
{
const auto relative=original.lexically_relative(file);
const auto entry=ks::files::readArchiveMember(file,relative,cache,limit,progress);
return ks::files::RemoteTextRevision{entry.size,entry.modified,false};
},{}};
if(!hex && ks::files::isImagePath(path)) openPanelImage(panel,path,&archive);
else ks::files::openRemoteTextWindow(GetParent(panel.list),path,false,textWindowDialogs(),archive,{},
false,{.hex=hex});
}
void openSelectedText(const Panel &panel, bool edit, bool external,bool hex)
{
if(panelListsLocations(panel)) return;
const auto row=currentPanelRow(panel);
if(row==LB_ERR || panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") return;
if(panel.archive)
{
if(edit || external) setStatus(L"Archive entries are read-only. Use F5 to extract them.");
else openArchiveText(panel,panel.rows[row],hex);
return;
}
if((panel.peer || panel.ftp) && external)
{
setStatus(L"Copy the remote file to a local panel before opening it.");
return;
}
const auto &path=panel.rows[row];
if(panel.ftp)
{
const auto ftp=transferTextSource(*panel.ftp);
if(!edit && !hex && ks::files::isImagePath(path)) openPanelImage(panel,path,&ftp);
else ks::files::openRemoteTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),ftp,{},false,{.hex=hex});
return;
}
if(external)
openPanelFile(panel,path,edit?L"edit":L"open",
edit?L"No editor is registered for this file.":L"Cannot open the selected file.");
else if(!edit && !hex && ks::files::isImagePath(path)) openPanelImage(panel,path);
else if(edit && !hex && !panel.peer && !windowsNetworkPath(path) && ks::files::isEditableImagePath(path))
{
const auto dialogs=imageEditDialogs();
ks::files::openImageWindow(GetParent(panel.list),{path},path,textWindowDialogs(),nullptr,nullptr,&dialogs);
}
else ks::files::openTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),
panel.peer?&*panel.peer:nullptr,{},false,{.hex=hex});
}
void enter(Panel &panel)
{
if(recentFolderList(panel)) {openRecentFolder(panel);return;}
if(panel.listing) {enterSmbPanel(panel);return;}
const auto row=currentPanelRow(panel);
if(row!=LB_ERR)
{
if(transferProfileList(panel))
{
const auto &profiles=transferProfiles(panel.ftp->protocol).rows;
if(static_cast<size_t>(row)<profiles.size()) openOn(panel,{},false,{},{},{},profiles[row]);
return;
}
auto target = panel.rows[row];
if(panel.archive)
{
if(panel.sizes[row]==L"Up") parentArchive(panel);
else if(panel.sizes[row]==L"Folder") open(panel,target);
else openArchiveText(panel,target);
return;
}
if(panel.findOrigin)
{
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;
if(panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") open(panel,target,true);
else if(panel.ftp) openSelectedText(panel,false,false);
else if(!panel.peer && ks::files::isArchivePath(target))
openOn(panel,target,false,{},{},{},{},{},ArchiveLocation{target,{}});
else openPanelFile(panel, target, nullptr, L"Cannot open the selected file.");
}
}
enum class ConflictMode { ask, overwrite, skip, rename, append, newer };
struct CopyDestination
{
fs::path directory, newName;
bool useSourcePeer{};
};
struct CopyOptions
{
std::wstring mask=L"*";
std::vector<fs::path> additional;
bool preserveTime=true, preservePermissions{};
};
struct CopyRequest
{
std::vector<fs::path> sources;
fs::path destination;
fs::path newName;
fs::path otherDirectory;
ConflictMode conflictMode{};
bool askReadOnly=true;
bool move{};
const FilesPeer *sourcePeer{}, *destinationPeer{}, *otherPeer{};
std::future<CopyDestination> validation;
std::wstring ftpDestination;
bool upload{};
bool ftpRename{}, externalSources{}, archiveSource{};
CopyOptions options;
};
bool directoryExists(const FilesPeer *peer,const fs::path &path)
{
if(!peer)
{
std::error_code error;
return fs::is_directory(path,error);
}
FilesConnection host(peer);
const auto info=statFile(host,path);
return info && (info->attributes&FILE_ATTRIBUTE_DIRECTORY);
}
HBRUSH warningBrush{};
LRESULT CALLBACK dialogButtonEnter(HWND button,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR);
void installDialogButtonKeys(HWND dialog)
{
EnumChildWindows(dialog,[](HWND control,LPARAM)->BOOL
{
wchar_t name[16]{};
GetClassNameW(control,name,static_cast<int>(std::size(name)));
if(lstrcmpiW(name,L"Button")==0 && (GetWindowLongPtrW(control,GWL_STYLE)&WS_TABSTOP))
SetWindowSubclass(control,dialogButtonEnter,1,0);
return TRUE;
},0);
}
constexpr wchar_t farEditClass[]=L"KSwitcher.Files.FarEdit";
WNDPROC nativeEditProcedure{};
bool isDialogEdit(HWND control)
{
wchar_t name[32]{};
GetClassNameW(control,name,static_cast<int>(std::size(name)));
return lstrcmpiW(name,L"Edit")==0 || lstrcmpiW(name,farEditClass)==0;
}
void centerDialogEditText(HWND field)
{
RECT edit{};
GetClientRect(field,&edit);
if(const auto dc=GetDC(field))
{
const auto oldFont=SelectObject(dc,reinterpret_cast<HFONT>(SendMessageW(field,WM_GETFONT,0,0)));
TEXTMETRICW metrics{};
if(GetTextMetricsW(dc,&metrics))
edit.top=std::max(0L,(edit.bottom-metrics.tmHeight)/2);
SelectObject(dc,oldFont);
ReleaseDC(field,dc);
}
if(lavenderFiles()) InflateRect(&edit,-LavenderMetrics(field).px(6),0);
SendMessageW(field,EM_SETRECTNP,0,reinterpret_cast<LPARAM>(&edit));
}
LRESULT CALLBACK farEditProcedure(HWND field,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_CHAR && (wp==L'\r' || wp==L'\n')) return 0;
if(message==WM_PASTE && !(GetWindowLongPtrW(field,GWL_STYLE)&ES_READONLY) && OpenClipboard(field))
{
std::wstring line;
bool multiline=false;
if(const auto handle=GetClipboardData(CF_UNICODETEXT))
if(const auto data=static_cast<const wchar_t *>(GlobalLock(handle)))
{
const auto end=data+GlobalSize(handle)/sizeof(wchar_t);
const auto stop=std::find_if(data,end,[](wchar_t c){return c==0 || c==L'\r' || c==L'\n';});
multiline=stop!=end && *stop!=0;
if(multiline) line.assign(data,stop);
GlobalUnlock(handle);
}
CloseClipboard();
if(multiline)
{
if(!line.empty()) SendMessageW(field,EM_REPLACESEL,TRUE,reinterpret_cast<LPARAM>(line.c_str()));
return 0;
}
}
const auto result=CallWindowProcW(nativeEditProcedure,field,message,wp,lp);
if(message==WM_SIZE || message==WM_SETFONT) centerDialogEditText(field);
if(message==WM_GETDLGCODE && lp)
{
const auto key=reinterpret_cast<const MSG *>(lp)->wParam;
if(key==VK_RETURN || key==VK_TAB || key==VK_ESCAPE) return result&~DLGC_WANTALLKEYS;
}
return result;
}
bool registerFarEdit(HINSTANCE instance)
{
WNDCLASSEXW type{sizeof(type)};
if(!GetClassInfoExW(nullptr,L"Edit",&type)) return false;
nativeEditProcedure=type.lpfnWndProc;
type.hInstance=instance;
type.lpszClassName=farEditClass;
type.lpfnWndProc=farEditProcedure;
return RegisterClassExW(&type)!=0;
}
void prepareDialogEdit(HWND field)
{
SendMessageW(field,WM_SETFONT,reinterpret_cast<WPARAM>(dialogUiFont()),FALSE);
const auto margin=MulDiv(2,GetDpiForWindow(field),96);
SendMessageW(field,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,MAKELPARAM(margin,margin));
}
void fitFarEditToLine(HWND field)
{
TEXTMETRICW metrics{};
const auto dc=GetDC(field);
if(!dc) return;
const auto font=reinterpret_cast<HFONT>(SendMessageW(field,WM_GETFONT,0,0));
const auto previous=SelectObject(dc,font);
const bool measured=GetTextMetricsW(dc,&metrics)!=FALSE;
SelectObject(dc,previous);
ReleaseDC(field,dc);
if(!measured) return;
const auto parent=GetParent(field);
RECT cell{};
GetWindowRect(field,&cell);
MapWindowPoints(nullptr,parent,reinterpret_cast<POINT *>(&cell),2);
const auto height=lavenderFiles()?std::min(cell.bottom-cell.top,
metrics.tmHeight+LavenderMetrics(field).px(8)):std::max(metrics.tmHeight,1L);
SetWindowPos(field,nullptr,cell.left,cell.top+(cell.bottom-cell.top-height)/2,
cell.right-cell.left,height,SWP_NOZORDER|SWP_NOACTIVATE);
}
void prepareCopyDialog(HWND dialog)
{
installDialogButtonKeys(dialog);
EnumChildWindows(dialog,[](HWND control,LPARAM)->BOOL
{
if(isDialogEdit(control)) prepareDialogEdit(control);
return TRUE;
},0);
const auto style=GetWindowLongPtrW(dialog,GWL_STYLE);
if(style&WS_MAXIMIZEBOX) return;
SetWindowLongPtrW(dialog,GWL_STYLE,style&~(WS_CAPTION|WS_SYSMENU|WS_THICKFRAME));
const auto extended=GetWindowLongPtrW(dialog,GWL_EXSTYLE);
SetWindowLongPtrW(dialog,GWL_EXSTYLE,extended&~WS_EX_DLGMODALFRAME);
SetWindowPos(dialog,nullptr,0,0,0,0,
SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE|SWP_FRAMECHANGED);
}
RECT dialogControlBounds(HWND dialog,int id)
{
RECT bounds{};
GetWindowRect(GetDlgItem(dialog,id),&bounds);
MapWindowPoints(nullptr,dialog,reinterpret_cast<POINT*>(&bounds),2);
return bounds;
}
void layoutDialogContent(HWND dialog,int firstControl)
{
const auto dpi=GetDpiForWindow(dialog);
const auto frame=dialogFrameMetrics(dpi);
const auto first=dialogControlBounds(dialog,firstControl);
const int dx=frame.content()-first.left;
const int header=isLavenderFileOperation(dialog)?LavenderMetrics(dialog).px(operationHeaderHeight+2):0;
const int dy=std::max(header,dialogListInset(frame,textHeight)+MulDiv(1,dpi,96))-first.top;
for(auto control=GetWindow(dialog,GW_CHILD);control;control=GetWindow(control,GW_HWNDNEXT))
{
RECT bounds{};
GetWindowRect(control,&bounds);
MapWindowPoints(nullptr,dialog,reinterpret_cast<POINT*>(&bounds),2);
SetWindowPos(control,nullptr,bounds.left+dx,bounds.top+dy,0,0,
SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
}
RECT outer{};
GetWindowRect(dialog,&outer);
SetWindowPos(dialog,nullptr,0,0,outer.right-outer.left+2*dx,outer.bottom-outer.top+dy,
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
}
int dialogFooterInset(HWND dialog)
{
const auto dpi=GetDpiForWindow(dialog);
const auto metrics=dialogFrameMetrics(dpi);
return metrics.innerLine();
}
LONG dialogDividerY(HWND dialog,int id)
{
const auto bounds=dialogControlBounds(dialog,id);
if(id==ks::files::searchOptionsDivider || id==ks::files::searchButtonsDivider)
return bounds.top;
if(id==214)
{
const auto combo=dialogControlBounds(dialog,213);
const auto path=dialogControlBounds(dialog,211);
return bounds.bottom+std::max(0L,(combo.top-path.bottom-1)/2);
}
if(id==213) return (dialogControlBounds(dialog,211).bottom+bounds.top-1)/2;
return bounds.top-4;
}
void centerDialogRow(HWND dialog,int upperDivider,int lowerDivider,std::initializer_list<int> controls)
{
RECT client{};
GetClientRect(dialog,&client);
const auto top=dialogDividerY(dialog,upperDivider)+1;
const auto bottom=lowerDivider?dialogDividerY(dialog,lowerDivider):client.bottom-dialogFooterInset(dialog);
for(const auto id:controls)
{
const auto bounds=dialogControlBounds(dialog,id);
SetWindowPos(GetDlgItem(dialog,id),nullptr,bounds.left,(top+bottom-(bounds.bottom-bounds.top))/2,
0,0,SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
}
}
int dialogColumnGap() { return std::max(2,cellWidth/2); }
int dialogRowGap() { return std::max(2,textHeight/5); }
LONG farDialogButtonWidth(HWND button)
{
wchar_t label[32]{};
const auto length=GetWindowTextW(button,label,static_cast<int>(std::size(label)));
const auto characters=length-(wcschr(label,L'&')!=nullptr?1:0);
return (characters+5)*cellWidth;
}
LONG dialogButtonWidth(HWND dialog,int id,bool native)
{
if(!native) return farDialogButtonWidth(GetDlgItem(dialog,id));
const auto bounds=dialogControlBounds(dialog,id);
return bounds.right-bounds.left;
}
LONG dialogButtonGroupWidth(HWND dialog,std::initializer_list<int> controls,bool native=false)
{
const auto gap=dialogColumnGap();
LONG width=-gap;
for(const auto id:controls) width+=dialogButtonWidth(dialog,id,native)+gap;
return std::max(0L,width);
}
void groupDialogButtons(HWND dialog,std::initializer_list<int> controls,bool native=false)
{
RECT client{};
GetClientRect(dialog,&client);
const auto gap=dialogColumnGap();
const auto rowWidth=dialogButtonGroupWidth(dialog,controls,native);
if(rowWidth>client.right) return;
auto x=native?dialogControlBounds(dialog,*(controls.end()-1)).right-rowWidth:
(client.right-rowWidth)/2;
for(const auto id:controls)
{
const auto bounds=dialogControlBounds(dialog,id);
const auto buttonWidth=dialogButtonWidth(dialog,id,native);
SetWindowPos(GetDlgItem(dialog,id),nullptr,x,bounds.top,buttonWidth,bounds.bottom-bounds.top,
SWP_NOZORDER|SWP_NOACTIVATE);
x+=buttonWidth+gap;
}
}
void layoutDialogButtons(HWND dialog,int divider,std::initializer_list<int> controls)
{
RECT client{},window{};
GetClientRect(dialog,&client);
GetWindowRect(dialog,&window);
const auto dpi=GetDpiForWindow(dialog);
const auto frame=dialogFrameMetrics(dpi);
const auto extra=frame.inner-dialogFrameMetrics(dpi,defaultDialogFramePadding).inner;
LONG tallest{};
for(const auto id:controls)
{
const auto bounds=dialogControlBounds(dialog,id);
tallest=std::max(tallest,bounds.bottom-bounds.top);
}
const auto footerHeight=std::max(tallest,static_cast<LONG>(textHeight))+
2*std::max(dialogRowGap(),dialogRowGap()+extra);
const auto height=dialogDividerY(dialog,divider)+1+footerHeight+dialogFooterInset(dialog);
const auto width=window.right-window.left;
const auto outerHeight=window.bottom-window.top+height-client.bottom;
RECT owner{};
const bool centered=GetWindowRect(GetWindow(dialog,GW_OWNER),&owner)!=FALSE;
SetWindowPos(dialog,nullptr,(owner.left+owner.right-width)/2,
(owner.top+owner.bottom-outerHeight)/2,width,outerHeight,
(centered?0:SWP_NOMOVE)|SWP_NOZORDER|SWP_NOACTIVATE);
groupDialogButtons(dialog,controls);
centerDialogRow(dialog,divider,0,controls);
}
void drawFarDialogLabel(HDC dc,RECT bounds,std::wstring caption,bool centered)
{
if(lavenderFiles())
{
DrawTextW(dc,caption.c_str(),-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|
(centered?DT_CENTER:DT_LEFT));
return;
}
const auto access=caption.find(L'&');
if(access!=caption.npos) caption.erase(access,1);
SIZE extent{};
GetTextExtentPoint32W(dc,caption.c_str(),static_cast<int>(caption.size()),&extent);
RECT label=bounds;
if(centered) label.left+=std::max(0L,(bounds.right-bounds.left-extent.cx)/2);
DrawTextW(dc,caption.c_str(),-1,&label,DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_END_ELLIPSIS);
TEXTMETRICW metrics{};
GetTextMetricsW(dc,&metrics);
ks::files::paintMenuAccessKey(dc,bounds,{label.left,bounds.top+(bounds.bottom-bounds.top-metrics.tmHeight)/2},
caption,access,RGB(255,255,0));
}
void paintDialogButton(const DRAWITEMSTRUCT &item,COLORREF surface,COLORREF foreground,bool farAccessKeys=false)
{
const auto defaultButton=SendMessageW(GetParent(item.hwndItem),DM_GETDEFID,0,0);
const bool isDefault=HIWORD(defaultButton)==DC_HASDEFID && LOWORD(defaultButton)==item.CtlID;
if(lavenderFiles())
{
paintLavenderDialogButton(item.hwndItem,item.hDC,item.rcItem,(item.itemState&ODS_SELECTED)!=0,
(item.itemState&ODS_FOCUS)!=0,isDefault);
return;
}
wchar_t label[32]{};
GetWindowTextW(item.hwndItem,label,static_cast<int>(std::size(label)));
const bool focused=(item.itemState&(ODS_FOCUS|ODS_SELECTED))!=0;
const auto focusSurface=surface==RGB(128,0,0)?RGB(0,0,0):
surface==colors[Dialog]?colors[Selection]:colors[Dialog];
SetDCBrushColor(item.hDC,focused?focusSurface:surface);
FillRect(item.hDC,&item.rcItem,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
SelectObject(item.hDC,mono);
SetBkMode(item.hDC,TRANSPARENT);
SetTextColor(item.hDC,(item.itemState&ODS_DISABLED)?RGB(128,128,128):focused?colors[Text]:foreground);
auto rect=item.rcItem;
const auto caption=(isDefault?L"{ ":L"[ ")+std::wstring(label)+(isDefault?L" }":L" ]");
if(farAccessKeys && !(item.itemState&ODS_DISABLED)) drawFarDialogLabel(item.hDC,rect,caption,true);
else DrawTextW(item.hDC,caption.c_str(),-1,&rect,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
}
INT_PTR paintCopyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp,
const wchar_t *caption, bool warning, std::initializer_list<int> dividers, bool useDialogPalette=false,
HWND scrollControl=nullptr,bool scrollEdit=false)
{
if(message==WM_INITDIALOG && warning && lavenderFiles())
SetPropW(dialog,lavenderDialogWarning,reinterpret_cast<HANDLE>(1));
if(message==WM_NCDESTROY) RemovePropW(dialog,lavenderDialogWarning);
const auto foreground=useDialogPalette?colors[Text]:warning?RGB(255,255,255):RGB(0,0,0);
const auto surface=useDialogPalette?colors[Dialog]:warning?RGB(128,0,0):RGB(192,192,192);
const auto brush=useDialogPalette?teal:warning?warningBrush:static_cast<HBRUSH>(GetStockObject(LTGRAY_BRUSH));
if(message==WM_CTLCOLORDLG) return reinterpret_cast<INT_PTR>(brush);
if(message==WM_CTLCOLORSTATIC || message==WM_CTLCOLOREDIT || message==WM_CTLCOLORBTN ||
(message==WM_CTLCOLORLISTBOX && (useDialogPalette || reinterpret_cast<HWND>(lp)==scrollControl)))
{
const auto dc=reinterpret_cast<HDC>(wp);
const bool edit=message==WM_CTLCOLOREDIT ||
(message==WM_CTLCOLORSTATIC && isDialogEdit(reinterpret_cast<HWND>(lp)));
SetTextColor(dc,edit?colors[Text]:foreground);
SetBkColor(dc,edit?colors[Dialog]:surface);
return reinterpret_cast<INT_PTR>(edit?teal:brush);
}
if(message==WM_PAINT)
{
PAINTSTRUCT paint{};
const auto dc=BeginPaint(dialog,&paint);
RECT bounds{};
GetClientRect(dialog,&bounds);
const auto client=bounds;
const auto black=static_cast<HBRUSH>(GetStockObject(useDialogPalette?DC_BRUSH:warning?WHITE_BRUSH:BLACK_BRUSH));
if(useDialogPalette) SetDCBrushColor(dc,foreground);
const bool lavender=lavenderFiles();
bounds=lavender?paintLavenderDialogFrame(dialog,dc,client,caption):
paintDialogFrame(dc,client,dialogFrameMetrics(GetDpiForWindow(dialog)),brush,black);
for(const auto control:dividers)
{
const auto y=dialogDividerY(dialog,control);
RECT divider{bounds.left+1,y,bounds.right-1,y+1};
if(lavender) lavender::fill(dc,divider,isLavenderFileOperation(dialog)?operationBorder:lavender::line);
else FillRect(dc,&divider,black);
}
if(!lavender) paintDialogFrameCaptions(dc,client,bounds,caption,brush,foreground,mono);
if(scrollControl) paintScrollPosition(dialog,dc,scrollControl,
lavender?lavenderDialogSurface(dialog):surface,scrollEdit);
EndPaint(dialog,&paint);
return TRUE;
}
if(message==WM_DRAWITEM)
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT*>(lp);
paintDialogButton(item,surface,foreground);
return TRUE;
}
return FALSE;
}
INT_PTR paintFileOperationDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp,const wchar_t *caption,
bool warning,std::initializer_list<int> dividers)
{
if(message==WM_INITDIALOG) markLavenderFileOperation(dialog);
return paintCopyDialog(dialog,message,wp,lp,caption,warning,dividers);
}
struct FarDropDownBounds
{
RECT field,arrow;
};
ks::files::FarDropDownPalette farDropDownPalette()
{
if(lavenderFiles()) return {lavender::path,lavender::ink,lavender::selection};
return {colors[Dialog],colors[Text],colors[Selection]};
}
FarDropDownBounds farDropDownBounds(RECT bounds)
{
const auto split=std::max(bounds.left,bounds.right-static_cast<LONG>(cellWidth));
return {{bounds.left,bounds.top,split,bounds.bottom},{split,bounds.top,bounds.right,bounds.bottom}};
}
void paintFarDropDownText(HDC dc,RECT bounds,const wchar_t *text,bool enabled)
{
FillRect(dc,&bounds,teal);
SelectObject(dc,mono);
SetBkMode(dc,TRANSPARENT);
SetTextColor(dc,enabled?farDropDownPalette().text:RGB(128,128,128));
bounds.left+=5;
DrawTextW(dc,text,-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_END_ELLIPSIS);
}
LRESULT CALLBACK paintFarCombo(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_LBUTTONDOWN || (message==WM_KEYDOWN && wp==VK_F4) ||
(message==WM_SYSKEYDOWN && wp==VK_DOWN) || (message==CB_SHOWDROPDOWN && wp))
{
if(!IsWindowEnabled(control)) return 0;
SetFocus(control);
std::vector<ks::files::FarHistoryEntry> entries;
const auto count=SendMessageW(control,CB_GETCOUNT,0,0);
for(LRESULT index=0;index<count;++index)
{
const auto length=SendMessageW(control,CB_GETLBTEXTLEN,index,0);
if(length==CB_ERR) return 0;
std::wstring label(static_cast<size_t>(length)+1,L'\0');
const auto copied=SendMessageW(control,CB_GETLBTEXT,index,reinterpret_cast<LPARAM>(label.data()));
if(copied==CB_ERR) return 0;
label.resize(copied);
entries.push_back({{},std::move(label)});
}
const auto previous=SendMessageW(control,CB_GETCURSEL,0,0);
const auto selected=ks::files::chooseFarDropDown(control,entries,static_cast<int>(previous),
farDropDownPalette(),cellWidth);
if(selected>=0 && selected!=previous)
{
SendMessageW(control,CB_SETCURSEL,selected,0);
SendMessageW(GetParent(control),WM_COMMAND,MAKEWPARAM(GetDlgCtrlID(control),CBN_SELCHANGE),
reinterpret_cast<LPARAM>(control));
}
InvalidateRect(control,nullptr,FALSE);
return message==CB_SHOWDROPDOWN?TRUE:0;
}
if(message!=WM_PAINT && message!=WM_PRINTCLIENT && message!=WM_PRINT)
return DefSubclassProc(control,message,wp,lp);
PAINTSTRUCT paint{};
const auto dc=message==WM_PAINT?BeginPaint(control,&paint):reinterpret_cast<HDC>(wp);
RECT bounds{};
GetClientRect(control,&bounds);
std::wstring label;
const auto selected=SendMessageW(control,CB_GETCURSEL,0,0);
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;
if(lavenderFiles()) paintLavenderComboFace(control,dc,bounds,label.c_str());
else
{
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);
return 0;
}
void installFarCombo(HWND combo,HWND lineField)
{
RECT field{},bounds{};
GetWindowRect(lineField,&field);
GetWindowRect(combo,&bounds);
const LONG line=field.bottom-field.top;
const auto selection=SendMessageW(combo,CB_GETITEMHEIGHT,static_cast<WPARAM>(-1),0);
const auto frame=selection==CB_ERR?0L:std::max(0L,bounds.bottom-bounds.top-static_cast<LONG>(selection));
SendMessageW(combo,CB_SETITEMHEIGHT,0,line);
SendMessageW(combo,CB_SETITEMHEIGHT,static_cast<WPARAM>(-1),std::max(1L,line-frame));
SetWindowSubclass(combo,paintFarCombo,1,0);
}
enum class FarCheckboxSurface : DWORD_PTR { gray, dialog, warning };
void showFarCheckboxCaret(HWND field)
{
const auto dc=GetDC(field);
if(!dc) return;
const auto font=reinterpret_cast<HFONT>(SendMessageW(field,WM_GETFONT,0,0));
const auto previous=SelectObject(dc,font);
TEXTMETRICW metrics{};
GetTextMetricsW(dc,&metrics);
SIZE bracket{},space{};
GetTextExtentPoint32W(dc,L"[",1,&bracket);
GetTextExtentPoint32W(dc,L" ",1,&space);
SelectObject(dc,previous);
ReleaseDC(field,dc);
RECT bounds{};
GetClientRect(field,&bounds);
const auto width=std::max(1L,space.cx-2);
const auto height=std::max(2L,metrics.tmHeight/6);
const auto y=(bounds.bottom-metrics.tmHeight)/2+metrics.tmAscent+metrics.tmDescent-height;
if(CreateCaret(field,nullptr,width,height))
{
SetCaretPos(bracket.cx+1,std::max(0L,y));
ShowCaret(field);
}
}
LRESULT CALLBACK paintFarCheckbox(HWND field,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR palette)
{
if(message==WM_ERASEBKGND) return TRUE;
if(message!=WM_PAINT)
{
if(message==WM_KILLFOCUS) DestroyCaret();
const auto result=DefSubclassProc(field,message,wp,lp);
if(!lavenderFiles() && (message==WM_SETFOCUS || ((message==WM_SIZE || message==WM_SETFONT) && GetFocus()==field)))
showFarCheckboxCaret(field);
if(message==BM_SETCHECK || message==WM_SETTEXT || message==WM_ENABLE)
InvalidateRect(field,nullptr,FALSE);
return result;
}
PAINTSTRUCT paint{};
const auto dc=BeginPaint(field,&paint);
RECT bounds{};
GetClientRect(field,&bounds);
if(lavenderFiles())
{
paintLavenderToggle(field,dc,bounds,(GetWindowLongPtrW(field,GWL_STYLE)&BS_TYPEMASK)==BS_AUTORADIOBUTTON);
EndPaint(field,&paint);
return 0;
}
const auto surface=static_cast<FarCheckboxSurface>(palette);
const auto background=surface==FarCheckboxSurface::gray?RGB(192,192,192):
surface==FarCheckboxSurface::warning?RGB(128,0,0):colors[Dialog];
const auto ink=surface==FarCheckboxSurface::gray?RGB(0,0,0):
surface==FarCheckboxSurface::warning?RGB(255,255,255):colors[Text];
SetDCBrushColor(dc,background);
FillRect(dc,&bounds,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
SelectObject(dc,reinterpret_cast<HFONT>(SendMessageW(field,WM_GETFONT,0,0)));
SetBkMode(dc,TRANSPARENT);
SetTextColor(dc,IsWindowEnabled(field)?ink:RGB(128,128,128));
wchar_t label[80]{};
GetWindowTextW(field,label,static_cast<int>(std::size(label)));
const bool radio=(GetWindowLongPtrW(field,GWL_STYLE)&BS_TYPEMASK)==BS_AUTORADIOBUTTON;
const bool checked=SendMessageW(field,BM_GETCHECK,0,0)==BST_CHECKED;
const auto text=(radio?(checked?L"(•) ":L"( ) "):(checked?L"[x] ":L"[ ] "))+std::wstring(label);
if(IsWindowEnabled(field)) drawFarDialogLabel(dc,bounds,text,false);
else DrawTextW(dc,text.c_str(),-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS);
EndPaint(field,&paint);
return 0;
}
void installFarCheckbox(HWND field,FarCheckboxSurface surface)
{
SetWindowSubclass(field,paintFarCheckbox,1,static_cast<DWORD_PTR>(surface));
}
bool validFtpCopyName(std::wstring_view name,bool upload)
{
if(upload)
return !name.empty() && name!=L"." && name!=L".." &&
name.find_first_of(L"/\\:\r\n") == name.npos &&
std::none_of(name.begin(),name.end(),[](wchar_t ch){return ch<32;});
return ks::files::validWindowsFileName(name);
}
void drawFarComboRow(const DRAWITEMSTRUCT &item)
{
wchar_t label[64]{};
if(item.itemID!=UINT(-1))
SendMessageW(item.hwndItem,CB_GETLBTEXT,item.itemID,reinterpret_cast<LPARAM>(label));
const bool selected=(item.itemState&ODS_SELECTED)!=0 && (item.itemState&ODS_COMBOBOXEDIT)==0;
const auto palette=farDropDownPalette();
if(lavenderFiles()) paintDialogListRow(item.hDC,item.rcItem,label,dialogUiFont(),palette.text,
selected?palette.selection:palette.surface,LavenderMetrics(item.hwndItem).px(6));
else paintText(item.hDC,item.rcItem,label,palette.text,selected?palette.selection:palette.surface);
}
CopyDestination validateCopyDestination(CopyRequest request,const std::wstring &value,
const std::optional<FilesPeer> &source,const std::optional<FilesPeer> &other)
{
if(!request.ftpDestination.empty())
{
if(request.sources.size()==1)
{
if(!validFtpCopyName(value,request.upload))
throw std::runtime_error("Enter a valid name for the copy.");
if(value!=request.sources.front().filename().native()) request.newName=value;
}
if(!request.upload && !directoryExists(nullptr,request.destination))
throw std::runtime_error("The destination folder is unavailable.");
return {std::move(request.destination),std::move(request.newName)};
}
request.sourcePeer=source?&*source:nullptr;
request.otherPeer=request.destinationPeer=other?&*other:nullptr;
bool useSourcePeer=false;
if(request.move)
{
const fs::path entered(value);
const bool bareName=request.sources.size()==1 && entered==entered.filename() &&
entered!=L"." && entered!=L"..";
const auto initial=request.otherDirectory;
const bool usesOtherPanel=entered==initial || entered==initial/L"" ||
(request.otherPeer && entered.is_absolute());
const auto target=usesOtherPanel?entered:request.sources.front().parent_path()/entered;
const auto peer=usesOtherPanel?request.otherPeer:request.sourcePeer;
const bool targetIsDirectory=!value.empty() && value.find_first_of(L"<>|?*")==value.npos &&
!bareName && directoryExists(peer,target);
if(value.empty() || value.find_first_of(L"<>|?*")!=value.npos ||
(!targetIsDirectory && (request.sources.size()!=1 || !target.has_filename())))
throw std::runtime_error(ks::utf8(L"Enter an existing destination folder, or a new name for one item."));
request.destinationPeer=peer;
useSourcePeer=!usesOtherPanel;
request.newName.clear();
if(targetIsDirectory)
{
request.destination=target.lexically_normal();
if(!request.destination.has_filename() && request.destination.has_relative_path())
request.destination=request.destination.parent_path();
}
else
{
request.destination=target.parent_path();
request.newName=target.filename();
}
}
else if(request.sources.size()==1)
{
const auto &name=value;
if(request.archiveSource?!ks::files::validWindowsFileName(name):!validFileName(name))
throw std::runtime_error(ks::utf8(L"Enter a valid name for the copy."));
if(CompareStringOrdinal(name.c_str(),-1,request.sources.front().filename().c_str(),-1,TRUE)!=CSTR_EQUAL)
request.newName=name;
else request.newName.clear();
}
const auto sourceDirectory=request.sources.front().parent_path();
const bool renameInSource=!request.externalSources && !request.archiveSource && !request.move && !request.newName.empty();
const auto destination=renameInSource?sourceDirectory:request.destination;
std::error_code error;
const auto peer=renameInSource?request.sourcePeer:request.destinationPeer;
if(!directoryExists(peer,destination))
throw std::runtime_error(ks::utf8(L"The destination folder is unavailable."));
const bool sameHost=(!peer && !request.sourcePeer) ||
(peer && request.sourcePeer && peer->id==request.sourcePeer->id);
const bool containsDestination=sameHost && request.newName.empty() &&
std::any_of(request.sources.begin(),request.sources.end(),[&](const auto &path)
{
const auto parent=path.parent_path();
return peer?CompareStringOrdinal(destination.c_str(),-1,parent.c_str(),-1,TRUE)==CSTR_EQUAL:
fs::equivalent(destination,parent,error);
});
if(containsDestination)
throw std::runtime_error(ks::utf8(L"Open a different folder in the other panel, or enter a new name for a single item."));
return {std::move(request.destination),std::move(request.newName),useSourcePeer};
}
#include "files_copy_options.inl"
#include "files_image_edit_options.inl"
INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
{
constexpr int summary=210, pathField=211, conflicts=212;
if(message==WM_DRAWITEM && wp==213)
{
drawFarComboRow(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
}
if(message==WM_CTLCOLORLISTBOX)
{
const auto dc=reinterpret_cast<HDC>(wp);
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[Dialog]);
return reinterpret_cast<INT_PTR>(teal);
}
const auto prompt=reinterpret_cast<const CopyRequest*>(GetWindowLongPtrW(dialog,DWLP_USER));
const auto painted=prompt && prompt->ftpRename?paintFileOperationDialog(dialog,message,wp,lp,L" Rename ",false,{217}):
paintFileOperationDialog(dialog,message,wp,lp,prompt && prompt->move?L" Rename/Move ":L" Copy ",false,{213,214});
if(painted)
return painted;
if(message==WM_INITDIALOG)
{
auto &request=*reinterpret_cast<CopyRequest*>(lp);
prepareCopyDialog(dialog);
layoutDialogContent(dialog,summary);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
if(request.ftpRename)
{
SendDlgItemMessageW(dialog,summary,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
const auto field=GetDlgItem(dialog,pathField);
SetWindowTextW(field,request.sources.front().filename().c_str());
fitFarEditToLine(field);
layoutDialogButtons(dialog,217,{IDOK,IDCANCEL});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(field);
SendMessageW(field,EM_SETSEL,0,-1);
return FALSE;
}
for(const auto label:{L"Ask",L"Overwrite",L"Skip",L"Rename",L"Append",L"Only newer file(s)"})
if((!request.move && request.ftpDestination.empty()) || std::wstring_view(label)!=L"Append")
SendDlgItemMessageW(dialog,213,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
SendDlgItemMessageW(dialog,213,CB_SETCURSEL,0,0);
const std::wstring action=request.move?L"Rename or move ":L"Copy ";
const auto label=action+(request.sources.size()==1?request.sources.front().filename().wstring():
std::to_wstring(request.sources.size())+L" items")+
(request.ftpDestination.empty() || request.sources.size()!=1?L" to:":L" to "+request.ftpDestination);
SetDlgItemTextW(dialog,summary,label.c_str());
const bool single=request.sources.size()==1;
auto fieldText=single && !request.move?request.sources.front().filename():request.destination;
if(request.move && fieldText.has_filename()) fieldText/=L"";
SetDlgItemTextW(dialog,pathField,!single && !request.ftpDestination.empty()?
request.ftpDestination.c_str():fieldText.c_str());
SendDlgItemMessageW(dialog,pathField,EM_SETREADONLY,!single && !request.move,0);
if(request.move) SetDlgItemTextW(dialog,IDOK,request.externalSources?L"&Move":L"&Rename");
fitFarEditToLine(GetDlgItem(dialog,pathField));
layoutDialogButtons(dialog,214,{IDOK,215,IDCANCEL});
installFarCheckbox(GetDlgItem(dialog,214),FarCheckboxSurface::gray);
CheckDlgButton(dialog,214,request.askReadOnly?BST_CHECKED:BST_UNCHECKED);
SendDlgItemMessageW(dialog,summary,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendDlgItemMessageW(dialog,conflicts,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
for(const auto control:{213,214})
SendDlgItemMessageW(dialog,control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
installFarCombo(GetDlgItem(dialog,213),GetDlgItem(dialog,pathField));
RECT combo{}, caption{};
const auto captionControl=GetDlgItem(dialog,conflicts);
GetWindowRect(GetDlgItem(dialog,213),&combo);
GetWindowRect(captionControl,&caption);
MapWindowPoints(nullptr,dialog,reinterpret_cast<POINT*>(&combo),2);
MapWindowPoints(nullptr,dialog,reinterpret_cast<POINT*>(&caption),2);
SetWindowPos(captionControl,nullptr,caption.left,combo.top,
caption.right-caption.left,combo.bottom-combo.top,SWP_NOZORDER|SWP_NOACTIVATE);
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SendDlgItemMessageW(dialog,pathField,EM_SETSEL,0,-1);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
constexpr UINT_PTR validationTimer=1;
if(message!=WM_COMMAND && !(message==WM_TIMER && wp==validationTimer)) return FALSE;
auto &request=*reinterpret_cast<CopyRequest*>(GetWindowLongPtrW(dialog,DWLP_USER));
const auto showError=[&](const wchar_t *message)
{
showFilesNotice(dialog,message,L"Error",{.tone=FilesNoticeTone::warning});
SetFocus(GetDlgItem(dialog,pathField));
};
if(message==WM_TIMER)
{
if(!request.validation.valid() ||
request.validation.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return TRUE;
KillTimer(dialog,validationTimer);
for(const auto control:{pathField,213,214,215,IDOK}) EnableWindow(GetDlgItem(dialog,control),TRUE);
try
{
auto result=request.validation.get();
request.destination=std::move(result.directory);
request.newName=std::move(result.newName);
request.destinationPeer=result.useSourcePeer?request.sourcePeer:request.otherPeer;
FilesModalDialog::finish(dialog,IDOK);
}
catch(const std::system_error &e) {showError(fileError(e).c_str());}
catch(const std::exception &e) {showError(ks::wide(e.what()).c_str());}
return TRUE;
}
if(LOWORD(wp)==213)
{
InvalidateRect(GetDlgItem(dialog,213),nullptr,FALSE);
return FALSE;
}
if(LOWORD(wp)==215)
{
CopyOptionsPrompt options{request.options, request.ftpDestination.empty() && !request.archiveSource, request.move,
request.upload};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(129),dialog,copyOptionsDialog,
reinterpret_cast<LPARAM>(&options))==IDOK) request.options=std::move(options.value);
return TRUE;
}
if(LOWORD(wp)!=IDOK) return FALSE;
if(request.validation.valid()) return TRUE;
try
{
const auto field=GetDlgItem(dialog,pathField);
std::wstring value(GetWindowTextLengthW(field)+1,L'\0');
value.resize(GetWindowTextW(field,value.data(),static_cast<int>(value.size())));
if(request.ftpRename)
{
if(!validFtpCopyName(value,true)) showError(L"Enter a new name in the current remote folder.");
else if(value==request.sources.front().filename().native()) FilesModalDialog::finish(dialog,IDCANCEL);
else
{
request.newName=value;
FilesModalDialog::finish(dialog,IDOK);
}
return TRUE;
}
request.askReadOnly=IsDlgButtonChecked(dialog,214)==BST_CHECKED;
const auto mode=SendDlgItemMessageW(dialog,213,CB_GETCURSEL,0,0);
if(mode!=CB_ERR) request.conflictMode=static_cast<ConflictMode>(
(request.move || !request.ftpDestination.empty()) && mode==static_cast<int>(ConflictMode::append)?
static_cast<int>(ConflictMode::newer):mode);
const auto peer=[](const FilesPeer *value) {
return value?std::optional<FilesPeer>(*value):std::nullopt;
};
CopyRequest snapshot{request.sources,request.destination,{},request.otherDirectory};
snapshot.move=request.move;
snapshot.ftpDestination=request.ftpDestination;
snapshot.upload=request.upload;
snapshot.externalSources=request.externalSources;
snapshot.archiveSource=request.archiveSource;
std::packaged_task<CopyDestination()> validation(
[snapshot=std::move(snapshot),value=std::move(value),
source=peer(request.sourcePeer),other=peer(request.otherPeer)]() mutable {
return validateCopyDestination(std::move(snapshot),value,source,other);
});
auto ready=validation.get_future();
if(!SetTimer(dialog,validationTimer,50,nullptr))
throw std::runtime_error("Could not start destination validation.");
std::thread(std::move(validation)).detach();
request.validation=std::move(ready);
SetFocus(GetDlgItem(dialog,IDCANCEL));
for(const auto control:{pathField,213,214,215,IDOK}) EnableWindow(GetDlgItem(dialog,control),FALSE);
}
catch(const std::exception &e)
{
KillTimer(dialog,validationTimer);
showError(ks::wide(e.what()).c_str());
}
return TRUE;
}
// Run blocking file work on one worker while the existing modal dialog owns input.
class FileOperationUi
{
Handle wake_{CreateEventW(nullptr,FALSE,FALSE,nullptr)};
std::mutex mutex_;
std::function<void()> request_;
public:
template<class F> auto invoke(F &&action)
{
std::packaged_task<std::invoke_result_t<F>()> task(std::forward<F>(action));
auto result=task.get_future();
{
std::lock_guard lock(mutex_);
request_=[&task] {task();};
}
SetEvent(wake_.value);
return result.get();
}
template<class F> void run(HWND window,std::atomic_bool &canceled,F &&work)
{
if(!wake_.value) throw std::system_error(GetLastError(),std::system_category());
std::packaged_task<void()> task(std::forward<F>(work));
auto result=task.get_future();
std::thread worker([&] {task();SetEvent(wake_.value);});
std::optional<int> quit;
const auto owner=GetWindow(window,GW_OWNER);
while(result.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
{
MsgWaitForMultipleObjectsEx(1,&wake_.value,INFINITE,QS_ALLINPUT,MWMO_INPUTAVAILABLE);
MSG message{};
while(PeekMessageW(&message,nullptr,0,0,PM_REMOVE))
{
if(message.message==WM_QUIT)
{
quit=static_cast<int>(message.wParam);
canceled=true;
continue;
}
if(message.message==WM_SYSKEYDOWN && message.wParam==VK_F4 &&
(message.hwnd==owner || IsChild(owner,message.hwnd)))
{
SendMessageW(owner,WM_CLOSE,0,0);
continue;
}
if(FilesModalDialog::handleMessage(window,message)) continue;
TranslateMessage(&message);
DispatchMessageW(&message);
}
std::function<void()> request;
{
std::lock_guard lock(mutex_);
request=std::exchange(request_,{});
}
if(request) request();
}
worker.join();
if(quit) PostQuitMessage(*quit);
result.get();
}
};
struct CopyProgress
{
FileOperationUi ui;
HWND window{};
std::atomic_bool canceled{};
bool closeOwner{};
bool move{}, fileSourcesOnly{};
bool writingArchive{}, deferRemoval{};
CopyOptions options;
int conflictChoice{};
ConflictMode conflictMode{};
bool askReadOnly=true;
uint64_t files{}, totalFiles{}, bytes{}, totalBytes{};
uint64_t skippedFiles{}, skippedBytes{};
const wchar_t *lastSkipReason=L"";
ULONGLONG lastPaint{}, sampleStart{}, lastSample{};
uint64_t sampleBytes{}, lastBytes{};
unsigned samples{};
fs::path from,to,renamedTarget;
fs::path localLockSource,localLockTarget;
};
bool copyInProgress{};
CopyProgress *activeCopy{};
LRESULT CALLBACK paintCopyProgressBar(HWND bar,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message!=WM_PAINT) return DefSubclassProc(bar,message,wp,lp);
PAINTSTRUCT paint{};
const auto dc=BeginPaint(bar,&paint);
RECT bounds{};
GetClientRect(bar,&bounds);
const auto percent=std::clamp(SendMessageW(bar,PBM_GETPOS,0,0),LRESULT{0},LRESULT{100});
auto filled=bounds;
filled.right=static_cast<LONG>(bounds.right*percent/100);
if(lavenderFiles())
{
const LavenderMetrics metrics(bar);
const auto label=std::to_wstring(percent)+L"%";
lavender::fill(dc,bounds,lavender::surface);
lavender::rounded(dc,bounds,metrics.px(6),lavender::idleSelection,lavender::line);
lavender::rounded(dc,filled,metrics.px(6),lavender::accent,lavender::accent);
lavender::text(dc,bounds,label.c_str(),lavender::ink,DT_CENTER);
const auto saved=SaveDC(dc);
IntersectClipRect(dc,filled.left,filled.top,filled.right,filled.bottom);
lavender::text(dc,bounds,label.c_str(),lavender::surface,DT_CENTER);
RestoreDC(dc,saved);
EndPaint(bar,&paint);
return 0;
}
FillRect(dc,&bounds,static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
FillRect(dc,&filled,static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));
const auto label=std::to_wstring(percent)+L"%";
SelectObject(dc,mono);
SetBkMode(dc,TRANSPARENT);
constexpr auto flags=DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX;
SetTextColor(dc,RGB(0,0,0));
auto labelBounds=bounds;
DrawTextW(dc,label.c_str(),-1,&labelBounds,flags);
const auto saved=SaveDC(dc);
if(saved)
{
IntersectClipRect(dc,filled.left,filled.top,filled.right,filled.bottom);
SetTextColor(dc,RGB(255,255,255));
labelBounds=bounds;
DrawTextW(dc,label.c_str(),-1,&labelBounds,flags);
RestoreDC(dc,saved);
}
EndPaint(bar,&paint);
return 0;
}
void updateCopyProgress(CopyProgress &progress,uint64_t current,uint64_t fileSize)
{
progress.lastPaint=GetTickCount64();
if(!progress.from.empty())
{
SetDlgItemTextW(progress.window,220,(L"From: "+progress.from.wstring()).c_str());
SetDlgItemTextW(progress.window,221,(L"To: "+progress.to.wstring()).c_str());
for(const auto id:{220,221}) InvalidateRect(GetDlgItem(progress.window,id),nullptr,FALSE);
}
const auto percent=[](uint64_t done,uint64_t total)
{
return total?static_cast<int>(100.0*std::min(done,total)/total):0;
};
const auto updateBar=[&](int bar,int value)
{
const auto control=GetDlgItem(progress.window,bar);
SendMessageW(control,PBM_SETPOS,value,0);
InvalidateRect(control,nullptr,FALSE);
};
const auto bytes=progress.bytes+current;
updateBar(222,fileSize?percent(current,fileSize):0);
updateBar(226,progress.totalBytes?
percent(bytes+progress.skippedBytes,progress.totalBytes):
percent(progress.files+progress.skippedFiles,progress.totalFiles));
SetDlgItemTextW(progress.window,224,(L"Files: "+std::to_wstring(progress.files)+L" / "+
std::to_wstring(progress.totalFiles)+(progress.skippedFiles?
L" Skipped: "+std::to_wstring(progress.skippedFiles)+L" ("+progress.lastSkipReason+L")":L"")).c_str());
auto sizeText=L"Size: "+formatSize(bytes)+L" / "+formatSize(progress.totalBytes);
if(!progress.sampleStart || progress.lastPaint-progress.lastSample>1500 || bytes<progress.lastBytes)
{
progress.sampleStart=progress.lastSample=progress.lastPaint;
progress.sampleBytes=progress.lastBytes=bytes;
progress.samples=0;
}
else if(bytes>progress.lastBytes && progress.lastPaint-progress.lastSample>=200)
{
progress.lastSample=progress.lastPaint;
progress.lastBytes=bytes;
++progress.samples;
}
const auto elapsed=progress.lastSample-progress.sampleStart;
const auto accounted=std::min(progress.totalBytes,bytes+progress.skippedBytes);
if(progress.samples>=3 && elapsed>=1200 && bytes>progress.sampleBytes && accounted<progress.totalBytes)
{
const auto estimate=std::ceil((progress.totalBytes-accounted)*(elapsed/1000.0)/(bytes-progress.sampleBytes));
const auto seconds=static_cast<uint64_t>(std::min(estimate,360000000.0));
sizeText+=L" Remaining: "+std::to_wstring(seconds/3600)+L":"+
(seconds%3600/60<10?L"0":L"")+std::to_wstring(seconds%3600/60)+L":"+
(seconds%60<10?L"0":L"")+std::to_wstring(seconds%60);
}
SetDlgItemTextW(progress.window,225,sizeText.c_str());
}
void reportCopyProgress(CopyProgress &progress,uint64_t current,uint64_t fileSize,bool force=false)
{
if(force || GetTickCount64()-progress.lastPaint>=200)
progress.ui.invoke([&] {updateCopyProgress(progress,current,fileSize);});
}
LRESULT CALLBACK dialogButtonEnter(HWND button,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_GETDLGCODE)
{
const auto key=reinterpret_cast<const MSG*>(lp);
if(key && key->message==WM_KEYDOWN && key->wParam==VK_RETURN)
return DefSubclassProc(button,message,wp,lp)|DLGC_WANTMESSAGE;
}
if(message==WM_KEYDOWN && wp==VK_RETURN)
{
SendMessageW(button,BM_CLICK,0,0);
return 0;
}
return DefSubclassProc(button,message,wp,lp);
}
INT_PTR paintTextDialog(HWND window,UINT message,WPARAM wp,LPARAM lp,const wchar_t *caption)
{
return paintCopyDialog(window,message,wp,lp,caption,false,{},true);
}
INT_PTR paintSearchDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_DRAWITEM)
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
if(item.CtlID==ks::files::searchHistoryButton)
{
if(lavenderFiles()) paintLavenderComboFace(item.hwndItem,item.hDC,item.rcItem,L"");
else ks::files::paintFarFieldArrow(item.hDC,item.rcItem,
!(item.itemState&ODS_DISABLED),GetDpiForWindow(item.hwndItem));
if(item.itemState&ODS_FOCUS) DrawFocusRect(item.hDC,&item.rcItem);
return TRUE;
}
if(item.CtlType==ODT_STATIC)
{
if(lavenderFiles()) lavender::fill(item.hDC,item.rcItem,lavender::surface);
else FillRect(item.hDC,&item.rcItem,static_cast<HBRUSH>(GetStockObject(LTGRAY_BRUSH)));
SelectObject(item.hDC,dialogUiFont());
SetBkMode(item.hDC,TRANSPARENT);
SetTextColor(item.hDC,lavenderFiles()?lavender::ink:RGB(0,0,0));
wchar_t label[40]{};
GetWindowTextW(item.hwndItem,label,static_cast<int>(std::size(label)));
drawFarDialogLabel(item.hDC,item.rcItem,label,false);
return TRUE;
}
paintDialogButton(item,RGB(192,192,192),RGB(0,0,0),true);
return TRUE;
}
return paintCopyDialog(window,message,wp,lp,L" Search ",false,
{ks::files::searchOptionsDivider,ks::files::searchButtonsDivider});
}
LONG searchDialogInset(HWND dialog)
{
return std::max<LONG>(dialogFrameMetrics(GetDpiForWindow(dialog)).content(),2*cellWidth);
}
void layoutSearchDialog(HWND dialog)
{
RECT client{};
GetClientRect(dialog,&client);
const LONG inset=searchDialogInset(dialog);
const LONG gap=dialogColumnGap();
const LONG available=client.right-2*inset;
const auto size=[&](int id)
{
const auto bounds=dialogControlBounds(dialog,id);
return SIZE{bounds.right-bounds.left,bounds.bottom-bounds.top};
};
const auto place=[&](int id,LONG x,LONG y,LONG width,LONG height)
{
SetWindowPos(GetDlgItem(dialog,id),nullptr,x,y,width,height,
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
};
const auto options=std::array{106,107};
const auto actions=std::array{103,IDOK,IDCANCEL};
const auto rowWidth=[&](const auto &ids)
{
LONG width=-gap;
for(const auto id:ids) width+=size(id).cx+gap;
return width;
};
const LONG row=textHeight;
const LONG spacing=dialogRowGap();
LONG y=dialogFrameMetrics(GetDpiForWindow(dialog)).content()+spacing;
const auto field=size(100);
const auto optionWidth=rowWidth(options);
const auto optionRowFits=optionWidth<=available;
const auto optionsBesideLabel=optionWidth+gap+11*cellWidth<=available;
const auto buttons=[&](const auto &ids,LONG left,bool singleRow)
{
for(const auto id:ids)
{
const auto bounds=size(id);
place(id,singleRow?left:(client.right-bounds.cx)/2,y,bounds.cx,row);
left+=bounds.cx+gap;
if(!singleRow) y+=row;
}
if(singleRow) y+=row;
};
place(109,inset,y,optionsBesideLabel?available-optionWidth-gap:available,row);
if(optionsBesideLabel) buttons(options,client.right-inset-optionWidth,true);
else y+=row;
const auto parts=farDropDownBounds({inset,y,client.right-inset,y+field.cy});
place(100,parts.field.left,y,parts.field.right-parts.field.left,field.cy);
place(ks::files::searchHistoryButton,parts.arrow.left,y,parts.arrow.right-parts.arrow.left,field.cy);
y+=field.cy+spacing;
if(!optionsBesideLabel) buttons(options,(client.right-optionWidth)/2,optionRowFits);
place(ks::files::searchOptionsDivider,inset,y,1,1);
y+=spacing;
for(const auto id:{101,102})
{
place(id,inset,y,available,row);
y+=row;
}
y+=std::max(1L,spacing/2);
place(ks::files::searchButtonsDivider,inset,y,1,1);
y+=spacing;
const auto actionsWidth=rowWidth(actions);
buttons(actions,(client.right-actionsWidth)/2,actionsWidth<=available);
RECT bounds{},owner{};
GetWindowRect(dialog,&bounds);
GetWindowRect(GetWindow(dialog,GW_OWNER),&owner);
const auto height=y+dialogFrameMetrics(GetDpiForWindow(dialog)).content()+spacing;
if(height!=bounds.bottom-bounds.top)
SetWindowPos(dialog,nullptr,bounds.left,(owner.top+owner.bottom-height)/2,client.right,height,
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
}
void prepareTextDialog(HWND dialog)
{
prepareCopyDialog(dialog);
TEXTMETRICW templateMetrics{}, filesMetrics{};
const auto dc=GetDC(dialog);
if(dc)
{
const auto templateFont=reinterpret_cast<HFONT>(SendMessageW(dialog,WM_GETFONT,0,0));
const auto previous=SelectObject(dc,templateFont);
GetTextMetricsW(dc,&templateMetrics);
SelectObject(dc,dialogUiFont());
GetTextMetricsW(dc,&filesMetrics);
SelectObject(dc,previous);
ReleaseDC(dialog,dc);
}
const auto scale=[&](LONG value,LONG original,LONG actual)
{
return original>0?MulDiv(value,std::max(original,actual),original):value;
};
const auto x=[&](LONG value){return scale(value,templateMetrics.tmAveCharWidth,filesMetrics.tmAveCharWidth);};
const auto y=[&](LONG value){return scale(value,templateMetrics.tmHeight,filesMetrics.tmHeight);};
RECT bounds{};
GetWindowRect(dialog,&bounds);
const auto width=x(bounds.right-bounds.left),height=y(bounds.bottom-bounds.top);
SetWindowPos(dialog,nullptr,(bounds.left+bounds.right-width)/2,(bounds.top+bounds.bottom-height)/2,
width,height,SWP_NOZORDER|SWP_NOACTIVATE);
SendMessageW(dialog,WM_SETFONT,reinterpret_cast<WPARAM>(dialogUiFont()),FALSE);
const bool search=GetDlgItem(dialog,ks::files::searchOptionsDivider)!=nullptr;
for(auto field=GetWindow(dialog,GW_CHILD);field;field=GetWindow(field,GW_HWNDNEXT))
{
RECT rect{};
GetWindowRect(field,&rect);
MapWindowPoints(nullptr,dialog,reinterpret_cast<POINT*>(&rect),2);
SetWindowPos(field,nullptr,x(rect.left),y(rect.top),x(rect.right)-x(rect.left),y(rect.bottom)-y(rect.top),
SWP_NOZORDER|SWP_NOACTIVATE);
SendMessageW(field,WM_SETFONT,reinterpret_cast<WPARAM>(dialogUiFont()),FALSE);
wchar_t type[16]{};
GetClassNameW(field,type,static_cast<int>(std::size(type)));
if(lstrcmpiW(type,L"Button")==0 && (GetWindowLongPtrW(field,GWL_STYLE)&BS_TYPEMASK)==BS_AUTOCHECKBOX)
installFarCheckbox(field,search?FarCheckboxSurface::gray:FarCheckboxSurface::dialog);
}
if(search)
{
fitFarEditToLine(GetDlgItem(dialog,100));
LONG widest{};
for(const auto id:{103,IDOK,IDCANCEL,106,107})
{
const auto button=GetDlgItem(dialog,id);
const auto width=farDialogButtonWidth(button);
SetWindowPos(button,nullptr,0,0,width,textHeight,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
widest=std::max(widest,width);
}
FilesModalDialog::fitWidthToOwner(dialog,2*searchDialogInset(dialog)+std::max<LONG>(widest,22*cellWidth),layoutSearchDialog);
}
}
INT_PTR CALLBACK textSaveDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
prepareTextDialog(window);
groupDialogButtons(window,{IDYES,IDNO,IDCANCEL});
SendMessageW(window,DM_SETDEFID,IDCANCEL,0);
SetFocus(GetDlgItem(window,IDCANCEL));
return FALSE;
}
if(const auto painted=paintTextDialog(window,message,wp,lp,L" Editor ")) return painted;
if(message==WM_COMMAND && (LOWORD(wp)==IDYES || LOWORD(wp)==IDNO || LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(window,LOWORD(wp));
return TRUE;
}
return FALSE;
}
INT_PTR confirmTextSave(HWND owner,bool draft)
{
if(draft)
return showFilesNotice(owner,L"Save changes to this file?",L"Editor",
{.tone=FilesNoticeTone::warning,.saveChanges=true});
return FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(603),owner,textSaveDialog,0);
}
struct FilesNotice
{
const wchar_t *text;
std::wstring title;
FilesNoticeOptions options;
};
constexpr int showProcessesButton=103;
void layoutFilesNotice(HWND dialog)
{
const auto &notice=*reinterpret_cast<const FilesNotice *>(GetWindowLongPtrW(dialog,DWLP_USER));
const auto frame=dialogFrameMetrics(GetDpiForWindow(dialog));
const auto inset=frame.content();
const int header=isLavenderFileOperation(dialog)?LavenderMetrics(dialog).px(operationHeaderHeight+2):0;
const auto top=std::max(header,dialogListInset(frame,textHeight));
const auto field=GetDlgItem(dialog,100);
RECT client{};
GetClientRect(dialog,&client);
const auto contentWidth=std::max(1L,client.right-2*inset);
TEXTMETRICW metrics{};
if(const auto dc=GetDC(field))
{
const auto previous=SelectObject(dc,dialogUiFont());
GetTextMetricsW(dc,&metrics);
SelectObject(dc,previous);
ReleaseDC(field,dc);
}
const auto lineHeight=std::max(1L,metrics.tmHeight);
const auto place=[&](int id,int y,int height)
{
SetWindowPos(GetDlgItem(dialog,id),nullptr,inset,y,contentWidth,height,SWP_NOZORDER|SWP_NOACTIVATE);
};
constexpr LRESULT maxLines=8;
place(100,top,maxLines*lineHeight);
const auto lines=SendMessageW(field,EM_GETLINECOUNT,0,0);
const bool overflow=lines>maxLines;
const auto height=static_cast<int>(std::clamp<LRESULT>(lines,1,maxLines))*lineHeight;
place(100,top,height);
if(overflow) SetWindowPos(field,nullptr,inset,top,
std::max(1L,contentWidth-scrollBarWidth(field)),height,SWP_NOZORDER|SWP_NOACTIVATE);
const auto style=GetWindowLongPtrW(field,GWL_STYLE);
SetWindowLongPtrW(field,GWL_STYLE,overflow?style|WS_TABSTOP:style&~WS_TABSTOP);
if(!overflow) SendMessageW(field,EM_LINESCROLL,0,-SendMessageW(field,EM_GETFIRSTVISIBLELINE,0,0));
auto bottom=top+height;
if(notice.options.remember)
{
bottom+=dialogRowGap();
place(101,bottom,textHeight);
bottom+=textHeight;
}
place(102,bottom+dialogRowGap()+4,1);
if(notice.options.saveChanges || notice.options.chooseTransfer) layoutDialogButtons(dialog,102,{IDYES,IDNO,IDCANCEL});
else if(notice.options.confirm) layoutDialogButtons(dialog,102,{IDYES,IDNO});
else if(notice.options.processes) layoutDialogButtons(dialog,102,{showProcessesButton,IDOK});
else layoutDialogButtons(dialog,102,{IDOK});
}
INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(window,DWLP_USER,lp);
const auto &notice=*reinterpret_cast<const FilesNotice *>(lp);
if(notice.options.fileOperation || isLavenderFileOperation(GetWindow(window,GW_OWNER)))
markLavenderFileOperation(window);
prepareTextDialog(window);
const auto field=GetDlgItem(window,100);
SendMessageW(field,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,0);
SetWindowTextW(field,notice.text);
installScrollBar(field,window,noticeScrollBar);
if(notice.options.remember)
{
const auto checkbox=GetDlgItem(window,101);
installFarCheckbox(checkbox,notice.options.tone==FilesNoticeTone::warning?FarCheckboxSurface::warning:
notice.options.tone==FilesNoticeTone::neutral?FarCheckboxSurface::gray:FarCheckboxSurface::dialog);
ShowWindow(checkbox,SW_SHOW);
}
if(notice.options.confirm || notice.options.saveChanges || notice.options.chooseTransfer)
{
ShowWindow(GetDlgItem(window,IDOK),SW_HIDE);
ShowWindow(GetDlgItem(window,IDYES),SW_SHOW);
ShowWindow(GetDlgItem(window,IDNO),SW_SHOW);
}
if(notice.options.accept) SetDlgItemTextW(window,IDYES,notice.options.accept);
if(notice.options.decline) SetDlgItemTextW(window,IDNO,notice.options.decline);
if(notice.options.saveChanges)
{
SetDlgItemTextW(window,IDYES,L"&Save");
SetDlgItemTextW(window,IDNO,L"&Discard");
ShowWindow(GetDlgItem(window,IDCANCEL),SW_SHOW);
}
if(notice.options.chooseTransfer)
{
SetDlgItemTextW(window,IDYES,L"&Copy");
SetDlgItemTextW(window,IDNO,L"&Move");
SetDlgItemTextW(window,IDCANCEL,L"Ca&ncel");
ShowWindow(GetDlgItem(window,IDCANCEL),SW_SHOW);
}
if(notice.options.processes) ShowWindow(GetDlgItem(window,showProcessesButton),SW_SHOW);
RECT caption{},text{};
if(const auto dc=GetDC(window))
{
const auto previous=SelectObject(dc,dialogUiFont());
DrawTextW(dc,notice.title.c_str(),-1,&caption,DT_CALCRECT|DT_SINGLELINE|DT_NOPREFIX);
DrawTextW(dc,notice.text,-1,&text,DT_CALCRECT|DT_NOPREFIX|DT_EXPANDTABS);
SelectObject(dc,previous);
ReleaseDC(window,dc);
}
const auto inset=dialogFrameMetrics(GetDpiForWindow(window)).content();
const auto minimum=std::max({24L*cellWidth,caption.right+6*cellWidth,
notice.options.remember || notice.options.processes || notice.options.saveChanges || notice.options.chooseTransfer?34L*cellWidth:0L})+2*inset;
const auto width=std::clamp(text.right+cellWidth+2*inset,minimum,std::max(minimum,60L*cellWidth+2*inset));
SetWindowPos(window,nullptr,0,0,width,1,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
layoutFilesNotice(window);
FilesModalDialog::fitWidthToOwner(window,minimum,layoutFilesNotice);
const auto defaultButton=(notice.options.saveChanges || notice.options.chooseTransfer)?IDCANCEL:notice.options.confirm?IDNO:IDOK;
SendMessageW(window,DM_SETDEFID,defaultButton,0);
SetFocus(GetDlgItem(window,defaultButton));
return FALSE;
}
const auto *notice=reinterpret_cast<const FilesNotice *>(GetWindowLongPtrW(window,DWLP_USER));
if(!notice) return FALSE;
const bool warning=notice->options.tone==FilesNoticeTone::warning;
const bool palette=notice->options.tone==FilesNoticeTone::dialog;
if(warning && lavenderFiles()) SetPropW(window,lavenderDialogWarning,reinterpret_cast<HANDLE>(1));
if(message==WM_CTLCOLORSTATIC && reinterpret_cast<HWND>(lp)==GetDlgItem(window,100) && !palette)
{
const auto dc=reinterpret_cast<HDC>(wp);
SetTextColor(dc,warning?RGB(255,255,255):RGB(0,0,0));
SetBkColor(dc,warning?RGB(128,0,0):RGB(192,192,192));
return reinterpret_cast<INT_PTR>(warning?warningBrush:GetStockObject(LTGRAY_BRUSH));
}
if(const auto painted=paintCopyDialog(window,message,wp,lp,notice->title.c_str(),warning,{102},palette,GetDlgItem(window,100),true))
return painted;
const auto command=LOWORD(wp);
if(message==WM_COMMAND && (command==IDOK || command==IDCANCEL || command==IDYES || command==IDNO ||
(command==showProcessesButton && notice->options.processes)))
{
if(command==IDYES && notice->options.remember)
*notice->options.remember=IsDlgButtonChecked(window,101)==BST_CHECKED;
FilesModalDialog::finish(window,command);
return TRUE;
}
return FALSE;
}
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options)
{
const bool createBrush=options.tone==FilesNoticeTone::warning && !warningBrush;
if(createBrush) warningBrush=CreateSolidBrush(RGB(128,0,0));
FilesNotice notice{text,std::wstring(L" ")+title+L" ",options};
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(607),owner,filesNoticeDialog,
reinterpret_cast<LPARAM>(&notice));
if(createBrush)
{
DeleteObject(warningBrush);
warningBrush=nullptr;
}
return result;
}
#include "files_lock_processes.inl"
void showFileOperationError(HWND owner,const wchar_t *title,const std::wstring &message,
std::vector<fs::path> lockPaths={})
{
setStatus(L"");
const auto choice=showFilesNotice(owner,message.c_str(),title,
{.tone=FilesNoticeTone::warning,.processes=!lockPaths.empty(),.fileOperation=true});
if(choice==showProcessesButton) showProcesses(owner,std::move(lockPaths));
}
void showTextMessage(HWND owner,const wchar_t *text)
{
showFilesNotice(owner,text,L"KSwitcher Files");
}
INT_PTR CALLBACK cancelOperationDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(const auto painted=paintFileOperationDialog(window,message,wp,lp,L" Operation interrupted ",true,{236}))
return painted;
if(message==WM_INITDIALOG)
{
prepareCopyDialog(window);
layoutDialogContent(window,235);
SetDlgItemTextW(window,235,reinterpret_cast<const wchar_t*>(lp));
SendDlgItemMessageW(window,235,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
layoutDialogButtons(window,236,{IDYES,IDNO});
SendMessageW(window,DM_SETDEFID,IDNO,0);
SetFocus(GetDlgItem(window,IDNO));
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND &&
(LOWORD(wp)==IDYES || LOWORD(wp)==IDNO || LOWORD(wp)==IDCANCEL)))
{
FilesModalDialog::finish(window,message==WM_COMMAND && LOWORD(wp)==IDYES?IDYES:IDNO);
return TRUE;
}
return FALSE;
}
bool confirmOperationCancellation(HWND owner,const wchar_t *question)
{
const auto previous=warningBrush;
if(!previous) warningBrush=CreateSolidBrush(RGB(128,0,0));
const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(105),owner,
cancelOperationDialog,reinterpret_cast<LPARAM>(question));
if(!previous)
{
DeleteObject(warningBrush);
warningBrush=nullptr;
}
return answer==IDYES;
}
INT_PTR CALLBACK copyProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_DRAWITEM && (wp==220 || wp==221))
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT*>(lp);
std::wstring path(GetWindowTextLengthW(item.hwndItem)+1,L'\0');
GetWindowTextW(item.hwndItem,path.data(),static_cast<int>(path.size()));
auto bounds=item.rcItem;
if(lavenderFiles()) lavender::fill(item.hDC,bounds,lavenderDialogSurface(window));
else FillRect(item.hDC,&bounds,static_cast<HBRUSH>(GetStockObject(LTGRAY_BRUSH)));
SelectObject(item.hDC,dialogUiFont());
SetBkMode(item.hDC,TRANSPARENT);
SetTextColor(item.hDC,lavenderFiles()?lavender::ink:RGB(0,0,0));
constexpr auto flags=DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX;
const int prefix=wp==220?6:4;
if(GetWindowTextLengthW(item.hwndItem)>prefix && path[prefix-2]==L':')
{
SIZE width{};
GetTextExtentPoint32W(item.hDC,path.data(),prefix,&width);
DrawTextW(item.hDC,path.data(),prefix,&bounds,flags);
bounds.left+=width.cx;
DrawTextW(item.hDC,path.data()+prefix,-1,&bounds,flags|DT_PATH_ELLIPSIS|DT_END_ELLIPSIS);
}
else DrawTextW(item.hDC,path.data(),-1,&bounds,flags|DT_END_ELLIPSIS);
return TRUE;
}
const auto operation=reinterpret_cast<const CopyProgress*>(GetWindowLongPtrW(window,DWLP_USER));
if(const auto painted=paintFileOperationDialog(window,message,wp,lp,
operation && operation->writingArchive?L" Pack ":operation && operation->move?L" Move ":L" Copy ",false,{228,229}))
return painted;
if(message==WM_DPICHANGED)
{
PostMessageW(window,refreshProgressLayout,0,0);
return FALSE;
}
if(message==WM_INITDIALOG || message==refreshProgressLayout)
{
if(message==WM_INITDIALOG)
{
prepareCopyDialog(window);
layoutDialogContent(window,220);
SetWindowLongPtrW(window,DWLP_USER,lp);
}
for(const auto control:{220,221,224,225})
{
SendDlgItemMessageW(window,control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
const auto bounds=dialogControlBounds(window,control);
SetWindowPos(GetDlgItem(window,control),nullptr,0,0,bounds.right-bounds.left,textHeight,
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
}
for(const auto id:{222,226})
{
const auto bar=GetDlgItem(window,id);
const auto bounds=dialogControlBounds(window,id);
SetWindowPos(bar,nullptr,0,0,bounds.right-bounds.left,textHeight+8,
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowSubclass(bar,paintCopyProgressBar,1,0);
}
const auto moveRow=[&](int id,LONG top)
{
const auto bounds=dialogControlBounds(window,id);
SetWindowPos(GetDlgItem(window,id),nullptr,bounds.left,top,0,0,
SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
};
const auto frame=dialogFrameMetrics(GetDpiForWindow(window));
const auto padding=std::max(0,frame.inner);
moveRow(221,std::max(dialogControlBounds(window,221).top,dialogControlBounds(window,220).bottom));
moveRow(222,std::max(dialogControlBounds(window,222).top,dialogControlBounds(window,221).bottom+4));
const auto firstBottom=dialogControlBounds(window,222).bottom;
moveRow(228,firstBottom+padding+4);
const auto offset=dialogDividerY(window,228)+1+padding-dialogControlBounds(window,224).top;
for(const auto id:{224,225,226})
moveRow(id,dialogControlBounds(window,id).top+offset);
moveRow(225,std::max(dialogControlBounds(window,225).top,dialogControlBounds(window,224).bottom));
moveRow(226,std::max(dialogControlBounds(window,226).top,dialogControlBounds(window,225).bottom+4));
const auto secondBottom=dialogControlBounds(window,226).bottom;
moveRow(229,secondBottom+padding+4);
layoutDialogButtons(window,229,{IDCANCEL});
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
return TRUE;
}
if(message==WM_NCHITTEST)
{
RECT bounds{};
GetWindowRect(window,&bounds);
if(GET_Y_LPARAM(lp)<bounds.top+18)
{
SetWindowLongPtrW(window,DWLP_MSGRESULT,HTCAPTION);
return TRUE;
}
}
if(message!=WM_CLOSE && (message!=WM_COMMAND || LOWORD(wp)!=IDCANCEL)) return FALSE;
auto &progress=*reinterpret_cast<CopyProgress*>(GetWindowLongPtrW(window,DWLP_USER));
if(!progress.canceled)
progress.canceled=confirmOperationCancellation(window,progress.writingArchive?
L"Do you really want to cancel writing the archive?":progress.move?
L"Do you really want to cancel moving?":L"Do you really want to cancel copying?");
return TRUE;
}
struct WarningPrompt
{
const wchar_t *message;
const wchar_t *details;
const wchar_t *accept;
const wchar_t *decline;
FileInfo incoming,existing;
bool remember{};
};
std::wstring conflictFileDetails(const FileInfo &file)
{
wchar_t date[32]=L"—";
if(const auto time=localFileTime(file.modified))
swprintf_s(date,L"%04u-%02u-%02u %02u:%02u:%02u",unsigned(time->wYear),
unsigned(time->wMonth),unsigned(time->wDay),unsigned(time->wHour),
unsigned(time->wMinute),unsigned(time->wSecond));
auto bytes=std::to_wstring(file.size);
for(auto position=bytes.size();position>3;)
{
position-=3;
bytes.insert(position,1,L'\u202F');
}
return bytes+L" B "+date;
}
LRESULT CALLBACK warningButtonKeys(HWND button,UINT message,WPARAM wp,LPARAM lp,
UINT_PTR,DWORD_PTR index)
{
if(message==WM_GETDLGCODE) return DefSubclassProc(button,message,wp,lp)|DLGC_WANTARROWS;
if(message==WM_KEYDOWN && (wp==VK_UP || wp==VK_DOWN))
{
if(index<3 && wp==VK_UP) SetFocus(GetDlgItem(GetParent(button),232));
if(index==3 && wp==VK_DOWN) SetFocus(GetDlgItem(GetParent(button),IDYES));
return 0;
}
if(message==WM_KEYDOWN && index<3 && (wp==VK_LEFT || wp==VK_RIGHT))
{
constexpr int buttons[]{IDYES,IDNO,IDCANCEL};
SetFocus(GetDlgItem(GetParent(button),buttons[(index+(wp==VK_LEFT?2:1))%3]));
return 0;
}
return DefSubclassProc(button,message,wp,lp);
}
INT_PTR CALLBACK warningDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(const auto painted=paintFileOperationDialog(window,message,wp,lp,L" Warning ",true,{233,333,234}))
return painted;
if(message==WM_INITDIALOG)
{
prepareCopyDialog(window);
layoutDialogContent(window,230);
SetWindowLongPtrW(window,DWLP_USER,lp);
const auto &warning=*reinterpret_cast<WarningPrompt*>(lp);
SetDlgItemTextW(window,230,warning.message);
SetDlgItemTextW(window,231,warning.details);
SetDlgItemTextW(window,330,conflictFileDetails(warning.incoming).c_str());
SetDlgItemTextW(window,332,conflictFileDetails(warning.existing).c_str());
SetDlgItemTextW(window,IDYES,warning.accept);
SetDlgItemTextW(window,IDNO,warning.decline);
for(const auto control:{230,231,232,329,330,331,332})
SendDlgItemMessageW(window,control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
installFarCheckbox(GetDlgItem(window,232),FarCheckboxSurface::warning);
centerDialogRow(window,333,234,{232});
layoutDialogButtons(window,234,{IDYES,IDNO,IDCANCEL});
SendMessageW(window,DM_SETDEFID,IDNO,0);
constexpr int buttons[]{IDYES,IDNO,IDCANCEL};
for(size_t i=0;i<std::size(buttons);++i)
SetWindowSubclass(GetDlgItem(window,buttons[i]),warningButtonKeys,1,i);
SetWindowSubclass(GetDlgItem(window,232),warningButtonKeys,1,std::size(buttons));
SetFocus(GetDlgItem(window,IDNO));
return FALSE;
}
if(message==WM_CLOSE)
{
FilesModalDialog::finish(window,IDCANCEL);
return TRUE;
}
if(message==WM_COMMAND && (LOWORD(wp)==IDYES || LOWORD(wp)==IDNO || LOWORD(wp)==IDCANCEL))
{
auto &warning=*reinterpret_cast<WarningPrompt*>(GetWindowLongPtrW(window,DWLP_USER));
warning.remember=IsDlgButtonChecked(window,232)==BST_CHECKED;
const auto choice=LOWORD(wp);
FilesModalDialog::finish(window,choice);
return TRUE;
}
return FALSE;
}
using FileEntries=std::vector<std::pair<fs::path,FileInfo>>;
FileEntries childrenOf(FilesConnection &host,const fs::path &path)
{
FileEntries children;
listFiles(host,path,[&](const fs::path &child,const FileInfo &info)
{
children.emplace_back(child,info);
return true;
});
return children;
}
#include "files_elevation.inl"
#include "files_ftp_copy.inl"
#include "files_compare.inl"
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();
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,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=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};
};
};
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)
{
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;
}
struct CopyNode
{
fs::path path;
FileInfo info;
std::vector<CopyNode> children;
bool whole=true;
};
std::optional<CopyNode> planCopy(CopyHost &host,const fs::path &path,CopyProgress &progress)
{
if(progress.canceled) throw std::system_error(ERROR_CANCELLED,std::system_category());
const auto info=host.stat(path,progress.canceled);
if(!info) throw std::system_error(ERROR_FILE_NOT_FOUND,std::system_category());
const bool directory=info->attributes&FILE_ATTRIBUTE_DIRECTORY;
if(!directory && !matchesFileMask(path.filename().native(),progress.options.mask)) return {};
if(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT)
throw std::system_error(ERROR_NOT_SUPPORTED,std::system_category());
if(progress.fileSourcesOnly && directory)
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
CopyNode node{path,*info,{}};
if(!directory)
{
++progress.totalFiles;
progress.totalBytes+=info->size;
}
else
{
for(const auto &[child,entry]:host.children(path,progress.canceled))
{
auto item=planCopy(host,child,progress);
node.whole=node.whole && item && item->whole;
if(item) node.children.push_back(std::move(*item));
}
if(node.children.empty() && progress.options.mask!=L"*") return {};
}
return node;
}
void verifyCopyPlan(CopyHost &source,const CopyNode &node,const std::atomic_bool &canceled)
{
if(canceled) throw std::system_error(ERROR_CANCELLED,std::system_category());
const auto current=source.stat(node.path,canceled);
if(!current || current->size!=node.info.size || current->modified!=node.info.modified ||
((current->attributes^node.info.attributes)&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)))
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
for(const auto &child:node.children) verifyCopyPlan(source,child,canceled);
}
void removeCopiedPlan(CopyHost &source,const CopyNode &node,CopyProgress &progress,bool local)
{
if(progress.canceled) throw std::system_error(ERROR_CANCELLED,std::system_category());
const bool directory=node.info.attributes&FILE_ATTRIBUTE_DIRECTORY;
for(const auto &child:node.children) removeCopiedPlan(source,child,progress,local);
if(directory && !node.whole) return;
progress.localLockSource=local?node.path:fs::path{};
progress.localLockTarget.clear();
auto action=fileRequest(directory?"rmdir":"remove",node.path);
if(!directory)
{
action["size"]=node.info.size;
action["modified"]=node.info.modified;
}
checkFileReply(source.request(action));
}
enum class CopyResult { complete, skipped, failed };
struct CopyEndpoints
{
CopyHost &source, &target;
bool sameHost;
std::string sourceId;
bool sourceLocal, targetLocal;
};
void transferFile(const CopyEndpoints &hosts,const fs::path &from,const fs::path &to,
const FileInfo &info,bool replace,bool append,CopyProgress &progress)
{
const auto update=[&](uint64_t done,uint64_t total)
{
reportCopyProgress(progress,done,total);
return !progress.canceled;
};
if(hosts.source.ftp)
{
downloadTransferFile(*hosts.source.ftp,*hosts.target.files,from,to,info,replace,update);
return;
}
if(hosts.target.ftp)
{
uploadTransferFile(*hosts.source.files,*hosts.target.ftp,from,to,info,replace,update,nullptr,progress.options.preserveTime);
hosts.target.listedDirectory.clear();
return;
}
if(hosts.sameHost)
{
auto request=fileRequest("copy",from);
request["target"]=ks::utf8(to.native());
request["replace"]=replace;
request["append"]=append;
request["size"]=info.size;
request["modified"]=info.modified;
checkFileReply(hosts.source.request(request,update));
return;
}
ks::lan::streamFile(*hosts.source.files,*hosts.target.files,hosts.sourceId,from,to,
info.size,info.modified,replace,append,update);
}
void applyCopyMetadata(const CopyEndpoints &hosts,const fs::path &to,const FileInfo &info,
const CopyOptions &options,const Json &permissions,bool directory)
{
if(hosts.target.ftp)
{
if(directory && options.preserveTime) hosts.target.ftp->preserveModificationTime(to,info.modified);
return;
}
auto request=fileRequest("applyCopyMetadata",to);
if(directory && options.preserveTime && info.modified && hosts.target.supportsCopyMetadata())
request["modified"]=info.modified;
else if(!directory && !options.preserveTime)
request["modified"]=uint64_t{};
if(!permissions.is_null()) request["permissions"]=permissions;
if(request.size()>2) checkFileReply(hosts.target.request(request));
}
CopyResult copyItem(const CopyEndpoints &hosts,const CopyNode &node,const fs::path &to,CopyProgress &progress,
bool topLevel=false,bool singleItem=false)
{
const auto &from=node.path;
if(progress.canceled) return CopyResult::failed;
if((hosts.source.ftp || hosts.target.ftp) && !validFtpCopyName(to.filename().native(),hosts.target.ftp.has_value()))
throw std::system_error(ERROR_INVALID_NAME,std::system_category());
progress.localLockSource=hosts.sourceLocal?from:fs::path{};
progress.localLockTarget=hosts.targetLocal?to:fs::path{};
const auto incoming=hosts.source.stat(from,progress.canceled);
if(!incoming || (incoming->attributes&FILE_ATTRIBUTE_REPARSE_POINT))
throw std::system_error(incoming?ERROR_NOT_SUPPORTED:ERROR_FILE_NOT_FOUND,std::system_category());
if(((incoming->attributes^node.info.attributes)&FILE_ATTRIBUTE_DIRECTORY) ||
(!(incoming->attributes&FILE_ATTRIBUTE_DIRECTORY) &&
(incoming->size!=node.info.size || incoming->modified!=node.info.modified)))
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
const auto readPermissions=[&] {
if(!progress.options.preservePermissions) return Json(nullptr);
const auto reply=hosts.source.request(fileRequest("copyPermissions",from));
checkFileReply(reply);
return Json(reply.at("permissions"));
};
const auto removeImmediately=progress.move && !progress.deferRemoval;
const auto moveOnHost=[&](const fs::path &target,bool replace)
{
if(!removeImmediately || !hosts.sameHost) return false;
auto request=fileRequest("move",from);
request["target"]=ks::utf8(target.native());
request["replace"]=replace;
const auto reply=hosts.source.request(request);
if(reply.at("error")==ERROR_NOT_SAME_DEVICE) return false;
checkFileReply(reply);
return true;
};
const auto existing=hosts.target.stat(to,progress.canceled);
if(incoming->attributes&FILE_ATTRIBUTE_DIRECTORY)
{
if(existing && (!(existing->attributes&FILE_ATTRIBUTE_DIRECTORY) ||
(existing->attributes&FILE_ATTRIBUTE_REPARSE_POINT)))
throw std::system_error(ERROR_ALREADY_EXISTS,std::system_category());
if(!existing && singleItem && moveOnHost(to,false))
{
progress.files=progress.totalFiles;
progress.bytes=progress.totalBytes;
return CopyResult::complete;
}
const auto permissions=existing?Json(nullptr):readPermissions();
if(!existing) hosts.target.makeDirectory(to);
auto result=CopyResult::complete;
for(const auto &child:node.children)
{
const auto outcome=copyItem(hosts,child,to/child.path.filename(),progress);
if(outcome==CopyResult::failed) return outcome;
if(outcome==CopyResult::skipped) result=outcome;
}
if(!existing) applyCopyMetadata(hosts,to,*incoming,progress.options,permissions,true);
if(removeImmediately && result==CopyResult::complete)
{
progress.localLockSource=hosts.sourceLocal?from:fs::path{};
progress.localLockTarget.clear();
checkFileReply(hosts.source.request(fileRequest("rmdir",from)));
}
return result;
}
progress.from=from;
progress.to=to;
const auto fileSize=incoming->size;
const auto transfer=[&](const fs::path &target,bool replace=false,bool append=false)
{
if(hosts.targetLocal) progress.localLockTarget=target;
if(!moveOnHost(target,replace))
{
const auto permissions=readPermissions();
transferFile(hosts,from,target,*incoming,replace,append,progress);
applyCopyMetadata(hosts,target,*incoming,progress.options,permissions,false);
if(removeImmediately)
{
auto remove=fileRequest("remove",from);
remove["size"]=incoming->size;
remove["modified"]=incoming->modified;
checkFileReply(hosts.source.request(remove));
}
}
progress.bytes+=fileSize;
++progress.files;
reportCopyProgress(progress,0,0);
return CopyResult::complete;
};
const auto skip=[&](const wchar_t *reason)
{
progress.skippedBytes+=fileSize;
++progress.skippedFiles;
progress.lastSkipReason=reason;
reportCopyProgress(progress,0,0);
return CopyResult::skipped;
};
reportCopyProgress(progress,0,fileSize);
if(!existing) return transfer(to);
if(existing->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT))
throw std::system_error(ERROR_ALREADY_EXISTS,std::system_category());
const bool readOnly=(existing->attributes&FILE_ATTRIBUTE_READONLY)!=0;
auto mode=progress.conflictMode;
if(readOnly && progress.askReadOnly) mode=ConflictMode::ask;
if(mode==ConflictMode::skip) return skip(L"existing file");
if(mode==ConflictMode::newer && incoming->modified<=existing->modified)
return skip(L"source is not newer");
if(mode==ConflictMode::rename)
{
for(unsigned index=2;index<=10000;++index)
{
if(progress.canceled) return CopyResult::failed;
const auto name=to.stem().wstring()+L" ("+std::to_wstring(index)+L")"+to.extension().wstring();
const auto candidate=to.parent_path()/name;
if(hosts.target.stat(candidate,progress.canceled)) continue;
const auto result=transfer(candidate);
if(topLevel) progress.renamedTarget=candidate;
return result;
}
throw std::system_error(ERROR_ALREADY_EXISTS,std::system_category());
}
const bool forceAsk=readOnly && progress.askReadOnly && progress.conflictMode!=ConflictMode::ask;
auto answer=mode==ConflictMode::ask?(forceAsk?0:static_cast<INT_PTR>(progress.conflictChoice)):IDYES;
if(!answer)
{
WarningPrompt warning{readOnly?L"Existing file is read-only":L"File already exists",
to.c_str(),L"&Overwrite",L"&Skip",*incoming,*existing};
answer=progress.ui.invoke([&] {
if(progress.canceled) return static_cast<INT_PTR>(IDCANCEL);
warningBrush=CreateSolidBrush(RGB(128,0,0));
const auto choice=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(104),progress.window,
warningDialog,reinterpret_cast<LPARAM>(&warning));
DeleteObject(warningBrush);
warningBrush=nullptr;
return choice;
});
if(warning.remember && (answer==IDYES || answer==IDNO))
progress.conflictChoice=static_cast<int>(answer);
}
if(answer==IDNO) return skip(readOnly?L"read-only conflict":L"conflict choice");
if(answer!=IDYES)
{
progress.canceled=answer==IDCANCEL;
return CopyResult::failed;
}
return transfer(to,true,mode==ConflictMode::append);
}
void pruneSearchResults(Panel &panel,const std::set<fs::path> &removed)
{
if(!panel.findOrigin || removed.empty()) return;
const bool visible=IsWindowVisible(panel.list);
if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0);
const auto cursor=currentPanelRow(panel);
LRESULT next=cursor;
for(size_t row=panel.rows.size();row>0;)
{
--row;
const auto &path=panel.rows[row];
if(!removed.contains(path)) continue;
panel.metadata.erase(path);
SendMessageW(panel.list,LB_DELETESTRING,row,0);
panel.rows.erase(panel.rows.begin()+row);
panel.sizes.erase(panel.sizes.begin()+row);
panel.dimmed.erase(panel.dimmed.begin()+row);
panel.marked.erase(panel.marked.begin()+row);
if(static_cast<LRESULT>(row)<cursor) --next;
}
if(cursor!=LB_ERR && !panel.rows.empty())
SendMessageW(panel.list,LB_SETCURSEL,std::min(next,static_cast<LRESULT>(panel.rows.size()-1)),0);
if(visible) SendMessageW(panel.list,WM_SETREDRAW,TRUE,0);
InvalidateRect(panel.list,nullptr,FALSE);
updateSelectionSummary(panel);
}
struct ArchiveStaging
{
fs::path directory;
void create()
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
throw std::runtime_error("Could not create temporary storage for archive entries.");
const auto path=fs::temp_directory_path()/(L"ks-files-archive-"+std::wstring(name));
if(!fs::create_directory(path)) throw std::runtime_error("Could not create temporary storage for archive entries.");
directory=path;
}
~ArchiveStaging()
{
if(directory.empty()) return;
std::error_code error;
fs::remove_all(directory,error);
}
};
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);
if(source.listing || (destination.listing && !ftpRename && !renameHere))
{
setStatus(L"Open a folder before copying or moving files.");
return;
}
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 && !renameHere)
{
setStatus(L"Close Quick View to use the destination pane.");
return;
}
if(destination.findOrigin && !ftpRename && !renameHere)
{
setStatus(L"Open a destination folder in the other panel before copying or moving files.");
return;
}
if(source.findOrigin && source.scanRequest)
{
setStatus(L"Wait for the search to finish.");
return;
}
if(destination.archive)
{
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,explicitItems.empty()?selectedPanelPaths(source):std::move(explicitItems));
return;
}
if(!archive.empty() && (move || destination.peer || destination.ftp))
{
setStatus(L"Use F5 to extract archive entries to a local folder.");
return;
}
const bool fromSearch=source.findOrigin.has_value();
const auto destinationFtp=ftpRename?sourceFtp:destination.ftp;
const bool ftp=sourceFtp || destinationFtp;
if(ftp && !ftpRename && (move || (sourceFtp && destinationFtp) || source.peer || destination.peer ||
transferProfileList(source) || transferProfileList(destination)))
{
setStatus(L"F5 copies between a local folder and a connected FTP or SFTP folder.");
return;
}
if(copyInProgress)
{
setStatus(L"A copy is already in progress.");
return;
}
if(targetFolder.empty()) targetFolder=ftpRename?source.directory:destination.directory;
CopyRequest request{{},targetFolder};
request.move=move;
request.ftpRename=ftpRename;
request.externalSources=!explicitItems.empty() && !renameHere;
request.archiveSource=!archive.empty();
if(ftp)
{
request.ftpDestination=panelLocation(destination);
request.upload=destinationFtp.has_value();
}
request.otherDirectory=ftpRename?destination.directory:targetFolder;
request.sourcePeer=source.peer?&*source.peer:nullptr;
request.otherPeer=request.destinationPeer=destination.peer?&*destination.peer:nullptr;
request.sources=explicitItems.empty()?selectedPanelPaths(source):std::move(explicitItems);
if(request.sources.empty()) return;
if(ftpRename)
{
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));
if(result==-1) showFileOperationError(owner,move?L"Move failed":L"Copy failed",L"Could not open the operation dialog.");
if(result!=IDOK) return;
const bool renamed=!request.newName.empty();
const bool renameInSource=renamed && !move && !ftp && !request.externalSources && archive.empty();
const auto targetDirectory=renameInSource?request.sources.front().parent_path():request.destination;
const auto *targetPeer=renameInSource?request.sourcePeer:request.destinationPeer;
const auto peerId=[](const FilesPeer *peer){return peer?peer->id:std::string{};};
const bool sameHost=!ftp && peerId(request.sourcePeer)==peerId(targetPeer);
CopyProgress progress;
progress.move=move;
progress.fileSourcesOnly=fromSearch;
progress.conflictMode=request.conflictMode;
progress.askReadOnly=request.askReadOnly;
progress.options=std::move(request.options);
progress.deferRemoval=move && (progress.options.mask!=L"*" || !progress.options.additional.empty() ||
progress.options.preservePermissions || !progress.options.preserveTime);
FilesModalDialog progressDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(103),owner,
copyProgressDialog,reinterpret_cast<LPARAM>(&progress));
progress.window=progressDialog.window();
if(!progress.window)
{
showFileOperationError(owner,move?L"Move failed":L"Copy failed",L"Could not open the progress dialog.");
return;
}
copyInProgress=true;
activeCopy=&progress;
for(auto &panel:panels) EnableWindow(panel.list,FALSE);
for(const auto command:commands) EnableWindow(command,FALSE);
progressDialog.show();
bool failed=false, skipped=false;
size_t copied=0, completedCopies=0, requestedCopies=0;
const bool multiple=!progress.options.additional.empty();
bool noMatchingFiles=false;
std::set<fs::path> results, removed;
fs::path failedDestination;
std::wstring failure;
std::vector<fs::path> lockPaths;
try
{
progress.ui.run(progress.window,progress.canceled,[&] {
FileOperationElevation elevation(progress.window,progress.canceled,&progress.ui);
auto *admin=archive.empty() && !ftp && !request.sourcePeer && !targetPeer?&elevation:nullptr;
ArchiveStaging staging;
auto sources=request.sources;
if(!archive.empty())
{
staging.create();
std::vector<fs::path> selection;
for(auto &path:sources)
{
selection.push_back(path.lexically_relative(archive));
path=staging.directory/path.filename();
}
progress.from=archive;
progress.to=targetDirectory;
ks::files::extractArchiveSelection(archive,archiveDirectory,selection,staging.directory,[&](uint64_t done,uint64_t total)
{
reportCopyProgress(progress,done,total);
return !progress.canceled;
});
}
CopyHost sourceHost(request.sourcePeer,sourceFtp,admin);
if(ftpRename)
{
const auto &path=request.sources.front();
const auto target=targetDirectory/request.newName;
const auto &entries=sourceHost.ftpListing(targetDirectory,progress.canceled);
if(std::any_of(entries.begin(),entries.end(),[&](const auto &entry)
{
return entry.first!=path &&
CompareStringOrdinal(entry.first.c_str(),-1,target.c_str(),-1,TRUE)==CSTR_EQUAL;
}))
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;
results.insert(target);
return;
}
std::unique_ptr<CopyHost> otherHost;
if(!sameHost) otherHost=std::make_unique<CopyHost>(targetPeer,destinationFtp,admin);
const CopyEndpoints hosts{sourceHost,otherHost?*otherHost:sourceHost,sameHost,
request.sourcePeer?request.sourcePeer->id:"local",!request.sourcePeer && !sourceFtp,
!targetPeer && !destinationFtp};
std::vector<std::pair<size_t,CopyNode>> plans;
for(size_t i=0;i<sources.size();++i)
if(auto plan=planCopy(sourceHost,sources[i],progress)) plans.emplace_back(i,std::move(*plan));
if(plans.empty()) { noMatchingFiles=true; return; }
const auto canonical=[&](const fs::path &name) {
const auto reply=hosts.target.request(fileRequest("canonical",name));
checkFileReply(reply);
return filePath(reply.at("path"));
};
const auto equalPath=[&](const fs::path &first,const fs::path &second) {
return destinationFtp?first==second:
CompareStringOrdinal(first.c_str(),-1,second.c_str(),-1,TRUE)==CSTR_EQUAL;
};
std::vector<fs::path> folders{targetDirectory};
std::vector<fs::path> locations{destinationFtp?targetDirectory:canonical(targetDirectory)};
for(const auto &folder:progress.options.additional)
{
const auto location=destinationFtp?folder:canonical(folder);
if(std::any_of(locations.begin(),locations.end(),[&](const auto &known) {return equalPath(known,location);}))
continue;
const auto info=folder==folder.root_path() && destinationFtp?std::optional<FileInfo>{
FileInfo{FILE_ATTRIBUTE_DIRECTORY,0,0}}:hosts.target.stat(folder,progress.canceled);
if(!info || !(info->attributes&FILE_ATTRIBUTE_DIRECTORY))
{
failedDestination=folder;
throw std::system_error(ERROR_PATH_NOT_FOUND,std::system_category());
}
folders.push_back(folder);
locations.push_back(location);
}
requestedCopies=plans.size()*folders.size();
progress.totalFiles*=folders.size();
progress.totalBytes*=folders.size();
if(progress.options.preservePermissions &&
(!hosts.source.supportsCopyMetadata() || !hosts.target.supportsCopyMetadata()))
throw std::runtime_error("Update both KSwitcher computers to preserve Windows permissions.");
if(!progress.options.preserveTime && !destinationFtp && !hosts.target.supportsCopyMetadata())
throw std::runtime_error("Update KSwitcher on the destination to set a new modification time.");
if(sameHost)
{
for(const auto &[index,plan]:plans)
{
const auto canonicalSource=canonical(plan.path);
for(const auto &folder:folders)
{
const auto target=folder/(renamed?request.newName:plan.path.filename());
const auto canonicalTarget=canonical(target);
for(auto ancestor=canonicalTarget;;ancestor=ancestor.parent_path())
{
if(equalPath(ancestor,canonicalSource))
{
failedDestination=target;
throw std::system_error(ERROR_INVALID_PARAMETER,std::system_category());
}
if(!ancestor.has_relative_path()) break;
}
}
}
}
reportCopyProgress(progress,0,0,true);
for(const auto &[index,plan]:plans)
{
const auto &path=plan.path;
bool allDestinations=true;
fs::path primaryResult;
for(size_t destinationIndex=0;destinationIndex<folders.size();++destinationIndex)
{
if(progress.canceled) return;
const auto to=folders[destinationIndex]/(renamed?request.newName:path.filename());
failedDestination=to;
progress.renamedTarget.clear();
const auto outcome=copyItem(hosts,plan,to,progress,true,plans.size()==1 && folders.size()==1);
if(outcome==CopyResult::failed) { failed=true; return; }
if(outcome==CopyResult::skipped) { skipped=true; allDestinations=false; continue; }
++completedCopies;
if(destinationIndex==0)
{
primaryResult=progress.renamedTarget.empty()?to:progress.renamedTarget;
results.insert(primaryResult);
}
}
if(!allDestinations) continue;
failedDestination.clear();
if(progress.deferRemoval)
{
verifyCopyPlan(sourceHost,plan,progress.canceled);
removeCopiedPlan(sourceHost,plan,progress,hosts.sourceLocal);
if(!plan.whole) skipped=true;
}
if(!primaryResult.empty() && primaryResult.filename()!=path.filename())
progress.renamedTarget=primaryResult;
++copied;
if(move && plan.whole && (fromSearch || treePanelActive(source))) removed.insert(path);
if(!request.externalSources && plan.whole) progress.ui.invoke([&] {
const auto row=std::find(source.rows.begin(),source.rows.end(),request.sources[index]);
if(row!=source.rows.end()) markPanelRow(source,row-source.rows.begin(),false);
else if(treePanelActive(source)) source.tree.marks.erase(path);
InvalidateRect(source.list,nullptr,FALSE);
});
}
});
}
catch(const std::system_error &e)
{
failed=true;
failure=fileError(e);
if(move && isSharingError(e.code().value()))
{
if(!progress.localLockSource.empty()) lockPaths.push_back(progress.localLockSource);
if(!progress.localLockTarget.empty() && progress.localLockTarget!=progress.localLockSource)
lockPaths.push_back(progress.localLockTarget);
}
}
catch(const std::exception &e)
{
failed=true;
failure=ks::wide(e.what());
}
const auto targetId=peerId(targetPeer);
const bool restoreFocus=GetForegroundWindow()==progress.window;
updateCopyProgress(progress,0,0);
RedrawWindow(progress.window,nullptr,nullptr,RDW_UPDATENOW|RDW_ALLCHILDREN);
progressDialog.close();
activeCopy=nullptr;
copyInProgress=false;
updateSelectionSummary(source);
for(auto &panel:panels) EnableWindow(panel.list,TRUE);
for(const auto command:commands) EnableWindow(command,TRUE);
if(progress.closeOwner)
{
PostMessageW(owner,WM_CLOSE,0,0);
return;
}
if(move)
{
if(treePanelActive(source)) pruneTreeMarks(source,removed);
if(fromSearch) pruneSearchResults(source,removed);
else open(source,source.directory);
if(!ftpRename && &source!=&destination) open(destination,destination.directory);
if(!fromSearch && renamed && copied && (sameHost || ftpRename))
{
const auto renamedPath=progress.renamedTarget.empty()?
targetDirectory/request.newName:progress.renamedTarget;
selectPanelPath(request.externalSources?destination:source,renamedPath);
}
}
else
{
auto &updated=renameInSource?source:destination;
if(!updated.findOrigin && updated.directory==targetDirectory)
open(updated,updated.directory);
}
if(!results.empty())
{
for(auto &panel:panels)
{
panel.transferResults.clear();
std::error_code error;
const bool hostMatches=destinationFtp?
panel.ftp && panel.ftp->name==destinationFtp->name && panel.ftp->host==destinationFtp->host &&
panel.ftp->port==destinationFtp->port && panel.ftp->user==destinationFtp->user:
!panel.ftp && peerId(panel.peer?&*panel.peer:nullptr)==targetId;
if(hostMatches && (panel.ftp?panel.directory==targetDirectory:panel.peer?CompareStringOrdinal(panel.directory.c_str(),-1,
targetDirectory.c_str(),-1,TRUE)==CSTR_EQUAL:fs::equivalent(panel.directory,targetDirectory,error)))
for(const auto &path:results) panel.transferResults.insert(panel.directory/path.filename());
InvalidateRect(panel.list,nullptr,FALSE);
}
transferHighlightPhase=0;
if(!SetTimer(owner,transferHighlightTimer,450,nullptr))
for(auto &panel:panels) panel.transferResults.clear();
}
if(restoreFocus)
{
SetForegroundWindow(owner);
SetFocus(panels[active].list);
}
const auto outcomeText=[&] {
auto text=std::to_wstring(completedCopies)+L" of "+std::to_wstring(requestedCopies)+
L" item copies completed across the requested folders. "+std::to_wstring(progress.files)+L" files copied.";
if(move) text+=L" Sources were removed only after their requested copies completed.";
return text;
};
if(failed && !progress.canceled)
{
if(failure.empty()) failure=L"Could not complete the operation.";
if(!failedDestination.empty()) failure+=L"\r\n\r\nDestination: "+failedDestination.native();
if(multiple && requestedCopies) failure+=L"\r\n\r\n"+outcomeText();
showFileOperationError(owner,ftpRename?L"Rename failed":move?L"Move failed":L"Copy failed",
failure,std::move(lockPaths));
}
else if(noMatchingFiles)
setStatus(L"No files match the copy mask.");
else if(multiple)
setStatus((progress.canceled?L"Canceled. ":skipped?L"Finished with skipped copies. ":L"")+outcomeText());
else if(ftpRename)
setStatus(copied?L"Rename complete.":L"Rename canceled.");
else if(move)
{
if(progress.canceled) setStatus(L"Move canceled.");
else if(skipped) setStatus(L"Move complete with skipped items.");
else setStatus(L"Move complete.");
}
else if(progress.canceled) setStatus(L"Copy canceled.");
else if(skipped) setStatus(L"Copy complete with skipped items.");
else setStatus(L"Copy complete.");
}
struct DeleteConfirmation
{
const wchar_t *message;
std::wstring entries;
int lines;
bool permanent;
bool folderPrompt;
bool readOnlyPrompt{};
};
INT_PTR CALLBACK deleteConfirmationDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG) SetWindowLongPtrW(window,DWLP_USER,lp);
const auto data=reinterpret_cast<const DeleteConfirmation*>(GetWindowLongPtrW(window,DWLP_USER));
if(!data) return FALSE;
if(const auto painted=paintFileOperationDialog(window,message,wp,lp,
data->readOnlyPrompt?L" Warning ":data->folderPrompt?L" Delete folder ":L" Delete ",
data->permanent || (lavenderFiles() && data->readOnlyPrompt),{243})) return painted;
if(message==WM_INITDIALOG)
{
prepareCopyDialog(window);
layoutDialogContent(window,240);
SetDlgItemTextW(window,240,data->message);
SetDlgItemTextW(window,241,data->entries.c_str());
if(data->permanent) SetDlgItemTextW(window,IDYES,L"&Delete");
for(const auto id:{240,241})
SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
const auto entries=dialogControlBounds(window,241);
const auto question=dialogControlBounds(window,240);
const std::vector<int> buttons=data->readOnlyPrompt?
std::vector<int>{IDYES,244,IDNO,249,IDCANCEL}:data->folderPrompt?
std::vector<int>{IDYES,244,IDNO,IDCANCEL}:std::vector<int>{IDYES,IDCANCEL};
if(!data->readOnlyPrompt) ShowWindow(GetDlgItem(window,249),SW_HIDE);
if(!data->folderPrompt && !data->readOnlyPrompt)
for(const auto id:{244,IDNO}) ShowWindow(GetDlgItem(window,id),SW_HIDE);
LONG buttonWidth=cellWidth*static_cast<LONG>(buttons.size()-1);
for(const auto id:buttons)
{
const auto rect=dialogControlBounds(window,id);
buttonWidth+=rect.right-rect.left;
}
LONG contentWidth=buttonWidth;
if(const auto dc=GetDC(window))
{
const auto previous=SelectObject(dc,mono);
const auto measure=[&](const wchar_t *text)
{
RECT rect{};
DrawTextW(dc,text,-1,&rect,DT_CALCRECT|DT_SINGLELINE|DT_NOPREFIX);
contentWidth=std::max(contentWidth,rect.right);
};
measure(data->message);
std::wistringstream names(data->entries);
for(std::wstring name;std::getline(names,name);)
{
if(!name.empty() && name.back()==L'\r') name.pop_back();
measure(name.c_str());
}
SelectObject(dc,previous);
ReleaseDC(window,dc);
}
MONITORINFO monitor{sizeof(monitor)};
if(GetMonitorInfoW(MonitorFromWindow(GetWindow(window,GW_OWNER),MONITOR_DEFAULTTONEAREST),&monitor))
contentWidth=std::min(contentWidth,std::max(buttonWidth,monitor.rcWork.right-monitor.rcWork.left-2*entries.left));
RECT outer{};
GetWindowRect(window,&outer);
const auto width=contentWidth+2*entries.left;
SetWindowPos(window,nullptr,0,0,width,outer.bottom-outer.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
for(const auto id:{240,241})
{
const auto control=GetDlgItem(window,id);
const bool centered=id==240 || data->lines==1;
SetWindowLongPtrW(control,GWL_STYLE,
(GetWindowLongPtrW(control,GWL_STYLE)&~SS_TYPEMASK)|(centered?SS_CENTER:SS_LEFT)|SS_NOPREFIX);
SetWindowPos(control,nullptr,entries.left,id==240?question.top:entries.top,
contentWidth,(id==240?1:data->lines)*textHeight,SWP_NOZORDER|SWP_NOACTIVATE);
}
SetWindowPos(GetDlgItem(window,243),nullptr,entries.left,entries.top+data->lines*textHeight+10,0,0,
SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
auto x=(width-buttonWidth)/2;
for(const auto id:buttons)
{
const auto rect=dialogControlBounds(window,id);
SetWindowPos(GetDlgItem(window,id),nullptr,x,rect.top,0,0,
SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
x+=rect.right-rect.left+cellWidth;
}
if(data->readOnlyPrompt) layoutDialogButtons(window,243,{IDYES,244,IDNO,249,IDCANCEL});
else if(data->folderPrompt) layoutDialogButtons(window,243,{IDYES,244,IDNO,IDCANCEL});
else layoutDialogButtons(window,243,{IDYES,IDCANCEL});
SendMessageW(window,DM_SETDEFID,IDCANCEL,0);
SetFocus(GetDlgItem(window,IDCANCEL));
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(window,IDCANCEL);
return TRUE;
}
if(message==WM_COMMAND && (LOWORD(wp)==IDYES ||
((data->folderPrompt || data->readOnlyPrompt) && (LOWORD(wp)==244 || LOWORD(wp)==IDNO)) ||
(data->readOnlyPrompt && LOWORD(wp)==249)))
{
FilesModalDialog::finish(window,LOWORD(wp));
return TRUE;
}
return FALSE;
}
INT_PTR CALLBACK deleteProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(const auto painted=paintFileOperationDialog(window,message,wp,lp,L" Delete ",false,{248}))
return painted;
if(message==WM_INITDIALOG)
{
prepareCopyDialog(window);
layoutDialogContent(window,245);
SetWindowLongPtrW(window,DWLP_USER,lp);
for(const auto id:{245,246})
SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SetWindowSubclass(GetDlgItem(window,247),paintCopyProgressBar,1,0);
layoutDialogButtons(window,248,{IDCANCEL});
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
auto &canceled=*reinterpret_cast<std::atomic_bool*>(GetWindowLongPtrW(window,DWLP_USER));
if(!canceled)
canceled=confirmOperationCancellation(window,L"Do you really want to cancel deletion?");
return TRUE;
}
return FALSE;
}
void deleteSelection(HWND owner,Panel &panel,bool permanent)
{
if(panel.archive) {setStatus(L"Archive entries are read-only."); return;}
const bool fromSearch=panel.findOrigin.has_value();
if(fromSearch && panel.scanRequest)
{
setStatus(L"Wait for the search to finish.");
return;
}
if(panelListsLocations(panel)) return;
if(copyInProgress) return;
const auto ftp=panel.ftp;
permanent=permanent || ftp.has_value();
auto paths=selectedPanelPaths(panel);
if(paths.empty()) return;
const auto shown=std::min<size_t>(paths.size(),10);
std::wstring entries;
for(size_t i=0;i<shown;++i)
{
if(i) entries+=L"\r\n";
entries+=fromSearch?paths[i].lexically_relative(panel.directory).native():paths[i].filename().native();
}
if(shown<paths.size()) entries+=L"\r\n…and "+std::to_wstring(paths.size()-shown)+L" more";
const auto instance=GetModuleHandleW(nullptr);
warningBrush=CreateSolidBrush(RGB(128,0,0));
const wchar_t *message=permanent?L"Delete the selected items permanently?":
L"Move the selected items to the Recycle Bin?";
if(paths.size()==1)
{
const auto row=std::find(panel.rows.begin(),panel.rows.end(),paths.front());
if(row!=panel.rows.end())
message=panel.sizes[row-panel.rows.begin()]==L"Folder"
? (permanent?L"Delete this folder permanently?":L"Move this folder to the Recycle Bin?")
: (permanent?L"Delete this file permanently?":L"Move this file to the Recycle Bin?");
}
DeleteConfirmation confirmation{message,entries,static_cast<int>(shown+(shown<paths.size())),
permanent,false};
if(FilesModalDialog::run(instance,MAKEINTRESOURCEW(106),owner,deleteConfirmationDialog,
reinterpret_cast<LPARAM>(&confirmation))!=IDYES)
{
DeleteObject(warningBrush);
warningBrush=nullptr;
// Restore the invoking list after the modal dialog closes.
SetFocus(panel.list);
return;
}
std::atomic_bool canceled{};
FileOperationUi ui;
FilesModalDialog progressDialog(instance,MAKEINTRESOURCEW(107),owner,deleteProgressDialog,
reinterpret_cast<LPARAM>(&canceled));
const auto window=progressDialog.window();
if(window)
{
progressDialog.show();
size_t done=0, skipped=0, failed=0, total=0;
bool all=false;
int readOnlyChoice=0;
std::vector<std::vector<fs::path>> groups;
std::wstring failure, sharingFailure;
std::set<fs::path> lockPaths, removed;
const auto recordFailure=[&](const std::system_error &error,const fs::path &path)
{
++failed;
failure=fileError(error);
if(!panel.peer && !ftp && isSharingError(error.code().value()))
{
lockPaths.insert(path);
if(sharingFailure.empty()) sharingFailure=failure;
}
};
try
{
ui.run(window,canceled,[&] {
FileOperationElevation elevation(window,canceled,&ui);
CopyHost host(panel.peer?&*panel.peer:nullptr,ftp,&elevation);
const auto collect=[&](auto &&self,const fs::path &path,std::vector<fs::path> &group)->void
{
for(const auto &[child,info]:host.children(path,canceled))
{
if(canceled) return;
group.push_back(child);
if((info.attributes&FILE_ATTRIBUTE_DIRECTORY) && !(info.attributes&FILE_ATTRIBUTE_REPARSE_POINT))
self(self,child,group);
}
};
for(const auto &path:paths)
{
if(canceled) break;
auto &group=groups.emplace_back(1,path);
if(permanent && !fromSearch)
{
try
{
const auto info=host.stat(path,canceled);
if(info && (info->attributes&FILE_ATTRIBUTE_DIRECTORY) &&
!(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT)) collect(collect,path,group);
}
catch(const std::system_error &e)
{
recordFailure(e,path);
++total;
group.clear();
}
}
total+=group.size();
}
ULONGLONG lastPaint=0;
fs::path current;
const auto update=[&](const fs::path &path,bool force)
{
const auto now=GetTickCount64();
if(!force && now-lastPaint<200) return;
lastPaint=now;
ui.invoke([&] {
SetDlgItemTextW(window,245,path.c_str());
const auto status=(permanent?L"Deleted: ":L"Moved: ")+std::to_wstring(done)+L" / "+std::to_wstring(total)+
L" Skipped: "+std::to_wstring(skipped)+L" Failed: "+std::to_wstring(failed);
SetDlgItemTextW(window,246,status.c_str());
const auto bar=GetDlgItem(window,247);
SendMessageW(bar,PBM_SETPOS,total?static_cast<int>(100.0*(done+skipped+failed)/total):0,0);
InvalidateRect(bar,nullptr,FALSE);
});
};
for(const auto &group:groups)
{
if(canceled) break;
if(group.empty()) continue;
if(group.size()>1 && !all)
{
DeleteConfirmation folder{L"The following folder will be deleted:",group.front().wstring(),1,true,true};
const auto answer=ui.invoke([&] {
return canceled?static_cast<INT_PTR>(IDCANCEL):
FilesModalDialog::run(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog,
reinterpret_cast<LPARAM>(&folder));
});
if(answer==244) all=true;
else if(answer==IDNO)
{
skipped+=group.size();
update(group.front(),false);
continue;
}
else if(answer!=IDYES) { canceled=true; break; }
}
for(auto it=group.rbegin();it!=group.rend() && !canceled;++it)
{
current=*it;
update(current,false);
bool readOnly=false;
try
{
const auto info=(permanent || fromSearch)?host.stat(current,canceled):std::optional<FileInfo>{};
if(fromSearch && info && (info->attributes&FILE_ATTRIBUTE_DIRECTORY))
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
const auto attributes=info?info->attributes:INVALID_FILE_ATTRIBUTES;
if(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_READONLY) &&
!(attributes&FILE_ATTRIBUTE_DIRECTORY))
{
auto answer=static_cast<INT_PTR>(readOnlyChoice);
if(!answer)
{
DeleteConfirmation warning{L"Delete this read-only file?",current.wstring(),1,true,false,true};
answer=ui.invoke([&] {
return canceled?static_cast<INT_PTR>(IDCANCEL):
FilesModalDialog::run(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog,
reinterpret_cast<LPARAM>(&warning));
});
if(answer==244 || answer==249) readOnlyChoice=static_cast<int>(answer);
}
if(answer==IDNO || answer==249)
{
++skipped;
continue;
}
if(answer!=IDYES && answer!=244)
{
canceled=true;
break;
}
if(attributes&FILE_ATTRIBUTE_REPARSE_POINT)
throw std::system_error(ERROR_ACCESS_DENIED,std::system_category());
readOnly=true;
}
if(!permanent && !panel.peer)
{
const auto error=probeDeleteAccess(current);
if(isSharingError(error)) throw std::system_error(error,std::system_category());
if(error==ERROR_ACCESS_DENIED)
checkFileReply(elevation.retry(fileRequest("recycle",current),{{"error",error}}));
else if(!ks::lan::recycleFile(window,current))
{
// The Shell can hide the error from an individual item in a folder.
lockPaths.insert(current);
throw std::system_error(ERROR_ACCESS_DENIED,std::system_category());
}
}
else host.remove(current,permanent,attributes,readOnly);
++done;
removed.insert(current);
}
catch(const std::system_error &e)
{
if(canceled && e.code().value()==ERROR_CANCELLED) break;
recordFailure(e,current);
if(e.code().value()>=10000) break;
}
}
}
update(current,true);
});
}
catch(const std::system_error &e){++failed;failure=fileError(e);}
catch(const std::exception &){++failed;failure=L"File connection interrupted.";}
RedrawWindow(window,nullptr,nullptr,RDW_UPDATENOW|RDW_ALLCHILDREN);
progressDialog.close();
for(auto &visible:panels)
{
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);
const auto summary=(canceled?L"Deletion canceled. ":L"Deletion finished. ")+
std::to_wstring(done)+(permanent?L" deleted, ":L" moved to Recycle Bin, ")+
std::to_wstring(skipped)+L" skipped, "+std::to_wstring(failed)+L" failed.";
if(failed)
{
const auto &reason=sharingFailure.empty()?failure:sharingFailure;
showFileOperationError(owner,L"Delete failed",summary+(reason.empty()?L"":L"\r\n"+reason),
{lockPaths.begin(),lockPaths.end()});
}
else setStatus(summary);
}
else showFileOperationError(owner,L"Delete failed",L"Could not open the progress dialog.");
DeleteObject(warningBrush);
warningBrush=nullptr;
}
bool pastePanelFiles(HWND owner,Panel &panel)
{
if(!IsClipboardFormatAvailable(CF_HDROP)) return false;
if(panel.peer || panel.ftp || panel.listing || panel.findOrigin)
{
setStatus(L"Open a local folder before pasting files.");
return true;
}
std::vector<fs::path> paths;
try {paths=ks::readClipboardFilePaths(owner);}
catch(const std::exception &)
{
setStatus(L"Could not read file paths from the clipboard.");
return true;
}
if(paths.empty())
{
setStatus(L"The clipboard has no usable file paths.");
return true;
}
if(panel.archive) addToArchive(owner,panel,std::move(paths));
else copySelection(owner,panel,panel,false,std::move(paths));
return true;
}
void selectPanelEdge(Panel &panel,bool first)
{
panelClipboardContext=true;
activatePanel(static_cast<int>(&panel-panels));
const auto count=SendMessageW(panel.list,LB_GETCOUNT,0,0);
if(count<=0) return;
SendMessageW(panel.list,LB_SETCURSEL,first?0:count-1,0);
InvalidateRect(panel.list,nullptr,FALSE);
showFileDetails(panel);
}
struct MakeFolderRequest
{
const fs::path &directory;
const FilesPeer *peer;
fs::path created;
std::vector<ks::files::FarHistoryEntry> history;
};
std::vector<std::wstring> folderNames(std::wstring_view input,bool multiple)
{
if(!multiple) return {std::wstring(input)};
std::vector<std::wstring> names;
std::wstring token;
bool quoted=false;
const auto append=[&]
{
const auto first=token.find_first_not_of(L" \t");
if(first!=token.npos)
names.push_back(token.substr(first,token.find_last_not_of(L" \t")-first+1));
token.clear();
};
for(const auto character:input)
{
if(character==L'"') quoted=!quoted;
else if(!quoted && (character==L',' || character==L';')) append();
else token+=character;
}
if(quoted) return {};
append();
return names;
}
std::wstring dialogFieldText(HWND field)
{
std::wstring value(GetWindowTextLengthW(field)+1,L'\0');
value.resize(GetWindowTextW(field,value.data(),static_cast<int>(value.size())));
return value;
}
#include "files_archive_dialog.inl"
INT_PTR CALLBACK makeFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG) markLavenderFileOperation(dialog);
constexpr int label=360,field=361,divider=362,history=363,linkLabel=364,linkType=365,
targetLabel=366,target=367,multiple=368,footer=369;
const auto input=GetDlgItem(dialog,field);
const auto combo=GetDlgItem(dialog,linkType);
const auto targetInput=GetDlgItem(dialog,target);
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
const auto &request=*reinterpret_cast<const MakeFolderRequest *>(lp);
prepareTextDialog(dialog);
installFarCheckbox(GetDlgItem(dialog,multiple),FarCheckboxSurface::gray);
for(const auto control:{input,targetInput}) fitFarEditToLine(control);
const auto edit=dialogControlBounds(dialog,field);
const auto arrow=GetDlgItem(dialog,history);
const auto parts=farDropDownBounds({edit.left,edit.top,dialogControlBounds(dialog,history).right,edit.bottom});
SetWindowPos(input,nullptr,edit.left,edit.top,parts.field.right-edit.left,edit.bottom-edit.top,
SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(arrow,nullptr,parts.arrow.left,edit.top,parts.arrow.right-parts.arrow.left,
edit.bottom-edit.top,SWP_NOZORDER|SWP_NOACTIVATE);
EnableWindow(arrow,!request.history.empty());
SendMessageW(input,EM_SETLIMITTEXT,511,0);
ks::files::installFarHistoryKey(input,history);
for(const auto text:{L"none",L"directory junction",L"symbolic link"})
SendMessageW(combo,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(text));
installFarCombo(combo,input);
SendMessageW(combo,CB_SETCURSEL,0,0);
EnableWindow(targetInput,FALSE);
EnableWindow(GetDlgItem(dialog,targetLabel),FALSE);
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(input);
return FALSE;
}
if(message==WM_DRAWITEM)
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
if(wp==linkType) { drawFarComboRow(item); return TRUE; }
if(wp==history)
{
if(lavenderFiles()) paintLavenderComboFace(item.hwndItem,item.hDC,item.rcItem,L"");
else ks::files::paintFarFieldArrow(item.hDC,item.rcItem,IsWindowEnabled(item.hwndItem),
GetDpiForWindow(item.hwndItem));
return TRUE;
}
if(wp==label || wp==linkLabel || wp==targetLabel)
{
if(lavenderFiles()) lavender::fill(item.hDC,item.rcItem,lavenderDialogSurface(dialog));
else FillRect(item.hDC,&item.rcItem,static_cast<HBRUSH>(GetStockObject(LTGRAY_BRUSH)));
SelectObject(item.hDC,dialogUiFont());
SetBkMode(item.hDC,TRANSPARENT);
SetTextColor(item.hDC,lavenderFiles()?(IsWindowEnabled(item.hwndItem)?lavender::ink:lavender::muted):
IsWindowEnabled(item.hwndItem)?RGB(0,0,0):RGB(128,128,128));
drawFarDialogLabel(item.hDC,item.rcItem,dialogFieldText(item.hwndItem),false);
return TRUE;
}
}
if(message==WM_CTLCOLORLISTBOX)
{
const auto dc=reinterpret_cast<HDC>(wp);
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[Dialog]);
return reinterpret_cast<INT_PTR>(teal);
}
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Make folder ",false,{divider,footer}))
return painted;
if(message!=WM_COMMAND) return FALSE;
const auto command=LOWORD(wp);
if(command==IDCANCEL)
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
auto *request=reinterpret_cast<MakeFolderRequest *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!request) return FALSE;
if(command==history)
{
ks::files::showFarHistory(dialog,field,request->history,farDropDownPalette());
return TRUE;
}
const auto kind=SendMessageW(combo,CB_GETCURSEL,0,0);
if(command==linkType && HIWORD(wp)==CBN_SELCHANGE)
{
EnableWindow(targetInput,kind>0);
EnableWindow(GetDlgItem(dialog,targetLabel),kind>0);
InvalidateRect(combo,nullptr,FALSE);
return TRUE;
}
if(command!=IDOK) return FALSE;
const auto error=[&](const wchar_t *text,HWND focus)
{
showFilesNotice(dialog,text,L"Error",{.tone=FilesNoticeTone::warning});
SetFocus(focus);
};
const auto entered=dialogFieldText(input);
const auto names=folderNames(entered,IsDlgButtonChecked(dialog,multiple)==BST_CHECKED);
if(names.empty() || !std::all_of(names.begin(),names.end(),validFileName))
{
error(L"Enter a valid folder name.",input);
return TRUE;
}
const fs::path linkTarget=dialogFieldText(targetInput);
if(kind>0 && (linkTarget.empty() || (linkTarget.has_root_name() && !linkTarget.is_absolute())))
{
error(L"Enter a target directory path.",targetInput);
return TRUE;
}
fs::path current;
std::atomic_bool canceled{};
FileOperationElevation elevation(dialog,canceled);
try
{
FilesConnection host(request->peer);
for(const auto &name:names)
{
current=request->directory/name;
auto operation=fileRequest(kind>0?"mkdir-link":"mkdir",current);
if(kind>0)
{
const auto resolved=linkTarget.is_absolute()?linkTarget:request->directory/linkTarget;
operation["target"]=ks::utf8(resolved.lexically_normal().native());
operation["kind"]=kind==1?"junction":"symlink";
}
checkFileReply(request->peer?host.call(operation):elevation.call(host,operation));
request->created=current;
}
}
catch(const std::system_error &failure)
{
if(!canceled)
{
const auto details=current.filename().wstring()+L": "+fileError(failure);
error(details.c_str(),input);
}
if(!request->created.empty()) FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
catch(const std::exception &)
{
error(L"Could not create the folder.",input);
if(!request->created.empty()) FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
ks::files::rememberFarHistory(ks::files::FarHistoryKind::folder,entered);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
void makeFolder(HWND owner,Panel &panel)
{
if(panel.findOrigin)
{
setStatus(L"Open the folder before making changes.");
return;
}
if(panel.ftp) return;
if(panel.archive) {setStatus(L"Archive entries are read-only."); return;}
if(panel.directory.empty()) return;
const auto directory=panel.directory;
MakeFolderRequest request{directory,panel.peer?&*panel.peer:nullptr,{},
ks::files::loadFarHistory(ks::files::FarHistoryKind::folder)};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(108),owner,makeFolderDialog,
reinterpret_cast<LPARAM>(&request))!=IDOK) return;
open(panel,directory);
selectPanelPath(panel,request.created);
}
struct TextFilePrompt
{
fs::path directory,path;
ks::files::TextSaveFormat format;
bool saving{};
};
constexpr const wchar_t *textCodePages[]{L"Default",L"65001 | UTF-8",L"1200 | UTF-16 LE",
L"1201 | UTF-16 BE",L"1252 | Windows-1252"};
constexpr int textPathField=461,textCodePage=463,textBom=464,textFooter=467,textFirstLineEnding=470;
void layoutTextFilePrompt(HWND dialog)
{
RECT client{};
GetClientRect(dialog,&client);
const auto frame=dialogFrameMetrics(GetDpiForWindow(dialog));
const auto inset=frame.content(),gap=dialogRowGap();
const auto width=client.right-2*inset;
const auto place=[&](int id,int x,int y,int w,int h)
{
SetWindowPos(GetDlgItem(dialog,id),nullptr,x,y,w,h,SWP_NOZORDER|SWP_NOACTIVATE);
};
auto y=dialogListInset(frame,textHeight);
const auto row=[&](int id)
{
place(id,inset,y,width,textHeight);
y+=textHeight;
};
const auto divider=[&](int id)
{
y+=gap;
place(id,inset,y+4,1,1);
y+=gap+1;
};
row(460);
row(textPathField);
fitFarEditToLine(GetDlgItem(dialog,textPathField));
divider(466);
const auto labelWidth=12*cellWidth;
place(462,inset,y,labelWidth,textHeight);
place(textCodePage,inset+labelWidth,y,width-labelWidth,textHeight);
y+=textHeight;
if(GetDlgItem(dialog,textBom))
{
row(textBom);
divider(468);
row(469);
for(int i=0;i<4;++i) row(textFirstLineEnding+i);
}
divider(textFooter);
layoutDialogButtons(dialog,textFooter,{IDOK,IDCANCEL});
}
fs::path unnamedTextFile(const fs::path &directory)
{
SYSTEMTIME time{};
GetLocalTime(&time);
wchar_t stem[64]{};
swprintf_s(stem,L"New_File_%04u-%02u-%02u_%02u.%02u.%02u.%03u",
unsigned(time.wYear),unsigned(time.wMonth),unsigned(time.wDay),unsigned(time.wHour),
unsigned(time.wMinute),unsigned(time.wSecond),unsigned(time.wMilliseconds));
auto path=directory/(std::wstring(stem)+L".txt");
for(unsigned suffix=1;GetFileAttributesW(path.c_str())!=INVALID_FILE_ATTRIBUTES;++suffix)
path=directory/(std::wstring(stem)+L"_"+std::to_wstring(suffix)+L".txt");
return path;
}
INT_PTR CALLBACK textFilePrompt(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
using namespace ks::files;
const auto field=GetDlgItem(dialog,textPathField);
const auto combo=GetDlgItem(dialog,textCodePage);
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
const auto &prompt=*reinterpret_cast<const TextFilePrompt *>(lp);
prepareTextDialog(dialog);
const auto inset=dialogFrameMetrics(GetDpiForWindow(dialog)).content();
SetWindowPos(dialog,nullptr,0,0,48*cellWidth+2*inset,1,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
layoutTextFilePrompt(dialog);
if(prompt.saving)
{
SetWindowTextW(field,prompt.path.filename().c_str());
installFarCheckbox(GetDlgItem(dialog,textBom),FarCheckboxSurface::gray);
for(int i=0;i<4;++i)
installFarCheckbox(GetDlgItem(dialog,textFirstLineEnding+i),FarCheckboxSurface::gray);
CheckDlgButton(dialog,textBom,prompt.format.bom?BST_CHECKED:BST_UNCHECKED);
CheckRadioButton(dialog,textFirstLineEnding,textFirstLineEnding+3,
textFirstLineEnding+static_cast<int>(prompt.format.lineEnding));
}
const int first=prompt.saving?1:0;
for(int i=first;i<static_cast<int>(std::size(textCodePages));++i)
SendMessageW(combo,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(textCodePages[i]));
installFarCombo(combo,field);
SendMessageW(combo,CB_SETCURSEL,static_cast<int>(prompt.format.encoding)-first,0);
if(prompt.saving) EnableWindow(GetDlgItem(dialog,textBom),prompt.format.encoding!=TextEncoding::windows1252);
FilesModalDialog::fitWidthToOwner(dialog,36*cellWidth+2*inset,layoutTextFilePrompt);
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(field);
SendMessageW(field,EM_SETSEL,0,-1);
return FALSE;
}
auto *prompt=reinterpret_cast<TextFilePrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!prompt) return FALSE;
if(message==WM_DRAWITEM && wp==textCodePage)
{
drawFarComboRow(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
}
if(message==WM_CTLCOLORLISTBOX)
{
const auto dc=reinterpret_cast<HDC>(wp);
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[Dialog]);
return reinterpret_cast<INT_PTR>(teal);
}
const auto painted=prompt->saving?paintCopyDialog(dialog,message,wp,lp,L" Editor ",false,{466,468,textFooter}):
paintCopyDialog(dialog,message,wp,lp,L" Editor ",false,{466,textFooter});
if(painted) return painted;
if(message!=WM_COMMAND) return FALSE;
const auto command=LOWORD(wp);
if(command==IDCANCEL) {FilesModalDialog::finish(dialog,IDCANCEL); return TRUE;}
const auto selected=SendMessageW(combo,CB_GETCURSEL,0,0);
const auto encoding=static_cast<TextEncoding>(std::max<LRESULT>(0,selected)+prompt->saving);
if(command==textCodePage && HIWORD(wp)==CBN_SELCHANGE && prompt->saving)
{
EnableWindow(GetDlgItem(dialog,textBom),encoding!=TextEncoding::windows1252);
return TRUE;
}
if(command!=IDOK) return FALSE;
const auto entered=dialogFieldText(field);
const fs::path name=entered;
const auto path=(name.empty()?unnamedTextFile(prompt->directory):prompt->directory/name).lexically_normal();
const auto parent=GetFileAttributesW(path.parent_path().c_str());
const auto attributes=GetFileAttributesW(path.c_str());
if((name.has_root_name() && !name.is_absolute()) || !validFileName(path.filename().native()) ||
parent==INVALID_FILE_ATTRIBUTES || !(parent&FILE_ATTRIBUTE_DIRECTORY) ||
(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)))
{
showFilesNotice(dialog,L"Enter a valid file name in an existing folder.",L"Editor");
SetFocus(field);
return TRUE;
}
if(prompt->saving && attributes!=INVALID_FILE_ATTRIBUTES)
{
showFilesNotice(dialog,L"A file with this name already exists. Choose another name.",L"Editor");
SetFocus(field);
return TRUE;
}
prompt->path=path;
prompt->format.encoding=encoding;
if(prompt->saving)
{
prompt->format.bom=encoding!=TextEncoding::windows1252 &&
IsDlgButtonChecked(dialog,textBom)==BST_CHECKED;
for(int i=0;i<4;++i)
if(IsDlgButtonChecked(dialog,textFirstLineEnding+i)==BST_CHECKED)
prompt->format.lineEnding=static_cast<TextLineEnding>(i);
}
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
bool chooseTextSaveOptions(HWND owner,fs::path &destination,ks::files::TextSaveFormat &format)
{
TextFilePrompt prompt{destination.parent_path(),destination,format,true};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(612),owner,textFilePrompt,
reinterpret_cast<LPARAM>(&prompt))!=IDOK) return false;
destination=std::move(prompt.path);
format=prompt.format;
return true;
}
void openOrCreateText(HWND owner,const Panel &panel)
{
if(panel.findOrigin)
{
setStatus(L"Open the folder before making changes.");
return;
}
if(panel.ftp) return;
if(panel.peer)
{
setStatus(L"Open/create file is available in local panels.");
return;
}
if(panel.archive) {setStatus(L"Archive entries are read-only."); return;}
if(panel.directory.empty()) return;
TextFilePrompt prompt{panel.directory,{}, {.encoding=ks::files::TextEncoding::automatic}};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(611),owner,textFilePrompt,
reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
const auto attributes=GetFileAttributesW(prompt.path.c_str());
const bool draft=attributes==INVALID_FILE_ATTRIBUTES && GetLastError()==ERROR_FILE_NOT_FOUND;
ks::files::openTextWindow(owner,prompt.path,true,textWindowDialogs(),nullptr,{},false,
{prompt.format.encoding,draft});
}
void editTransferProfile(Panel &panel,bool create);
#include "files_drag_drop.inl"
#include "files_properties.inl"
#include "files_context_menu.inl"
void runFilesKeyCommand(HWND owner,int side,FilesKey command)
{
auto &panel=panels[side];
switch(command)
{
case FilesKey::Refresh: refreshPanel(panel); break;
case FilesKey::View:
case FilesKey::Edit:
{
const bool edit=command==FilesKey::Edit;
if(recentFolderList(panel)) break;
if(panel.listing)
{
if(edit) editSmbProfile(panel,false);
break;
}
if(transferProfileList(panel))
{
if(edit) editTransferProfile(panel,false);
break;
}
const auto row=currentPanelRow(panel);
if(edit || row==LB_ERR || !calculateFolderSizes(panel,row)) openSelectedText(panel,edit,false);
break;
}
case FilesKey::Copy:
case FilesKey::Move: copySelection(owner,panel,panels[1-side],command==FilesKey::Move); break;
case FilesKey::Mkdir: makeFolder(owner,panel); break;
case FilesKey::Delete:
if(recentFolderList(panel)) removeRecentFolder(panel);
else if(panel.listing) removeSmbProfile(panel);
else deleteSelection(owner,panel,false);
break;
case FilesKey::Exit: SendMessageW(owner,WM_CLOSE,0,0); break;
case FilesKey::Compare: compareSelectedFiles(owner); break;
case FilesKey::Previous: recallPreviousCommand(); break;
case FilesKey::Next:
if(terminalHistoryIndex<terminalHistory.size()) recallCommand(terminalHistoryIndex+1);
break;
case FilesKey::History: showCommandHistory(owner); break;
case FilesKey::Pack: createArchive(owner,panel); break;
case FilesKey::Find: findPanelFiles(owner,panel); break;
case FilesKey::ExternalView:
case FilesKey::ExternalEdit: openSelectedText(panel,command==FilesKey::ExternalEdit,true); break;
case FilesKey::QuickView: toggleQuickView(owner); break;
case FilesKey::FullPath: copyFullPanelPath(owner,panel); break;
case FilesKey::HexView: openSelectedText(panel,false,false,true); break;
case FilesKey::Swap: swapPanels(owner); break;
case FilesKey::Properties: showPanelItemProperties(owner,panel); break;
case FilesKey::Count: break;
}
}
bool handleFilesKeyChord(HWND owner,const MSG &message)
{
if(message.message!=WM_KEYDOWN && message.message!=WM_SYSKEYDOWN) return false;
if(copyInProgress || FilesModalDialog::activeFor(owner) ||
(message.hwnd!=owner && message.hwnd!=terminalInput && message.hwnd!=panels[0].list &&
message.hwnd!=panels[1].list && !IsChild(owner,message.hwnd))) return false;
const bool input=message.hwnd==terminalInput || message.hwnd==panels[0].list || message.hwnd==panels[1].list;
const auto binding=currentFilesChord(message.wParam);
if(!binding) return false;
const auto command=boundFilesCommand(binding,terminalVisible?terminalKeyContext:panelKeyContext);
if(!command || (!input && *command!=FilesKey::History && *command!=FilesKey::Exit)) return false;
if(!commandLineAvailable(owner) && *command!=FilesKey::History && *command!=FilesKey::Exit) return false;
if(*command==FilesKey::Properties && (!panelItemPropertiesAvailable(panels[active]) ||
(message.hwnd==terminalInput && GetWindowTextLengthW(terminalInput)))) return false;
if(!(message.lParam&(1LL<<30)) || *command==FilesKey::Previous || *command==FilesKey::Next)
{
hidePicker();
showMenu(false);
runFilesKeyCommand(owner,message.hwnd==panels[1].list?1:message.hwnd==panels[0].list?0:active,*command);
}
return true;
}
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)};
if(rightClickMarks && !(wp&MK_SHIFT) && commandLineAvailable(GetParent(window)))
{
auto &panel=panels[index];
const auto row=panelRowAt(window,screen,SendMessageW(window,LB_GETTOPINDEX,0,0),panel.rows.size());
if(row!=LB_ERR && panel.sizes[row]!=L"Up" && !panelListsLocations(panel))
{
closePanelSearch();
SetFocus(window);
activatePanel(index);
panelClipboardContext=true;
clearTerminalSelection();
const auto previous=currentPanelRow(panel);
SendMessageW(window,LB_SETCURSEL,row,0);
markPanelRow(panel,row,!panel.marked[row]);
invalidatePanelRow(window,row);
if(previous!=row) invalidatePanelRow(window,previous);
updateSelectionSummary(panel);
showFileDetails(panel);
return 0;
}
}
ClientToScreen(window,&screen);
showPanelContextMenu(window,MAKELPARAM(screen.x,screen.y));
return 0;
}
if(message==WM_MOUSEMOVE && (wp&MK_LBUTTON) && GetCapture()==window && panelDragStart)
{
const auto dpi=GetDpiForWindow(window);
if(std::abs(GET_X_LPARAM(lp)-panelDragStart->x)>=GetSystemMetricsForDpi(SM_CXDRAG,dpi) ||
std::abs(GET_Y_LPARAM(lp)-panelDragStart->y)>=GetSystemMetricsForDpi(SM_CYDRAG,dpi))
{
ReleaseCapture();
beginPanelDrag(window);
restoreCommandFocus();
}
return 0;
}
if(message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK ||
(message==WM_MOUSEMOVE && (wp&MK_LBUTTON) && GetCapture()==window))
{
if(message==WM_LBUTTONDOWN)
{
panelClipboardContext=true;
clearTerminalSelection();
}
auto &panel=panels[index];
const auto count=SendMessageW(window,LB_GETCOUNT,0,0);
if(count<=0)
{
activatePanel(index);
return 0;
}
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
const auto top=SendMessageW(window,LB_GETTOPINDEX,0,0);
const auto row=panelRowAt(window,point,top,count);
const bool rowHit=row!=LB_ERR;
const auto previous=SendMessageW(window,LB_GETCURSEL,0,0);
const auto target=rowHit?row:point.y>=0 && message==WM_LBUTTONDOWN?count-1:previous;
if(target!=previous && index!=active)
{
// The native list can repaint during selection. Activate it only after moving the cursor.
const bool visible=IsWindowVisible(window);
if(visible) SendMessageW(window,WM_SETREDRAW,FALSE,0);
SendMessageW(window,LB_SETCURSEL,target,0);
if(visible) SendMessageW(window,WM_SETREDRAW,TRUE,0);
if(top!=SendMessageW(window,LB_GETTOPINDEX,0,0))
InvalidateRect(window,nullptr,FALSE);
else if(panelRowStyle(panel,previous,true,false)!=panelRowStyle(panel,previous,false,false))
invalidatePanelRow(window,previous);
}
else if(target!=previous)
{
// The list box can draw synchronously before committing its new selection.
SendMessageW(window,LB_SETCURSEL,target,0);
invalidatePanelCursorChange(window,previous);
}
activatePanel(index);
if(message==WM_LBUTTONDOWN)
{
if(rowHit && treePanelActive(panel))
{
const auto depth=panel.tree.depths.find(panel.rows[row]);
if(depth!=panel.tree.depths.end())
{
const auto start=2*static_cast<int>(std::min<size_t>(depth->second,40))*cellWidth;
if(point.x>=start && point.x<=start+2*cellWidth && toggleTreeRow(panel,row)) return 0;
}
}
if(rowHit && panel.sizes[row]!=L"Up") panelDragStart=point;
SetCapture(window);
}
if(message==WM_LBUTTONDBLCLK && rowHit) enter(panel);
return 0;
}
if(message==WM_LBUTTONUP && GetCapture()==window)
{
ReleaseCapture();
restoreCommandFocus();
return 0;
}
if(message==WM_KEYDOWN && (wp==VK_LEFT || wp==VK_RIGHT) &&
!(GetKeyState(VK_SHIFT)&0x8000) && !(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
moveTreeCursor(panels[index],wp==VK_RIGHT))
{
panelClipboardContext=true;
return 0;
}
const bool rangeKey=wp==VK_UP || wp==VK_DOWN || wp==VK_LEFT || wp==VK_RIGHT;
if(message==WM_KEYDOWN && (wp==VK_INSERT || (rangeKey && (GetKeyState(VK_SHIFT)&0x8000))))
{
panelClipboardContext=true;
auto &panel=panels[index];
const auto row=SendMessageW(window,LB_GETCURSEL,0,0);
if(row<0 || static_cast<size_t>(row)>=panel.marked.size()) return 0;
const auto last=static_cast<LRESULT>(panel.marked.size()-1);
auto target=row;
switch(wp)
{
case VK_UP: target=std::max<LRESULT>(0,row-1); break;
case VK_LEFT: target=0; break;
case VK_RIGHT: target=last; break;
default: target=std::min(last,row+1); break;
}
const bool mark=!panel.marked[row];
const bool toBoundary=wp==VK_LEFT || wp==VK_RIGHT;
const auto first=toBoundary ? std::min(row,target) : row;
const auto end=toBoundary ? std::max(row,target) : row;
for(auto i=first;i<=end;++i) markPanelRow(panel,i,mark);
SendMessageW(window,LB_SETCURSEL,target,0);
InvalidateRect(window,nullptr,FALSE);
updateSelectionSummary(panel);
showFileDetails(panel);
return 0;
}
if(message==WM_KEYDOWN)
{
if(wp==VK_LEFT) wp=VK_HOME;
else if(wp==VK_RIGHT) wp=VK_END;
}
if(message==WM_SETFOCUS) activatePanel(static_cast<int>(index));
if(message==WM_CHAR && wp>=32 && wp!=127)
{
SetFocus(terminalInput);
return SendMessageW(terminalInput,message,wp,lp);
}
if (message == WM_KEYDOWN || message==WM_SYSKEYDOWN)
{
if(wp==VK_TAB)
{
if(plainPanelTab())
{
panelClipboardContext=true;
activatePanel(1-index);
SetFocus(terminalInput);
}
return 0;
}
if (wp == VK_RETURN) { enter(panels[index]); return 0; }
if(const auto command=boundFilesCommand(currentFilesChord(wp),panelKeyContext))
{
runFilesKeyCommand(GetParent(window),static_cast<int>(index),*command);
return 0;
}
if(wp==VK_DELETE && (GetKeyState(VK_SHIFT)&0x8000))
{
deleteSelection(GetParent(window),panels[index],true);
return 0;
}
}
const bool movesCursor=message==WM_KEYDOWN &&
(wp==VK_UP || wp==VK_DOWN || wp==VK_PRIOR || wp==VK_NEXT || wp==VK_HOME || wp==VK_END);
const auto previous=movesCursor?SendMessageW(window,LB_GETCURSEL,0,0):LB_ERR;
auto result=DefSubclassProc(window,message,wp,lp);
if(movesCursor)
{
panelClipboardContext=true;
invalidatePanelCursorChange(window,previous);
}
if(message==WM_LBUTTONUP && GetFocus()==window) restoreCommandFocus();
if(message==WM_PAINT && hasPanelColumns(panels[index]) && !lavenderFiles())
{
auto dc=GetDC(window);
if(dc)
{
RECT line{};
GetClientRect(window,&line);
paintPanelColumnLines(dc,panelColumns(panels[index],line));
ReleaseDC(window,dc);
}
}
return result;
}
#include "files_folder_shortcuts.inl"
#include "files_ftp_dialog.inl"
#include "files_command_history_dialog.inl"
bool loadFilesPreferences(HWND window)
{
const auto [font,points]=readFilesFont();
if(!applyFont(window,font,points)) return false;
filesAppearance=preference(filesAppearanceKey,0)==static_cast<DWORD>(FilesAppearance::Lavender)?
FilesAppearance::Lavender:FilesAppearance::Far;
loadColors();
dialogFramePadding={
std::min(preference(dialogFrameOuterKey,defaultDialogFramePadding.outer),maxDialogFramePadding),
std::min(preference(dialogFrameInnerKey,defaultDialogFramePadding.inner),maxDialogFramePadding),
std::min(preference(dialogRowTextKey,defaultDialogFramePadding.rowText),maxDialogRowTextPadding)};
loadFileStyles();
loadFolderShortcuts();
for(int i=0;i<2;++i)
{
auto &panel=panels[i];
const auto previous=effectivePanelColumns(panel);
panel.mode=readPanelMode(i);
loadPanelColumns(i);
if(panel.list && ((previous^effectivePanelColumns(panel))&extendedColumnMask)) refreshPanelColumnData(panel);
}
sizeWidth=static_cast<int>(std::clamp(preference(L"SizeWidth",defaultSizeWidth),6UL,16UL));
alignExtensions=preference(L"AlignExtensions",defaultAlignExtensions)!=0;
showDetails=preference(L"ShowDetails",defaultShowDetails)!=0;
alignFolders=preference(L"AlignFolders",defaultAlignFolders)!=0;
rightClickMarks=preference(rightClickMarksKey,0)!=0;
showDriveButtons=preference(driveButtonsKey,0)!=0;
compactLayout=preference(compactLayoutKey,0)!=0;
restoreDocuments=preference(restoreDocumentsKey,0)!=0;
statusFields=preference(L"StatusFields",defaultStatusFields)&15;
loadFilesKeySettings();
return true;
}
#include "files_find.inl"
struct OptionsWriteLock
{
HANDLE mutex=CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.OptionsWrite");
DWORD result=mutex?WaitForSingleObject(mutex,2000):WAIT_FAILED;
bool acquired() const { return result==WAIT_OBJECT_0 || result==WAIT_ABANDONED; }
~OptionsWriteLock()
{
if(acquired()) ReleaseMutex(mutex);
if(mutex) CloseHandle(mutex);
}
};
#include "files_key_schemes_dialog.inl"
#include "files_options.inl"
#include "files_panel_columns_dialog.inl"
#include "files_space_analyzer.inl"
#include "files_environment.inl"
#include "files_mcp_ui.inl"
void openMenu(HWND window, int index)
{
if(index==3)
{
hidePicker();
showMenu(false);
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_UPDATENOW|RDW_NOERASE);
editOptions(window);
return;
}
menuIndex=index;
folderPicker.reset();
commandPicker=true;
SendMessageW(picker,LB_RESETCONTENT,0,0);
std::vector<std::wstring> rows;
if(index==0 || index==4)
{
const auto &panel=panels[index==4];
for(size_t i=0;i<std::size(panelModeNames);++i)
{
const auto prefix=static_cast<size_t>(panel.mode)==i?L"✓ ":L" ";
auto label=std::wstring(prefix)+panelModeNames[i];
if(i<2) label+=i==0?L"\tCtrl+F1":L"\tCtrl+F2";
rows.push_back(std::move(label));
}
rows.push_back(index==0?L" Change drive\tAlt+F1":L" Change drive\tAlt+F2");
if(panelViewAvailable(panel))
{
constexpr const wchar_t *sortLabels[]{L"Sort by name\tCtrl+F3",L"Sort by extension\tCtrl+F4",
L"Sort by size\tCtrl+F5",L"Sort by modified\tCtrl+F6"};
for(size_t i=0;i<std::size(sortLabels);++i)
{
const auto mark=static_cast<size_t>(panel.view.sort)!=i?L" ":panel.view.descending?L"↓ ":L"↑ ";
rows.push_back(std::wstring(mark)+sortLabels[i]);
}
rows.push_back(panel.view.foldersFirst?L"✓ Folders first\tCtrl+F7":L" Folders first\tCtrl+F7");
rows.push_back(panel.view.mask.empty()?L" Filter by mask…\tCtrl+F8":L"✓ Filter by mask…\tCtrl+F8");
rows.push_back(panel.view.showHidden?L"✓ Show hidden and system\tCtrl+F9":L" Show hidden and system\tCtrl+F9");
rows.push_back(panel.view.tree?L" List view\tCtrl+F10":L" Tree view\tCtrl+F10");
rows.push_back(panel.view.automaticSizes?L"✓ Background folder sizes\tCtrl+F11":
L" Background folder sizes\tCtrl+F11");
if(detailedPanel(panel)) rows.push_back(L" Columns…");
}
}
else if(index==1) rows={filesKeyMenuLabel(FilesKey::Copy),filesKeyMenuLabel(FilesKey::Move),
filesKeyMenuLabel(FilesKey::Mkdir),filesKeyMenuLabel(FilesKey::Exit),filesKeyMenuLabel(FilesKey::Pack,L"Pack files…"),
filesKeyMenuLabel(FilesKey::Properties,L"Properties…"),L"Locking processes…"};
else if(index==2)
{
rows={filesKeyMenuLabel(FilesKey::Refresh),filesKeyMenuLabel(FilesKey::View),filesKeyMenuLabel(FilesKey::Edit),
L"Folder shortcuts",filesKeyMenuLabel(FilesKey::ExternalView),filesKeyMenuLabel(FilesKey::ExternalEdit),
L"Hibernate remote PC",L"Update remote KSwitcher",filesKeyMenuLabel(FilesKey::Compare),
filesKeyMenuLabel(FilesKey::Find),filesKeyMenuLabel(FilesKey::QuickView,quickViewWindow?L"Close Quick View":L"Quick View"),
filesKeyMenuLabel(FilesKey::FullPath),L"Space Analyzer",filesKeyMenuLabel(FilesKey::HexView),
L"Viewer bookmarks…",L"Processes…",L"Git Changes…",L"Environment Variables…",filesKeyMenuLabel(FilesKey::Swap),
filesKeyMenuLabel(FilesKey::History),L"Keyboard shortcuts…",
terminalVisible?L"Terminal appearance…":L"Panel appearance…",L"Help…\tF1",L"Files log…",
filesMcp.port()?L"Files MCP (running)…":L"Files MCP…"};
}
const auto &panel=panels[active];
const bool remoteResults=remoteSearchResults(panel);
const auto resultRow=remoteResults?currentPanelRow(panel):LB_ERR;
commandActions.clear();
if(index==1 && remoteResults)
{
if(remoteSearchActionAvailable(113)) commandActions.push_back(0);
if(remoteSearchActionAvailable(114))
{
if(panel.ftp) rows[1]=filesKeyMenuLabel(FilesKey::Move,L"Rename");
commandActions.push_back(1);
}
commandActions.push_back(3);
if(panelItemPropertiesAvailable(panel)) commandActions.push_back(5);
}
else if(index==1)
{
commandActions={0,1,2,3,4};
if(panelItemPropertiesAvailable(panel)) commandActions.push_back(5);
if(panelLockSearchAvailable(panel)) commandActions.push_back(6);
}
else if(index==2)
{
commandActions={0,3,11,-1,1,13,14,2,4,5,8};
if(!terminalVisible) commandActions.insert(commandActions.begin()+1,18);
if(!terminalVisible) commandActions.push_back(15);
if(gitChangesAvailable(panel)) commandActions.push_back(16);
if(!terminalVisible) commandActions.push_back(17);
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)
{
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});
commandActions.insert(commandActions.end(),{-1,19,20,21,23,24,22});
}
else
for(size_t i=0;i<rows.size();++i) commandActions.push_back(static_cast<int>(i));
std::set<wchar_t> used;
std::vector<size_t> accessPositions(rows.size(),std::wstring::npos);
const auto reserve=[&](size_t row,wchar_t key)
{
const auto &text=rows[row];
for(size_t pos=0;pos<text.size() && text[pos]!=L'\t';++pos)
if(towupper(text[pos])==key && used.insert(key).second)
{
accessPositions[row]=pos;
return true;
}
return false;
};
if(index==0 || index==4)
{
reserve(0,L'B');reserve(1,L'W');reserve(2,L'M');reserve(3,L'F');reserve(4,L'C');
}
if(index==1) {reserve(0,L'C');reserve(2,L'F');reserve(3,L'X');}
if(index==2) {reserve(1,L'V');reserve(2,L'E');}
for(size_t i=0;i<rows.size();++i)
{
const auto &text=rows[i];
if(accessPositions[i]==std::wstring::npos)
for(const auto ch:text)
{
if(ch==L'\t') break;
const auto key=towupper(ch);
if(key>=L'A' && key<=L'Z' && reserve(i,static_cast<wchar_t>(key))) break;
}
}
commandAccessPositions.clear();
for(const auto action:commandActions)
{
commandAccessPositions.push_back(action<0?std::wstring::npos:accessPositions[action]);
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(action<0?L"":rows[action].c_str()));
}
RECT anchor{}, client{};
GetWindowRect(menuItems[index],&anchor);
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&anchor),2);
GetClientRect(window,&client);
const int inset=dialogFrameMetrics(GetDpiForWindow(window)).content();
int columns=26;
for(const auto action:commandActions)
if(action>=0) columns=std::max(columns,static_cast<int>(rows[action].size())+3);
const int width=std::max(1,std::min(static_cast<int>(client.right)-2*inset,columns*cellWidth+16));
const int x=std::clamp(static_cast<int>(anchor.left)+inset,inset,
std::max(inset,static_cast<int>(client.right)-width-inset));
const int y=anchor.bottom+5;
const int rowHeight=static_cast<int>(SendMessageW(picker,LB_GETITEMHEIGHT,0,0));
const int maxRows=std::max(1,(static_cast<int>(client.bottom)-y-inset)/rowHeight);
const int height=std::min(static_cast<int>(commandActions.size()),maxRows)*rowHeight;
showFramedList(picker,pickerFrame,x,y,width,height,inset);
SendMessageW(picker,LB_SETCURSEL,0,0);
SetFocus(picker);
showMenu(true);
}
void toggleFilesMenu()
{
const bool visible=IsWindowVisible(menuBar);
hidePicker();
if(!visible) menuIndex=active==0?0:4;
showMenu(!visible);
if(visible) SetFocus(panels[active].list);
}
bool handleFilesMenuKey(HWND window,UINT message,WPARAM key,LPARAM flags,bool modified)
{
const bool repeated=(flags & (1LL << 30))!=0;
if(message==WM_SYSKEYDOWN && key==VK_MENU)
{
return !modified;
}
if((message==WM_SYSKEYUP || message==WM_KEYUP) && key==VK_MENU)
return !modified;
if(message!=WM_KEYDOWN && message!=WM_SYSKEYDOWN) return false;
if(modified) return false;
if(message==WM_KEYDOWN && key==VK_F9)
{
if(!repeated) toggleFilesMenu();
return true;
}
if(IsWindowVisible(menuBar) && message==WM_SYSKEYDOWN &&
(flags & (1LL << 29)) && key>=L'A' && key<=L'Z')
{
const auto category=menuAccessKeys.find(static_cast<wchar_t>(key));
if(category!=menuAccessKeys.npos)
{
if(!repeated) openMenu(window,static_cast<int>(category));
return true;
}
}
return false;
}
void searchPanelByPrefix(HWND window,wchar_t character)
{
if(character==L'\b')
{
if(!panelSearchPrefix.empty()) panelSearchPrefix.pop_back();
}
else panelSearchPrefix+=character;
auto &panel=panels[active];
const auto length=static_cast<int>(panelSearchPrefix.size());
for(size_t row=0;length && row<panel.rows.size();++row)
{
if(panel.sizes[row]==L"Up") continue;
const auto *profiles=transferProfileList(panel)?&transferProfiles(panel.ftp->protocol).rows:nullptr;
const auto name=panel.listing && row<panel.listing->rows.size()?panel.listing->rows[row].second:
profiles && row<profiles->size()?(*profiles)[row].name:panel.rows[row].filename().native();
if(name.size()<panelSearchPrefix.size() ||
CompareStringOrdinal(name.data(),length,panelSearchPrefix.data(),length,TRUE)!=CSTR_EQUAL)
continue;
SendMessageW(panel.list,LB_SETCURSEL,row,0);
InvalidateRect(panel.list,nullptr,FALSE);
showFileDetails(panel);
if(!IsWindowVisible(panelSearchPopup))
{
placePanelSearch(window);
ShowWindow(panelSearchPopup,SW_SHOWNA);
}
break;
}
if(IsWindowVisible(panelSearchPopup)) InvalidateRect(panelSearchPopup,nullptr,FALSE);
else panelSearchPrefix.clear();
}
bool handlePanelSearchKey(HWND window,MSG &message)
{
const bool searching=IsWindowVisible(panelSearchPopup);
if(message.message==WM_LBUTTONDOWN || message.message==WM_RBUTTONDOWN ||
message.message==WM_NCLBUTTONDOWN || message.message==WM_MOUSEWHEEL)
{
if(searching && message.hwnd!=panelSearchPopup) closePanelSearch();
return false;
}
const bool input=message.hwnd==terminalInput || message.hwnd==panels[0].list ||
message.hwnd==panels[1].list;
if(!input || terminalVisible || IsWindowVisible(menuBar) || IsWindowVisible(picker)) return false;
const bool modified=(GetKeyState(VK_CONTROL)&0x8000) || (GetKeyState(VK_LWIN)&0x8000) ||
(GetKeyState(VK_RWIN)&0x8000);
const bool alt=(message.lParam & (1LL<<29))!=0;
if((message.message==WM_SYSCHAR && alt) || (searching && message.message==WM_CHAR))
{
if(!modified && (message.wParam==L'\b' ||
(message.wParam>=32 && message.wParam!=127 && (!alt || message.wParam!=L' '))))
{
searchPanelByPrefix(window,static_cast<wchar_t>(message.wParam));
return true;
}
return false;
}
if(message.message!=WM_KEYDOWN && message.message!=WM_SYSKEYDOWN) return false;
if(!modified && message.wParam!=VK_SPACE && message.message==WM_SYSKEYDOWN && alt &&
(message.wParam==VK_BACK || MapVirtualKeyW(static_cast<UINT>(message.wParam),MAPVK_VK_TO_CHAR)))
{
TranslateMessage(&message);
return true;
}
if(!searching || message.wParam==VK_MENU || message.wParam==VK_SHIFT) return false;
if(!modified && !alt && (message.wParam==VK_BACK ||
MapVirtualKeyW(static_cast<UINT>(message.wParam),MAPVK_VK_TO_CHAR)) &&
message.wParam!=VK_RETURN && message.wParam!=VK_ESCAPE && message.wParam!=VK_TAB)
{
TranslateMessage(&message);
return true;
}
closePanelSearch();
if(message.wParam==VK_RETURN && !modified && !alt)
{
SendMessageW(panels[active].list,message.message,message.wParam,message.lParam);
return true;
}
return message.wParam==VK_ESCAPE && !modified && !alt;
}
bool commandLineAvailable(HWND owner)
{
return !copyInProgress && !commandHistoryWindow && !FilesModalDialog::activeFor(owner) &&
!IsWindowVisible(menuBar) && !IsWindowVisible(picker);
}
#include "files_git_panel.inl"
void restoreCommandFocus()
{
if(gitChangesView)
{
const auto focus=GetFocus();
if(focus==GetParent(terminalInput)) SetFocus(gitChangesView->list);
return;
}
if(GetFocus()!=terminalInput && !GetCapture() && commandLineAvailable(GetParent(terminalInput)))
SetFocus(terminalInput);
}
void handleFilesReturn(bool shift)
{
closePanelSearch();
if(terminalVisible || GetWindowTextLengthW(terminalInput)) runCommandLine();
else if(shift) openSelectedWithSystem(panels[active]);
else enter(panels[active]);
}
#include "files_smb.inl"
#include "files_path_bar.inl"
#include "files_path_navigation.inl"
LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
{
if(quickViewWindow && ks::files::windowsAppThemeChanged(message,lp))
SendMessageW(quickViewWindow,message,wp,lp);
if(message==filesPreferencesChanged)
{
if(quickViewWindow) SendNotifyMessageW(quickViewWindow,message,wp,lp);
if(gitChangesView) SendNotifyMessageW(gitChangesView->preview,message,wp,lp);
if(reinterpret_cast<HWND>(wp)!=window)
{
loadFilesPreferences(window);
refreshFilesKeyBar();
layout(window);
layoutOpenCommandHistory();
showFileDetails(panels[active]);
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
}
return 0;
}
switch (message)
{
case ks::files::filesMcpQueryMessage:
filesMcp.answer(readFilesMcpTool);
return 0;
case WM_SETFOCUS:
restoreCommandFocus();
return 0;
case WM_ACTIVATEAPP:
if(!wp)
{
closePanelSearch();
resetCompletion();
}
break;
case WM_COPYDATA:
{
const auto *reply=reinterpret_cast<const COPYDATASTRUCT*>(lp);
auto *lookup=peerLookupRequest;
if(!lookup || reinterpret_cast<HWND>(wp)!=lookup->service || !reply ||
reply->dwData!=FilesLanPeersReply || reply->cbData>FilesLanPeersLimit ||
(!reply->cbData || !reply->lpData)) return FALSE;
try
{
const auto *begin=static_cast<const char*>(reply->lpData);
const auto rows=Json::parse(begin,begin+reply->cbData);
if(!rows.is_array()) return FALSE;
for(const auto &row:rows)
lookup->peers.push_back({row.at("id"),row.at("address"),ks::wide(row.at("name")),ks::lan::FilesPort,
row.value("filesBrowse",false)});
}
catch(const std::exception &){lookup->peers.clear();return FALSE;}
lookup->received=true;
return TRUE;
}
case ks::files::quickViewToggleMessage:
if(quickViewWindow && !copyInProgress && !FilesModalDialog::activeFor(window)) toggleQuickView(window);
return 0;
case panelDropReady:
performPanelDrop(window);
return 0;
case directoryScanReady:
if(!FilesModalDialog::activeFor(window))
{
collectDirectoryScans();
collectSmbConnections(window);
collectTreeBranches();
}
return 0;
case WM_TIMER:
if(wp==driveQueryTimer) {pollDriveQueries(window);return 0;}
if(wp==terminalTimer)
{
if(pendingPeerAction.valid() &&
pendingPeerAction.wait_for(std::chrono::seconds(0))==std::future_status::ready)
setStatus(pendingPeerAction.get());
updateTerminalOutput(window);
updateCompletion(window);
return 0;
}
if(wp==directoryWatchTimer)
{
if(!FilesModalDialog::activeFor(window))
{
collectDirectoryScans();
collectSmbConnections(window);
collectTreeBranches();
pollRemotePanels();
refreshChangedPanels();
showDirectoryScanProgress(panels[active]);
}
for(auto &panel:panels) collectFolderSizes(panel);
return 0;
}
if(wp!=transferHighlightTimer) break;
++transferHighlightPhase;
for(auto &panel:panels)
{
if(panel.transferResults.empty()) continue;
if(transferHighlightPhase==4) panel.transferResults.clear();
InvalidateRect(panel.list,nullptr,FALSE);
}
if(transferHighlightPhase==4) KillTimer(window,transferHighlightTimer);
return 0;
case WM_CREATE:
{
auto instance = GetModuleHandleW(nullptr);
if(!loadFilesPreferences(window)) return -1;
lavender::setFont(GetDpiForWindow(window));
FilesModalDialog::styleControls=[](HWND dialog) { if(lavenderFiles()) styleLavenderDialogControls(dialog); };
FilesModalDialog::styleBackground=lavenderDialogColors;
menuBar=CreateWindowW(L"BUTTON",L"",WS_CHILD|WS_CLIPSIBLINGS|BS_OWNERDRAW,
0,0,0,0,window,reinterpret_cast<HMENU>(120),instance,nullptr);
const wchar_t *menus[]{L"Left",L"Files",L"Commands",L"Options",L"Right"};
for(int i=0;i<5;++i)
{
menuItems[i]=CreateWindowW(L"BUTTON",menus[i],WS_CHILD|WS_CLIPSIBLINGS|BS_OWNERDRAW,
0,0,0,0,window,reinterpret_cast<HMENU>(130+static_cast<INT_PTR>(i)),instance,nullptr);
if(!menuItems[i]) return -1;
}
picker=CreateWindowExW(0,L"LISTBOX",L"Change drive",
WS_CHILD|WS_CLIPSIBLINGS|LBS_NOTIFY|LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT,
0,0,0,0,window,reinterpret_cast<HMENU>(121),instance,nullptr);
pickerFrame=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_OWNERDRAW,
0,0,0,0,window,reinterpret_cast<HMENU>(122),instance,nullptr);
SetWindowSubclass(picker,pickerKeys,1,0);
installScrollBar(picker,pickerFrame);
SendMessageW(picker,LB_SETITEMHEIGHT,0,textHeight);
status = CreateWindowW(L"STATIC", L"", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | SS_PATHELLIPSIS,
0, 0, 0, 0, window, reinterpret_cast<HMENU>(144), instance, nullptr);
panelSearchPopup=CreateWindowW(L"STATIC",L"Search",WS_CHILD|WS_CLIPSIBLINGS|SS_OWNERDRAW|SS_NOTIFY,
0,0,0,0,window,reinterpret_cast<HMENU>(148),instance,nullptr);
terminalInput=CreateWindowW(L"EDIT",L"",WS_CHILD|WS_VISIBLE|ES_AUTOHSCROLL,
0,0,0,0,window,nullptr,instance,nullptr);
terminalPrompt=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_VISIBLE|SS_PATHELLIPSIS|SS_NOTIFY,
0,0,0,0,window,nullptr,instance,nullptr);
terminalOutput=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
0,0,0,0,window,reinterpret_cast<HMENU>(145),instance,nullptr);
completionList=CreateWindowW(L"LISTBOX",L"Command suggestions",
WS_CHILD|WS_CLIPSIBLINGS|LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT,
0,0,0,0,window,reinterpret_cast<HMENU>(149),instance,nullptr);
completionFrame=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_OWNERDRAW,
0,0,0,0,window,nullptr,instance,nullptr);
if(!completionList || !completionFrame) return -1;
SetWindowSubclass(completionList,completionClick,1,0);
installScrollBar(completionList,completionFrame);
terminalBackground=CreateSolidBrush(terminalSurface);
if(!terminalInput || !terminalOutput || !terminalPrompt || !terminalBackground) return -1;
for(const auto control:{terminalInput,terminalOutput,terminalPrompt})
SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(terminalFont),FALSE);
SendMessageW(terminalInput,EM_SETLIMITTEXT,2048,0);
SendMessageW(terminalInput,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,0);
SetWindowSubclass(terminalInput,terminalInputKeys,1,0);
SetTimer(window,terminalTimer,50,nullptr);
SetTimer(window,directoryWatchTimer,static_cast<UINT>(folderSpinnerInterval),nullptr);
if (!mono || !blue || !teal || !menuBar || !picker || !pickerFrame || !status || !panelSearchPopup) return -1;
SendMessageW(status, WM_SETFONT, reinterpret_cast<WPARAM>(mono), FALSE);
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
commands[i] = CreateWindowW(L"BUTTON", filesKeyBarLabel(keyBar[i].command,keyBar[i].label).c_str(),
WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
0, 0, 0, 0, window, reinterpret_cast<HMENU>(static_cast<INT_PTR>(keyBar[i].id)), instance, nullptr);
for(int i=0;i<static_cast<int>(driveButtons.size());++i)
{
const wchar_t letter[]{static_cast<wchar_t>(L'A'+i),L':',0};
driveButtons[i]=CreateWindowW(L"BUTTON",i==26?L"…":letter,WS_CHILD|BS_OWNERDRAW|WS_CLIPSIBLINGS,
0,0,0,0,window,reinterpret_cast<HMENU>(static_cast<INT_PTR>(firstDriveButton+i)),instance,nullptr);
if(!driveButtons[i]) return -1;
}
for (int i = 0; i < 2; ++i)
{
auto &panel = panels[i];
loadPanelView(i);
panel.path = CreateWindowW(L"STATIC", L"", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | SS_OWNERDRAW | SS_NOTIFY,
0, 0, 0, 0, window, reinterpret_cast<HMENU>(142 + static_cast<INT_PTR>(i)), instance, nullptr);
panel.list = CreateWindowExW(0, L"LISTBOX", L"",
WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS,
0, 0, 0, 0, window, reinterpret_cast<HMENU>(102 + static_cast<INT_PTR>(i)), instance, nullptr);
panel.heading=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_OWNERDRAW|SS_NOTIFY,
0,0,0,0,window,reinterpret_cast<HMENU>(140+static_cast<INT_PTR>(i)),instance,nullptr);
panel.selectionSummary=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_ENDELLIPSIS,
0,0,0,0,window,reinterpret_cast<HMENU>(154+static_cast<INT_PTR>(i)),instance,nullptr);
if (!panel.path || !panel.list || !panel.heading || !panel.selectionSummary) return -1;
for (auto child : {panel.path, panel.list, panel.selectionSummary})
SendMessageW(child, WM_SETFONT, reinterpret_cast<WPARAM>(mono), FALSE);
SendMessageW(panel.list,LB_SETITEMHEIGHT,0,textHeight);
restorePanelLocation(panel,i);
SetWindowSubclass(panel.list, panelKeys, 1, 0);
if(auto target=new(std::nothrow) PanelDropTarget(panel.list))
{
RegisterDragDrop(panel.list,target);
target->Release();
}
SetWindowSubclass(panel.path,pathBarInput,1,0);
SetWindowSubclass(panel.heading,panelHeadingInput,1,0);
installScrollBar(panel.list,window,firstPanelScrollBar+i);
}
SetFocus(panels[0].list);
return 0;
}
case WM_DPICHANGED:
{
hidePicker();
const auto &bounds=*reinterpret_cast<const RECT*>(lp);
applyFont(window,displayFont,fontPoints);
lavender::setFont(LOWORD(wp));
SetWindowPos(window,nullptr,bounds.left,bounds.top,bounds.right-bounds.left,
bounds.bottom-bounds.top,SWP_NOZORDER|SWP_NOACTIVATE);
layout(window);
if(activeCopy) PostMessageW(activeCopy->window,refreshProgressLayout,0,0);
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
return 0;
}
case WM_DEVICECHANGE:
if(showDriveButtons)
{
layout(window);
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
}
break;
case WM_SIZE:
hideCompletion();
hidePicker();
layout(window);
return 0;
case WM_GETMINMAXINFO:
{
const LavenderMetrics metrics(window);
reinterpret_cast<MINMAXINFO *>(lp)->ptMinTrackSize=lavenderFiles()?
POINT{metrics.px(540),metrics.px(230)}:POINT{540,220};
return 0;
}
case WM_SETCURSOR:
case WM_LBUTTONDOWN:
{
POINT point{};
GetCursorPos(&point);
ScreenToClient(window, &point);
RECT rect{};
GetClientRect(window, &rect);
const int width = rect.right;
const int middle=panelDivider(width);
if (point.y >= 0 && point.y < rect.bottom-2*textHeight-14 && abs(point.x - middle) <= 4)
{
SetCursor(LoadCursorW(nullptr, IDC_SIZEWE));
if (message == WM_LBUTTONDOWN) { dragging = true; SetCapture(window); }
return TRUE;
}
if(message==WM_LBUTTONDOWN && !terminalVisible)
{
for(auto &panel:panels)
{
RECT list{};
if(!GetWindowRect(panel.list,&list)) continue;
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&list),2);
if(point.x>=list.left && point.x<list.right && point.y>=0 && point.y<list.top)
{
selectPanelEdge(panel,true);
return 0;
}
}
}
break;
}
case WM_MOUSEMOVE:
if(dragging)
{
RECT client{};
GetClientRect(window,&client);
setPanelDivider(window,client.right,GET_X_LPARAM(lp));
}
return 0;
case WM_LBUTTONUP:
if (dragging) ReleaseCapture();
return 0;
case WM_CAPTURECHANGED:
dragging = false;
return 0;
case WM_ERASEBKGND:
return 1;
case WM_PAINT:
{
PAINTSTRUCT paint{};
auto dc=BeginPaint(window,&paint);
if(lavenderFiles() && !terminalVisible)
{
const LavenderMetrics metrics(window);
lavender::fill(dc,paint.rcPaint,lavender::canvas);
for(int index=0;index<2;++index)
{
const auto &panel=panels[index];
if(!IsWindowVisible(panel.list)) continue;
RECT list{},path{};
GetWindowRect(panel.list,&list);
GetWindowRect(panel.path,&path);
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&list),2);
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&path),2);
const int inset=metrics.px(8);
const RECT card{path.left-inset,path.top-inset,path.right+inset,
list.bottom+textHeight*(1+hasSelectionSummary())+metrics.px(9)};
lavender::rounded(dc,card,metrics.px(11),lavender::surface,
index==active?lavender::activeEdge:lavender::line);
lavender::fill(dc,{card.left+1,list.bottom,card.right-1,list.bottom+1},lavender::line);
if(scrollPosition(panel.list,false).last()) paintScrollPosition(window,dc,panel.list,lavender::surface);
}
EndPaint(window,&paint);
return 0;
}
FillRect(dc,&paint.rcPaint,terminalVisible?terminalBackground:blue);
auto border=CreateSolidBrush(colors[Frame]);
for(const auto &panel:panels)
{
if(terminalVisible) break;
RECT box{};
GetWindowRect(panel.list,&box);
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&box),2);
const auto columnX=firstPanelColumnDivider(panel,box);
box.right+=scrollBarWidth(panel.list);
InflateRect(&box,2,2);
box.left-=2;
RECT pathBounds{};
GetWindowRect(panel.path,&pathBounds);
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&pathBounds),2);
box.top=pathBounds.top+(pathBounds.bottom-pathBounds.top)/2-2;
RECT details{};
GetWindowRect(status,&details);
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&details),2);
const RECT divider{box.left+1,box.bottom-2,box.right-1,box.bottom-1};
box.bottom=std::max(box.bottom,details.bottom+(compactLayout?2:6));
FrameRect(dc,&box,border);
if(IsWindowVisible(panel.list)) paintScrollPosition(window,dc,panel.list,colors[PanelBlue]);
InflateRect(&box,-3,-3);
FrameRect(dc,&box,border);
FillRect(dc,&divider,border);
if(columnX)
{
RECT column{*columnX,box.top+1,*columnX+1,pathBounds.bottom+6};
FillRect(dc,&column,border);
}
}
DeleteObject(border);
EndPaint(window,&paint);
return 0;
}
case WM_CTLCOLOREDIT:
case WM_CTLCOLORSTATIC:
{
auto dc=reinterpret_cast<HDC>(wp);
const auto control=reinterpret_cast<HWND>(lp);
if(lavenderFiles() && (control==status || control==panels[0].selectionSummary ||
control==panels[1].selectionSummary || control==terminalPrompt || control==terminalInput))
{
SetTextColor(dc,lavender::muted);
SetBkColor(dc,lavender::surface);
return reinterpret_cast<LRESULT>(GetStockObject(WHITE_BRUSH));
}
if(reinterpret_cast<HWND>(lp)==terminalInput || reinterpret_cast<HWND>(lp)==terminalOutput ||
reinterpret_cast<HWND>(lp)==terminalPrompt)
{
SetTextColor(dc,RGB(232,232,232));
SetBkColor(dc,terminalSurface);
return reinterpret_cast<LRESULT>(terminalBackground);
}
SetTextColor(dc,colors[Frame]);
SetBkColor(dc,colors[PanelBlue]);
return reinterpret_cast<LRESULT>(blue);
}
case WM_CTLCOLORLISTBOX:
if(reinterpret_cast<HWND>(lp)==picker || reinterpret_cast<HWND>(lp)==completionList)
{
if(lavenderFiles())
{
SetDCBrushColor(reinterpret_cast<HDC>(wp),lavender::path);
return reinterpret_cast<LRESULT>(GetStockObject(DC_BRUSH));
}
return reinterpret_cast<LRESULT>(teal);
}
return reinterpret_cast<LRESULT>(lavenderFiles()?GetStockObject(WHITE_BRUSH):blue);
case WM_DRAWITEM:
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
if(item.hwndItem==menuBar && lavenderFiles())
{
lavender::fill(item.hDC,item.rcItem,lavender::canvas);
return TRUE;
}
if(item.hwndItem==panelSearchPopup)
{
const auto frame=dialogFrameMetrics(GetDpiForWindow(window));
auto field=item.rcItem;
InflateRect(&field,-frame.content(),-frame.content());
const auto cells=static_cast<size_t>(std::max(0L,field.right-field.left-10)/std::max(1,cellWidth));
const auto start=panelSearchPrefix.size()>cells?panelSearchPrefix.size()-cells:0;
if(lavenderFiles())
{
paintLavenderDialogFrame(window,item.hDC,item.rcItem,L"Search");
lavender::rounded(item.hDC,field,LavenderMetrics(window).px(5),lavender::path,lavender::line);
field.left+=LavenderMetrics(window).px(6);
lavender::text(item.hDC,field,panelSearchPrefix.c_str()+start,lavender::ink);
return TRUE;
}
const auto surface=GetSysColorBrush(COLOR_BTNFACE);
const auto border=GetSysColorBrush(COLOR_BTNTEXT);
const auto ink=GetSysColor(COLOR_BTNTEXT);
const auto box=paintDialogFrame(item.hDC,item.rcItem,frame,surface,border);
paintDialogFrameCaptions(item.hDC,item.rcItem,box,L"Search",surface,ink,mono);
paintText(item.hDC,field,panelSearchPrefix.c_str()+start,RGB(0,0,0),RGB(0,128,128));
return TRUE;
}
if(item.CtlID==142 || item.CtlID==143)
{
auto bounds=item.rcItem;
const auto &panel=panels[item.CtlID-142];
const bool highlighted=static_cast<int>(item.CtlID)-142==active;
const bool navigable=pathNavigationAvailable(panel);
if(lavenderFiles())
{
paintLavenderPanelPath(item,panel,navigable,highlighted);
return TRUE;
}
FillRect(item.hDC,&bounds,blue);
const auto middle=bounds.top+(bounds.bottom-bounds.top)/2;
SetDCBrushColor(item.hDC,colors[Frame]);
const auto lineBrush=static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
RECT upper{bounds.left,middle-2,bounds.right,middle-1};
RECT lower{bounds.left,middle+1,bounds.right,middle+2};
FillRect(item.hDC,&upper,lineBrush);
FillRect(item.hDC,&lower,lineBrush);
if(hasPanelColumns(panel))
{
const auto index=item.CtlID-142;
RECT list{};
GetWindowRect(panels[index].list,&list);
MapWindowPoints(nullptr,item.hwndItem,reinterpret_cast<POINT*>(&list),2);
if(const auto x=firstPanelColumnDivider(panel,list))
{
RECT column{*x,middle,*x+1,bounds.bottom};
FillRect(item.hDC,&column,lineBrush);
}
}
if(navigable)
{
paintPanelPath(item.hDC,item.hwndItem,bounds,panel,highlighted);
return TRUE;
}
const auto path=panelCaption(panel);
if(path.empty()) return TRUE;
const int saved=SaveDC(item.hDC);
SelectObject(item.hDC,mono);
SIZE text{};
GetTextExtentPoint32W(item.hDC,path.c_str(),static_cast<int>(path.size()),&text);
const auto width=std::min(bounds.right-bounds.left,text.cx+2L*cellWidth);
bounds.left+=(bounds.right-bounds.left-width)/2;
bounds.right=bounds.left+width;
FillRect(item.hDC,&bounds,highlighted?teal:blue);
const auto padding=std::min(static_cast<LONG>(cellWidth),width/4);
InflateRect(&bounds,-padding,0);
SetTextColor(item.hDC,colors[highlighted?Text:Frame]);
SetBkMode(item.hDC,TRANSPARENT);
DrawTextW(item.hDC,path.c_str(),-1,&bounds,
DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX|(panel.archive?DT_END_ELLIPSIS:DT_PATH_ELLIPSIS));
if(saved) RestoreDC(item.hDC,saved);
return TRUE;
}
if(item.CtlID==140 || item.CtlID==141)
{
const auto &panel=panels[item.CtlID-140];
const bool modern=lavenderFiles();
if(modern)
{
lavender::fill(item.hDC,item.rcItem,lavender::surface);
const auto &r=item.rcItem;
lavender::fill(item.hDC,{r.left,r.bottom-1,r.right,r.bottom},lavender::line);
}
const auto heading=[&](RECT bounds,const wchar_t *label,bool numeric)
{
if(modern)
{
InflateRect(&bounds,-LavenderMetrics(window).px(8),0);
lavender::text(item.hDC,bounds,label,lavender::muted,numeric?DT_RIGHT:DT_LEFT);
}
else paintText(item.hDC,bounds,label,RGB(255,255,0),colors[PanelBlue],numeric);
};
if(panel.findOrigin || panelListsLocations(panel))
{
heading(item.rcItem,panel.findOrigin?L"Relative path":L"Name",false);
return TRUE;
}
const auto columns=panelColumns(panel,item.rcItem);
static_assert(std::size(panelColumnNames)==panelColumnCount);
for(size_t i=0;i<columns.size();++i)
{
if(columns[i].left>=columns[i].right) continue;
std::wstring label=panelColumnNames[i];
if(i==nameColumn && !panel.view.mask.empty()) label+=L" *";
if(static_cast<size_t>(panel.view.sort)==i) label+=panel.view.descending?L" ↓":L" ↑";
heading(columns[i],label.c_str(),i==sizeColumn || i==allocationColumn || i==linkColumn);
}
if(!modern) paintPanelColumnLines(item.hDC,columns);
return TRUE;
}
if(item.hwndItem==pickerFrame || item.hwndItem==completionFrame)
{
const bool driveFrame=item.hwndItem==pickerFrame && !commandPicker && !folderPicker;
if(lavenderFiles())
{
const auto title=driveFrame?L"Change drive":folderPicker?folderPicker->caption:L"";
paintLavenderDialogFrame(window,item.hDC,item.rcItem,title);
paintScrollPosition(item.hwndItem,item.hDC,item.hwndItem==pickerFrame?picker:completionList,lavender::path);
return TRUE;
}
auto border=CreateSolidBrush(driveFrame?RGB(255,255,255):colors[Frame]);
const auto box=paintDialogFrame(item.hDC,item.rcItem,
dialogFrameMetrics(GetDpiForWindow(window)),teal,border);
if(driveFrame)
{
if(!drivePaths.empty())
{
RECT list{};
GetWindowRect(picker,&list);
MapWindowPoints(nullptr,pickerFrame,reinterpret_cast<POINT*>(&list),2);
for(size_t i=1;i<driveColumnStarts.size();++i)
{
const LONG x=list.left+driveColumnStarts[i]-driveColumnStarts[0]-1;
if(x<list.right)
{
const RECT line{x,box.top,x+1,list.top};
FillRect(item.hDC,&line,border);
}
}
}
paintDialogFrameCaptions(item.hDC,item.rcItem,box,L"Change drive",teal,colors[Text],mono);
}
if(item.hwndItem==pickerFrame && folderPicker)
paintDialogFrameCaptions(item.hDC,item.rcItem,box,folderPicker->caption,teal,colors[Text],mono);
const auto list=item.hwndItem==pickerFrame?picker:completionList;
paintScrollPosition(item.hwndItem,item.hDC,list,colors[Dialog]);
DeleteObject(border);
return TRUE;
}
std::wstring text;
if(item.CtlType==ODT_LISTBOX && item.itemID!=UINT(-1))
{
auto length=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0);
if(length>=0)
{
text.resize(length+1);
SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(text.data()));
}
}
if(item.CtlType==ODT_BUTTON)
{
wchar_t label[64]{};
GetWindowTextW(item.hwndItem,label,64);
text=label;
}
if(item.CtlID>=firstDriveButton && item.CtlID<=moreDriveButton)
{
const auto &panel=panels[active];
const auto drive=panel.directory.root_name().native();
const bool selected=item.CtlID!=moreDriveButton && !panel.peer && !panel.ftp && !panel.archive &&
drive.size()==2 && towupper(drive.front())==L'A'+item.CtlID-firstDriveButton;
auto bounds=item.rcItem;
FillRect(item.hDC,&bounds,selected?teal:blue);
SelectObject(item.hDC,mono);
SetBkMode(item.hDC,TRANSPARENT);
SetTextColor(item.hDC,colors[selected?Text:Frame]);
DrawTextW(item.hDC,text.c_str(),-1,&bounds,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX);
if(item.itemState&ODS_FOCUS) DrawFocusRect(item.hDC,&bounds);
return TRUE;
}
if(std::find(std::begin(commands),std::end(commands),item.hwndItem)!=std::end(commands))
{
if(item.CtlID==114 && remoteSearchResults(panels[active]) && panels[active].ftp)
text=filesKeyBarLabel(FilesKey::Move,L"Rename");
if(lavenderFiles())
{
const LavenderMetrics metrics(window);
if(!remoteSearchActionAvailable(item.CtlID))
if(const auto space=text.find(L' ');space!=text.npos) text.resize(space);
paintLavenderCommand(item,text,metrics,item.rcItem.bottom-item.rcItem.top>metrics.row);
return TRUE;
}
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);
auto shortcut=item.rcItem, action=item.rcItem;
shortcut.right=std::min(shortcut.right,shortcut.left+static_cast<LONG>(key.size())*cellWidth+8);
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,remoteSearchActionAvailable(item.CtlID)?text.c_str()+separator+1:L"",
colors[Selection],colors[Footer]);
return TRUE;
}
const bool popupRow=item.hwndItem==picker || item.hwndItem==completionList;
const bool modernPopup=popupRow && lavenderFiles();
const auto popupPalette=farDropDownPalette();
const auto popupLine=modernPopup?lavender::line:RGB(255,255,255);
const auto popupAccess=modernPopup?lavender::accent:RGB(255,255,0);
auto background=item.CtlType==ODT_BUTTON?Footer:popupRow?Dialog:PanelBlue;
auto foreground=modernPopup?popupPalette.text:colors[Text];
if(item.hwndItem==picker && !folderPicker && ((commandPicker && item.itemID<commandActions.size() && commandActions[item.itemID]<0) ||
(!commandPicker && !lanDrivePicker && item.itemID==drivePaths.size())))
{
lavender::fill(item.hDC,item.rcItem,popupPalette.surface);
const auto y=(item.rcItem.top+item.rcItem.bottom)/2;
const RECT line{item.rcItem.left,y,item.rcItem.right,y+1};
SetDCBrushColor(item.hDC,modernPopup?popupLine:colors[Frame]);
FillRect(item.hDC,&line,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
return TRUE;
}
if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID==lanHeaderRow())
{
auto row=item.rcItem;
if(modernPopup)
{
lavender::fill(item.hDC,row,popupPalette.surface);
lavender::text(item.hDC,row,L"KSwitcher LAN",lavender::muted,DT_CENTER);
return TRUE;
}
FillRect(item.hDC,&row,teal);
const RECT line{row.left,row.top,row.right,row.top+1};
SetDCBrushColor(item.hDC,RGB(255,255,255));
FillRect(item.hDC,&line,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
++row.top;
paintDialogCaption(item.hDC,row,L"KSwitcher LAN",teal,colors[Text],mono);
const RECT sectionLine{row.left,row.bottom-1,row.right,row.bottom};
FillRect(item.hDC,&sectionLine,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
return TRUE;
}
if(item.CtlID>=130 && item.CtlID<=134 && static_cast<int>(item.CtlID)-130==menuIndex)
background=Selection;
const bool panelRow=item.CtlID==102 || item.CtlID==103;
const bool lavenderRow=panelRow && lavenderFiles();
const LavenderMetrics metrics(window);
const bool activePanelRow=panelRow && item.hwndItem==panels[active].list;
if(!panelRow && (item.itemState&(ODS_SELECTED|ODS_FOCUS)))
background=Selection;
COLORREF rowBackground=modernPopup?(background==Selection?popupPalette.selection:popupPalette.surface):colors[background];
HFONT rowFont{};
std::wstring folderIndicator;
if(panelRow)
{
const auto &panel=panels[item.CtlID-102];
const bool cursor=item.itemID!=UINT(-1) && SendMessageW(panel.list,LB_GETCURSEL,0,0)==item.itemID;
traceTerminal("panel-draw",item.CtlID-102,item.itemID,activePanelRow && cursor);
const auto resolved=panelRowStyle(panel,item.itemID,cursor,activePanelRow);
foreground=resolved.foreground;
rowBackground=resolved.background;
rowFont=fileStyleFonts[resolved.decorations];
if(lavenderRow)
{
auto row=item.rcItem;
lavender::fill(item.hDC,row,lavender::surface);
if(rowBackground!=lavender::surface)
{
InflateRect(&row,-metrics.px(1),-metrics.px(1));
lavender::rounded(item.hDC,row,metrics.px(6),rowBackground,
cursor && activePanelRow?lavender::activeEdge:rowBackground);
}
if(item.itemID<panel.sizes.size())
{
paintLavenderFileIcon(item.hDC,item.rcItem,metrics,panel.sizes[item.itemID]==L"Folder" ||
panel.sizes[item.itemID]==L"Up" || transferProfileList(panel));
if(!detailedPanel(panel) && panel.sizes[item.itemID]==L"Folder")
text=panel.rows[item.itemID].filename().wstring();
}
}
if(item.itemID<panel.rows.size())
{
const auto &path=panel.rows[item.itemID];
folderIndicator=folderMeasurementText(panel,path,static_cast<size_t>(sizeWidth));
}
}
const auto paintRow=[&](RECT bounds,const wchar_t *label,bool right=false,bool icon=false)
{
if(lavenderRow)
{
bounds.left+=metrics.px(icon?30:5);
bounds.right-=metrics.px(8);
lavender::text(item.hDC,bounds,label,foreground,right?DT_RIGHT:DT_LEFT);
}
else paintText(item.hDC,bounds,label,foreground,rowBackground,right,right?nullptr:rowFont);
};
auto shortcut=text.find(L'\t');
if((item.hwndItem==picker && folderPicker) || (panelRow && recentFolderList(panels[item.CtlID-102])))
paintDialogListRow(item.hDC,item.rcItem,text,rowFont?rowFont:mono,foreground,rowBackground,
panelRow?5:dialogRowTextInset(cellWidth),DT_PATH_ELLIPSIS|DT_END_ELLIPSIS);
else if(item.hwndItem==picker && commandPicker && item.itemID<commandAccessPositions.size())
{
auto labelRect=item.rcItem, keyRect=item.rcItem;
const auto font=modernPopup?dialogUiFont():mono;
SelectObject(item.hDC,font);
SIZE extent{};
if(shortcut!=text.npos)
{
const auto key=text.c_str()+shortcut+1;
GetTextExtentPoint32W(item.hDC,key,lstrlenW(key),&extent);
keyRect.left=std::max(keyRect.left,keyRect.right-extent.cx-16);
labelRect.right=keyRect.left;
paintText(item.hDC,keyRect,key,foreground,rowBackground,true,font);
}
paintMenuLabel(item.hDC,labelRect,text.substr(0,shortcut),commandAccessPositions[item.itemID],
foreground,rowBackground,popupAccess,font);
}
else if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID<drivePaths.size())
{
SelectObject(item.hDC,mono);
SetTextColor(item.hDC,foreground);
const auto normal=popupPalette.surface;
const auto hover=ks::files::hoverSurface(normal);
SetBkColor(item.hDC,background==Dialog && static_cast<int>(item.itemID)==driveHover?
hover:rowBackground);
ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&item.rcItem,L"",0,nullptr);
SetBkMode(item.hDC,TRANSPARENT);
SetDCBrushColor(item.hDC,popupLine);
const auto brush=static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
size_t start=0;
for(size_t i=0;i<driveColumnStarts.size();++i)
{
const LONG x=item.rcItem.left+driveColumnStarts[i];
if(i)
{
const LONG divider=x-driveColumnStarts[0]-1;
if(divider<item.rcItem.right)
{
const RECT line{divider,item.rcItem.top,divider+1,item.rcItem.bottom};
FillRect(item.hDC,&line,brush);
}
}
const auto end=text.find(L'\t',start);
const auto length=end==text.npos?lstrlenW(text.c_str()+start):end-start;
SetTextColor(item.hDC,foreground);
ExtTextOutW(item.hDC,x,item.rcItem.top+3,ETO_CLIPPED,&item.rcItem,
text.c_str()+start,static_cast<UINT>(length),nullptr);
if(i==0 && length)
{
SetTextColor(item.hDC,popupAccess);
ExtTextOutW(item.hDC,x,item.rcItem.top+3,ETO_CLIPPED,&item.rcItem,text.c_str(),1,nullptr);
}
if(end==text.npos) break;
start=end+1;
}
SetBkMode(item.hDC,OPAQUE);
}
else if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID>=drivePaths.size())
{
auto bounds=item.rcItem;
RECT button{};
const auto choice=remoteDriveRows.find(item.itemID);
const bool wake=choice!=remoteDriveRows.end() && !choice->second.path;
const auto digit=item.itemID==ftpDriveRow()?ftpDriveDigit:
choice==remoteDriveRows.end()?L'\0':choice->second.digit;
SelectObject(item.hDC,mono);
SetTextColor(item.hDC,foreground);
SetBkColor(item.hDC,wake?popupPalette.surface:rowBackground);
if(wake)
{
button=driveWakeAction.bounds(bounds,cellWidth);
if(shortcut!=std::wstring::npos) text.resize(shortcut);
ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&bounds,L"",0,nullptr);
bounds.right=button.left;
}
const auto x=bounds.left+driveColumnStarts[0];
const auto y=bounds.top+3;
const auto indent=digit && !text.starts_with(L" ")?2*cellWidth:0;
ExtTextOutW(item.hDC,x+indent,y,ETO_OPAQUE|ETO_CLIPPED,&bounds,
text.c_str(),static_cast<UINT>(text.size()),nullptr);
if(digit)
{
const auto previous=SetTextColor(item.hDC,popupAccess);
ExtTextOutW(item.hDC,x,y,ETO_CLIPPED,&bounds,&digit,1,nullptr);
SetTextColor(item.hDC,previous);
}
if(wake)
{
const bool focused=(item.itemState&ODS_SELECTED) && GetFocus()==picker;
driveWakeAction.paint(item.hDC,button,3,foreground,popupPalette.surface,
focused || static_cast<int>(item.itemID)==driveHover);
}
}
else if(item.CtlID>=130 && item.CtlID<=134)
{
if(lavenderFiles()) paintMenuLabel(item.hDC,item.rcItem,text,0,lavender::ink,
background==Selection?lavender::selection:lavender::canvas,lavender::accent,dialogUiFont());
else paintMenuLabel(item.hDC,item.rcItem,text,0,foreground,colors[background]);
}
else if(!folderIndicator.empty() && !detailedPanel(panels[item.CtlID-102]))
{
auto name=item.rcItem, indicator=item.rcItem;
indicator.left=std::max(indicator.left,indicator.right-static_cast<LONG>(folderIndicator.size())*cellWidth-10);
name.right=indicator.left;
paintRow(name,text.c_str(),false,true);
paintRow(indicator,folderIndicator.c_str(),true);
}
else if(!lavenderRow || !hasPanelColumns(panels[item.CtlID-102]) ||
transferProfileList(panels[item.CtlID-102]) || item.itemID>=panels[item.CtlID-102].sizes.size())
paintRow(item.rcItem,text.c_str(),false,true);
if(item.CtlID==102 || item.CtlID==103)
{
const auto &panel=panels[item.CtlID-102];
if(hasPanelColumns(panel) && !transferProfileList(panel) && item.itemID<panel.sizes.size())
{
const auto columns=panelColumns(panel,item.rcItem);
const auto &path=panel.rows[item.itemID];
const auto &extension=columns[extensionColumn];
const auto &date=columns[dateColumn];
const auto &amount=panel.sizes[item.itemID];
const bool folder=amount==L"Folder",up=amount==L"Up",tree=treePanelActive(panel);
if(folder || (tree && !up)) text=path.filename().native();
const auto &settings=panel.columns[static_cast<size_t>(panel.mode)];
const bool useExtension=extension.left<extension.right && !up &&
(settings.customized || panel.mode==PanelMode::full || (folder?alignFolders:alignExtensions));
if(extension.left<extension.right)
{
auto suffix=useExtension?path.extension().native():std::wstring{};
if(suffix.size()>1)
{
suffix.erase(suffix.begin());
text=path.stem().native();
const auto capacity=static_cast<size_t>(std::max(1L,(extension.right-extension.left-6)/cellWidth));
if(suffix.size()>capacity)
{
suffix.resize(capacity-1);
if(!suffix.empty() && suffix.back()>=0xd800 && suffix.back()<=0xdbff) suffix.pop_back();
suffix+=L'…';
}
}
else suffix.clear();
if(lavenderRow) paintRow(extension,suffix.c_str(),true);
else paintText(item.hDC,extension,suffix.c_str(),foreground,rowBackground,true,rowFont);
}
if(tree) text=treeRowPrefix(panel,path,folder)+text;
const auto paintValue=[&](PanelColumn column,const std::wstring &value,bool align)
{
const auto &bounds=columns[column];
if(bounds.left<bounds.right)
{
if(lavenderRow) paintRow(bounds,value.c_str(),align,column==nameColumn);
else paintText(item.hDC,bounds,value.c_str(),foreground,rowBackground,align,rowFont);
}
};
const auto columnCells=[&](PanelColumn column) {
const auto &bounds=columns[column];
return static_cast<size_t>(std::max(1L,(bounds.right-bounds.left)/cellWidth-2));
};
paintValue(nameColumn,text,false);
if(date.left<date.right)
{
wchar_t modified[16]{};
if(const auto entry=panel.metadata.find(path);entry!=panel.metadata.end())
{
if(const auto time=localFileTime(entry->second.modified))
swprintf_s(modified,L"%04u-%02u-%02u",unsigned(time->wYear),unsigned(time->wMonth),unsigned(time->wDay));
}
paintValue(dateColumn,modified,true);
}
const auto &size=columns[sizeColumn];
if(size.left<size.right)
{
auto label=lavenderRow && (folder || up)?L"—":amount;
if(folder)
{
auto measured=folderMeasurementText(panel,path,columnCells(sizeColumn));
if(!measured.empty()) label=std::move(measured);
}
else if(!up) label=formatSize(std::stoull(amount),columnCells(sizeColumn));
paintValue(sizeColumn,label,true);
}
const auto details=panel.columnMetadata.find(path);
const std::wstring empty=up?L"":L"—";
const auto *extra=details==panel.columnMetadata.end()?nullptr:&details->second;
if(columns[allocationColumn].left<columns[allocationColumn].right)
paintValue(allocationColumn,extra && extra->allocated?
formatSize(*extra->allocated,columnCells(allocationColumn)):empty,true);
if(columns[linkColumn].left<columns[linkColumn].right)
paintValue(linkColumn,extra && extra->links?std::to_wstring(*extra->links):empty,true);
if(columns[ownerColumn].left<columns[ownerColumn].right)
paintValue(ownerColumn,extra && !extra->owner.empty()?extra->owner:empty,false);
if(!lavenderRow) paintPanelColumnLines(item.hDC,columns);
}
}
if (item.CtlType==ODT_LISTBOX && !popupRow)
{
RECT track{};
GetWindowRect(item.hwndItem,&track);
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&track),2);
track.left=track.right;
track.right+=5;
InvalidateRect(window,&track,FALSE);
}
return TRUE;
}
case WM_COMMAND:
if(reinterpret_cast<HWND>(lp)==terminalInput && HIWORD(wp)==EN_CHANGE)
{
panelClipboardContext=false;
clearTerminalSelection();
resetCompletion();
}
if(copyInProgress || commandHistoryWindow || FilesModalDialog::activeFor(window)) return 0;
if(reinterpret_cast<HWND>(lp)==terminalPrompt && HIWORD(wp)==STN_CLICKED)
{
handleTerminalPromptInput(window,L"focus-input");
return 0;
}
if(reinterpret_cast<HWND>(lp)==status && HIWORD(wp)==STN_CLICKED)
{
auto &panel=panels[active];
if(panel.remoteRetry && !panel.scan.valid())
{
const auto message=panel.remoteRetry->failure+L"\r\n\r\nRetry opening this folder?";
if(showFilesNotice(window,message.c_str(),L"Remote folder",{.confirm=true})==IDYES)
refreshPanel(panel);
}
return 0;
}
if(LOWORD(wp)==smbSignInCommand && HIWORD(wp)==BN_CLICKED)
{
signInSmbProfile(panels[active]);
return 0;
}
if(HIWORD(wp)==BN_CLICKED && LOWORD(wp)>=firstDriveButton && LOWORD(wp)<=moreDriveButton)
{
const auto id=LOWORD(wp);
if(id==moreDriveButton) chooseDrive(active);
else
{
const wchar_t root[]{static_cast<wchar_t>(L'A'+id-firstDriveButton),L':',L'\\',0};
openOn(panels[active],root,false,{});
restoreCommandFocus();
}
return 0;
}
if(LOWORD(wp)==121 && HIWORD(wp)==LBN_DBLCLK) selectDrive();
if(LOWORD(wp)>=130 && LOWORD(wp)<=134 && HIWORD(wp)==BN_CLICKED)
{
openMenu(window,LOWORD(wp)-130);
return 0;
}
if (HIWORD(wp) == BN_CLICKED)
{
for(const auto &command:keyBar)
if(LOWORD(wp)==command.id && remoteSearchActionAvailable(command.id))
runFilesKeyCommand(window,active,command.command);
}
if (LOWORD(wp) >= 102 && LOWORD(wp) <= 103 && HIWORD(wp) == LBN_DBLCLK)
enter(panels[LOWORD(wp) - 102]);
if (LOWORD(wp) >= 102 && LOWORD(wp) <= 103 && HIWORD(wp) == LBN_SELCHANGE)
{
const auto &panel=panels[LOWORD(wp) - 102];
showFileDetails(panel);
}
return 0;
case WM_CLOSE:
if(!activeCopy && FilesModalDialog::dismissOwned(window)) return 0;
if(gitChangesView && gitActionPending(*gitChangesView)) return 0;
if(activeCopy)
{
if(FilesModalDialog::activeFor(window)!=activeCopy->window)
{
setStatus(L"Resolve the copy prompt before closing.");
return 0;
}
SendMessageW(activeCopy->window,WM_COMMAND,IDCANCEL,0);
activeCopy->closeOwner=activeCopy->canceled;
return 0;
}
savePlacement(window);
ks::files::saveLocalDocumentSession(schemeKey,restoreDocuments);
for(int i=0;i<2;++i)
{
const auto &panel=panels[i];
saveFtpPanelLocation(panel,i);
if(panel.peer || panel.ftp) continue;
auto path=(panel.archive?panel.archive->file.parent_path():panel.directory).native();
const auto row=currentPanelRow(panel);
auto cursor=panel.archive?panel.archive->file.native():
row==LB_ERR?std::wstring{}:panel.rows[row].native();
if(panel.listing)
{
if(panel.navigation.history.empty()) continue;
const auto &previous=panel.navigation.history[panel.navigation.current];
if(previous.provider!=FolderProvider::local) continue;
path=previous.directory.native();
cursor=panel.listing->returnSelection.native();
}
if(!path.empty())
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelPathKeys[i],REG_SZ,path.c_str(),
static_cast<DWORD>((path.size()+1)*sizeof(wchar_t)));
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelCursorKeys[i],REG_SZ,cursor.c_str(),
static_cast<DWORD>((cursor.size()+1)*sizeof(wchar_t)));
}
DestroyWindow(window);
return 0;
case WM_DESTROY:
filesMcp.stop();
pendingPanelDrop.reset();
closeGitChanges(window,false);
for(auto &panel:panels)
if(panel.folderSizeJob) panel.folderSizeJob->stop.request_stop();
KillTimer(window,terminalTimer);
KillTimer(window,directoryWatchTimer);
for(auto &panel:panels)
{
panel.scanStop.request_stop();
cancelSmbConnection(panel);
stopTreeBranches(panel);
panel.watch.reset();
}
sshTerminal.stop();
sshView.close();
terminalView.close();
terminal.close();
if(remoteCommandThread.joinable())
{
remoteCommandThread.request_stop();
remoteCommandThread.join();
}
closeQuickViews();
ks::files::textWindowOwnerClosed();
return 0;
}
return DefWindowProcW(window, message, wp, lp);
}
#include "files_log_view.inl"
#include "files_help.inl"
}
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
{
int count{};
if(auto args=CommandLineToArgvW(GetCommandLineW(),&count))
{
if(count==4 && std::wstring_view(args[1])==L"--list-folder")
{
auto result=listElevatedFolder(fs::path(args[2]).parent_path(),args[3]);
LocalFree(args);
return static_cast<int>(result);
}
if(count==4 && std::wstring_view(args[1])==L"--elevated-file-operation")
{
const auto result=serveElevatedFileOperations(args[2],args[3]);
LocalFree(args);
return static_cast<int>(result);
}
for(int i=1;i<count;++i)
if(std::wstring_view(args[i])==L"--terminal-trace" ||
std::wstring_view(args[i])==L"--terminal-output-trace")
{
traceTerminalOutput=std::wstring_view(args[i])==L"--terminal-output-trace";
wchar_t temp[MAX_PATH]{};
const auto length=GetTempPathW(MAX_PATH,temp);
if(length && length<MAX_PATH)
terminalTrace.open(fs::path(temp)/(L"KSwitcher.Files.terminal-trace-"+
std::to_wstring(GetCurrentProcessId())+L".log"),std::ios::trunc);
traceTerminal("start");
}
LocalFree(args);
}
bool writeLog=ks::Settings{}.writeLog;
try
{
const auto settings=ks::dataDirectory()/L"settings.json";
if(std::filesystem::exists(settings))
writeLog=Json::parse(ks::readFile(settings,1024*1024)).value("writeLog",writeLog);
}
catch(const std::exception &) {}
ks::setLogFilename(L"kswitcher-files.log");
ks::setLoggingEnabled(writeLog);
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_STANDARD_CLASSES|ICC_PROGRESS_CLASS|ICC_TREEVIEW_CLASSES|
ICC_HOTKEY_CLASS|ICC_BAR_CLASSES};
InitCommonControlsEx(&controls);
loadCommandHistory();
WNDCLASSW type{};
type.hInstance = instance;
type.lpfnWndProc = filesWindow;
type.hIcon = LoadIconW(instance, MAKEINTRESOURCEW(1));
type.hCursor = LoadCursorW(nullptr, IDC_ARROW);
type.lpszClassName = L"KSwitcher.Files";
if (!registerFarEdit(instance) || !RegisterClassW(&type)) return 1;
const auto com=OleInitialize(nullptr);
auto window = CreateWindowW(type.lpszClassName, L"KSwitcher Files — local prototype",
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 900, 540, nullptr, nullptr, instance, nullptr);
if(!window)
{
if(SUCCEEDED(com)) OleUninitialize();
return 1;
}
if(!restorePlacement(window)) ShowWindow(window, show);
SetFocus(terminalInput);
if(restoreDocuments) ks::files::restoreLocalDocumentSession(window,textWindowDialogs(),schemeKey,imageEditDialogs());
MSG message{};
for(;;)
{
if(GetForegroundWindow()==window || IsChild(window,GetFocus())) restoreCommandFocus();
if(GetMessageW(&message,nullptr,0,0)<=0) break;
if(handleFilesHelpMessage(message) || handleComparisonMessage(message)) continue;
if(message.message==WM_KEYDOWN && message.wParam==VK_TAB &&
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
ks::files::cycleTextWindows(GetAncestor(message.hwnd,GA_ROOT),(GetKeyState(VK_SHIFT)&0x8000)!=0))
continue;
if(!IsWindow(window) || (message.hwnd && GetAncestor(message.hwnd,GA_ROOTOWNER)!=window))
{
TranslateMessage(&message);
DispatchMessageW(&message);
continue;
}
if(message.hwnd==window && message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST &&
GetFocus()==terminalInput)
message.hwnd=terminalInput;
if(gitChangesView)
{
if(!handleGitChangesKey(window,message))
{
TranslateMessage(&message);
DispatchMessageW(&message);
}
continue;
}
if(handlePanelPathKey(window,message) || handleFilesKeyChord(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) &&
!(GetKeyState(VK_RWIN)&0x8000) && commandLineAvailable(window) &&
handleCompletionKey(message.wParam,message.lParam))
continue;
if(message.message==WM_KEYDOWN && message.wParam==VK_RETURN &&
!(GetKeyState(VK_CONTROL)&0x8000) &&
!(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) &&
!(GetKeyState(VK_RWIN)&0x8000) && commandLineAvailable(window) &&
(message.hwnd==terminalInput || message.hwnd==panels[0].list || message.hwnd==panels[1].list))
{
if(!(message.lParam & (1LL<<30))) handleFilesReturn((GetKeyState(VK_SHIFT)&0x8000)!=0);
continue;
}
if(!copyInProgress && handlePanelSearchKey(window,message)) continue;
if(message.message==WM_KEYDOWN && message.wParam==VK_DELETE && !terminalVisible &&
!(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_SHIFT)&0x8000) &&
!(GetKeyState(VK_MENU)&0x8000) && commandLineAvailable(window) &&
(message.hwnd==panels[active].list ||
(message.hwnd==terminalInput && !GetWindowTextLengthW(terminalInput))) &&
recentFolderList(panels[active]))
{
if(!(message.lParam&(1LL<<30))) removeRecentFolder(panels[active]);
continue;
}
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE && !terminalVisible &&
commandLineAvailable(window) &&
(message.hwnd==terminalInput || message.hwnd==panels[0].list || message.hwnd==panels[1].list))
{
auto &panel=panels[active];
if(panel.scanRequest && (panel.scanRequest->find || panel.scanRequest->archive))
{
if(!panel.scanSuperseded) stopDirectoryScan();
continue;
}
if(panel.listing && !panel.scanRequest && !GetWindowTextLengthW(terminalInput))
{
if(recentFolderList(panel)) closePanelListing(panel);
else backSmbPanel(panel);
continue;
}
if(panel.archive && !panel.scanRequest)
{
parentArchive(panel);
continue;
}
if(panel.findOrigin && !panel.scanRequest)
{
open(panel,panel.directory);
continue;
}
if(panel.folderSizeJob)
{
collectFolderSizes(panel);
if(panel.folderSizeJob)
{
cancelFolderSizes(panel);
setStatus(L"Folder size calculation canceled.");
}
continue;
}
}
if(message.message==WM_KEYDOWN && (message.wParam==VK_UP || message.wParam==VK_DOWN) &&
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
(message.hwnd==window || IsChild(window,message.hwnd)) && !terminalVisible && !copyInProgress)
{
RECT bounds{};
GetClientRect(window,&bounds);
const auto maximum=std::max(0,static_cast<int>(bounds.bottom)/terminalTextHeight-8);
const int rows=std::clamp(terminalRows+(message.wParam==VK_UP?1:-1),0,maximum);
traceTerminal(message.wParam==VK_UP?"key-grow":"key-shrink",terminalRows,rows);
if(rows && !showCommandOutput(window,panels[active])) continue;
terminalRows=rows;
layout(window);
continue;
}
if(message.message==WM_KEYDOWN && message.wParam=='O' &&
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
(message.hwnd==window || IsChild(window,message.hwnd)) &&
!copyInProgress)
{
if(terminalVisible || showCommandOutput(window,panels[active])) showTerminal(window,!terminalVisible);
continue;
}
const bool panelFocused=message.hwnd==panels[0].list || message.hwnd==panels[1].list;
const bool mainInput=panelFocused || message.hwnd==terminalInput;
if(mainInput && !terminalVisible && !copyInProgress && !commandHistoryWindow &&
!FilesModalDialog::activeFor(window) && message.message==WM_KEYDOWN &&
(message.wParam==VK_LEFT || message.wParam==VK_RIGHT) &&
(GetKeyState(VK_CONTROL)&0x8000) &&
!((GetKeyState(VK_SHIFT)|GetKeyState(VK_MENU)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
{
RECT client{};
GetClientRect(window,&client);
const int direction=message.wParam==VK_LEFT?-1:1;
setPanelDivider(window,client.right,panelDivider(client.right)+direction*cellWidth);
continue;
}
if(message.message==WM_KEYDOWN && mainInput && !terminalVisible &&
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
!(GetKeyState(VK_LWIN)&0x8000) && !(GetKeyState(VK_RWIN)&0x8000) &&
message.wParam>='0' && message.wParam<='9' && !copyInProgress)
{
if(!(message.lParam & (1LL<<30)))
{
hidePicker();
showMenu(false);
auto &panel=panels[active];
const auto digit=static_cast<int>(message.wParam-'0');
if(GetKeyState(VK_SHIFT)&0x8000) addFolderShortcut(panel,digit);
else showFolderShortcuts(panel,digit);
}
continue;
}
const bool filesMessage=message.hwnd==window || IsChild(window,message.hwnd);
if(mainInput && !terminalVisible && !copyInProgress &&
(message.message==WM_KEYDOWN || (message.message==WM_SYSKEYDOWN && message.wParam==VK_F10)) &&
message.wParam>=VK_F1 && message.wParam<=VK_F12 &&
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
!(GetKeyState(VK_SHIFT)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) &&
!(GetKeyState(VK_RWIN)&0x8000))
{
if(!(message.lParam & (1LL<<30)) && message.wParam<=VK_F11)
{
hidePicker();
showMenu(false);
if(message.wParam<=VK_F2) setMode(active,message.wParam==VK_F2?PanelMode::wide:PanelMode::brief);
else panelViewAction(window,panels[active],static_cast<int>(message.wParam-VK_F3));
}
continue;
}
if(mainInput &&
!copyInProgress && message.message==WM_KEYDOWN &&
!(GetKeyState(VK_MENU)&0x8000) &&
!(GetKeyState(VK_LWIN)&0x8000) && !(GetKeyState(VK_RWIN)&0x8000))
{
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0;
const bool fileClipboard=!terminalVisible && (panelFocused || panelClipboardContext) &&
commandLineAvailable(window);
if(fileClipboard && ctrl && !shift && (message.wParam=='C' || message.wParam=='V'))
{
if(!(message.lParam&(1LL<<30)))
{
if(message.wParam=='C') copyPanelFiles(window,panels[active]);
else if(!pastePanelFiles(window,panels[active])) SendMessageW(terminalInput,WM_PASTE,0,0);
}
continue;
}
if(shift && !ctrl && message.wParam==VK_F4 && !terminalVisible)
{
if(!(message.lParam & (1LL<<30)) && commandLineAvailable(window))
{
auto &panel=panels[active];
if(recentFolderList(panel)) continue;
if(panel.listing) editSmbProfile(panel,true);
else if(transferProfileList(panel)) editTransferProfile(panel,true);
else openOrCreateText(window,panel);
}
continue;
}
if(ctrl && !shift &&
(message.wParam=='F' || message.wParam=='C' ||
message.wParam==VK_RETURN || message.wParam==VK_INSERT))
{
if(!(message.lParam & (1LL<<30)))
{
if(message.wParam=='F') insertCurrentPanelPath();
else if(message.wParam==VK_RETURN) insertCurrentPanelPath(true);
else if(message.wParam==VK_INSERT) copyCommandLineOrPanelNames(window);
else copyOrInterruptTerminal();
}
continue;
}
if(panelFocused && ((message.wParam=='V' && ctrl && !shift) ||
(message.wParam==VK_INSERT && shift && !ctrl)))
{
SetFocus(terminalInput);
SendMessageW(terminalInput,WM_PASTE,0,0);
continue;
}
}
const bool modified=(GetKeyState(VK_CONTROL)&0x8000) || (GetKeyState(VK_SHIFT)&0x8000) ||
(GetKeyState(VK_LWIN)&0x8000) || (GetKeyState(VK_RWIN)&0x8000);
if(filesMessage && !copyInProgress &&
handleFilesMenuKey(window,message.message,message.wParam,message.lParam,modified))
continue;
if((message.message==WM_LBUTTONDOWN || message.message==WM_RBUTTONDOWN ||
message.message==WM_NCLBUTTONDOWN) && message.hwnd!=menuBar && message.hwnd!=picker &&
message.hwnd!=pickerFrame &&
std::find(std::begin(menuItems),std::end(menuItems),message.hwnd)==std::end(menuItems))
{
if(message.hwnd!=completionList && message.hwnd!=completionFrame) hideCompletion();
showMenu(false);
hidePicker();
}
if((message.message==WM_CHAR || message.message==WM_SYSCHAR) && IsWindowVisible(menuBar))
{
const auto letter=towupper(static_cast<wchar_t>(message.wParam));
if(letter>=L'A' && letter<=L'Z')
{
if(!IsWindowVisible(picker))
{
const auto category=menuAccessKeys.find(static_cast<wchar_t>(letter));
if(category!=menuAccessKeys.npos) openMenu(window,static_cast<int>(category));
}
else if(commandPicker)
{
for(size_t row=0;row<commandAccessPositions.size();++row)
{
const auto pos=commandAccessPositions[row];
if(pos==std::wstring::npos) continue;
const auto length=SendMessageW(picker,LB_GETTEXTLEN,row,0);
if(length<=0 || pos>=static_cast<size_t>(length)) continue;
std::wstring label(static_cast<size_t>(length)+1,L'\0');
SendMessageW(picker,LB_GETTEXT,row,reinterpret_cast<LPARAM>(label.data()));
if(towupper(label[pos])==letter)
{
SendMessageW(picker,LB_SETCURSEL,row,0);
selectDrive();
break;
}
}
}
else
{
TranslateMessage(&message);
DispatchMessageW(&message);
}
continue;
}
}
if(message.message==WM_KEYDOWN && IsWindowVisible(menuBar) && !IsWindowVisible(picker))
{
if(message.wParam==VK_ESCAPE){showMenu(false);SetFocus(panels[active].list);continue;}
if(message.wParam==VK_LEFT || message.wParam==VK_RIGHT)
{
menuIndex=(menuIndex+(message.wParam==VK_LEFT?4:1))%5;
showMenu(true);
continue;
}
if(message.wParam==VK_RETURN || message.wParam==VK_DOWN)
{
SendMessageW(window,WM_COMMAND,MAKEWPARAM(130+menuIndex,BN_CLICKED),0);
continue;
}
}
if (message.message == WM_SYSKEYDOWN && (message.wParam == VK_F1 || message.wParam == VK_F2))
{
chooseDrive(static_cast<int>(message.wParam - VK_F1));
continue;
}
TranslateMessage(&message);
DispatchMessageW(&message);
}
for(auto font:fileStyleFonts) if(font) DeleteObject(font);
if(lavender::font) DeleteObject(lavender::font);
if(lavender::emphasis) DeleteObject(lavender::emphasis);
DeleteObject(mono);
DeleteObject(terminalFont);
DeleteObject(blue);
DeleteObject(teal);
DeleteObject(terminalBackground);
if(SUCCEEDED(com)) OleUninitialize();
return 0;
}