Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9bb2221b2b | ||
|
|
20d95b37aa | ||
|
|
6467481d2f | ||
|
|
7033c1e336 | ||
|
|
03145ae75a |
No files matched your search
+24
-6
@@ -42,6 +42,13 @@ Warning і початковий фокус на No.
|
||||
Назви файлів і папок передаються в UTF-8. Для старого сервера, який
|
||||
використовує системну кодову сторінку Windows, увімкни в профілі
|
||||
**Use Windows encoding for file names** і підключися знову.
|
||||
Після закриття Files окремо для кожної FTP-панелі зберігаються профіль,
|
||||
каталог і рядок курсора. При наступному запуску Files відкриває цей каталог
|
||||
і вибирає попередній рядок, якщо він ще існує. Коли каталог недоступний,
|
||||
панель показує попередню локальну папку й причину помилки. **Ctrl+R**
|
||||
повторює підключення. Натискання рядка стану відкриває повну причину
|
||||
помилки й підтвердження повторної спроби. Вибір іншого джерела скасовує
|
||||
відновлення.
|
||||
- F5 копіює поточний або позначені файли й папки між локальною та
|
||||
підключеною FTP-панелями в обидва боки. Призначенням є каталог іншої
|
||||
панелі. Для одного елемента можна вказати ім’я копії в цьому каталозі.
|
||||
@@ -553,6 +560,11 @@ Warning і початковий фокус на No.
|
||||
- Меню Change drive показує літеру, тип, загальний обсяг і вільне місце. Відкриття меню запускає нове LAN-виявлення. Секція KSwitcher LAN показує збережені пари, зокрема офлайн. Після кожного відкриття меню асинхронно запитує диски й показує їх під назвою відповідного ПК. Поки триває запит, видно стан завантаження. Якщо запит не вдався, видно помилку. Повторне відкриття запускає новий запит. Кожна панель має власний диск і шлях, а в заголовку віддаленої панелі перед шляхом показано назву ПК.
|
||||
|
||||
- Список дисків і файлові операції використовують права облікового запису Windows, під яким працює віддалений KSwitcher. Достатньо спарювання й доступного TCP 45885, спільні папки налаштовувати не потрібно.
|
||||
- Якщо читання LAN-папки переривається через мережеву помилку, Files
|
||||
зберігає поточний список і до трьох разів повторює читання того самого
|
||||
ПК, диска й каталогу. Після відновлення курсор залишається на наявному
|
||||
рядку. Рядок стану показує причину збою й дію **Ctrl+R** для повторної
|
||||
спроби. Перехід в інший каталог або джерело скасовує попередню спробу.
|
||||
- F5, F6, F8 і Shift+Delete у віддалених панелях використовують спільні підтвердження, попередження й прогрес. F5/F6 працюють із файлами та деревами папок між локальними й віддаленими панелями, зокрема між двома різними ПК. Між шляхами одного віддаленого ПК вміст копіюється на ньому. F8 використовує кошик того ПК, на якому лежить файл.
|
||||
- Після розриву з’єднання повтори F5 або F6 до того самого призначення. Віддалене копіювання відновлюється з підтвердженої позиції, якщо збережені байти відповідають початку вихідного файла. Підтверджене скасування видаляє частковий запис поточного файла. Завершені файли лишаються на місці. Наявний файл призначення замінюється після повного запису, а при переміщенні джерело видаляється після підтвердження запису призначення.
|
||||
|
||||
@@ -602,12 +614,15 @@ Warning і початковий фокус на No.
|
||||
показують перший кадр. Пошкоджені та надто великі файли показують повідомлення.
|
||||
|
||||
- **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує
|
||||
останні відвідані локальні папки. Повторний візит підіймає один запис
|
||||
угору, порядок зберігається після перезапуску. Enter або клік відкриває
|
||||
шлях у панелі, з якої викликали меню. Delete прибирає вибраний запис.
|
||||
останні відвідані локальні, FTP та LAN-папки. Повторний візит підіймає
|
||||
один запис угору, порядок зберігається після перезапуску. Enter або клік
|
||||
відкриває шлях у панелі, з якої викликали меню. Віддалені записи містять
|
||||
шлях і ідентифікатор збереженого FTP-профілю або спареного ПК. Паролі
|
||||
зберігаються лише в налаштуваннях FTP-профілів. Delete прибирає вибраний
|
||||
запис із недавніх.
|
||||
|
||||
- У локальному заголовку кнопки ← та → переходять назад і вперед
|
||||
в історії відповідної панелі. Стрілка ↑, Alt+↑ та рядок `..`
|
||||
- Кнопки ← та → переходять назад і вперед в історії відповідної панелі,
|
||||
зокрема між локальними, FTP та LAN-папками. Стрілка ↑, Alt+↑ та рядок `..`
|
||||
відкривають безпосередню батьківську папку. На корені стрілка вимкнена,
|
||||
а рядка немає. Alt+← і Alt+→ працюють з історією активної панелі.
|
||||
- Сегменти шляху відкривають папки. Якщо шлях не вміщується, ліва
|
||||
@@ -616,7 +631,10 @@ Warning і початковий фокус на No.
|
||||
відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях,
|
||||
а Esc повертає до тих самих панелей і курсора.
|
||||
|
||||
- Для LAN і FTP поточний шлях відображається по центру верхньої подвійної лінії панелі. Довгий шлях скорочується в межах панелі.
|
||||
- У заголовку FTP-папки клік по назві профілю відкриває збережені
|
||||
підключення. У LAN-папці клік по назві ПК відкриває спарені комп’ютери
|
||||
та їхні диски. Поле шляху й доповнення працюють у поточному джерелі.
|
||||
Для FTP абсолютний шлях починається з /.
|
||||
|
||||
## Спільні елементи діалогів
|
||||
|
||||
|
||||
@@ -75,6 +75,7 @@ void startFileSearch(Panel &panel,Panel::FindOptions options)
|
||||
{
|
||||
if(panel.scanRequest) return;
|
||||
cancelFolderSizes(panel);
|
||||
panel.remoteRetry.reset();
|
||||
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)};
|
||||
startDirectoryScan(panel);
|
||||
}
|
||||
|
||||
+52
-2
@@ -4,6 +4,7 @@ struct FtpProfile
|
||||
INTERNET_PORT port=INTERNET_DEFAULT_FTP_PORT;
|
||||
ks::Bytes secret;
|
||||
bool legacyNames{};
|
||||
std::string id;
|
||||
};
|
||||
|
||||
std::vector<FtpProfile> ftpProfiles;
|
||||
@@ -12,6 +13,11 @@ constexpr wchar_t ftpProfilesValue[]=L"FtpProfiles";
|
||||
constexpr DWORD ftpProfilesMaxBytes=1024*1024;
|
||||
const fs::path ftpRoot=L"\\";
|
||||
|
||||
bool isFtpFolderPath(const fs::path &path)
|
||||
{
|
||||
return path.has_root_directory() && !path.has_root_name();
|
||||
}
|
||||
|
||||
std::wstring ftpPath(const fs::path &path)
|
||||
{
|
||||
auto value=path.native();
|
||||
@@ -25,7 +31,7 @@ bool saveFtpProfiles(const std::vector<FtpProfile> &profiles)
|
||||
for(const auto &profile:profiles)
|
||||
rows.push_back({{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)},
|
||||
{"port",profile.port},{"user",ks::utf8(profile.user)},{"secret",profile.secret},
|
||||
{"legacyNames",profile.legacyNames}});
|
||||
{"legacyNames",profile.legacyNames},{"id",profile.id}});
|
||||
const auto data=rows.dump();
|
||||
return data.size()<=ftpProfilesMaxBytes &&
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,REG_BINARY,data.data(),
|
||||
@@ -58,7 +64,8 @@ bool loadFtpProfiles()
|
||||
if(!port || port>65535) return false;
|
||||
FtpProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")),
|
||||
ks::wide(row.at("user")),static_cast<INTERNET_PORT>(port),row.at("secret").get<ks::Bytes>(),
|
||||
row.value("legacyNames",false)};
|
||||
row.value("legacyNames",false),row.value("id",std::string{})};
|
||||
if(profile.id.empty()) profile.id="legacy:"+ks::utf8(profile.name);
|
||||
if(profile.name.empty() || profile.host.empty()) return false;
|
||||
profiles.push_back(std::move(profile));
|
||||
}
|
||||
@@ -69,6 +76,14 @@ bool loadFtpProfiles()
|
||||
catch(const std::exception &) {return false;}
|
||||
}
|
||||
|
||||
const FtpProfile *findFtpProfile(std::string_view id)
|
||||
{
|
||||
const auto profile=std::find_if(ftpProfiles.begin(),ftpProfiles.end(),[&](const auto &entry) {
|
||||
return entry.id==id;
|
||||
});
|
||||
return profile==ftpProfiles.end()?nullptr:&*profile;
|
||||
}
|
||||
|
||||
std::wstring ftpPassword(const FtpProfile &profile)
|
||||
{
|
||||
if(profile.secret.empty()) return {};
|
||||
@@ -99,6 +114,41 @@ void checkFileOperation(bool success)
|
||||
if(!success) requireFileOperation(false,GetLastError());
|
||||
}
|
||||
|
||||
std::wstring ftpFolderError(const std::system_error &error)
|
||||
{
|
||||
switch(error.code().value())
|
||||
{
|
||||
case ERROR_INTERNET_CANNOT_CONNECT: return L"Cannot reach FTP server.";
|
||||
case ERROR_INTERNET_NAME_NOT_RESOLVED: return L"FTP host name could not be resolved.";
|
||||
case ERROR_INTERNET_LOGIN_FAILURE: return L"FTP sign-in failed.";
|
||||
case ERROR_INTERNET_TIMEOUT: return L"FTP connection timed out.";
|
||||
default: break;
|
||||
}
|
||||
if(error.code().value()==ERROR_INTERNET_EXTENDED_ERROR)
|
||||
{
|
||||
DWORD response{},length{};
|
||||
InternetGetLastResponseInfoW(&response,nullptr,&length);
|
||||
if(length && length<=2048)
|
||||
{
|
||||
std::wstring text(length,L'\0');
|
||||
if(InternetGetLastResponseInfoW(&response,text.data(),&length))
|
||||
{
|
||||
text.resize(length);
|
||||
text.resize(std::min(text.size(),text.find_first_of(L"\r\n")));
|
||||
if(!text.empty()) return text;
|
||||
}
|
||||
}
|
||||
return L"The FTP server rejected the request.";
|
||||
}
|
||||
wchar_t message[256]{};
|
||||
const DWORD length=FormatMessageW(FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_IGNORE_INSERTS,
|
||||
GetModuleHandleW(L"wininet.dll"),error.code().value(),0,message,static_cast<DWORD>(std::size(message)),nullptr);
|
||||
if(!length) return fileError(error);
|
||||
std::wstring text(message,length);
|
||||
while(!text.empty() && (text.back()==L'\r' || text.back()==L'\n')) text.pop_back();
|
||||
return text;
|
||||
}
|
||||
|
||||
class FtpSession
|
||||
{
|
||||
FtpHandle internet_{InternetOpenW(L"KSwitcher Files",INTERNET_OPEN_TYPE_DIRECT,nullptr,nullptr,0)};
|
||||
|
||||
@@ -91,6 +91,7 @@ INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
profile.secret=ks::protect(bytes);
|
||||
SecureZeroMemory(bytes.data(),bytes.size());
|
||||
}
|
||||
profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16);
|
||||
auto updated=ftpProfiles;
|
||||
if(edit.index) updated[*edit.index]=std::move(profile);
|
||||
else updated.push_back(std::move(profile));
|
||||
|
||||
+211
-85
@@ -381,48 +381,72 @@ fs::path panelParentPath(const fs::path &directory,bool local)
|
||||
return parent;
|
||||
}
|
||||
|
||||
bool sameLocalFolder(const fs::path &a,const fs::path &b)
|
||||
enum class FolderProvider { local, ftp, lan };
|
||||
|
||||
struct FolderLocation
|
||||
{
|
||||
return CompareStringOrdinal(a.c_str(),-1,b.c_str(),-1,TRUE)==CSTR_EQUAL;
|
||||
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,provider==FolderProvider::ftp?FALSE:TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
bool inLocalBranch(const fs::path &ancestor,fs::path directory)
|
||||
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(sameLocalFolder(ancestor,directory)) return true;
|
||||
directory=panelParentPath(directory,true);
|
||||
if(sameFolderPath(ancestor,directory,provider)) return true;
|
||||
directory=panelParentPath(directory,provider==FolderProvider::local);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#include "files_recent_folders.inl"
|
||||
|
||||
struct LocalNavigation
|
||||
struct FolderNavigation
|
||||
{
|
||||
std::vector<fs::path> history;
|
||||
std::vector<FolderLocation> history;
|
||||
size_t current{};
|
||||
fs::path previousBranch;
|
||||
|
||||
void opened(const fs::path &directory,std::optional<size_t> position)
|
||||
void opened(FolderLocation location,std::optional<size_t> position)
|
||||
{
|
||||
if(!history.empty())
|
||||
{
|
||||
const auto &previous=history[current];
|
||||
if(sameLocalFolder(previous,directory)) return;
|
||||
if(inLocalBranch(directory,previous))
|
||||
if(sameFolderLocation(previous,location))
|
||||
{
|
||||
if(!inLocalBranch(previous,previousBranch)) previousBranch=previous;
|
||||
history[current]=std::move(location);
|
||||
return;
|
||||
}
|
||||
else if(!inLocalBranch(directory,previousBranch)) previousBranch.clear();
|
||||
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() && sameLocalFolder(history[*position],directory))
|
||||
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(directory);
|
||||
history.push_back(std::move(location));
|
||||
current=history.size()-1;
|
||||
}
|
||||
|
||||
@@ -493,11 +517,19 @@ struct ArchiveLocation
|
||||
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;
|
||||
};
|
||||
|
||||
struct Panel
|
||||
{
|
||||
HWND path{}, list{}, heading{};
|
||||
fs::path directory;
|
||||
LocalNavigation navigation;
|
||||
FolderNavigation navigation;
|
||||
std::optional<FilesPeer> peer;
|
||||
std::optional<FtpProfile> ftp;
|
||||
std::optional<ArchiveLocation> archive;
|
||||
@@ -552,7 +584,17 @@ struct Panel
|
||||
std::optional<FindOptions> find;
|
||||
std::optional<size_t> navigationPosition;
|
||||
std::optional<ArchiveLocation> archive;
|
||||
unsigned reconnectAttempt{};
|
||||
fs::path fallbackSelection;
|
||||
};
|
||||
struct RemoteRetry
|
||||
{
|
||||
RemotePanelLocation location;
|
||||
std::wstring failure;
|
||||
ULONGLONG retryAt{};
|
||||
unsigned reconnectAttempt{};
|
||||
};
|
||||
std::optional<RemoteRetry> remoteRetry;
|
||||
struct ScanResult
|
||||
{
|
||||
DirectoryWatch watch;
|
||||
@@ -610,6 +652,13 @@ bool ftpProfileList(const Panel &panel)
|
||||
return panel.ftp && panel.ftp->name.empty();
|
||||
}
|
||||
|
||||
FolderLocation folderLocation(const Panel &panel,const fs::path &directory)
|
||||
{
|
||||
if(panel.ftp) return {directory,FolderProvider::ftp,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(panel.ftp)
|
||||
@@ -703,7 +752,7 @@ bool commandPicker{};
|
||||
struct FolderPicker
|
||||
{
|
||||
const wchar_t *caption;
|
||||
std::vector<fs::path> paths;
|
||||
std::vector<FolderLocation> locations;
|
||||
bool recent{};
|
||||
};
|
||||
std::optional<FolderPicker> folderPicker;
|
||||
@@ -715,10 +764,17 @@ bool alignExtensions=defaultAlignExtensions, showDetails=defaultShowDetails;
|
||||
bool alignFolders=defaultAlignFolders;
|
||||
DWORD statusFields=defaultStatusFields;
|
||||
std::vector<fs::path> drivePaths;
|
||||
bool lanDrivePicker{};
|
||||
int driveHover=-1;
|
||||
std::array<LONG,3> driveColumnStarts{};
|
||||
HWND drivePeerService{};
|
||||
bool drivePeerReplyReceived{};
|
||||
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;
|
||||
@@ -778,7 +834,7 @@ void savePlacement(HWND window)
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,placementPreference,REG_BINARY,
|
||||
&placement,sizeof(placement));
|
||||
}
|
||||
void chooseDrive(int index, bool fromMenu = false);
|
||||
void chooseDrive(int index,bool fromMenu=false,bool lanOnly=false);
|
||||
enum class FilesNoticeTone { dialog, neutral, warning };
|
||||
struct FilesNoticeOptions
|
||||
{
|
||||
@@ -831,7 +887,7 @@ FileRowStyle panelRowStyle(const Panel &panel,size_t row,bool cursor,bool active
|
||||
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);
|
||||
void setStatus(const std::wstring &message,bool retryAction=false);
|
||||
void refreshCommandHistory();
|
||||
#include "files_command_history.inl"
|
||||
|
||||
@@ -1594,9 +1650,13 @@ void layout(HWND window,bool activeOnly)
|
||||
}
|
||||
|
||||
uint64_t statusRevision{};
|
||||
void setStatus(const std::wstring &message)
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -2059,12 +2119,15 @@ void copyCommandLineOrPanelNames(HWND 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)
|
||||
{
|
||||
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);
|
||||
@@ -2507,6 +2570,11 @@ void showFileDetails(const Panel &panel)
|
||||
{
|
||||
refreshQuickView(panel);
|
||||
if(&panel==&panels[active] && showDirectoryScanProgress(panels[active])) return;
|
||||
if(panel.remoteRetry)
|
||||
{
|
||||
setStatus(L"Ctrl+R to retry · "+panel.remoteRetry->failure,true);
|
||||
return;
|
||||
}
|
||||
if(panel.findOrigin)
|
||||
{
|
||||
const auto error=panel.findOrigin->error;
|
||||
@@ -2629,13 +2697,14 @@ std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &reque
|
||||
(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)
|
||||
{
|
||||
failure=L"Cannot read FTP folder on "+request.ftp->name+L": "+fileError(e);
|
||||
error=static_cast<DWORD>(e.code().value());
|
||||
failure=ftpFolderError(e)+L" ("+request.ftp->name+L")";
|
||||
}
|
||||
catch(const std::exception &e)
|
||||
{
|
||||
@@ -2683,7 +2752,11 @@ std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &reque
|
||||
opened=true;
|
||||
if(!complete) error=ERROR_CANCELLED;
|
||||
}
|
||||
catch(const std::system_error &e){result->failure=peer->name+L" — "+fileError(e);}
|
||||
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())
|
||||
{
|
||||
@@ -2728,7 +2801,7 @@ void appendTreeRows(Panel &panel,PanelRowsUpdate &rows);
|
||||
bool samePanelSource(const Panel &panel,const std::optional<FilesPeer> &peer,const std::optional<FtpProfile> &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->name==ftp->name);
|
||||
panel.ftp.has_value()==ftp.has_value() && (!panel.ftp || panel.ftp->id==ftp->id);
|
||||
}
|
||||
|
||||
bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResult &scan)
|
||||
@@ -2736,12 +2809,13 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
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 bool sameDirectory=previousDirectory==directory;
|
||||
const auto provider=peer?FolderProvider::lan:request.ftp?FolderProvider::ftp:FolderProvider::local;
|
||||
const bool sameDirectory=sameFolderPath(previousDirectory,directory,provider);
|
||||
auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=scan;
|
||||
const bool partial=error==ERROR_CANCELLED;
|
||||
if(!failure.empty())
|
||||
{
|
||||
setStatus(failure);
|
||||
if((!peer && !request.ftp) || &panel==&panels[active]) setStatus(failure);
|
||||
return false;
|
||||
}
|
||||
if(partial && !opened)
|
||||
@@ -2829,12 +2903,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
if(mark.parent_path()==folderPathWithoutSeparator(directory)) markedPaths.insert(mark);
|
||||
panel.listReturnMarks.clear();
|
||||
}
|
||||
if(peer || request.ftp) panel.navigation={};
|
||||
else if(!finding && !request.archive)
|
||||
{
|
||||
panel.navigation.opened(directory,request.navigationPosition);
|
||||
if(!sameDirectory && !panel.directory.empty() && !partial) updateRecentFolders(directory,true);
|
||||
}
|
||||
const bool rememberFolder=!sameDirectory && !partial && (!panel.directory.empty() || peer || request.ftp);
|
||||
panel.directory = directory;
|
||||
panel.peer=std::move(peer);
|
||||
panel.ftp=std::move(request.ftp);
|
||||
@@ -2852,6 +2921,12 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
std::swap(panel.watch.handle,nextWatch.handle);
|
||||
}
|
||||
const bool profiles=ftpProfileList(panel);
|
||||
if(!finding && !panel.archive && !profiles)
|
||||
{
|
||||
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 && !profiles && !panel.archive;
|
||||
panel.filteredMarks.clear();
|
||||
if(renderTree) replaceTreeRoot(panel,scan,sameDirectory,markedPaths);
|
||||
@@ -2978,15 +3053,18 @@ void startDirectoryScan(Panel &panel)
|
||||
|
||||
void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional<FilesPeer> peer,
|
||||
fs::path selection={},fs::path fallback={},std::optional<FtpProfile> ftp={},
|
||||
std::optional<size_t> navigationPosition={},std::optional<ArchiveLocation> archive={})
|
||||
std::optional<size_t> navigationPosition={},std::optional<ArchiveLocation> archive={},
|
||||
unsigned reconnectAttempt=0,fs::path fallbackSelection={})
|
||||
{
|
||||
if(directory.empty() && !ftp) return;
|
||||
panel.remoteRetry.reset();
|
||||
if(!panel.view.revealedFile.empty() &&
|
||||
(peer || ftp || panel.view.revealedFile.parent_path()!=directory)) panel.view.revealedFile.clear();
|
||||
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)};
|
||||
std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition,
|
||||
std::move(archive),reconnectAttempt,std::move(fallbackSelection)};
|
||||
if(panel.scan.valid())
|
||||
{
|
||||
panel.scanSuperseded=true;
|
||||
@@ -2996,6 +3074,8 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti
|
||||
else startDirectoryScan(panel);
|
||||
}
|
||||
|
||||
#include "files_panel_recovery.inl"
|
||||
|
||||
void collectDirectoryScans()
|
||||
{
|
||||
for(auto &panel:panels)
|
||||
@@ -3012,21 +3092,37 @@ void collectDirectoryScans()
|
||||
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(!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},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) continue;
|
||||
if(result->error==ERROR_CANCELLED && fallback.empty()) continue;
|
||||
}
|
||||
catch(const std::exception &) {setStatus(L"Could not read the folder.");}
|
||||
if(!applied && !fallback.empty()) openOn(panel,fallback,false,{});
|
||||
else if(applied && !panel.scan.valid() && !panel.peer && panel.watch.handle!=INVALID_HANDLE_VALUE &&
|
||||
WaitForSingleObject(panel.watch.handle,0)==WAIT_OBJECT_0)
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3202,7 +3298,9 @@ void refreshChangedPanels()
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3490,14 +3588,15 @@ void runActivePeerAction(HWND owner,bool update)
|
||||
(update?L"Requesting a KSwitcher update on ":L"Requesting hibernation for ")+peer.name+L"...");
|
||||
}
|
||||
|
||||
LRESULT ftpDriveRow() {return static_cast<LRESULT>(drivePaths.size())+1;}
|
||||
LRESULT recentDriveRow() {return ftpDriveRow()+1;}
|
||||
LRESULT ftpDriveRow() {return lanDrivePicker?-1:static_cast<LRESULT>(drivePaths.size())+1;}
|
||||
LRESULT recentDriveRow() {return lanDrivePicker?-1:ftpDriveRow()+1;}
|
||||
LRESULT lanHeaderRow() {return recentDriveRow()+1;}
|
||||
void showRecentFolders(int side);
|
||||
|
||||
bool selectablePickerRow(LRESULT row)
|
||||
{
|
||||
if(row<0) return false;
|
||||
if(folderPicker) return static_cast<size_t>(row)<folderPicker->paths.size();
|
||||
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 row<static_cast<LRESULT>(drivePaths.size()) || row==ftpDriveRow() || row==recentDriveRow() ||
|
||||
@@ -3510,10 +3609,10 @@ void selectDrive()
|
||||
if(!selectablePickerRow(row)) return;
|
||||
if(folderPicker)
|
||||
{
|
||||
const auto path=folderPicker->paths[row];
|
||||
const auto location=folderPicker->locations[row];
|
||||
auto &panel=panels[pickerPanel];
|
||||
hidePicker();
|
||||
openOn(panel,path,true,{});
|
||||
openFolderLocation(panel,location);
|
||||
return;
|
||||
}
|
||||
if(commandPicker) row=commandActions[row];
|
||||
@@ -3575,7 +3674,7 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT
|
||||
{
|
||||
const auto row=SendMessageW(window,LB_GETCURSEL,0,0);
|
||||
if(!selectablePickerRow(row)) return 0;
|
||||
auto &paths=folderPicker->paths;
|
||||
auto &paths=folderPicker->locations;
|
||||
if(!updateRecentFolders(paths[row],false))
|
||||
{
|
||||
setStatus(L"Could not remove the recent folder.");
|
||||
@@ -3586,7 +3685,7 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT
|
||||
if(paths.empty())
|
||||
{
|
||||
hidePicker();
|
||||
setStatus(L"No recent local folders.");
|
||||
setStatus(L"No recent folders.");
|
||||
}
|
||||
else SendMessageW(window,LB_SETCURSEL,std::min(row,static_cast<LRESULT>(paths.size()-1)),0);
|
||||
return 0;
|
||||
@@ -3713,44 +3812,51 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT
|
||||
return DefSubclassProc(window,msg,wp,lp);
|
||||
}
|
||||
|
||||
void queryDrivePeers()
|
||||
FilesPeerLookup lookupFilesPeers(HWND owner)
|
||||
{
|
||||
drivePeers.clear();
|
||||
drivePeerLookupError.clear();
|
||||
drivePeerReplyReceived=false;
|
||||
drivePeerService=FindWindowW(L"KSwitcher.Main",L"KSwitcher");
|
||||
if(drivePeerService)
|
||||
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(drivePeerService,WM_COPYDATA,
|
||||
reinterpret_cast<WPARAM>(GetParent(picker)),reinterpret_cast<LPARAM>(&request),
|
||||
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();
|
||||
if(!delivered || result!=1 || !drivePeerReplyReceived)
|
||||
peerLookupRequest=previous;
|
||||
if(!delivered || result!=1 || !lookup.received)
|
||||
{
|
||||
drivePeers.clear();
|
||||
lookup.peers.clear();
|
||||
if(delivered && result!=1)
|
||||
drivePeerLookupError=L"KSwitcher rejected the peer request";
|
||||
lookup.error=L"KSwitcher rejected the peer request";
|
||||
else if(delivered)
|
||||
drivePeerLookupError=L"Invalid peer list from KSwitcher";
|
||||
lookup.error=L"Invalid peer list from KSwitcher";
|
||||
else if(error==ERROR_ACCESS_DENIED)
|
||||
drivePeerLookupError=L"Access denied by Windows";
|
||||
lookup.error=L"Access denied by Windows";
|
||||
else if(error==ERROR_TIMEOUT)
|
||||
drivePeerLookupError=L"KSwitcher did not respond in time";
|
||||
lookup.error=L"KSwitcher did not respond in time";
|
||||
else
|
||||
drivePeerLookupError=L"Peer request failed (Windows code "+std::to_wstring(error)+L")";
|
||||
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
|
||||
{
|
||||
drivePeerLookupError=L"KSwitcher is not running";
|
||||
lookup.error=L"KSwitcher is not running";
|
||||
ks::log(L"LAN Files peer lookup failed: local KSwitcher window not found");
|
||||
}
|
||||
drivePeerService=nullptr;
|
||||
return lookup;
|
||||
}
|
||||
|
||||
void queryDrivePeers()
|
||||
{
|
||||
auto lookup=lookupFilesPeers(GetParent(picker));
|
||||
drivePeers=std::move(lookup.peers);
|
||||
drivePeerLookupError=std::move(lookup.error);
|
||||
}
|
||||
|
||||
void startDriveQuery(DriveQuery &query)
|
||||
@@ -3784,7 +3890,8 @@ void layoutDrivePicker(int selected,bool focus)
|
||||
const int panelWidth=panel.right-panel.left;
|
||||
const auto frame=dialogFrameMetrics(GetDpiForWindow(owner));
|
||||
const int inset=frame.content(),vertical=dialogListInset(frame,textHeight);
|
||||
const int width=std::clamp(drivePickerWidth,90,std::max(90,panelWidth*4/5-2*inset));
|
||||
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;
|
||||
@@ -3810,7 +3917,7 @@ 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>recentDriveRow()) selection=-1;
|
||||
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)
|
||||
@@ -3821,12 +3928,17 @@ void showRemoteDrives(bool focus=false,int initialRow=0)
|
||||
drivePickerWidth=std::max(drivePickerWidth,static_cast<int>(label.size()+2)*cellWidth);
|
||||
return SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
};
|
||||
add(L"");
|
||||
add(L"FTP");
|
||||
add(L"Recent folders");
|
||||
if(!lanDrivePicker)
|
||||
{
|
||||
add(L"");
|
||||
add(L"FTP");
|
||||
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 ¤t=panels[pickerPanel];
|
||||
for(const auto &query:driveQueries)
|
||||
{
|
||||
add(query.peer.name);
|
||||
@@ -3835,6 +3947,9 @@ void showRemoteDrives(bool focus=false,int initialRow=0)
|
||||
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);
|
||||
@@ -3859,6 +3974,7 @@ void showRemoteDrives(bool focus=false,int initialRow=0)
|
||||
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);
|
||||
@@ -3932,8 +4048,9 @@ void pollDriveQueries(HWND owner)
|
||||
if(!pending && !nextDriveRefresh) KillTimer(owner,driveQueryTimer);
|
||||
}
|
||||
|
||||
void chooseDrive(int index,bool fromMenu)
|
||||
void chooseDrive(int index,bool fromMenu,bool lanOnly)
|
||||
{
|
||||
lanDrivePicker=lanOnly;
|
||||
if(quickViewWindow && index!=quickViewSource) toggleQuickView(GetParent(picker));
|
||||
folderPicker.reset();
|
||||
commandPicker=false;
|
||||
@@ -3955,7 +4072,7 @@ void chooseDrive(int index,bool fromMenu)
|
||||
const auto now=GetTickCount64();
|
||||
nextDriveRefresh=now+500;
|
||||
driveRefreshDeadline=now+20000;
|
||||
const DWORD disks=GetLogicalDrives();
|
||||
const DWORD disks=lanOnly?0:GetLogicalDrives();
|
||||
int selected=0;
|
||||
int textWidth=0;
|
||||
auto dc=GetDC(picker);
|
||||
@@ -7766,7 +7883,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
case WM_COPYDATA:
|
||||
{
|
||||
const auto *reply=reinterpret_cast<const COPYDATASTRUCT*>(lp);
|
||||
if(!drivePeerService || reinterpret_cast<HWND>(wp)!=drivePeerService || !reply ||
|
||||
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
|
||||
@@ -7775,11 +7893,11 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
const auto rows=Json::parse(begin,begin+reply->cbData);
|
||||
if(!rows.is_array()) return FALSE;
|
||||
for(const auto &row:rows)
|
||||
drivePeers.push_back({row.at("id"),row.at("address"),ks::wide(row.at("name")),ks::lan::FilesPort,
|
||||
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 &){drivePeers.clear();return FALSE;}
|
||||
drivePeerReplyReceived=true;
|
||||
catch(const std::exception &){lookup->peers.clear();return FALSE;}
|
||||
lookup->received=true;
|
||||
return TRUE;
|
||||
}
|
||||
case ks::files::quickViewToggleMessage:
|
||||
@@ -7812,6 +7930,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
collectDirectoryScans();
|
||||
collectTreeBranches();
|
||||
pollRemotePanels();
|
||||
refreshChangedPanels();
|
||||
showDirectoryScanProgress(panels[active]);
|
||||
}
|
||||
@@ -7898,12 +8017,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
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);
|
||||
wchar_t system[MAX_PATH]{};
|
||||
GetWindowsDirectoryW(system, MAX_PATH);
|
||||
const auto saved=savedPanelPath(panelPathKeys[i]);
|
||||
const auto root=fs::path(system).root_path();
|
||||
openOn(panel,saved.is_absolute()?saved:root,false,{},savedPanelPath(panelCursorKeys[i]),
|
||||
saved.is_absolute() && saved!=root?root:fs::path{});
|
||||
restorePanelLocation(panel,i);
|
||||
SetWindowSubclass(panel.list, panelKeys, 1, 0);
|
||||
if(auto target=new(std::nothrow) PanelDropTarget(panel.list))
|
||||
{
|
||||
@@ -8087,9 +8201,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
}
|
||||
const bool highlighted=static_cast<int>(item.CtlID)-142==active;
|
||||
if(localNavigationAvailable(panel))
|
||||
if(pathNavigationAvailable(panel))
|
||||
{
|
||||
paintLocalPath(item.hDC,bounds,panel,highlighted);
|
||||
paintPanelPath(item.hDC,bounds,panel,highlighted);
|
||||
return TRUE;
|
||||
}
|
||||
if(path.empty()) return TRUE;
|
||||
@@ -8198,7 +8312,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
auto background=item.CtlType==ODT_BUTTON?Footer:popupRow?Dialog:PanelBlue;
|
||||
auto foreground=colors[Text];
|
||||
if(item.hwndItem==picker && !folderPicker && ((commandPicker && item.itemID<commandActions.size() && commandActions[item.itemID]<0) ||
|
||||
(!commandPicker && item.itemID==drivePaths.size())))
|
||||
(!commandPicker && !lanDrivePicker && item.itemID==drivePaths.size())))
|
||||
{
|
||||
FillRect(item.hDC,&item.rcItem,teal);
|
||||
const auto y=(item.rcItem.top+item.rcItem.bottom)/2;
|
||||
@@ -8207,7 +8321,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
FillRect(item.hDC,&line,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
return TRUE;
|
||||
}
|
||||
if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID==recentDriveRow()+1)
|
||||
if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID==lanHeaderRow())
|
||||
{
|
||||
auto row=item.rcItem;
|
||||
FillRect(item.hDC,&row,teal);
|
||||
@@ -8451,6 +8565,17 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
resetCompletion();
|
||||
}
|
||||
if(copyInProgress || commandHistoryWindow || FilesModalDialog::activeFor(window)) 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)==121 && HIWORD(wp)==LBN_DBLCLK) selectDrive();
|
||||
if(LOWORD(wp)>=130 && LOWORD(wp)<=134 && HIWORD(wp)==BN_CLICKED)
|
||||
{
|
||||
@@ -8486,6 +8611,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
savePlacement(window);
|
||||
for(int i=0;i<2;++i)
|
||||
{
|
||||
saveFtpPanelLocation(panels[i],i);
|
||||
const auto path=(panels[i].archive?panels[i].archive->file.parent_path():panels[i].directory).native();
|
||||
if(!panels[i].peer && !panels[i].ftp && !path.empty())
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelPathKeys[i],REG_SZ,path.c_str(),
|
||||
@@ -8607,7 +8733,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
if(message.hwnd==window && message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST &&
|
||||
GetFocus()==terminalInput)
|
||||
message.hwnd=terminalInput;
|
||||
if(handleQuickViewKey(window,message) || handleLocalPathKey(window,message)) continue;
|
||||
if(handleQuickViewKey(window,message) || handlePanelPathKey(window,message)) 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) &&
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
constexpr std::array<ULONGLONG,3> lanRetryDelays{1200,2500,5000};
|
||||
constexpr const wchar_t *ftpPanelLocationKeys[]{L"LeftFtpLocation",L"RightFtpLocation"};
|
||||
constexpr DWORD maxFtpLocationBytes=256*1024;
|
||||
|
||||
FilesPeerLookup lookupFilesPeers(HWND owner);
|
||||
|
||||
bool transientLanError(DWORD code)
|
||||
{
|
||||
switch(code)
|
||||
{
|
||||
case WSAENETDOWN:
|
||||
case WSAENETUNREACH:
|
||||
case WSAENETRESET:
|
||||
case WSAECONNABORTED:
|
||||
case WSAECONNRESET:
|
||||
case WSAECONNREFUSED:
|
||||
case WSAETIMEDOUT:
|
||||
case WSAEHOSTDOWN:
|
||||
case WSAEHOSTUNREACH:
|
||||
case ERROR_CONNECTION_ABORTED:
|
||||
case ERROR_NETNAME_DELETED:
|
||||
case ERROR_NETWORK_UNREACHABLE:
|
||||
case ERROR_SEM_TIMEOUT:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool retryRemotePanel(Panel &panel,bool automatic,const fs::path &fallback)
|
||||
{
|
||||
if(!panel.remoteRetry) return false;
|
||||
auto &retry=*panel.remoteRetry;
|
||||
auto location=retry.location;
|
||||
const auto attempt=automatic?retry.reconnectAttempt+1:0;
|
||||
if(location.peer)
|
||||
{
|
||||
const auto lookup=lookupFilesPeers(GetParent(panel.list));
|
||||
const auto peer=std::find_if(lookup.peers.begin(),lookup.peers.end(),[&](const auto &entry) {
|
||||
return entry.id==location.peer->id && !entry.address.empty();
|
||||
});
|
||||
if(peer!=lookup.peers.end()) location.peer=*peer;
|
||||
openOn(panel,location.directory,false,std::move(location.peer),location.cursor,
|
||||
{},{},location.navigationPosition,{},attempt);
|
||||
return true;
|
||||
}
|
||||
const bool loaded=loadFtpProfiles();
|
||||
const auto *profile=loaded?findFtpProfile(location.ftpProfile):nullptr;
|
||||
if(!profile)
|
||||
{
|
||||
retry.failure=loaded?L"The saved FTP connection is missing. Select a profile in Change drive → FTP.":
|
||||
L"Could not load the saved FTP connections.";
|
||||
if(&panel==&panels[active] && !panel.scan.valid()) showFileDetails(panel);
|
||||
return true;
|
||||
}
|
||||
openOn(panel,location.directory,false,{},location.cursor,fallback,*profile,location.navigationPosition,{},0,
|
||||
fallback.empty()?fs::path{}:savedPanelPath(panelCursorKeys[&panel-panels]));
|
||||
return true;
|
||||
}
|
||||
|
||||
void openFolderLocation(Panel &panel,const FolderLocation &location,std::optional<size_t> position={})
|
||||
{
|
||||
if(location.directory.empty()) return;
|
||||
if(location.provider==FolderProvider::local)
|
||||
{
|
||||
openOn(panel,location.directory,true,{},{},{},{},position);
|
||||
return;
|
||||
}
|
||||
if(location.sameSource(folderLocation(panel,panel.directory)))
|
||||
{
|
||||
openOn(panel,location.directory,false,panel.peer,{},{},panel.ftp,position);
|
||||
return;
|
||||
}
|
||||
RemotePanelLocation remote{location.directory,{},{},{},position};
|
||||
if(location.provider==FolderProvider::ftp) remote.ftpProfile=location.id;
|
||||
else remote.peer=FilesPeer{location.id,{},location.label.empty()?L"LAN peer":location.label};
|
||||
panel.remoteRetry=Panel::RemoteRetry{std::move(remote),L"Could not restore the remote folder."};
|
||||
retryRemotePanel(panel);
|
||||
}
|
||||
|
||||
void pollRemotePanels()
|
||||
{
|
||||
const auto now=GetTickCount64();
|
||||
for(auto &panel:panels)
|
||||
if(!panel.scan.valid() && panel.remoteRetry && panel.remoteRetry->retryAt &&
|
||||
now>=panel.remoteRetry->retryAt)
|
||||
retryRemotePanel(panel,true);
|
||||
}
|
||||
|
||||
std::optional<RemotePanelLocation> savedFtpPanelLocation(int index)
|
||||
{
|
||||
DWORD size{};
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpPanelLocationKeys[index],RRF_RT_REG_BINARY,nullptr,
|
||||
nullptr,&size)!=ERROR_SUCCESS || !size || size>maxFtpLocationBytes) return {};
|
||||
std::string data(size,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpPanelLocationKeys[index],RRF_RT_REG_BINARY,nullptr,
|
||||
data.data(),&size)!=ERROR_SUCCESS) return {};
|
||||
try
|
||||
{
|
||||
const auto saved=Json::parse(data.begin(),data.begin()+size);
|
||||
RemotePanelLocation location{fs::path(ks::wide(saved.at("directory"))),fs::path(ks::wide(saved.at("cursor"))),
|
||||
saved.at("profile").get<std::string>()};
|
||||
if(!isFtpFolderPath(location.directory) || location.ftpProfile.empty()) return {};
|
||||
if(!location.cursor.empty() && !isFtpFolderPath(location.cursor)) location.cursor.clear();
|
||||
return location;
|
||||
}
|
||||
catch(const std::exception &) {return {};}
|
||||
}
|
||||
|
||||
void saveFtpPanelLocation(const Panel &panel,int index)
|
||||
{
|
||||
RemotePanelLocation location;
|
||||
if(panel.ftp && !panel.ftp->id.empty())
|
||||
{
|
||||
const auto row=currentPanelRow(panel);
|
||||
location={panel.directory,row<0?fs::path{}:panel.rows[row],panel.ftp->id};
|
||||
}
|
||||
else if(panel.remoteRetry && !panel.remoteRetry->location.ftpProfile.empty())
|
||||
location=panel.remoteRetry->location;
|
||||
else if(panel.scanRequest && panel.scanRequest->ftp)
|
||||
location={panel.scanRequest->directory,panel.scanRequest->selection,panel.scanRequest->ftp->id};
|
||||
|
||||
const auto key=ftpPanelLocationKeys[index];
|
||||
if(location.ftpProfile.empty() || !isFtpFolderPath(location.directory))
|
||||
{
|
||||
RegDeleteKeyValueW(HKEY_CURRENT_USER,schemeKey,key);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
const auto data=Json{{"profile",location.ftpProfile},{"directory",ks::utf8(location.directory.native())},
|
||||
{"cursor",ks::utf8(location.cursor.native())}}.dump();
|
||||
if(data.size()<=maxFtpLocationBytes)
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,key,REG_BINARY,data.data(),static_cast<DWORD>(data.size()));
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
}
|
||||
|
||||
fs::path systemPanelRoot()
|
||||
{
|
||||
wchar_t system[MAX_PATH]{};
|
||||
GetWindowsDirectoryW(system,MAX_PATH);
|
||||
return fs::path(system).root_path();
|
||||
}
|
||||
|
||||
void restorePanelLocation(Panel &panel,int index)
|
||||
{
|
||||
const auto root=systemPanelRoot();
|
||||
const auto saved=savedPanelPath(panelPathKeys[index]);
|
||||
const auto local=saved.is_absolute()?saved:root;
|
||||
auto remote=savedFtpPanelLocation(index);
|
||||
if(remote)
|
||||
{
|
||||
panel.remoteRetry=Panel::RemoteRetry{std::move(*remote),L"Could not restore the saved FTP folder."};
|
||||
retryRemotePanel(panel,false,local);
|
||||
if(panel.scan.valid()) return;
|
||||
}
|
||||
auto retry=std::move(panel.remoteRetry);
|
||||
openOn(panel,local,false,{},savedPanelPath(panelCursorKeys[index]),local!=root?root:fs::path{});
|
||||
panel.remoteRetry=std::move(retry);
|
||||
}
|
||||
+152
-74
@@ -1,22 +1,28 @@
|
||||
|
||||
bool localNavigationAvailable(const Panel &panel)
|
||||
bool pathNavigationAvailable(const Panel &panel)
|
||||
{
|
||||
return !panel.peer && !panel.ftp && !panel.findOrigin && !panel.archive && !panel.directory.empty();
|
||||
return !ftpProfileList(panel) && !panel.findOrigin && !panel.archive && !panel.directory.empty();
|
||||
}
|
||||
|
||||
enum class PathAction { back, forward, up, edit, ancestors, previous, folder };
|
||||
enum class PathAction { back, forward, up, edit, source, ancestors, previous, folder };
|
||||
|
||||
void navigateLocal(Panel &panel,const fs::path &path,std::optional<size_t> position={})
|
||||
void navigatePanelPath(Panel &panel,const fs::path &path)
|
||||
{
|
||||
if(path.empty() || sameLocalFolder(path,panel.directory)) return;
|
||||
if(path.empty()) return;
|
||||
const auto current=folderLocation(panel,panel.directory);
|
||||
auto target=folderLocation(panel,path);
|
||||
if(sameFolderLocation(current,target)) return;
|
||||
closePanelSearch();
|
||||
openOn(panel,path,true,{},{},{},{},position);
|
||||
openFolderLocation(panel,target);
|
||||
}
|
||||
|
||||
void navigateLocalHistory(Panel &panel,int direction)
|
||||
void navigatePanelHistory(Panel &panel,int direction)
|
||||
{
|
||||
if(const auto next=panel.navigation.neighbor(direction))
|
||||
navigateLocal(panel,panel.navigation.history[*next],next);
|
||||
{
|
||||
closePanelSearch();
|
||||
openFolderLocation(panel,panel.navigation.history[*next],next);
|
||||
}
|
||||
}
|
||||
|
||||
struct PathPart
|
||||
@@ -29,17 +35,18 @@ struct PathPart
|
||||
bool current{}, dim{}, enabled=true;
|
||||
};
|
||||
|
||||
std::wstring pathSegmentLabel(const fs::path &path)
|
||||
std::wstring pathSegmentLabel(const fs::path &path,FolderProvider provider)
|
||||
{
|
||||
return panelParentPath(path,true).empty()?path.native():path.filename().native();
|
||||
if(provider==FolderProvider::ftp && path==ftpRoot) return L"/";
|
||||
return panelParentPath(path,provider==FolderProvider::local).empty()?path.native():path.filename().native();
|
||||
}
|
||||
|
||||
LONG segmentWidth(const fs::path &path)
|
||||
LONG segmentWidth(const fs::path &path,FolderProvider provider)
|
||||
{
|
||||
return static_cast<LONG>(pathSegmentLabel(path).size()+2)*cellWidth;
|
||||
return static_cast<LONG>(pathSegmentLabel(path,provider).size()+2)*cellWidth;
|
||||
}
|
||||
|
||||
std::vector<PathPart> localPathParts(const Panel &panel,RECT bounds)
|
||||
std::vector<PathPart> panelPathParts(const Panel &panel,RECT bounds)
|
||||
{
|
||||
const LONG total=bounds.right-bounds.left;
|
||||
if(total<=0) return {};
|
||||
@@ -52,64 +59,74 @@ std::vector<PathPart> localPathParts(const Panel &panel,RECT bounds)
|
||||
bounds.left=part.rect.right;
|
||||
parts.push_back(std::move(part));
|
||||
};
|
||||
const auto parent=panelParentPath(panel.directory,true);
|
||||
const auto location=folderLocation(panel,panel.directory);
|
||||
const auto provider=location.provider;
|
||||
const auto local=provider==FolderProvider::local;
|
||||
const auto parent=panelParentPath(panel.directory,local);
|
||||
add({.action=PathAction::back,.label=L"←",.enabled=panel.navigation.neighbor(-1).has_value()},width);
|
||||
add({.action=PathAction::forward,.label=L"→",.enabled=panel.navigation.neighbor(1).has_value()},width);
|
||||
add({.action=PathAction::up,.label=L"↑",.target=parent,.enabled=!parent.empty()},width);
|
||||
add({.action=PathAction::edit,.label=L"✎"},width);
|
||||
|
||||
std::vector<fs::path> ancestors, previous;
|
||||
for(auto path=parent;!path.empty();path=panelParentPath(path,true)) ancestors.push_back(path);
|
||||
std::reverse(ancestors.begin(),ancestors.end());
|
||||
if(inLocalBranch(panel.directory,panel.navigation.previousBranch))
|
||||
if(!local)
|
||||
{
|
||||
for(auto path=panel.navigation.previousBranch;!sameLocalFolder(path,panel.directory);
|
||||
path=panelParentPath(path,true))
|
||||
const auto available=std::max(1L,(bounds.right-bounds.left)/2);
|
||||
const auto sourceWidth=std::min(available,static_cast<LONG>(location.label.size()+2)*cellWidth);
|
||||
add({.action=PathAction::source,.label=location.label},sourceWidth);
|
||||
}
|
||||
|
||||
std::vector<fs::path> ancestors, previous;
|
||||
for(auto path=parent;!path.empty();path=panelParentPath(path,local)) ancestors.push_back(path);
|
||||
std::reverse(ancestors.begin(),ancestors.end());
|
||||
if(inFolderBranch(panel.directory,panel.navigation.previousBranch,provider))
|
||||
{
|
||||
for(auto path=panel.navigation.previousBranch;!sameFolderPath(path,panel.directory,provider);
|
||||
path=panelParentPath(path,local))
|
||||
previous.push_back(path);
|
||||
std::reverse(previous.begin(),previous.end());
|
||||
}
|
||||
|
||||
const LONG room=bounds.right-bounds.left;
|
||||
LONG required=segmentWidth(panel.directory);
|
||||
for(const auto &path:ancestors) required+=segmentWidth(path);
|
||||
for(const auto &path:previous) required+=segmentWidth(path);
|
||||
LONG required=segmentWidth(panel.directory,provider);
|
||||
for(const auto &path:ancestors) required+=segmentWidth(path,provider);
|
||||
for(const auto &path:previous) required+=segmentWidth(path,provider);
|
||||
size_t firstAncestor=0,visiblePrevious=previous.size();
|
||||
LONG currentWidth=segmentWidth(panel.directory);
|
||||
LONG currentWidth=segmentWidth(panel.directory,provider);
|
||||
if(required>room)
|
||||
{
|
||||
const LONG reserved=(!ancestors.empty()?width:0)+(!previous.empty()?width:0);
|
||||
currentWidth=std::min(currentWidth,std::max(1L,room-reserved));
|
||||
LONG remaining=room-currentWidth-reserved;
|
||||
firstAncestor=ancestors.size();
|
||||
while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1]))
|
||||
remaining-=segmentWidth(ancestors[--firstAncestor]);
|
||||
while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1],provider))
|
||||
remaining-=segmentWidth(ancestors[--firstAncestor],provider);
|
||||
visiblePrevious=0;
|
||||
while(visiblePrevious<previous.size() && remaining>=segmentWidth(previous[visiblePrevious]))
|
||||
remaining-=segmentWidth(previous[visiblePrevious++]);
|
||||
while(visiblePrevious<previous.size() && remaining>=segmentWidth(previous[visiblePrevious],provider))
|
||||
remaining-=segmentWidth(previous[visiblePrevious++],provider);
|
||||
}
|
||||
|
||||
if(firstAncestor)
|
||||
add({.action=PathAction::ancestors,.label=L"…",
|
||||
.hidden={ancestors.begin(),ancestors.begin()+firstAncestor}},width);
|
||||
for(size_t i=firstAncestor;i<ancestors.size();++i)
|
||||
add({.action=PathAction::folder,.label=pathSegmentLabel(ancestors[i]),.target=ancestors[i]},
|
||||
segmentWidth(ancestors[i]));
|
||||
add({.action=PathAction::edit,.label=pathSegmentLabel(panel.directory),.current=true},currentWidth);
|
||||
add({.action=PathAction::folder,.label=pathSegmentLabel(ancestors[i],provider),.target=ancestors[i]},
|
||||
segmentWidth(ancestors[i],provider));
|
||||
add({.action=PathAction::edit,.label=pathSegmentLabel(panel.directory,provider),.current=true},currentWidth);
|
||||
for(size_t i=0;i<visiblePrevious;++i)
|
||||
add({.action=PathAction::folder,.label=pathSegmentLabel(previous[i]),.target=previous[i],.dim=true},
|
||||
segmentWidth(previous[i]));
|
||||
add({.action=PathAction::folder,.label=pathSegmentLabel(previous[i],provider),.target=previous[i],.dim=true},
|
||||
segmentWidth(previous[i],provider));
|
||||
if(visiblePrevious<previous.size())
|
||||
add({.action=PathAction::previous,.label=L"…",
|
||||
.hidden={previous.begin()+visiblePrevious,previous.end()},.dim=true},width);
|
||||
return parts;
|
||||
}
|
||||
|
||||
void paintLocalPath(HDC dc,RECT bounds,const Panel &panel,bool activePanel)
|
||||
void paintPanelPath(HDC dc,RECT bounds,const Panel &panel,bool activePanel)
|
||||
{
|
||||
const int saved=SaveDC(dc);
|
||||
SelectObject(dc,mono);
|
||||
SetBkMode(dc,TRANSPARENT);
|
||||
for(const auto &part:localPathParts(panel,bounds))
|
||||
for(const auto &part:panelPathParts(panel,bounds))
|
||||
{
|
||||
const bool current=activePanel && part.current;
|
||||
FillRect(dc,&part.rect,current?teal:blue);
|
||||
@@ -126,6 +143,8 @@ constexpr int addressField=485,addressLabel=486,addressFooter=487;
|
||||
struct PathPrompt
|
||||
{
|
||||
fs::path base, result;
|
||||
std::optional<FilesPeer> peer;
|
||||
std::optional<FtpProfile> ftp;
|
||||
std::wstring completionInput;
|
||||
std::future<std::wstring> completion;
|
||||
};
|
||||
@@ -133,30 +152,62 @@ struct PathPrompt
|
||||
constexpr UINT addressComplete=WM_APP+29;
|
||||
constexpr UINT_PTR addressCompletionTimer=1;
|
||||
|
||||
fs::path enteredPanelPath(const fs::path &base,std::wstring text)
|
||||
fs::path enteredPanelPath(const fs::path &base,std::wstring text,bool ftp)
|
||||
{
|
||||
if(text.size()>=2 && text.front()==L'"' && text.back()==L'"')
|
||||
text=text.substr(1,text.size()-2);
|
||||
return fs::path(text).is_absolute()?fs::path(std::move(text)):base/fs::path(std::move(text));
|
||||
if(ftp && text.find_first_of(L":\r\n")!=text.npos) return {};
|
||||
auto path=fs::path(std::move(text));
|
||||
if(ftp)
|
||||
{
|
||||
if(path.has_root_name()) return {};
|
||||
return (path.has_root_directory()?path:base/path).lexically_normal();
|
||||
}
|
||||
return path.is_absolute()?path:base/path;
|
||||
}
|
||||
|
||||
std::wstring panelPathCompletion(const fs::path &base,const std::wstring &text)
|
||||
std::wstring panelPathCompletion(const fs::path &base,const std::wstring &text,
|
||||
const std::optional<FilesPeer> &peer,const std::optional<FtpProfile> &ftp)
|
||||
{
|
||||
const auto path=enteredPanelPath(base,text);
|
||||
const auto path=enteredPanelPath(base,text,ftp.has_value());
|
||||
if(path.empty()) return {};
|
||||
const auto directory=path.has_filename()?path.parent_path():path;
|
||||
const auto prefix=path.filename().native();
|
||||
fs::path best;
|
||||
std::error_code error;
|
||||
for(fs::directory_iterator it(directory,error),end;!error && it!=end;it.increment(error))
|
||||
const auto accept=[&](const fs::path &candidate)
|
||||
{
|
||||
const auto name=it->path().filename().native();
|
||||
const auto name=candidate.filename().native();
|
||||
if(name.size()<prefix.size() || (!prefix.empty() && CompareStringOrdinal(name.data(),
|
||||
static_cast<int>(prefix.size()),prefix.data(),static_cast<int>(prefix.size()),TRUE)!=CSTR_EQUAL))
|
||||
continue;
|
||||
std::error_code typeError;
|
||||
if(it->is_directory(typeError) && (best.empty() || it->path()<best)) best=it->path();
|
||||
static_cast<int>(prefix.size()),prefix.data(),static_cast<int>(prefix.size()),ftp?FALSE:TRUE)!=CSTR_EQUAL))
|
||||
return;
|
||||
if(best.empty() || candidate<best) best=candidate;
|
||||
};
|
||||
const auto visit=[&](const fs::path &candidate,const FileInfo &info)
|
||||
{
|
||||
if(info.attributes&FILE_ATTRIBUTE_DIRECTORY) accept(candidate);
|
||||
return true;
|
||||
};
|
||||
if(peer)
|
||||
{
|
||||
FilesConnection host(&*peer);
|
||||
listFiles(host,directory,visit);
|
||||
}
|
||||
return best.empty()?std::wstring{}:best.native()+L"\\";
|
||||
else if(ftp)
|
||||
{
|
||||
FtpSession host(*ftp);
|
||||
listFtpDirectory(host,directory,visit);
|
||||
}
|
||||
else
|
||||
{
|
||||
std::error_code error;
|
||||
for(fs::directory_iterator it(directory,error),end;!error && it!=end;it.increment(error))
|
||||
{
|
||||
std::error_code typeError;
|
||||
if(it->is_directory(typeError)) accept(it->path());
|
||||
}
|
||||
}
|
||||
if(best.empty()) return {};
|
||||
return ftp?ftpPath(best)+L"/":best.native()+L"\\";
|
||||
}
|
||||
|
||||
LRESULT CALLBACK addressFieldKeys(HWND field,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
@@ -194,7 +245,8 @@ INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
layoutDialogButtons(dialog,addressFooter,{IDOK,IDCANCEL});
|
||||
const auto field=GetDlgItem(dialog,addressField);
|
||||
SendMessageW(field,EM_SETLIMITTEXT,32767,0);
|
||||
SetWindowTextW(field,(prompt.base/fs::path{}).c_str());
|
||||
const auto initial=prompt.base/fs::path{};
|
||||
SetWindowTextW(field,(prompt.ftp?ftpPath(initial):initial.native()).c_str());
|
||||
SetWindowSubclass(field,addressFieldKeys,4,0);
|
||||
SetFocus(field);
|
||||
SendMessageW(field,EM_SETSEL,0,-1);
|
||||
@@ -205,9 +257,10 @@ INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(prompt.completion.valid()) return TRUE;
|
||||
prompt.completionInput=shortcutField(dialog,addressField);
|
||||
std::packaged_task<std::wstring()> task([base=prompt.base,text=prompt.completionInput]
|
||||
std::packaged_task<std::wstring()> task([base=prompt.base,text=prompt.completionInput,
|
||||
peer=prompt.peer,ftp=prompt.ftp]
|
||||
{
|
||||
return panelPathCompletion(base,text);
|
||||
return panelPathCompletion(base,text,peer,ftp);
|
||||
});
|
||||
if(!SetTimer(dialog,addressCompletionTimer,30,nullptr)) return TRUE;
|
||||
prompt.completion=task.get_future();
|
||||
@@ -237,8 +290,8 @@ INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
|
||||
{
|
||||
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
auto path=enteredPanelPath(prompt.base,shortcutField(dialog,addressField)).lexically_normal();
|
||||
if(!path.is_absolute())
|
||||
auto path=enteredPanelPath(prompt.base,shortcutField(dialog,addressField),prompt.ftp.has_value()).lexically_normal();
|
||||
if(prompt.ftp?!isFtpFolderPath(path):!path.is_absolute())
|
||||
{
|
||||
showFilesNotice(dialog,L"Enter a folder path.",L"Go to folder");
|
||||
return TRUE;
|
||||
@@ -258,25 +311,33 @@ INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
|
||||
void editPanelPath(Panel &panel)
|
||||
{
|
||||
PathPrompt prompt{panel.directory};
|
||||
PathPrompt prompt{panel.directory,{},panel.peer,panel.ftp};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(117),GetParent(panel.list),
|
||||
editPathDialog,reinterpret_cast<LPARAM>(&prompt))==IDOK)
|
||||
navigateLocal(panel,prompt.result);
|
||||
navigatePanelPath(panel,prompt.result);
|
||||
}
|
||||
|
||||
void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<fs::path> paths,RECT anchor,bool recent=false)
|
||||
void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<FolderLocation> locations,
|
||||
RECT anchor,bool recent=false)
|
||||
{
|
||||
hidePicker();
|
||||
showMenu(false);
|
||||
commandPicker=false;
|
||||
pickerPanel=side;
|
||||
folderPicker=FolderPicker{caption,std::move(paths),recent};
|
||||
folderPicker=FolderPicker{caption,std::move(locations),recent};
|
||||
SendMessageW(picker,LB_RESETCONTENT,0,0);
|
||||
size_t longest=wcslen(caption);
|
||||
for(const auto &path:folderPicker->paths)
|
||||
for(const auto &location:folderPicker->locations)
|
||||
{
|
||||
longest=std::max(longest,path.native().size());
|
||||
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(path.c_str()));
|
||||
auto label=location.provider==FolderProvider::ftp?ftpPath(location.directory):location.directory.native();
|
||||
if(recent && location.provider!=FolderProvider::local)
|
||||
{
|
||||
const auto &source=location.label;
|
||||
const auto kind=location.provider==FolderProvider::ftp?L"FTP":L"LAN";
|
||||
label=std::wstring(kind)+L" · "+(source.empty()?std::wstring{}:source+L" · ")+label;
|
||||
}
|
||||
longest=std::max(longest,label.size());
|
||||
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
}
|
||||
RECT client{};
|
||||
GetClientRect(owner,&client);
|
||||
@@ -289,7 +350,7 @@ void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<fs:
|
||||
GetWindowRect(terminalInput,&input);
|
||||
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT *>(&input),2);
|
||||
const int bottom=std::min(client.bottom,input.top);
|
||||
const int shown=std::clamp((bottom-y-inset)/row,1,static_cast<int>(folderPicker->paths.size()));
|
||||
const int shown=std::clamp((bottom-y-inset)/row,1,static_cast<int>(folderPicker->locations.size()));
|
||||
showFramedList(picker,pickerFrame,x,y,width,row*shown,inset);
|
||||
SendMessageW(picker,LB_SETCURSEL,0,0);
|
||||
SetFocus(picker);
|
||||
@@ -297,17 +358,23 @@ void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<fs:
|
||||
|
||||
void showRecentFolders(int side)
|
||||
{
|
||||
auto paths=readRecentFolders();
|
||||
if(paths.empty())
|
||||
auto locations=readRecentFolders();
|
||||
if(locations.empty())
|
||||
{
|
||||
setStatus(L"No recent local folders.");
|
||||
setStatus(L"No recent folders.");
|
||||
return;
|
||||
}
|
||||
const auto owner=GetParent(picker);
|
||||
RECT anchor{};
|
||||
GetWindowRect(panels[side].path,&anchor);
|
||||
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT *>(&anchor),2);
|
||||
showFolderPicker(owner,side,L"Recent folders",std::move(paths),anchor,true);
|
||||
if(loadFtpProfiles())
|
||||
for(auto &location:locations)
|
||||
{
|
||||
if(location.provider!=FolderProvider::ftp) continue;
|
||||
if(const auto *profile=findFtpProfile(location.id)) location.label=profile->name;
|
||||
}
|
||||
showFolderPicker(owner,side,L"Recent folders",std::move(locations),anchor,true);
|
||||
}
|
||||
|
||||
void showHiddenPathParts(HWND window,int side,const PathPart &part)
|
||||
@@ -315,8 +382,11 @@ void showHiddenPathParts(HWND window,int side,const PathPart &part)
|
||||
const auto owner=GetParent(window);
|
||||
auto anchor=part.rect;
|
||||
MapWindowPoints(window,owner,reinterpret_cast<POINT*>(&anchor),2);
|
||||
std::vector<FolderLocation> locations;
|
||||
locations.reserve(part.hidden.size());
|
||||
for(const auto &path:part.hidden) locations.push_back(folderLocation(panels[side],path));
|
||||
showFolderPicker(owner,side,part.action==PathAction::ancestors?L"Parent folders":L"Previous path",
|
||||
part.hidden,anchor);
|
||||
std::move(locations),anchor);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
@@ -333,7 +403,7 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_
|
||||
if(index<0 || index>=2) return 0;
|
||||
panelClipboardContext=true;
|
||||
auto &panel=panels[index];
|
||||
if(!localNavigationAvailable(panel))
|
||||
if(!pathNavigationAvailable(panel))
|
||||
{
|
||||
selectPanelEdge(panel,true);
|
||||
return 0;
|
||||
@@ -342,16 +412,24 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
const POINT mouse{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
const auto parts=localPathParts(panel,bounds);
|
||||
const auto parts=panelPathParts(panel,bounds);
|
||||
for(const auto &part:parts)
|
||||
{
|
||||
if(!part.enabled || !PtInRect(&part.rect,mouse)) continue;
|
||||
switch(part.action)
|
||||
{
|
||||
case PathAction::back: navigateLocalHistory(panel,-1); break;
|
||||
case PathAction::forward: navigateLocalHistory(panel,1); break;
|
||||
case PathAction::up: case PathAction::folder: navigateLocal(panel,part.target); break;
|
||||
case PathAction::back: navigatePanelHistory(panel,-1); break;
|
||||
case PathAction::forward: navigatePanelHistory(panel,1); break;
|
||||
case PathAction::up: case PathAction::folder: navigatePanelPath(panel,part.target); break;
|
||||
case PathAction::edit: editPanelPath(panel); break;
|
||||
case PathAction::source:
|
||||
if(panel.peer) chooseDrive(index,false,true);
|
||||
else
|
||||
{
|
||||
const auto *profile=findFtpProfile(panel.ftp->id);
|
||||
showFtpProfiles(panel,profile?ftpRoot/std::to_wstring(profile-ftpProfiles.data()):fs::path{});
|
||||
}
|
||||
break;
|
||||
case PathAction::ancestors: case PathAction::previous: showHiddenPathParts(window,index,part); break;
|
||||
}
|
||||
break;
|
||||
@@ -361,7 +439,7 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_
|
||||
return DefSubclassProc(window,message,wp,lp);
|
||||
}
|
||||
|
||||
bool handleLocalPathKey(HWND owner,const MSG &message)
|
||||
bool handlePanelPathKey(HWND owner,const MSG &message)
|
||||
{
|
||||
if(!commandLineAvailable(owner) || terminalVisible ||
|
||||
(message.hwnd!=terminalInput && message.hwnd!=panels[active].list) ||
|
||||
@@ -374,7 +452,7 @@ bool handleLocalPathKey(HWND owner,const MSG &message)
|
||||
if(!(message.lParam&(1LL<<30))) parentArchive(panel);
|
||||
return true;
|
||||
}
|
||||
if(!localNavigationAvailable(panel)) return false;
|
||||
if(!pathNavigationAvailable(panel)) return false;
|
||||
if(message.message==WM_KEYDOWN && message.wParam=='L' &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000))
|
||||
{
|
||||
@@ -384,9 +462,9 @@ bool handleLocalPathKey(HWND owner,const MSG &message)
|
||||
if(message.message!=WM_SYSKEYDOWN || !(message.lParam&(1LL<<29)) ||
|
||||
(GetKeyState(VK_CONTROL)&0x8000)) return false;
|
||||
if(message.wParam==VK_UP)
|
||||
navigateLocal(panel,panelParentPath(panel.directory,true));
|
||||
navigatePanelPath(panel,panelParentPath(panel.directory,!panel.peer && !panel.ftp));
|
||||
else if(message.wParam==VK_LEFT || message.wParam==VK_RIGHT)
|
||||
navigateLocalHistory(panel,message.wParam==VK_LEFT?-1:1);
|
||||
navigatePanelHistory(panel,message.wParam==VK_LEFT?-1:1);
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
@@ -1,24 +1,53 @@
|
||||
constexpr wchar_t recentFoldersKey[]=L"RecentFolders";
|
||||
constexpr size_t recentFoldersLimit=100;
|
||||
|
||||
std::vector<fs::path> readRecentFolders()
|
||||
std::optional<FolderLocation> readRecentFolder(const Json &entry)
|
||||
{
|
||||
FolderLocation location;
|
||||
if(entry.is_string()) location.directory=filePath(entry);
|
||||
else if(entry.is_object())
|
||||
{
|
||||
const auto source=entry.value("source",std::string{});
|
||||
if(source=="ftp") location.provider=FolderProvider::ftp;
|
||||
else if(source=="lan") location.provider=FolderProvider::lan;
|
||||
else return {};
|
||||
location.id=entry.at("id").get<std::string>();
|
||||
if(location.id.empty()) return {};
|
||||
location.label=ks::wide(entry.value("label",std::string{}));
|
||||
location.directory=filePath(entry.at("path"));
|
||||
}
|
||||
else return {};
|
||||
const auto &path=location.directory;
|
||||
if(path.native().find(L'\0')!=std::wstring::npos) return {};
|
||||
if(location.provider==FolderProvider::ftp)
|
||||
{
|
||||
if(!isFtpFolderPath(path)) return {};
|
||||
}
|
||||
else if(!path.is_absolute()) return {};
|
||||
return location;
|
||||
}
|
||||
|
||||
std::vector<FolderLocation> readRecentFolders()
|
||||
{
|
||||
const auto saved=readFilesJsonPreference(recentFoldersKey);
|
||||
std::vector<fs::path> folders;
|
||||
std::vector<FolderLocation> folders;
|
||||
if(!saved || !saved->is_array()) return folders;
|
||||
for(const auto &entry:*saved)
|
||||
{
|
||||
if(!entry.is_string()) continue;
|
||||
const auto path=filePath(entry);
|
||||
if(!path.is_absolute() || path.native().find(L'\0')!=std::wstring::npos) continue;
|
||||
if(std::none_of(folders.begin(),folders.end(),[&](const auto &known){return sameLocalFolder(path,known);}))
|
||||
folders.push_back(path);
|
||||
try
|
||||
{
|
||||
auto location=readRecentFolder(entry);
|
||||
if(location && std::none_of(folders.begin(),folders.end(),
|
||||
[&](const auto &known){return sameFolderLocation(*location,known);}))
|
||||
folders.push_back(std::move(*location));
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
if(folders.size()==recentFoldersLimit) break;
|
||||
}
|
||||
return folders;
|
||||
}
|
||||
|
||||
bool updateRecentFolders(const fs::path &path,bool remember)
|
||||
bool updateRecentFolders(const FolderLocation &location,bool remember)
|
||||
{
|
||||
const Handle lock{CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.RecentFolders")};
|
||||
if(!lock.value) return false;
|
||||
@@ -28,11 +57,17 @@ bool updateRecentFolders(const fs::path &path,bool remember)
|
||||
try
|
||||
{
|
||||
auto folders=readRecentFolders();
|
||||
std::erase_if(folders,[&](const auto &known){return sameLocalFolder(path,known);});
|
||||
if(remember) folders.insert(folders.begin(),path);
|
||||
std::erase_if(folders,[&](const auto &known){return sameFolderLocation(location,known);});
|
||||
if(remember) folders.insert(folders.begin(),location);
|
||||
if(folders.size()>recentFoldersLimit) folders.resize(recentFoldersLimit);
|
||||
auto data=Json::array();
|
||||
for(const auto &folder:folders) data.push_back(ks::utf8(folder.native()));
|
||||
for(const auto &folder:folders)
|
||||
{
|
||||
const auto path=ks::utf8(folder.directory.native());
|
||||
if(folder.provider==FolderProvider::local) data.push_back(path);
|
||||
else data.push_back({{"source",folder.provider==FolderProvider::ftp?"ftp":"lan"},{"id",folder.id},
|
||||
{"label",ks::utf8(folder.label)},{"path",path}});
|
||||
}
|
||||
saved=writeFilesJsonPreference(recentFoldersKey,data);
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
|
||||
@@ -24,6 +24,7 @@ public static class FilesCommandsUi {
|
||||
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr window, ref Point point);
|
||||
[DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags);
|
||||
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr window, IntPtr target, uint flags);
|
||||
[DllImport("user32.dll", EntryPoint="PostMessageW")] public static extern bool Post(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
|
||||
|
||||
@@ -5,7 +5,8 @@ Add-Type -AssemblyName System.Drawing
|
||||
. "$PSScriptRoot/files_commands_ui.ps1"
|
||||
|
||||
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance'
|
||||
$names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance',
|
||||
'LeftFtpLocation', 'RightFtpLocation'
|
||||
$saved = @{}
|
||||
foreach ($name in $names) {
|
||||
if ($name -in $preferences.GetValueNames()) {
|
||||
@@ -16,6 +17,24 @@ $temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
|
||||
$root = Join-Path $temp ('ks-files-splitter-' + [Guid]::NewGuid().ToString('N'))
|
||||
$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
$process = $null
|
||||
|
||||
function Render-ComparisonList([IntPtr]$List, [FilesCommandsUi+Rect]$Bounds) {
|
||||
$bitmap = [Drawing.Bitmap]::new($Bounds.Right, $Bounds.Bottom)
|
||||
try {
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try {
|
||||
$dc = $graphics.GetHdc()
|
||||
try {
|
||||
if (![FilesCommandsUi]::PrintWindow($List, $dc, 3)) { throw 'Could not render the comparison list.' }
|
||||
} finally { $graphics.ReleaseHdc($dc) }
|
||||
} finally { $graphics.Dispose() }
|
||||
} catch {
|
||||
$bitmap.Dispose()
|
||||
throw
|
||||
}
|
||||
$bitmap
|
||||
}
|
||||
|
||||
try {
|
||||
$left = Join-Path $root 'left'
|
||||
$right = Join-Path $root 'right'
|
||||
@@ -25,7 +44,8 @@ try {
|
||||
[IO.File]::WriteAllText((Join-Path $right 'sample.txt'), "one`nthree")
|
||||
$preferences.SetValue('LeftPath', $left)
|
||||
$preferences.SetValue('RightPath', $right)
|
||||
foreach ($name in 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance') {
|
||||
foreach ($name in 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance',
|
||||
'LeftFtpLocation', 'RightFtpLocation') {
|
||||
$preferences.DeleteValue($name, $false)
|
||||
}
|
||||
|
||||
@@ -42,14 +62,14 @@ try {
|
||||
[void][FilesCommandsUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero)
|
||||
}
|
||||
Invoke-FilesCommand $main 'Compare files*'
|
||||
$comparison = Wait-For 'the foreground comparison window' {
|
||||
$comparison = Wait-For 'the rendered comparison window' {
|
||||
$dialog = [IntPtr]::Zero
|
||||
while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) {
|
||||
[uint32]$ownerPid = 0
|
||||
[void][FilesCommandsUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid)
|
||||
if ($ownerPid -ne $process.Id) { continue }
|
||||
$control = [FilesCommandsUi]::GetDlgItem($dialog, 402)
|
||||
if ([FilesCommandsUi]::IsWindowVisible($control) -and [FilesCommandsUi]::Activate($dialog)) {
|
||||
if ([FilesCommandsUi]::IsWindowVisible($control)) {
|
||||
return $dialog
|
||||
}
|
||||
}
|
||||
@@ -62,21 +82,17 @@ try {
|
||||
$destination = [int]($bounds.Right * 0.65)
|
||||
$mouseY = 30 -shl 16
|
||||
[void][FilesCommandsUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle))
|
||||
for ($x = $middle + 5; $x -lt $destination; $x += 5) {
|
||||
for ($step = 1; $step -lt 8; ++$step) {
|
||||
$x = $middle + [int](($destination - $middle) * $step / 8)
|
||||
[void][FilesCommandsUi]::Send($list, 512, [IntPtr]1, [IntPtr]($mouseY -bor $x))
|
||||
[void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
|
||||
}
|
||||
[void][FilesCommandsUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination))
|
||||
[void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
|
||||
$origin = [FilesCommandsUi+Point]::new()
|
||||
[void][FilesCommandsUi]::ClientToScreen($list, [ref]$origin)
|
||||
$bitmap = [Drawing.Bitmap]::new($bounds.Right, 1)
|
||||
$bitmap = Render-ComparisonList $list $bounds
|
||||
try {
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try { $graphics.CopyFromScreen($origin.X, ($origin.Y + $bounds.Bottom - 10), 0, 0, $bitmap.Size) }
|
||||
finally { $graphics.Dispose() }
|
||||
$ink = @(for ($x = $middle - 4; $x -le $destination + 4; ++$x) {
|
||||
if ($bitmap.GetPixel($x, 0).ToArgb() -ne [Drawing.Color]::White.ToArgb()) { $x }
|
||||
if ($bitmap.GetPixel($x, $bounds.Bottom - 10).ToArgb() -ne [Drawing.Color]::White.ToArgb()) { $x }
|
||||
})
|
||||
# Desktop scaling can spread the single-pixel divider across two adjacent screen pixels.
|
||||
if (!$ink.Count -or $ink.Count -gt 2 -or [Math]::Abs($ink[0] - $destination) -gt 1 -or
|
||||
@@ -92,14 +108,13 @@ try {
|
||||
[void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
|
||||
$height = [FilesCommandsUi]::Send($list, 0x1A1, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
|
||||
# This part of the first unchanged row contains the right line number in the default font.
|
||||
$numbers = [Drawing.Bitmap]::new([int]($height * 1.45), $height)
|
||||
$numbers = Render-ComparisonList $list $bounds
|
||||
try {
|
||||
$graphics = [Drawing.Graphics]::FromImage($numbers)
|
||||
try { $graphics.CopyFromScreen(($origin.X + [int]($height * 3.6)), $origin.Y, 0, 0, $numbers.Size) }
|
||||
finally { $graphics.Dispose() }
|
||||
$left = [int]($height * 3.6)
|
||||
$right = [int]($height * 5.05)
|
||||
$hasNumber = $false
|
||||
for ($y = [int]($height / 4); $y -lt [int]($height * 3 / 4) -and !$hasNumber; ++$y) {
|
||||
for ($x = 0; $x -lt $numbers.Width; ++$x) {
|
||||
for ($x = $left; $x -lt $right; ++$x) {
|
||||
$pixel = $numbers.GetPixel($x, $y)
|
||||
if ($pixel.R -lt 90 -and $pixel.G -lt 90 -and $pixel.B -lt 90) {
|
||||
$hasNumber = $true
|
||||
@@ -109,7 +124,7 @@ try {
|
||||
}
|
||||
if (!$hasNumber) { throw 'The right line number did not render in the Unified view.' }
|
||||
} finally { $numbers.Dispose() }
|
||||
'Verified the dragged divider and both line numbers in the Unified view.'
|
||||
'Verified the dragged divider and the right line number in the Unified view.'
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() }
|
||||
foreach ($name in $names) {
|
||||
|
||||
Reference in new issue
Block a user