Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b252bd111 | ||
|
|
7577d19a84 | ||
|
|
24fbf72d60 | ||
|
|
291d7597e3 | ||
|
|
ea6338e9b9 | ||
|
|
5ea222ad8a |
No files matched your search
@@ -198,6 +198,11 @@ add_test(NAME files-comparison-splitter
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_comparison_splitter.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>")
|
||||
set_tests_properties(files-comparison-splitter PROPERTIES RUN_SERIAL TRUE TIMEOUT 35)
|
||||
add_test(NAME files-space-analyzer-layout
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_space_analyzer_layout.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>")
|
||||
set_tests_properties(files-space-analyzer-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 25)
|
||||
find_program(KSWITCHER_NODE NAMES node)
|
||||
if(KSWITCHER_NODE)
|
||||
add_test(NAME files-terminal-enter
|
||||
|
||||
+36
-5
@@ -294,7 +294,7 @@ Warning і початковий фокус на No.
|
||||
|
||||
- Ctrl+Shift+0–9 відкриває діалог Title і Path із поточною папкою. OK додає запис без дублювання, Escape скасовує. Title необов’язковий, порожнє значення показує шлях. Записи LAN зберігають ID ПК, а редагування Path залишає запис на тому самому ПК.
|
||||
- Ctrl+0–9 відкриває лише папки, призначені натиснутій цифрі. Єдина папка відкривається одразу. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису.
|
||||
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F9 керують сортуванням і фільтром активної панелі. Ctrl+F10–F12 зарезервовані для інших режимів панелей. Brief і Wide також доступні в меню Left/Right та Options.
|
||||
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F9 керують сортуванням і фільтром активної панелі. Ctrl+F10 перемикає List і Tree. Ctrl+F11 перемикає фоновий підрахунок розмірів папок. Brief і Wide також доступні в меню Left/Right та Options.
|
||||
|
||||
## Налаштування Files
|
||||
|
||||
@@ -455,10 +455,41 @@ Warning і початковий фокус на No.
|
||||
переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
|
||||
з тією самою маскою й видимістю прихованих файлів.
|
||||
|
||||
- **Commands → Space Analyzer** аналізує поточну локальну папку у фоні
|
||||
тим самим обходом, що й підрахунок розмірів F3. У дереві показано розмір
|
||||
і відсоток від батьківської папки. Посилання на каталоги не обходяться.
|
||||
Stop лишає часткові результати, а Rescan повторює аналіз із початку.
|
||||
- **Left/Right → Tree view** або Ctrl+F10 перемикає вигляд відповідної
|
||||
панелі незалежно від Brief і Wide. Enter, подвійний клік чи стрілка біля
|
||||
папки розкриває або згортає гілку. Стрілки вправо й вліво працюють із
|
||||
гілкою та її батьківською папкою. Вміст гілки читається у фоні під час
|
||||
розкриття. Позначки згорнутих гілок залишаються доступними для F5, F6 і F8.
|
||||
Якщо позначено папку та її вміст, команда обробляє їх одним деревом.
|
||||
Повернення до List відкриває батьківську папку поточного елемента.
|
||||
- **Background folder sizes** або Ctrl+F11 вмикає вимірювання видимих папок
|
||||
у фоні для відповідної панелі. Під час оновлення попереднє число лишається
|
||||
поруч із символом … . Знак + позначає частковий розмір. Error з’являється,
|
||||
коли вимірювання недоступне. Якщо попереднє число є, позначка ! відрізняє
|
||||
його від свіжого результату.
|
||||
|
||||
- **Commands → Space Analyzer** показує місткість і вільне місце за даними
|
||||
Windows перед скануванням. Volume вибирає корінь тому, Folder повертає
|
||||
поточну локальну папку, Start запускає фоновий аналіз тим самим обходом,
|
||||
що й підрахунок розмірів F3. Посилання на каталоги всередині області
|
||||
сканування позначаються як link. Stop залишає часткові результати, а
|
||||
Rescan повторює аналіз із початку.
|
||||
- Дерево показує логічний розмір, зайняті байти та частку логічного розміру
|
||||
від батьківської папки. Знак + позначає частковий підрахунок. Зайняті байти
|
||||
підсумовуються за файловими записами, включно з окремими іменами для
|
||||
жорстких посилань. Службові дані файлової системи в цей підсумок не входять.
|
||||
Відсутні дані про зайняті байти позначаються в рядку стану.
|
||||
- Treemap показує дочірні елементи вибраної папки прямокутниками,
|
||||
пропорційними до їхнього логічного розміру. Дрібні елементи доступні в
|
||||
дереві. Клік по плитці відкриває точний елемент у сусідній панелі. Стрілки
|
||||
переводять фокус між плитками, Enter відкриває плитку у фокусі.
|
||||
- Sunburst показує до трьох рівнів вкладеності секторами за логічним
|
||||
розміром. Клік по сектору та Enter у відповідному рядку списку ведуть
|
||||
до одного елемента. Обраний рядок підсвічує відповідний сектор.
|
||||
- Під час аналізу всього NTFS-тому Files використовує індекс MFT за
|
||||
наявності доступу Windows. Звичайний обхід працює без такого доступу.
|
||||
Обидва режими перераховують доступні записи каталогів, ураховують
|
||||
жорсткі посилання за їхніми іменами та позначають недоступні гілки.
|
||||
- View відкриває вибраний файл у спільному переглядачі Files. Show in
|
||||
other panel відкриває вибрану папку або ставить курсор на файл у сусідній
|
||||
панелі. Команди роботи з файлами доступні там. Якщо фільтр приховує
|
||||
|
||||
+9
-2
@@ -433,17 +433,24 @@ BEGIN
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17
|
||||
END
|
||||
|
||||
118 DIALOGEX 0, 0, 385, 209
|
||||
118 DIALOGEX 0, 0, 420, 209
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Space Analyzer"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 488, 16, 15, 353, 13, SS_PATHELLIPSIS
|
||||
LTEXT "", 495, 16, 28, 353, 13, SS_ENDELLIPSIS
|
||||
CONTROL "Vo&lume", 496, "Button", BS_OWNERDRAW | WS_TABSTOP, 16, 43, 64, 16
|
||||
CONTROL "Tree&map", 497, "Button", BS_OWNERDRAW | WS_TABSTOP, 84, 43, 64, 16
|
||||
CONTROL "S&unburst", 499, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 43, 64, 16
|
||||
LTEXT "Sunburst items", 501, 171, 43, 201, 16, NOT WS_VISIBLE
|
||||
LISTBOX 500, 171, 60, 201, 105, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | NOT WS_VISIBLE
|
||||
CONTROL "", 498, "Static", SS_OWNERDRAW | SS_NOTIFY | WS_TABSTOP | NOT WS_VISIBLE, 16, 60, 353, 105
|
||||
CONTROL "", 489, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 16, 32, 353, 131
|
||||
LTEXT "", 490, 16, 167, 353, 14, SS_ENDELLIPSIS
|
||||
LTEXT "", 491, 12, 184, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "S&top", 492, "Button", BS_OWNERDRAW | WS_TABSTOP, 22, 189, 46, 16
|
||||
CONTROL "&Rescan", 493, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 189, 50, 16
|
||||
CONTROL "St&art", 493, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 189, 50, 16
|
||||
CONTROL "&View", 494, "Button", BS_OWNERDRAW | WS_TABSTOP, 126, 189, 46, 16
|
||||
CONTROL "&Show in other panel", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 176, 189, 102, 16
|
||||
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 282, 189, 50, 16
|
||||
|
||||
+312
-154
@@ -1,9 +1,12 @@
|
||||
#include <windows.h>
|
||||
#include <commctrl.h>
|
||||
#include <windowsx.h>
|
||||
#include <winioctl.h>
|
||||
#include <shellapi.h>
|
||||
#include <shlobj.h>
|
||||
#include <commdlg.h>
|
||||
#include <cmath>
|
||||
#include <numbers>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
@@ -22,6 +25,7 @@
|
||||
#include <winternl.h>
|
||||
#include <wininet.h>
|
||||
#include "files_terminal.h"
|
||||
#include "files_win32_directory.h"
|
||||
#include "files_command_completion.h"
|
||||
#include "files_text_window.h"
|
||||
#include "files_menu_navigation.h"
|
||||
@@ -48,7 +52,12 @@ using ks::lan::fileRequest;
|
||||
using ks::lan::filePath;
|
||||
using ks::lan::checkFileReply;
|
||||
|
||||
struct FileInfo { DWORD attributes; uint64_t size, modified; };
|
||||
struct FileInfo
|
||||
{
|
||||
DWORD attributes;
|
||||
uint64_t size, modified;
|
||||
std::optional<uint64_t> allocated{};
|
||||
};
|
||||
FileInfo fileInfo(const Json &row)
|
||||
{
|
||||
return {row.at("attributes"),row.at("size"),row.at("modified")};
|
||||
@@ -164,32 +173,17 @@ DWORD listElevatedFolder(const fs::path &directory, const std::wstring &pipeName
|
||||
FILE_FLAG_BACKUP_SEMANTICS,nullptr)};
|
||||
if(folder.value==INVALID_HANDLE_VALUE) return GetLastError();
|
||||
|
||||
alignas(FILE_ID_BOTH_DIR_INFO) unsigned char buffer[16384];
|
||||
while(GetFileInformationByHandleEx(folder.value,FileIdBothDirectoryInfo,buffer,sizeof(buffer)))
|
||||
{
|
||||
auto entry=reinterpret_cast<const FILE_ID_BOTH_DIR_INFO*>(buffer);
|
||||
for(;;)
|
||||
{
|
||||
std::wstring_view name(entry->FileName,entry->FileNameLength/sizeof(wchar_t));
|
||||
if(name!=L"." && name!=L"..")
|
||||
{
|
||||
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();
|
||||
}
|
||||
if(!entry->NextEntryOffset) break;
|
||||
entry=reinterpret_cast<const FILE_ID_BOTH_DIR_INFO*>(
|
||||
reinterpret_cast<const unsigned char*>(entry)+entry->NextEntryOffset);
|
||||
}
|
||||
}
|
||||
const auto error=GetLastError();
|
||||
return error==ERROR_NO_MORE_FILES?ERROR_SUCCESS:error;
|
||||
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
|
||||
@@ -286,7 +280,7 @@ DWORD readElevatedFolder(const ElevatedHelper &session,const fs::path &directory
|
||||
struct FolderSize
|
||||
{
|
||||
uint64_t bytes{};
|
||||
bool partial{};
|
||||
bool partial{}, failed{}, previous{};
|
||||
|
||||
void add(uint64_t amount)
|
||||
{
|
||||
@@ -327,6 +321,7 @@ FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDir
|
||||
const FolderMeasurementObserver &observe={})
|
||||
{
|
||||
FolderSize size;
|
||||
bool readable=false;
|
||||
std::vector<fs::path> pending{root};
|
||||
while(!pending.empty() && !stop.stop_requested())
|
||||
{
|
||||
@@ -338,6 +333,7 @@ FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDir
|
||||
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);
|
||||
@@ -346,6 +342,7 @@ FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDir
|
||||
});
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
readable|=complete;
|
||||
if(!complete)
|
||||
{
|
||||
size.partial=true;
|
||||
@@ -353,6 +350,7 @@ FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDir
|
||||
}
|
||||
}
|
||||
if(stop.stop_requested()) size.partial=true;
|
||||
size.failed=size.partial && !readable && !stop.stop_requested();
|
||||
return size;
|
||||
}
|
||||
|
||||
@@ -361,6 +359,12 @@ constexpr auto schemeKey = L"Software\\KSwitcher\\Files";
|
||||
#include "files_ftp.inl"
|
||||
|
||||
|
||||
fs::path folderPathWithoutSeparator(fs::path path)
|
||||
{
|
||||
if(!path.has_filename() && path.has_relative_path()) return path.parent_path();
|
||||
return path;
|
||||
}
|
||||
|
||||
fs::path panelParentPath(const fs::path &directory,bool local)
|
||||
{
|
||||
if(!directory.has_relative_path()) return {};
|
||||
@@ -427,7 +431,7 @@ enum class PanelSort { name, extension, size, modified };
|
||||
struct PanelView
|
||||
{
|
||||
PanelSort sort{PanelSort::name};
|
||||
bool descending{}, foldersFirst{true}, showHidden{true};
|
||||
bool descending{}, foldersFirst{true}, showHidden{true}, tree{}, automaticSizes{};
|
||||
std::wstring mask;
|
||||
fs::path revealedFile;
|
||||
};
|
||||
@@ -508,6 +512,22 @@ struct Panel
|
||||
fs::path ftpInitialDirectory;
|
||||
std::vector<DirectoryRow> ordered;
|
||||
};
|
||||
struct TreeBranch
|
||||
{
|
||||
std::vector<DirectoryRow> ordered;
|
||||
std::map<fs::path,FolderEntryMetadata> metadata;
|
||||
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;
|
||||
@@ -767,13 +787,16 @@ void loadPanelView(int index)
|
||||
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.descending?4:0) | (view.foldersFirst?0:8) | (view.showHidden?0:16) |
|
||||
(view.tree?32:0) | (view.automaticSizes?64:0));
|
||||
}
|
||||
|
||||
void setMode(int index, bool wide)
|
||||
@@ -1772,6 +1795,8 @@ void copyTerminalText(HWND owner)
|
||||
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);
|
||||
@@ -1781,8 +1806,18 @@ LRESULT currentPanelRow(const Panel &panel)
|
||||
std::vector<fs::path> selectedPanelPaths(const Panel &panel)
|
||||
{
|
||||
std::vector<fs::path> paths;
|
||||
for(size_t i=0;i<panel.rows.size();++i)
|
||||
if(panel.marked[i] && panel.sizes[i]!=L"Up") paths.push_back(panel.rows[i]);
|
||||
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);
|
||||
@@ -1859,7 +1894,7 @@ void startFileSearch(Panel &panel,Panel::FindOptions options);
|
||||
void refreshPanel(Panel &panel)
|
||||
{
|
||||
cancelFolderSizes(panel);
|
||||
panel.folderSizes.clear();
|
||||
if(!panel.view.automaticSizes) panel.folderSizes.clear();
|
||||
updateSelectionSummary(panel);
|
||||
if(panel.findOrigin) startFileSearch(panel,panel.findOrigin->options);
|
||||
else open(panel,panel.directory,false);
|
||||
@@ -2212,33 +2247,28 @@ void updateSelectionSummary(const Panel &panel)
|
||||
size_t marked=0,unmeasured=0;
|
||||
uint64_t total=0;
|
||||
bool partial=false;
|
||||
if(!ftpProfileList(panel))
|
||||
visitPanelMarks(panel,[&](const fs::path &path,const FolderEntryMetadata &entry)
|
||||
{
|
||||
for(size_t row=0;row<panel.marked.size();++row)
|
||||
++marked;
|
||||
auto bytes=entry.size;
|
||||
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)
|
||||
{
|
||||
if(!panel.marked[row] || panel.sizes[row]==L"Up") continue;
|
||||
++marked;
|
||||
uint64_t bytes;
|
||||
if(panel.sizes[row]==L"Folder")
|
||||
const auto measured=panel.folderSizes.find(path);
|
||||
if(measured==panel.folderSizes.end() || (measured->second.failed && !measured->second.previous))
|
||||
{
|
||||
const auto measured=panel.folderSizes.find(panel.rows[row]);
|
||||
if(measured==panel.folderSizes.end())
|
||||
{
|
||||
++unmeasured;
|
||||
continue;
|
||||
}
|
||||
bytes=measured->second.bytes;
|
||||
partial|=measured->second.partial;
|
||||
++unmeasured;
|
||||
return;
|
||||
}
|
||||
else bytes=std::stoull(panel.sizes[row]);
|
||||
if(bytes>UINT64_MAX-total)
|
||||
{
|
||||
total=UINT64_MAX;
|
||||
partial=true;
|
||||
}
|
||||
else total+=bytes;
|
||||
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)
|
||||
{
|
||||
@@ -2261,6 +2291,42 @@ std::optional<SYSTEMTIME> localFileTime(uint64_t ticks)
|
||||
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);
|
||||
@@ -2305,11 +2371,12 @@ void showFileDetails(const Panel &panel)
|
||||
if(statusFields&2)
|
||||
{
|
||||
const auto &size=panel.sizes[row];
|
||||
const auto measured=panel.folderSizes.find(path);
|
||||
if(size==L"Folder" && measured!=panel.folderSizes.end())
|
||||
details+=L" "+formatSize(measured->second.bytes)+(measured->second.partial?L" (partial)":L"");
|
||||
else
|
||||
details+=L" "+(size==L"Folder" || size==L"Up"?size:formatSize(std::stoull(size)));
|
||||
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);
|
||||
@@ -2441,6 +2508,12 @@ std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &reque
|
||||
}
|
||||
|
||||
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<FtpProfile> &ftp)
|
||||
{
|
||||
@@ -2540,6 +2613,12 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
}
|
||||
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();
|
||||
}
|
||||
if(peer || request.ftp) panel.navigation={};
|
||||
else if(!finding)
|
||||
{
|
||||
@@ -2560,49 +2639,29 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
panel.watch.reset();
|
||||
std::swap(panel.watch.handle,nextWatch.handle);
|
||||
}
|
||||
panel.filteredMarks.clear();
|
||||
if(!finding)
|
||||
{
|
||||
if(!partial) std::erase_if(markedPaths,[&](const auto &path){return !metadata.contains(path);});
|
||||
panel.filteredMarks=markedPaths;
|
||||
}
|
||||
panel.metadata=std::move(metadata);
|
||||
panel.rows.clear();
|
||||
panel.sizes.clear();
|
||||
panel.dimmed.clear();
|
||||
panel.marked.clear();
|
||||
panel.fileExtensionLength=panel.folderExtensionLength=0;
|
||||
const bool profiles=ftpProfileList(panel);
|
||||
const bool renderTree=panel.view.tree && !finding && !profiles;
|
||||
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);
|
||||
}
|
||||
const auto parent=finding?fs::path{}:panelParentPath(directory,!panel.peer && !panel.ftp);
|
||||
const bool hasParent=!parent.empty();
|
||||
const auto rowCount=profiles?ftpProfiles.size():finding?files.size():ordered.size()+hasParent;
|
||||
panel.rows.reserve(rowCount);
|
||||
panel.sizes.reserve(rowCount);
|
||||
panel.dimmed.reserve(rowCount);
|
||||
panel.marked.reserve(rowCount);
|
||||
const bool visible=IsWindowVisible(panel.list);
|
||||
if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0);
|
||||
SendMessageW(panel.list, LB_RESETCONTENT, 0, 0);
|
||||
SendMessageW(panel.list, LB_INITSTORAGE, rowCount, 0);
|
||||
auto add = [&](const fs::path &path, const std::wstring &label, bool folder)
|
||||
const auto rowCount=profiles?ftpProfiles.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)
|
||||
{
|
||||
if (SendMessageW(panel.list, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(label.c_str())) >= 0)
|
||||
{
|
||||
panel.rows.push_back(path);
|
||||
if(label!=L"..")
|
||||
{
|
||||
const auto extension=path.extension().native();
|
||||
auto &longest=folder?panel.folderExtensionLength:panel.fileExtensionLength;
|
||||
if(extension.size()>1) longest=std::max(longest,extension.size()-1);
|
||||
}
|
||||
const bool marked=label!=L".." && markedPaths.contains(path);
|
||||
panel.marked.push_back(marked);
|
||||
if(marked) panel.filteredMarks.erase(path);
|
||||
const auto entry=label==L".." || profiles ? FolderEntryMetadata{} : panel.metadata.at(path);
|
||||
panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0);
|
||||
panel.sizes.push_back(profiles?L"":folder ? (label==L".." ? L"Up" : L"Folder") :
|
||||
std::to_wstring(entry.size));
|
||||
}
|
||||
const bool marked=markedPaths.contains(path);
|
||||
if(rows.add(path,label,folder,marked) && marked) panel.filteredMarks.erase(path);
|
||||
};
|
||||
if(profiles)
|
||||
{
|
||||
@@ -2611,15 +2670,20 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
}
|
||||
else
|
||||
{
|
||||
if(hasParent) add(parent,L"..",true);
|
||||
if(finding)
|
||||
if(hasParent) rows.add(parent,L"..",true,false,true);
|
||||
if(renderTree) appendTreeRows(panel,rows);
|
||||
else if(finding)
|
||||
{
|
||||
for(const auto &file:files) add(file,file.lexically_relative(directory).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());
|
||||
@@ -2649,7 +2713,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
if(sameDirectory) SendMessageW(panel.list,LB_SETTOPINDEX,previousTop,0);
|
||||
SendMessageW(panel.list,LB_SETCURSEL,selected-panel.rows.begin(),0);
|
||||
}
|
||||
if(visible) SendMessageW(panel.list,WM_SETREDRAW,TRUE,0);
|
||||
rows.finish();
|
||||
InvalidateRect(panel.list,nullptr,FALSE);
|
||||
updateSelectionSummary(panel);
|
||||
refreshQuickView(panel);
|
||||
@@ -2659,16 +2723,15 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
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 && !profiles) queueAutomaticPanelSizes(panel,true);
|
||||
return true;
|
||||
}
|
||||
|
||||
void startDirectoryScan(Panel &panel)
|
||||
std::future<std::unique_ptr<Panel::ScanResult>> scanDirectoryInBackground(HWND owner,Panel::ScanRequest request,
|
||||
PanelView view,std::shared_ptr<std::atomic_size_t> entries,std::stop_token stop)
|
||||
{
|
||||
panel.scanStop=std::stop_source{};
|
||||
panel.scanEntriesRead=std::make_shared<std::atomic_size_t>(0);
|
||||
const auto owner=GetParent(panel.list);
|
||||
std::packaged_task<std::unique_ptr<Panel::ScanResult>()> task(
|
||||
[request=*panel.scanRequest,view=panel.view,entries=panel.scanEntriesRead,stop=panel.scanStop.get_token()]
|
||||
[request=std::move(request),view=std::move(view),entries=std::move(entries),stop]
|
||||
{
|
||||
auto result=scanDirectory(request,*entries,stop);
|
||||
if(result->opened && !request.find) orderDirectoryRows(*result,view);
|
||||
@@ -2680,7 +2743,15 @@ void startDirectoryScan(Panel &panel)
|
||||
task();
|
||||
PostMessageW(owner,directoryScanReady,0,0);
|
||||
}).detach();
|
||||
panel.scan=std::move(future);
|
||||
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,
|
||||
panel.scanEntriesRead,panel.scanStop.get_token());
|
||||
panel.scanSuperseded=false;
|
||||
if(&panel==&panels[active]) showDirectoryScanProgress(panel);
|
||||
}
|
||||
@@ -2744,6 +2815,8 @@ void open(Panel &panel,const fs::path &directory,bool offerElevation=false)
|
||||
openOn(panel,directory,offerElevation,panel.peer,{},{},panel.ftp);
|
||||
}
|
||||
|
||||
#include "files_panel_tree.inl"
|
||||
|
||||
bool panelViewAvailable(const Panel &panel)
|
||||
{
|
||||
return !panel.findOrigin && !ftpProfileList(panel) && !panel.directory.empty() &&
|
||||
@@ -2785,11 +2858,41 @@ void togglePanelView(Panel &panel,bool foldersFirst)
|
||||
|
||||
void editPanelFilter(HWND owner,Panel &panel);
|
||||
|
||||
void setTreePanelMode(Panel &panel)
|
||||
{
|
||||
if(!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(!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);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK panelHeadingInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
@@ -2852,11 +2955,13 @@ void refreshChangedPanels()
|
||||
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);
|
||||
open(panel,directory);
|
||||
}
|
||||
}
|
||||
|
||||
void collectFolderSizes(Panel &panel);
|
||||
bool queueFolderMeasurements(Panel &panel,const std::vector<fs::path> &folders,bool foreground);
|
||||
|
||||
bool calculateFolderSizes(Panel &panel,LRESULT current)
|
||||
{
|
||||
@@ -2875,6 +2980,12 @@ bool calculateFolderSizes(Panel &panel,LRESULT current)
|
||||
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()) return false;
|
||||
if(const auto running=panel.folderSizeJob)
|
||||
{
|
||||
bool queued=false;
|
||||
@@ -2896,7 +3007,7 @@ bool calculateFolderSizes(Panel &panel,LRESULT current)
|
||||
if(queued)
|
||||
{
|
||||
if(added) InvalidateRect(panel.list,nullptr,FALSE);
|
||||
setStatus(L"Calculating folder sizes... [Esc]");
|
||||
if(foreground) setStatus(L"Calculating folder sizes... [Esc]");
|
||||
return true;
|
||||
}
|
||||
collectFolderSizes(panel);
|
||||
@@ -2958,8 +3069,8 @@ bool calculateFolderSizes(Panel &panel,LRESULT current)
|
||||
catch(const std::exception &)
|
||||
{
|
||||
std::lock_guard lock(job->mutex);
|
||||
if(!job->current.empty()) job->completed.try_emplace(job->current,FolderSize{0,true});
|
||||
for(const auto &folder:job->pending) job->completed.try_emplace(folder,FolderSize{0,true});
|
||||
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;
|
||||
}
|
||||
};
|
||||
@@ -2970,35 +3081,54 @@ bool calculateFolderSizes(Panel &panel,LRESULT current)
|
||||
return true;
|
||||
}
|
||||
panel.folderSizeJob=std::move(job);
|
||||
panel.folderSizeWaiting.insert(std::next(folders.begin()),folders.end());
|
||||
if(!panel.folderSizeWaiting.empty()) InvalidateRect(panel.list,nullptr,FALSE);
|
||||
setStatus(L"Calculating folder sizes... [Esc]");
|
||||
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 || ftpProfileList(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 current, spinner;
|
||||
fs::path spinner;
|
||||
bool finished;
|
||||
{
|
||||
std::lock_guard lock(job->mutex);
|
||||
completed.swap(job->completed);
|
||||
finished=job->finished;
|
||||
current=job->current;
|
||||
if(!finished && GetTickCount64()-job->started>=folderSpinnerDelay)
|
||||
spinner=current;
|
||||
spinner=job->current;
|
||||
}
|
||||
if(panel.folderSizeWaiting.erase(current)) invalidateFolderSizeRow(panel,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);
|
||||
panel.folderSizes.insert_or_assign(path,size);
|
||||
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);
|
||||
@@ -3797,6 +3927,7 @@ void enter(Panel &panel)
|
||||
revealLocalFile(panel,target);
|
||||
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 openPanelFile(panel, target, nullptr, L"Cannot open the selected file.");
|
||||
@@ -4046,26 +4177,34 @@ LONG farDialogButtonWidth(HWND button)
|
||||
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 width=[&](int id)
|
||||
{
|
||||
if(!native) return farDialogButtonWidth(GetDlgItem(dialog,id));
|
||||
const auto bounds=dialogControlBounds(dialog,id);
|
||||
return bounds.right-bounds.left;
|
||||
};
|
||||
LONG rowWidth=-gap;
|
||||
for(const auto id:controls) rowWidth+=width(id)+gap;
|
||||
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=width(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;
|
||||
@@ -5815,7 +5954,8 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
results.insert(progress.renamedTarget.empty()?to:progress.renamedTarget);
|
||||
if(!request.externalSources) progress.ui.invoke([&] {
|
||||
const auto row=std::find(source.rows.begin(),source.rows.end(),path);
|
||||
if(row!=source.rows.end()) source.marked[row-source.rows.begin()]=false;
|
||||
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);
|
||||
});
|
||||
}
|
||||
@@ -5850,6 +5990,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
}
|
||||
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);
|
||||
@@ -6257,6 +6398,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
|
||||
progressDialog.close();
|
||||
for(auto &visible:panels)
|
||||
{
|
||||
if(treePanelActive(visible) && samePanelSource(panel,visible.peer,visible.ftp)) pruneTreeMarks(visible,removed);
|
||||
if(visible.findOrigin) pruneSearchResults(visible,removed);
|
||||
else if(!visible.directory.empty()) open(visible,visible.directory);
|
||||
}
|
||||
@@ -6774,6 +6916,15 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
|
||||
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);
|
||||
}
|
||||
@@ -6786,6 +6937,13 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
|
||||
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))))
|
||||
{
|
||||
@@ -6806,8 +6964,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
|
||||
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)
|
||||
if(panel.sizes[i]!=L"Up") panel.marked[i]=mark;
|
||||
for(auto i=first;i<=end;++i) markPanelRow(panel,i,mark);
|
||||
SendMessageW(window,LB_SETCURSEL,target,0);
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
updateSelectionSummary(panel);
|
||||
@@ -6960,6 +7117,9 @@ void openMenu(HWND window, int index)
|
||||
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");
|
||||
}
|
||||
}
|
||||
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10"};
|
||||
@@ -7240,7 +7400,11 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
performPanelDrop(window);
|
||||
return 0;
|
||||
case directoryScanReady:
|
||||
if(!FilesModalDialog::activeFor(window)) collectDirectoryScans();
|
||||
if(!FilesModalDialog::activeFor(window))
|
||||
{
|
||||
collectDirectoryScans();
|
||||
collectTreeBranches();
|
||||
}
|
||||
return 0;
|
||||
case WM_TIMER:
|
||||
if(wp==driveQueryTimer) {pollDriveQueries(window);return 0;}
|
||||
@@ -7258,6 +7422,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
if(!FilesModalDialog::activeFor(window))
|
||||
{
|
||||
collectDirectoryScans();
|
||||
collectTreeBranches();
|
||||
refreshChangedPanels();
|
||||
showDirectoryScanProgress(panels[active]);
|
||||
}
|
||||
@@ -7671,7 +7836,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
background=Selection;
|
||||
COLORREF rowBackground=colors[background];
|
||||
HFONT rowFont{};
|
||||
const wchar_t *folderIndicator=nullptr;
|
||||
std::wstring folderIndicator;
|
||||
if(panelRow)
|
||||
{
|
||||
const auto &panel=panels[item.CtlID-102];
|
||||
@@ -7684,12 +7849,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
if(item.itemID<panel.rows.size())
|
||||
{
|
||||
const auto &path=panel.rows[item.itemID];
|
||||
if(path==panel.folderSpinner)
|
||||
{
|
||||
constexpr const wchar_t *frames[]{L"|",L"/",L"-",L"\\"};
|
||||
folderIndicator=frames[(GetTickCount64()/folderSpinnerInterval)%std::size(frames)];
|
||||
}
|
||||
else if(panel.folderSizeWaiting.contains(path)) folderIndicator=L"Queued";
|
||||
folderIndicator=folderMeasurementText(panel,path,static_cast<size_t>(sizeWidth));
|
||||
}
|
||||
}
|
||||
auto shortcut=text.find(L'\t');
|
||||
@@ -7790,13 +7950,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
else if(item.CtlID>=130 && item.CtlID<=134)
|
||||
paintMenuLabel(item.hDC,item.rcItem,text,0,foreground,colors[background]);
|
||||
else if(folderIndicator && !panels[item.CtlID-102].wide)
|
||||
else if(!folderIndicator.empty() && !panels[item.CtlID-102].wide)
|
||||
{
|
||||
auto name=item.rcItem, indicator=item.rcItem;
|
||||
indicator.left=std::max(indicator.left,indicator.right-lstrlenW(folderIndicator)*cellWidth-10);
|
||||
indicator.left=std::max(indicator.left,indicator.right-static_cast<LONG>(folderIndicator.size())*cellWidth-10);
|
||||
name.right=indicator.left;
|
||||
paintText(item.hDC,name,text.c_str(),foreground,rowBackground,false,rowFont);
|
||||
paintText(item.hDC,indicator,folderIndicator,foreground,rowBackground,true);
|
||||
paintText(item.hDC,indicator,folderIndicator.c_str(),foreground,rowBackground,true);
|
||||
}
|
||||
else paintText(item.hDC,item.rcItem,text.c_str(),foreground,rowBackground,false,rowFont);
|
||||
if(item.CtlID==102 || item.CtlID==103)
|
||||
@@ -7809,7 +7969,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
const auto &extension=columns[extensionColumn];
|
||||
const auto &date=columns[dateColumn];
|
||||
const bool folder=panel.sizes[item.itemID]==L"Folder";
|
||||
if(folder) text=path.filename().native();
|
||||
const bool tree=treePanelActive(panel);
|
||||
if(folder || (tree && panel.sizes[item.itemID]!=L"Up")) text=path.filename().native();
|
||||
const bool separateExtension=extension.left<extension.right && (folder?alignFolders:alignExtensions);
|
||||
if(separateExtension)
|
||||
{
|
||||
@@ -7818,6 +7979,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
paintText(item.hDC,extension,showSuffix?suffix.c_str()+1:L"",foreground,rowBackground,true,rowFont);
|
||||
if(showSuffix) text=path.stem().native();
|
||||
}
|
||||
if(tree) text=treeRowPrefix(panel,path,folder)+text;
|
||||
auto name=columns[nameColumn];
|
||||
if(!separateExtension) name.right=extension.right;
|
||||
paintText(item.hDC,name,text.c_str(),foreground,rowBackground,false,rowFont);
|
||||
@@ -7833,14 +7995,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
const auto &amount=panel.sizes[item.itemID];
|
||||
auto visible=amount;
|
||||
const auto measured=folder?panel.folderSizes.find(panel.rows[item.itemID]):panel.folderSizes.end();
|
||||
if(folderIndicator) visible=folderIndicator;
|
||||
else if(measured!=panel.folderSizes.end())
|
||||
{
|
||||
const auto partial=measured->second.partial;
|
||||
visible=formatSize(measured->second.bytes,static_cast<size_t>(sizeWidth)-(partial?1:0));
|
||||
if(partial) visible+=L"+";
|
||||
}
|
||||
if(!folderIndicator.empty()) visible=folderIndicator;
|
||||
else if(amount!=L"Folder" && amount!=L"Up")
|
||||
visible=formatSize(std::stoull(amount),static_cast<size_t>(sizeWidth));
|
||||
paintText(item.hDC,columns[sizeColumn],visible.c_str(),foreground,rowBackground,true);
|
||||
@@ -7922,6 +8077,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
for(auto &panel:panels)
|
||||
{
|
||||
panel.scanStop.request_stop();
|
||||
stopTreeBranches(panel);
|
||||
panel.watch.reset();
|
||||
}
|
||||
terminalView.close();
|
||||
@@ -8160,12 +8316,13 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
continue;
|
||||
}
|
||||
if(mainInput && !terminalVisible && !copyInProgress &&
|
||||
message.message==WM_KEYDOWN && message.wParam>=VK_F1 && message.wParam<=VK_F12 &&
|
||||
(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_F9)
|
||||
if(!(message.lParam & (1LL<<30)) && message.wParam<=VK_F11)
|
||||
{
|
||||
hidePicker();
|
||||
showMenu(false);
|
||||
@@ -8298,7 +8455,8 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
}
|
||||
}
|
||||
if (message.message == WM_SYSKEYDOWN && message.wParam == VK_F10 &&
|
||||
!(GetKeyState(VK_MENU) & 0x8000) && !(GetKeyState(VK_SHIFT) & 0x8000))
|
||||
!(GetKeyState(VK_CONTROL) & 0x8000) && !(GetKeyState(VK_MENU) & 0x8000) &&
|
||||
!(GetKeyState(VK_SHIFT) & 0x8000))
|
||||
{
|
||||
SendMessageW(window, WM_CLOSE, 0, 0);
|
||||
continue;
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
constexpr DWORD spaceFileShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
|
||||
|
||||
bool sameVolumeRoot(const fs::path &directory,const fs::path &root)
|
||||
{
|
||||
if(root.empty()) return false;
|
||||
const auto comparable=[](const fs::path &path) {
|
||||
auto value=std::wstring_view(path.native());
|
||||
if(!value.empty() && (value.back()==L'\\' || value.back()==L'/')) value.remove_suffix(1);
|
||||
return value;
|
||||
};
|
||||
const auto left=comparable(directory),right=comparable(root);
|
||||
return !left.empty() && !right.empty() && CompareStringOrdinal(left.data(),static_cast<int>(left.size()),
|
||||
right.data(),static_cast<int>(right.size()),TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
bool isNtfsVolume(const fs::path &root)
|
||||
{
|
||||
wchar_t filesystem[16]{};
|
||||
return GetVolumeInformationW(root.c_str(),nullptr,0,nullptr,nullptr,nullptr,filesystem,
|
||||
static_cast<DWORD>(std::size(filesystem))) && std::wstring_view(filesystem)==L"NTFS";
|
||||
}
|
||||
|
||||
using NtfsDirectoryIds=std::set<uint64_t>;
|
||||
|
||||
bool appendMftDirectories(std::span<const unsigned char> records,NtfsDirectoryIds &directories)
|
||||
{
|
||||
struct UsnRow
|
||||
{
|
||||
DWORD length;
|
||||
WORD major,minor;
|
||||
DWORDLONG id,parent;
|
||||
USN usn;
|
||||
LARGE_INTEGER time;
|
||||
DWORD reason,source,security,attributes;
|
||||
WORD nameLength,nameOffset;
|
||||
};
|
||||
constexpr auto header=offsetof(UsnRow,nameOffset)+sizeof(WORD);
|
||||
static_assert(header==60);
|
||||
while(!records.empty())
|
||||
{
|
||||
if(records.size()<header) return false;
|
||||
UsnRow row{};
|
||||
memcpy(&row,records.data(),header);
|
||||
if(row.major!=2 || row.length<header || row.length>records.size()) return false;
|
||||
if((row.attributes&FILE_ATTRIBUTE_DIRECTORY) && !(row.attributes&FILE_ATTRIBUTE_REPARSE_POINT))
|
||||
directories.insert(row.id);
|
||||
records=records.subspan(row.length);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool isExpectedNtfsDirectory(HANDLE handle,const fs::path &directory)
|
||||
{
|
||||
std::wstring name(MAX_PATH,L'\0');
|
||||
const auto getName=[&] {
|
||||
return GetFinalPathNameByHandleW(handle,name.data(),static_cast<DWORD>(name.size()),
|
||||
FILE_NAME_OPENED|VOLUME_NAME_DOS);
|
||||
};
|
||||
auto length=getName();
|
||||
if(length>=name.size())
|
||||
{
|
||||
name.resize(length+1);
|
||||
length=getName();
|
||||
}
|
||||
if(!length || length>=name.size()) return false;
|
||||
name.resize(length);
|
||||
constexpr std::wstring_view devicePrefix=LR"(\\?\)";
|
||||
const auto &expected=directory.native();
|
||||
std::wstring_view actual(name);
|
||||
if(actual.starts_with(devicePrefix) && !std::wstring_view(expected).starts_with(devicePrefix))
|
||||
actual.remove_prefix(devicePrefix.size());
|
||||
return CompareStringOrdinal(actual.data(),static_cast<int>(actual.size()),expected.data(),
|
||||
static_cast<int>(expected.size()),TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
bool readMftDirectoryIds(const fs::path &root,NtfsDirectoryIds &directories,std::stop_token stop)
|
||||
{
|
||||
wchar_t name[64]{};
|
||||
if(!GetVolumeNameForVolumeMountPointW(root.c_str(),name,static_cast<DWORD>(std::size(name)))) return false;
|
||||
const auto length=wcslen(name);
|
||||
if(!length || name[length-1]!=L'\\') return false;
|
||||
name[length-1]=L'\0';
|
||||
const Handle volume{CreateFileW(name,GENERIC_READ,spaceFileShare,nullptr,OPEN_EXISTING,0,nullptr)};
|
||||
if(volume.value==INVALID_HANDLE_VALUE) return false;
|
||||
struct Enumeration {DWORDLONG first; USN low,high;};
|
||||
static_assert(sizeof(Enumeration)==24);
|
||||
Enumeration request{0,0,std::numeric_limits<USN>::max()};
|
||||
auto buffer=std::vector<unsigned char>(512*1024);
|
||||
while(!stop.stop_requested())
|
||||
{
|
||||
DWORD bytes{};
|
||||
if(!DeviceIoControl(volume.value,FSCTL_ENUM_USN_DATA,&request,sizeof(request),buffer.data(),
|
||||
static_cast<DWORD>(buffer.size()),&bytes,nullptr))
|
||||
return GetLastError()==ERROR_HANDLE_EOF && !directories.empty();
|
||||
DWORDLONG next{};
|
||||
if(bytes<sizeof(next) || bytes>buffer.size()) return false;
|
||||
memcpy(&next,buffer.data(),sizeof(next));
|
||||
if(next<=request.first) return false;
|
||||
if(!appendMftDirectories(std::span<const unsigned char>(buffer).subspan(sizeof(next),bytes-sizeof(next)),
|
||||
directories)) return false;
|
||||
request.first=next;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
class NtfsSpaceWalk
|
||||
{
|
||||
public:
|
||||
NtfsSpaceWalk(const fs::path &root,const fs::path &mount,std::stop_token stop) : root(root),
|
||||
volumeHint{CreateFileW(root.c_str(),FILE_READ_ATTRIBUTES,spaceFileShare,nullptr,OPEN_EXISTING,
|
||||
FILE_FLAG_BACKUP_SEMANTICS,nullptr)}
|
||||
{
|
||||
if(volumeHint.value!=INVALID_HANDLE_VALUE)
|
||||
{
|
||||
try {indexed=readMftDirectoryIds(mount,mft,stop);}
|
||||
catch(const std::exception &) {}
|
||||
}
|
||||
if(!indexed) mft.clear();
|
||||
}
|
||||
|
||||
bool usedMft() const { return usedIndex; }
|
||||
|
||||
bool list(const fs::path &directory,const FileVisitor &visit,std::stop_token stop,FilesConnection &fallback)
|
||||
{
|
||||
const bool atRoot=directory==root;
|
||||
const auto known=byPath.extract(directory);
|
||||
constexpr DWORD openFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT;
|
||||
Handle handle{INVALID_HANDLE_VALUE};
|
||||
if(known && mft.contains(known.mapped()))
|
||||
{
|
||||
FILE_ID_DESCRIPTOR id{};
|
||||
id.dwSize=sizeof(id);
|
||||
id.Type=FileIdType;
|
||||
id.FileId.QuadPart=static_cast<LONGLONG>(known.mapped());
|
||||
handle.value=OpenFileById(volumeHint.value,&id,FILE_LIST_DIRECTORY|FILE_READ_ATTRIBUTES,
|
||||
spaceFileShare,nullptr,openFlags);
|
||||
if(handle.value!=INVALID_HANDLE_VALUE)
|
||||
{
|
||||
if(isExpectedNtfsDirectory(handle.value,directory)) usedIndex=true;
|
||||
else
|
||||
{
|
||||
CloseHandle(handle.value);
|
||||
handle.value=INVALID_HANDLE_VALUE;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(handle.value==INVALID_HANDLE_VALUE)
|
||||
handle.value=CreateFileW(directory.c_str(),FILE_LIST_DIRECTORY|FILE_READ_ATTRIBUTES,
|
||||
spaceFileShare,nullptr,OPEN_EXISTING,atRoot?FILE_FLAG_BACKUP_SEMANTICS:openFlags,nullptr);
|
||||
if(handle.value==INVALID_HANDLE_VALUE) return false;
|
||||
|
||||
FILE_ATTRIBUTE_TAG_INFO tag{};
|
||||
if(!GetFileInformationByHandleEx(handle.value,FileAttributeTagInfo,&tag,sizeof(tag)) ||
|
||||
!(tag.FileAttributes&FILE_ATTRIBUTE_DIRECTORY) ||
|
||||
(!atRoot && (tag.FileAttributes&FILE_ATTRIBUTE_REPARSE_POINT))) return false;
|
||||
|
||||
bool emitted=false;
|
||||
const auto status=ks::files::visitDirectoryRecords(handle.value,[&](const FILE_ID_BOTH_DIR_INFO &row,
|
||||
std::wstring_view name) -> DWORD
|
||||
{
|
||||
if(stop.stop_requested()) return ERROR_CANCELLED;
|
||||
const auto path=directory/name;
|
||||
const auto attributes=row.FileAttributes;
|
||||
const auto directoryEntry=(attributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
|
||||
if(directoryEntry && !(attributes&FILE_ATTRIBUTE_REPARSE_POINT) && indexed)
|
||||
{
|
||||
const auto id=static_cast<uint64_t>(row.FileId.QuadPart);
|
||||
if(mft.contains(id)) byPath.try_emplace(path,id);
|
||||
}
|
||||
FileInfo entry{attributes,static_cast<uint64_t>(row.EndOfFile.QuadPart),
|
||||
static_cast<uint64_t>(row.LastWriteTime.QuadPart)};
|
||||
if(!(attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT|
|
||||
FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE)) && row.AllocationSize.QuadPart>=0)
|
||||
entry.allocated=static_cast<uint64_t>(row.AllocationSize.QuadPart);
|
||||
emitted=true;
|
||||
return visit(path,entry)?ERROR_SUCCESS:ERROR_CANCELLED;
|
||||
});
|
||||
if(!emitted && (status==ERROR_NOT_SUPPORTED || status==ERROR_INVALID_PARAMETER || status==ERROR_INVALID_FUNCTION))
|
||||
{
|
||||
if(atRoot) return !stop.stop_requested() && listFiles(fallback,directory,visit);
|
||||
return listMeasuredDirectory(fallback,directory,visit,stop);
|
||||
}
|
||||
return status==ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
private:
|
||||
fs::path root;
|
||||
Handle volumeHint;
|
||||
NtfsDirectoryIds mft;
|
||||
std::map<fs::path,uint64_t> byPath;
|
||||
bool indexed{}, usedIndex{};
|
||||
};
|
||||
@@ -29,9 +29,7 @@ void orderDirectoryRows(Panel::ScanResult &result,const PanelView &view)
|
||||
const auto &metadata=result.metadata.at(path);
|
||||
const uint64_t value=view.sort==PanelSort::modified?metadata.modified:
|
||||
view.sort==PanelSort::size?metadata.size:0;
|
||||
const bool visible=(view.showHidden || !(metadata.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM))) &&
|
||||
(folder || view.mask.empty() || matchesFileMask(directoryRowName(path),view.mask));
|
||||
if(visible || path==view.revealedFile) rows.push_back({std::move(path),value,folder});
|
||||
if(visibleToPanelView(view,path,metadata)) rows.push_back({std::move(path),value,folder});
|
||||
}
|
||||
};
|
||||
append(result.folders,true);
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
class PanelRowsUpdate
|
||||
{
|
||||
public:
|
||||
PanelRowsUpdate(Panel &panel,size_t count) : panel(panel),visible(IsWindowVisible(panel.list)),
|
||||
profiles(ftpProfileList(panel))
|
||||
{
|
||||
if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0);
|
||||
panel.rows.clear();
|
||||
panel.sizes.clear();
|
||||
panel.dimmed.clear();
|
||||
panel.marked.clear();
|
||||
panel.fileExtensionLength=panel.folderExtensionLength=0;
|
||||
panel.rows.reserve(count);
|
||||
panel.sizes.reserve(count);
|
||||
panel.dimmed.reserve(count);
|
||||
panel.marked.reserve(count);
|
||||
SendMessageW(panel.list,LB_RESETCONTENT,0,0);
|
||||
SendMessageW(panel.list,LB_INITSTORAGE,count,0);
|
||||
}
|
||||
|
||||
~PanelRowsUpdate() {finish();}
|
||||
|
||||
bool add(const fs::path &path,const std::wstring &label,bool folder,bool marked,bool up=false)
|
||||
{
|
||||
if(SendMessageW(panel.list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()))<0) return false;
|
||||
panel.rows.push_back(path);
|
||||
if(!up)
|
||||
{
|
||||
const auto extension=path.extension().native();
|
||||
auto &longest=folder?panel.folderExtensionLength:panel.fileExtensionLength;
|
||||
if(extension.size()>1) longest=std::max(longest,extension.size()-1);
|
||||
}
|
||||
panel.marked.push_back(!up && marked);
|
||||
const auto found=panel.metadata.find(path);
|
||||
const auto entry=up || profiles || found==panel.metadata.end()?FolderEntryMetadata{}:found->second;
|
||||
panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0);
|
||||
panel.sizes.push_back(profiles?L"":folder?(up?L"Up":L"Folder"):std::to_wstring(entry.size));
|
||||
return true;
|
||||
}
|
||||
|
||||
void finish()
|
||||
{
|
||||
if(visible)
|
||||
{
|
||||
SendMessageW(panel.list,WM_SETREDRAW,TRUE,0);
|
||||
visible=false;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
Panel &panel;
|
||||
bool visible,profiles;
|
||||
};
|
||||
|
||||
bool treePanelActive(const Panel &panel)
|
||||
{
|
||||
return panel.view.tree && !panel.findOrigin && !panel.tree.root.empty();
|
||||
}
|
||||
|
||||
void markPanelRow(Panel &panel,size_t row,bool mark)
|
||||
{
|
||||
if(row>=panel.rows.size() || panel.sizes[row]==L"Up") return;
|
||||
panel.marked[row]=mark;
|
||||
if(!treePanelActive(panel)) return;
|
||||
const auto &path=panel.rows[row];
|
||||
if(mark) panel.tree.marks.insert(path);
|
||||
else panel.tree.marks.erase(path);
|
||||
}
|
||||
|
||||
const FolderEntryMetadata *treePanelEntry(const Panel &panel,const fs::path &path)
|
||||
{
|
||||
const auto branch=panel.tree.branches.find(path.parent_path());
|
||||
if(branch==panel.tree.branches.end()) return nullptr;
|
||||
const auto item=branch->second.metadata.find(path);
|
||||
return item==branch->second.metadata.end()?nullptr:&item->second;
|
||||
}
|
||||
|
||||
bool matchesFileMask(std::wstring_view name,std::wstring_view mask);
|
||||
|
||||
bool visibleToPanelView(const PanelView &view,const fs::path &path,const FolderEntryMetadata &metadata)
|
||||
{
|
||||
if(path==view.revealedFile) return true;
|
||||
return (view.showHidden || !(metadata.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM))) &&
|
||||
((metadata.attributes&FILE_ATTRIBUTE_DIRECTORY) || view.mask.empty() ||
|
||||
matchesFileMask(path.filename().native(),view.mask));
|
||||
}
|
||||
|
||||
template<class Visitor>
|
||||
void visitPanelMarks(const Panel &panel,const Visitor &visit)
|
||||
{
|
||||
if(treePanelActive(panel))
|
||||
{
|
||||
for(const auto &path:panel.tree.marks)
|
||||
{
|
||||
const auto entry=treePanelEntry(panel,path);
|
||||
if(!entry || !visibleToPanelView(panel.view,path,*entry)) continue;
|
||||
auto directory=path.parent_path();
|
||||
while(directory!=panel.tree.root)
|
||||
{
|
||||
const auto parent=treePanelEntry(panel,directory);
|
||||
const auto ancestor=directory.parent_path();
|
||||
if(!parent || ancestor==directory || !visibleToPanelView(panel.view,directory,*parent)) break;
|
||||
directory=ancestor;
|
||||
}
|
||||
if(directory==panel.tree.root) visit(path,*entry);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(ftpProfileList(panel)) return;
|
||||
for(size_t i=0;i<panel.rows.size();++i)
|
||||
{
|
||||
if(!panel.marked[i] || panel.sizes[i]==L"Up") continue;
|
||||
if(const auto item=panel.metadata.find(panel.rows[i]);item!=panel.metadata.end())
|
||||
visit(item->first,item->second);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
void stopTreeBranches(Panel &panel)
|
||||
{
|
||||
for(auto &[path,branch]:panel.tree.branches) branch.stop.request_stop();
|
||||
panel.tree={};
|
||||
}
|
||||
|
||||
bool canExpandTreeEntry(const FolderEntryMetadata &entry)
|
||||
{
|
||||
return (entry.attributes&FILE_ATTRIBUTE_DIRECTORY) && !(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT);
|
||||
}
|
||||
|
||||
void startPendingTreeScans(Panel &panel)
|
||||
{
|
||||
if(!treePanelActive(panel)) return;
|
||||
auto running=std::count_if(panel.tree.branches.begin(),panel.tree.branches.end(),
|
||||
[](const auto &item){return item.second.scan.valid();});
|
||||
for(auto &[path,branch]:panel.tree.branches)
|
||||
{
|
||||
if(running>=2) break;
|
||||
if(!branch.expanded || !branch.needsScan || branch.scan.valid() || path==panel.tree.root) continue;
|
||||
branch.needsScan=false;
|
||||
const auto entry=treePanelEntry(panel,path);
|
||||
if(!entry || !canExpandTreeEntry(*entry)) continue;
|
||||
branch.stop=std::stop_source{};
|
||||
Panel::ScanRequest request{.directory=path,.peer=panel.peer,.ftp=panel.ftp};
|
||||
try
|
||||
{
|
||||
branch.scan=scanDirectoryInBackground(GetParent(panel.list),std::move(request),panel.view,
|
||||
std::make_shared<std::atomic_size_t>(0),branch.stop.get_token());
|
||||
++running;
|
||||
}
|
||||
catch(const std::exception &) {branch.failed=true;}
|
||||
}
|
||||
}
|
||||
|
||||
void refreshTreeBranches(Panel &panel)
|
||||
{
|
||||
if(!treePanelActive(panel)) return;
|
||||
for(auto &[path,branch]:panel.tree.branches)
|
||||
if(branch.expanded && path!=panel.tree.root) branch.needsScan=true;
|
||||
startPendingTreeScans(panel);
|
||||
}
|
||||
|
||||
void replaceTreeRoot(Panel &panel,Panel::ScanResult &scan,bool sameDirectory,const std::set<fs::path> &marks)
|
||||
{
|
||||
auto directory=folderPathWithoutSeparator(panel.directory);
|
||||
if(!sameDirectory || panel.tree.root!=directory) stopTreeBranches(panel);
|
||||
panel.tree.root=std::move(directory);
|
||||
auto &root=panel.tree.branches[panel.tree.root];
|
||||
root.expanded=root.loaded=true;
|
||||
root.ordered=std::move(scan.ordered);
|
||||
root.metadata=std::move(scan.metadata);
|
||||
panel.tree.marks.insert(marks.begin(),marks.end());
|
||||
if(scan.error!=ERROR_CANCELLED)
|
||||
std::erase_if(panel.tree.marks,[&](const auto &path) {
|
||||
return path.parent_path()==panel.tree.root && !root.metadata.contains(path);
|
||||
});
|
||||
refreshTreeBranches(panel);
|
||||
}
|
||||
|
||||
void pruneTreeMarks(Panel &panel,const std::set<fs::path> &removed)
|
||||
{
|
||||
if(!treePanelActive(panel) || removed.empty()) return;
|
||||
std::erase_if(panel.tree.marks,[&](auto path) {
|
||||
for(;path!=panel.tree.root && path!=path.parent_path();path=path.parent_path())
|
||||
if(removed.contains(path)) return true;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
std::wstring treeRowPrefix(const Panel &panel,const fs::path &path,bool folder)
|
||||
{
|
||||
const auto depth=panel.tree.depths.find(path);
|
||||
if(depth==panel.tree.depths.end()) return {};
|
||||
std::wstring prefix(2*std::min<size_t>(depth->second,40),L' ');
|
||||
if(!folder) return prefix+L" ";
|
||||
const auto branch=panel.tree.branches.find(path);
|
||||
if(branch!=panel.tree.branches.end())
|
||||
{
|
||||
if(branch->second.scan.valid() || branch->second.needsScan) return prefix+L"… ";
|
||||
if(branch->second.expanded) return prefix+(branch->second.failed?L"! ":L"▾ ");
|
||||
}
|
||||
if(const auto entry=treePanelEntry(panel,path);entry && canExpandTreeEntry(*entry)) return prefix+L"▸ ";
|
||||
return prefix+L" ";
|
||||
}
|
||||
|
||||
void appendTreeRows(Panel &panel,PanelRowsUpdate &rows)
|
||||
{
|
||||
panel.tree.depths.clear();
|
||||
panel.metadata.clear();
|
||||
struct BranchRows {const Panel::TreeBranch *branch; size_t next;};
|
||||
std::vector<BranchRows> stack{{&panel.tree.branches.at(panel.tree.root),0}};
|
||||
while(!stack.empty())
|
||||
{
|
||||
auto ¤t=stack.back();
|
||||
if(current.next==current.branch->ordered.size())
|
||||
{
|
||||
stack.pop_back();
|
||||
continue;
|
||||
}
|
||||
const auto &entry=current.branch->ordered[current.next++];
|
||||
const auto &path=entry.path;
|
||||
panel.tree.depths.emplace(path,stack.size()-1);
|
||||
const auto metadata=current.branch->metadata.find(path);
|
||||
if(metadata==current.branch->metadata.end() || !visibleToPanelView(panel.view,path,metadata->second)) continue;
|
||||
panel.metadata.emplace(path,metadata->second);
|
||||
const auto label=treeRowPrefix(panel,path,entry.folder)+path.filename().native();
|
||||
rows.add(path,label,entry.folder,panel.tree.marks.contains(path));
|
||||
const auto child=panel.tree.branches.find(path);
|
||||
if(entry.folder && child!=panel.tree.branches.end() && child->second.expanded && child->second.loaded)
|
||||
stack.push_back({&child->second,0});
|
||||
}
|
||||
}
|
||||
|
||||
void redrawTreeRows(Panel &panel)
|
||||
{
|
||||
if(!treePanelActive(panel)) return;
|
||||
const auto current=SendMessageW(panel.list,LB_GETCURSEL,0,0);
|
||||
const auto top=SendMessageW(panel.list,LB_GETTOPINDEX,0,0);
|
||||
auto selected=current>=0 && static_cast<size_t>(current)<panel.rows.size()?panel.rows[current]:fs::path{};
|
||||
const auto parent=panelParentPath(panel.directory,!panel.peer && !panel.ftp);
|
||||
PanelRowsUpdate rows(panel,panel.rows.size());
|
||||
if(!parent.empty()) rows.add(parent,L"..",true,false,true);
|
||||
appendTreeRows(panel,rows);
|
||||
auto position=std::find(panel.rows.begin(),panel.rows.end(),selected);
|
||||
while(position==panel.rows.end() && !selected.empty() && selected!=panel.tree.root)
|
||||
{
|
||||
const auto next=selected.parent_path();
|
||||
if(next==selected) break;
|
||||
selected=next;
|
||||
position=std::find(panel.rows.begin(),panel.rows.end(),selected);
|
||||
}
|
||||
if(!panel.rows.empty())
|
||||
{
|
||||
SendMessageW(panel.list,LB_SETTOPINDEX,top,0);
|
||||
SendMessageW(panel.list,LB_SETCURSEL,position==panel.rows.end()?
|
||||
std::clamp<LRESULT>(current,0,panel.rows.size()-1):position-panel.rows.begin(),0);
|
||||
}
|
||||
rows.finish();
|
||||
InvalidateRect(panel.list,nullptr,FALSE);
|
||||
InvalidateRect(panel.heading,nullptr,FALSE);
|
||||
updateSelectionSummary(panel);
|
||||
refreshQuickView(panel);
|
||||
}
|
||||
|
||||
void collectTreeBranches()
|
||||
{
|
||||
for(auto &panel:panels)
|
||||
{
|
||||
if(!treePanelActive(panel)) continue;
|
||||
bool updated=false;
|
||||
for(auto &[path,branch]:panel.tree.branches)
|
||||
{
|
||||
if(!branch.scan.valid() || branch.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready) continue;
|
||||
updated=true;
|
||||
try
|
||||
{
|
||||
auto scan=branch.scan.get();
|
||||
const auto error=scan->error;
|
||||
branch.failed=!scan->opened || !scan->failure.empty() ||
|
||||
(error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND);
|
||||
if(scan->opened && scan->failure.empty())
|
||||
{
|
||||
branch.loaded=true;
|
||||
branch.ordered=std::move(scan->ordered);
|
||||
branch.metadata=std::move(scan->metadata);
|
||||
if(!branch.failed) std::erase_if(panel.tree.marks,[&](const auto &marked) {
|
||||
return marked.parent_path()==path && !branch.metadata.contains(marked);
|
||||
});
|
||||
}
|
||||
}
|
||||
catch(const std::exception &) {branch.failed=true;}
|
||||
if(branch.failed && &panel==&panels[active] && branch.expanded)
|
||||
setStatus(L"Could not read tree folder: "+path.native());
|
||||
}
|
||||
if(updated)
|
||||
{
|
||||
startPendingTreeScans(panel);
|
||||
redrawTreeRows(panel);
|
||||
queueAutomaticPanelSizes(panel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool toggleTreeRow(Panel &panel,size_t row,std::optional<bool> expanded={})
|
||||
{
|
||||
if(!treePanelActive(panel) || row>=panel.rows.size() || panel.sizes[row]!=L"Folder") return false;
|
||||
const auto path=panel.rows[row];
|
||||
const auto entry=treePanelEntry(panel,path);
|
||||
if(!entry || !canExpandTreeEntry(*entry)) return false;
|
||||
auto &branch=panel.tree.branches[path];
|
||||
const auto next=expanded.value_or(!branch.expanded);
|
||||
if(next==branch.expanded) return false;
|
||||
branch.expanded=next;
|
||||
if(next)
|
||||
{
|
||||
branch.needsScan=true;
|
||||
startPendingTreeScans(panel);
|
||||
}
|
||||
else branch.needsScan=false;
|
||||
redrawTreeRows(panel);
|
||||
if(&panel==&panels[active])
|
||||
{
|
||||
if(next && branch.scan.valid()) setStatus(L"Reading tree folder: "+path.native());
|
||||
else showFileDetails(panel);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool moveTreeCursor(Panel &panel,bool forward)
|
||||
{
|
||||
if(!treePanelActive(panel)) return false;
|
||||
const auto position=SendMessageW(panel.list,LB_GETCURSEL,0,0);
|
||||
if(position<0 || static_cast<size_t>(position)>=panel.rows.size() || panel.sizes[position]==L"Up") return false;
|
||||
if(toggleTreeRow(panel,static_cast<size_t>(position),forward)) return true;
|
||||
const auto &path=panel.rows[position];
|
||||
if(forward)
|
||||
{
|
||||
if(static_cast<size_t>(position+1)<panel.rows.size() && panel.rows[position+1].parent_path()==path)
|
||||
SendMessageW(panel.list,LB_SETCURSEL,position+1,0);
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto parent=std::find(panel.rows.begin(),panel.rows.end(),path.parent_path());
|
||||
if(parent!=panel.rows.end()) SendMessageW(panel.list,LB_SETCURSEL,parent-panel.rows.begin(),0);
|
||||
}
|
||||
invalidatePanelCursorChange(panel.list,position);
|
||||
return true;
|
||||
}
|
||||
+296
-31
@@ -1,12 +1,96 @@
|
||||
constexpr int spacePath=488,spaceTree=489,spaceStatus=490,spaceFooter=491;
|
||||
constexpr int spaceStop=492,spaceRescan=493,spaceView=494;
|
||||
constexpr int spaceCapacity=495,spaceScope=496,spaceMapButton=497,spaceMap=498;
|
||||
constexpr int spaceSunburstButton=499,spaceSunburstList=500,spaceSunburstLabel=501;
|
||||
constexpr UINT_PTR spaceUpdateTimer=1;
|
||||
constexpr UINT_PTR spaceVolumeTimer=2;
|
||||
constexpr size_t spaceBatchSize=256;
|
||||
constexpr std::initializer_list<int> spaceFooterButtons{spaceStop,spaceRescan,spaceView,IDOK,IDCANCEL};
|
||||
|
||||
struct SpaceVolume
|
||||
{
|
||||
fs::path root;
|
||||
std::optional<std::pair<uint64_t,uint64_t>> capacity;
|
||||
};
|
||||
|
||||
std::future<SpaceVolume> readSpaceVolume(const fs::path &folder)
|
||||
{
|
||||
std::packaged_task<SpaceVolume()> task([folder] {
|
||||
SpaceVolume result;
|
||||
std::wstring root(32768,L'\0');
|
||||
if(GetVolumePathNameW(folder.c_str(),root.data(),static_cast<DWORD>(root.size())))
|
||||
{
|
||||
root.resize(wcslen(root.c_str()));
|
||||
result.root=fs::path(std::move(root));
|
||||
}
|
||||
ULARGE_INTEGER total{},free{};
|
||||
if(GetDiskFreeSpaceExW(result.root.empty()?folder.c_str():result.root.c_str(),&free,&total,nullptr))
|
||||
result.capacity=std::pair{total.QuadPart,free.QuadPart};
|
||||
return result;
|
||||
});
|
||||
auto result=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
return result;
|
||||
}
|
||||
|
||||
std::optional<uint64_t> allocatedFileBytes(const fs::path &path,DWORD attributes)
|
||||
{
|
||||
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
|
||||
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
|
||||
if(file.value==INVALID_HANDLE_VALUE) return {};
|
||||
if(attributes&(FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE))
|
||||
{
|
||||
FILE_COMPRESSION_INFO compression{};
|
||||
if(GetFileInformationByHandleEx(file.value,FileCompressionInfo,&compression,sizeof(compression)) &&
|
||||
compression.CompressedFileSize.QuadPart>=0)
|
||||
return static_cast<uint64_t>(compression.CompressedFileSize.QuadPart);
|
||||
return {};
|
||||
}
|
||||
FILE_STANDARD_INFO metadata{};
|
||||
if(GetFileInformationByHandleEx(file.value,FileStandardInfo,&metadata,sizeof(metadata)) &&
|
||||
!metadata.Directory && metadata.AllocationSize.QuadPart>=0)
|
||||
return static_cast<uint64_t>(metadata.AllocationSize.QuadPart);
|
||||
return {};
|
||||
}
|
||||
|
||||
struct SpaceAllocation
|
||||
{
|
||||
FolderSize known;
|
||||
size_t measured{}, unavailable{};
|
||||
|
||||
void add(std::optional<uint64_t> size)
|
||||
{
|
||||
if(size)
|
||||
{
|
||||
++measured;
|
||||
known.add(*size);
|
||||
}
|
||||
else ++unavailable;
|
||||
}
|
||||
};
|
||||
|
||||
struct SpaceTile
|
||||
{
|
||||
RECT box;
|
||||
size_t node;
|
||||
};
|
||||
|
||||
#include "files_ntfs_space.inl"
|
||||
|
||||
struct SpaceSector
|
||||
{
|
||||
size_t node;
|
||||
unsigned ring;
|
||||
double start,end;
|
||||
};
|
||||
|
||||
enum class SpaceDisplay { tree, treemap, sunburst };
|
||||
|
||||
struct SpaceEvent
|
||||
{
|
||||
fs::path path;
|
||||
std::optional<FileInfo> item;
|
||||
std::optional<uint64_t> allocated;
|
||||
};
|
||||
|
||||
struct SpaceRun
|
||||
@@ -15,13 +99,13 @@ struct SpaceRun
|
||||
std::mutex mutex;
|
||||
std::deque<std::vector<SpaceEvent>> pending;
|
||||
FolderSize result;
|
||||
bool finished{}, stopped{};
|
||||
bool finished{}, stopped{}, indexed{};
|
||||
};
|
||||
|
||||
std::shared_ptr<SpaceRun> startSpaceRun(const fs::path &root)
|
||||
std::shared_ptr<SpaceRun> startSpaceRun(const fs::path &root,const fs::path &mount)
|
||||
{
|
||||
auto run=std::make_shared<SpaceRun>();
|
||||
std::thread([run,root] {
|
||||
std::thread([run,root,mount] {
|
||||
std::vector<SpaceEvent> batch;
|
||||
auto lastUpdate=GetTickCount64();
|
||||
const auto publish=[&] {
|
||||
@@ -36,10 +120,28 @@ std::shared_ptr<SpaceRun> startSpaceRun(const fs::path &root)
|
||||
try
|
||||
{
|
||||
FilesConnection host(nullptr);
|
||||
const bool volume=!mount.empty();
|
||||
std::optional<NtfsSpaceWalk> ntfs;
|
||||
if(volume && isNtfsVolume(mount)) ntfs.emplace(root,mount,stop);
|
||||
bool indexReported=false;
|
||||
total=measureFolder(root,stop,[&](const fs::path &directory,const FileVisitor &visit) {
|
||||
if(ntfs)
|
||||
{
|
||||
const auto result=ntfs->list(directory,visit,stop,host);
|
||||
if(!indexReported && ntfs->usedMft())
|
||||
{
|
||||
std::lock_guard lock(run->mutex);
|
||||
run->indexed=indexReported=true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if(volume && directory==root) return !stop.stop_requested() && listFiles(host,directory,visit);
|
||||
return listMeasuredDirectory(host,directory,visit,stop);
|
||||
},[&](const fs::path &path,const FileInfo *info) {
|
||||
batch.push_back({path,info?std::optional<FileInfo>(*info):std::nullopt});
|
||||
const auto allocate=info && !(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT));
|
||||
const auto allocation=allocate?(info->allocated?info->allocated:allocatedFileBytes(path,info->attributes)):
|
||||
std::nullopt;
|
||||
batch.push_back({path,info?std::optional<FileInfo>(*info):std::nullopt,allocation});
|
||||
if(batch.size()>=spaceBatchSize || GetTickCount64()-lastUpdate>=80) publish();
|
||||
});
|
||||
publish();
|
||||
@@ -57,6 +159,7 @@ struct SpaceNode
|
||||
{
|
||||
fs::path path;
|
||||
FolderSize size;
|
||||
SpaceAllocation allocated;
|
||||
size_t parent{};
|
||||
std::vector<size_t> children;
|
||||
HTREEITEM item{};
|
||||
@@ -65,13 +168,19 @@ struct SpaceNode
|
||||
|
||||
struct SpaceAnalyzer
|
||||
{
|
||||
fs::path root, selected;
|
||||
bool selectedFolder{};
|
||||
fs::path folder, root, selected;
|
||||
SpaceVolume volume;
|
||||
std::future<SpaceVolume> pendingVolume;
|
||||
bool selectedFolder{}, volumeScope{};
|
||||
SpaceDisplay display{SpaceDisplay::tree};
|
||||
std::shared_ptr<SpaceRun> run;
|
||||
std::vector<SpaceNode> nodes;
|
||||
std::map<fs::path,size_t> directories;
|
||||
size_t files{};
|
||||
bool scanning{};
|
||||
size_t files{}, mapFolder{}, selectedTile{};
|
||||
std::vector<SpaceTile> tiles;
|
||||
std::vector<SpaceSector> sectors;
|
||||
ULONGLONG lastMapUpdate{};
|
||||
bool scanning{}, hasResults{};
|
||||
};
|
||||
|
||||
void layoutSpaceAnalyzer(HWND dialog)
|
||||
@@ -86,12 +195,37 @@ void layoutSpaceAnalyzer(HWND dialog)
|
||||
};
|
||||
auto top=dialogListInset(frame,textHeight);
|
||||
place(spacePath,top,textHeight);
|
||||
top+=textHeight;
|
||||
place(spaceCapacity,top,textHeight);
|
||||
top+=textHeight+dialogRowGap();
|
||||
const auto buttonHeight=textHeight;
|
||||
auto x=inset;
|
||||
for(const auto id:{spaceScope,spaceMapButton,spaceSunburstButton})
|
||||
{
|
||||
const auto button=GetDlgItem(dialog,id);
|
||||
const auto width=std::max(12L*cellWidth,farDialogButtonWidth(button));
|
||||
SetWindowPos(button,nullptr,x,top,width,buttonHeight,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
x+=width+dialogColumnGap();
|
||||
}
|
||||
top+=buttonHeight+dialogRowGap();
|
||||
place(spaceTree,top,9*textHeight);
|
||||
const auto state=reinterpret_cast<const SpaceAnalyzer *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(state && state->display==SpaceDisplay::sunburst)
|
||||
{
|
||||
const auto graphWidth=width*3/5;
|
||||
const auto gap=dialogColumnGap();
|
||||
SetWindowPos(GetDlgItem(dialog,spaceSunburstLabel),nullptr,inset+graphWidth,top-textHeight-dialogRowGap(),
|
||||
width-graphWidth,textHeight,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
SetWindowPos(GetDlgItem(dialog,spaceMap),nullptr,inset,top,graphWidth-gap,9*textHeight,
|
||||
SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
SetWindowPos(GetDlgItem(dialog,spaceSunburstList),nullptr,inset+graphWidth,top,width-graphWidth,
|
||||
9*textHeight,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
}
|
||||
else place(spaceMap,top,9*textHeight);
|
||||
top+=9*textHeight+dialogRowGap();
|
||||
place(spaceStatus,top,textHeight);
|
||||
place(spaceFooter,top+textHeight+dialogRowGap(),1);
|
||||
layoutDialogButtons(dialog,spaceFooter,{spaceStop,spaceRescan,spaceView,IDOK,IDCANCEL});
|
||||
layoutDialogButtons(dialog,spaceFooter,spaceFooterButtons);
|
||||
}
|
||||
|
||||
HTREEITEM insertSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index)
|
||||
@@ -139,6 +273,7 @@ void addSpaceEvent(HWND tree,SpaceAnalyzer &state,SpaceEvent event)
|
||||
else ++state.files;
|
||||
state.nodes.push_back({.path=std::move(event.path),.size={bytes,false},.parent=parent->second,
|
||||
.folder=folder,.link=link});
|
||||
if(!folder && !link) state.nodes[index].allocated.add(event.allocated);
|
||||
auto &parentNode=state.nodes[parent->second];
|
||||
parentNode.children.push_back(index);
|
||||
if(parentNode.item && parentNode.expanded)
|
||||
@@ -149,10 +284,25 @@ void addSpaceEvent(HWND tree,SpaceAnalyzer &state,SpaceEvent event)
|
||||
for(auto i=parent->second;;i=state.nodes[i].parent)
|
||||
{
|
||||
state.nodes[i].size.add(bytes);
|
||||
if(!folder && !link) state.nodes[i].allocated.add(event.allocated);
|
||||
if(!i) break;
|
||||
}
|
||||
}
|
||||
|
||||
std::wstring spaceLogicalSize(const SpaceNode &node)
|
||||
{
|
||||
return formatSize(node.size.bytes)+(node.size.partial?L"+ logical":L" logical");
|
||||
}
|
||||
|
||||
std::wstring spaceAllocatedSize(const SpaceNode &node)
|
||||
{
|
||||
const auto &allocation=node.allocated;
|
||||
if(!allocation.measured && allocation.unavailable) return L"— on disk";
|
||||
auto result=formatSize(allocation.known.bytes);
|
||||
if(allocation.unavailable || allocation.known.partial || node.size.partial) result+=L"+";
|
||||
return result+L" on disk";
|
||||
}
|
||||
|
||||
std::wstring spaceNodeText(const SpaceAnalyzer &state,size_t index)
|
||||
{
|
||||
const auto &node=state.nodes[index];
|
||||
@@ -165,9 +315,9 @@ std::wstring spaceNodeText(const SpaceAnalyzer &state,size_t index)
|
||||
if(name.back()>=0xD800 && name.back()<=0xDBFF) name.pop_back();
|
||||
name+=L"…";
|
||||
}
|
||||
if(!state.hasResults) return name;
|
||||
if(node.link) return name+L" [link]";
|
||||
auto result=name+L" — "+formatSize(node.size.bytes);
|
||||
if(node.size.partial) result+=L"+";
|
||||
auto result=name+L" — "+spaceLogicalSize(node)+L" · "+spaceAllocatedSize(node);
|
||||
if(parent.size.bytes)
|
||||
{
|
||||
wchar_t share[48]{};
|
||||
@@ -187,16 +337,19 @@ std::optional<size_t> selectedSpaceNode(HWND tree,const SpaceAnalyzer &state)
|
||||
return {};
|
||||
}
|
||||
|
||||
#include "files_space_map.inl"
|
||||
|
||||
void updateSpaceTree(HWND dialog,SpaceAnalyzer &state)
|
||||
{
|
||||
const auto tree=GetDlgItem(dialog,spaceTree);
|
||||
const auto budget=GetTickCount64()+15;
|
||||
bool finished=false,stopped=false,changed=false;
|
||||
bool finished=false,stopped=false,changed=false,indexed=false;
|
||||
do
|
||||
{
|
||||
std::vector<SpaceEvent> batch;
|
||||
{
|
||||
std::lock_guard lock(state.run->mutex);
|
||||
indexed=state.run->indexed;
|
||||
if(!state.run->pending.empty())
|
||||
{
|
||||
batch=std::move(state.run->pending.front());
|
||||
@@ -216,21 +369,31 @@ void updateSpaceTree(HWND dialog,SpaceAnalyzer &state)
|
||||
} while(GetTickCount64()<budget);
|
||||
if(finished) state.scanning=false;
|
||||
if(changed) SendMessageW(tree,WM_SETREDRAW,TRUE,0);
|
||||
if(state.display!=SpaceDisplay::tree && (finished || (changed && GetTickCount64()-state.lastMapUpdate>=200)))
|
||||
refreshSpaceChart(GetDlgItem(dialog,spaceMap),state);
|
||||
if(changed || finished) InvalidateRect(tree,nullptr,FALSE);
|
||||
|
||||
const bool stopping=state.run->stop.stop_requested();
|
||||
auto status=finished?(stopped?L"Stopped · partial":state.nodes[0].size.partial?L"Partial results":L"Complete"):
|
||||
stopping?L"Stopping…":L"Scanning…";
|
||||
SetDlgItemTextW(dialog,spaceStatus,(std::wstring(status)+L" · "+std::to_wstring(state.files)+L" files · shares of parent").c_str());
|
||||
const auto &allocation=state.nodes[0].allocated;
|
||||
auto label=std::wstring(status)+L" · "+std::to_wstring(state.files)+L" files";
|
||||
if(indexed) label+=L" · NTFS index";
|
||||
if(allocation.unavailable || allocation.known.partial) label+=L" · on-disk sizes partial";
|
||||
else label+=state.display==SpaceDisplay::treemap?L" · logical size by area":
|
||||
state.display==SpaceDisplay::sunburst?L" · logical size by angle":L" · logical shares of parent";
|
||||
SetDlgItemTextW(dialog,spaceStatus,label.c_str());
|
||||
if(finished)
|
||||
{
|
||||
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() &&
|
||||
!sameVolumeRoot(state.folder,state.volume.root));
|
||||
KillTimer(dialog,spaceUpdateTimer);
|
||||
}
|
||||
}
|
||||
|
||||
void rescanSpace(HWND dialog,SpaceAnalyzer &state)
|
||||
void resetSpaceResults(HWND dialog,SpaceAnalyzer &state,bool scanning)
|
||||
{
|
||||
const auto tree=GetDlgItem(dialog,spaceTree);
|
||||
TreeView_DeleteAllItems(tree);
|
||||
@@ -239,13 +402,62 @@ void rescanSpace(HWND dialog,SpaceAnalyzer &state)
|
||||
state.directories.clear();
|
||||
state.directories.emplace(state.root,0);
|
||||
state.files=0;
|
||||
state.scanning=true;
|
||||
state.mapFolder=0;
|
||||
state.tiles.clear();
|
||||
state.sectors.clear();
|
||||
state.selectedTile=0;
|
||||
state.scanning=scanning;
|
||||
state.hasResults=scanning;
|
||||
TreeView_SelectItem(tree,insertSpaceNode(tree,state,0));
|
||||
if(state.display!=SpaceDisplay::tree) refreshSpaceChart(GetDlgItem(dialog,spaceMap),state);
|
||||
EnableWindow(GetDlgItem(dialog,spaceView),FALSE);
|
||||
EnableWindow(GetDlgItem(dialog,IDOK),state.display==SpaceDisplay::tree);
|
||||
}
|
||||
|
||||
void prepareSpaceScope(HWND dialog,SpaceAnalyzer &state)
|
||||
{
|
||||
state.run.reset();
|
||||
const auto scope=state.volumeScope?state.volume.root:state.folder;
|
||||
state.root=folderPathWithoutSeparator(scope);
|
||||
SetDlgItemTextW(dialog,spacePath,scope.c_str());
|
||||
SetDlgItemTextW(dialog,spaceScope,state.volumeScope?L"&Folder":L"Vo&lume");
|
||||
SetDlgItemTextW(dialog,spaceRescan,L"St&art");
|
||||
SetDlgItemTextW(dialog,spaceStatus,L"Ready to scan");
|
||||
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
|
||||
resetSpaceResults(dialog,state,false);
|
||||
layoutSpaceAnalyzer(dialog);
|
||||
}
|
||||
|
||||
void updateSpaceVolume(HWND dialog,SpaceAnalyzer &state)
|
||||
{
|
||||
if(!state.pendingVolume.valid() ||
|
||||
state.pendingVolume.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
|
||||
try {state.volume=state.pendingVolume.get();}
|
||||
catch(const std::exception &) {}
|
||||
KillTimer(dialog,spaceVolumeTimer);
|
||||
std::wstring caption=L"Volume capacity unavailable";
|
||||
if(const auto capacity=state.volume.capacity)
|
||||
{
|
||||
caption=L"Capacity "+formatSize(capacity->first)+L" · Free "+formatSize(capacity->second);
|
||||
if(!state.volume.root.empty()) caption+=L" · "+state.volume.root.native();
|
||||
}
|
||||
SetDlgItemTextW(dialog,spaceCapacity,caption.c_str());
|
||||
EnableWindow(GetDlgItem(dialog,spaceScope),
|
||||
!state.volume.root.empty() && !sameVolumeRoot(state.folder,state.volume.root));
|
||||
prepareSpaceScope(dialog,state);
|
||||
}
|
||||
|
||||
void rescanSpace(HWND dialog,SpaceAnalyzer &state)
|
||||
{
|
||||
resetSpaceResults(dialog,state,true);
|
||||
SetDlgItemTextW(dialog,spaceRescan,L"&Rescan");
|
||||
EnableWindow(GetDlgItem(dialog,spaceRescan),FALSE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceScope),FALSE);
|
||||
try
|
||||
{
|
||||
state.run=startSpaceRun(state.root);
|
||||
const bool volume=state.volumeScope || sameVolumeRoot(state.root,state.volume.root);
|
||||
state.run=startSpaceRun(state.root,volume?state.volume.root:fs::path{});
|
||||
EnableWindow(GetDlgItem(dialog,spaceStop),TRUE);
|
||||
SetTimer(dialog,spaceUpdateTimer,60,nullptr);
|
||||
updateSpaceTree(dialog,state);
|
||||
@@ -255,7 +467,9 @@ void rescanSpace(HWND dialog,SpaceAnalyzer &state)
|
||||
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
|
||||
state.scanning=false;
|
||||
SetDlgItemTextW(dialog,spaceStatus,L"Could not start folder analysis.");
|
||||
EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() &&
|
||||
!sameVolumeRoot(state.folder,state.volume.root));
|
||||
SetDlgItemTextW(dialog,spaceStatus,L"Could not start space analysis.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,21 +480,52 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l
|
||||
auto &state=*reinterpret_cast<SpaceAnalyzer *>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
SetDlgItemTextW(dialog,spacePath,state.root.c_str());
|
||||
SetDlgItemTextW(dialog,spacePath,state.folder.c_str());
|
||||
SetDlgItemTextW(dialog,spaceCapacity,L"Reading volume capacity…");
|
||||
const auto tree=GetDlgItem(dialog,spaceTree);
|
||||
SetWindowSubclass(GetDlgItem(dialog,spaceMap),spaceMapInput,1,reinterpret_cast<DWORD_PTR>(&state));
|
||||
SetWindowSubclass(GetDlgItem(dialog,spaceSunburstList),spaceSunburstListKeys,1,reinterpret_cast<DWORD_PTR>(&state));
|
||||
TreeView_SetBkColor(tree,RGB(255,255,255));
|
||||
TreeView_SetTextColor(tree,RGB(0,0,0));
|
||||
layoutSpaceAnalyzer(dialog);
|
||||
const auto inset=dialogFrameMetrics(GetDpiForWindow(dialog)).content();
|
||||
FilesModalDialog::fitWidthToOwner(dialog,54*cellWidth+2*inset,layoutSpaceAnalyzer);
|
||||
// Rescan is one character wider than the initial Start label.
|
||||
const auto minimum=dialogButtonGroupWidth(dialog,spaceFooterButtons)+cellWidth+2*inset;
|
||||
FilesModalDialog::fitWidthToOwner(dialog,minimum,layoutSpaceAnalyzer);
|
||||
SendMessageW(dialog,DM_SETDEFID,IDCANCEL,0);
|
||||
rescanSpace(dialog,state);
|
||||
resetSpaceResults(dialog,state,false);
|
||||
EnableWindow(GetDlgItem(dialog,spaceScope),FALSE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceRescan),FALSE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
|
||||
try
|
||||
{
|
||||
state.pendingVolume=readSpaceVolume(state.folder);
|
||||
SetTimer(dialog,spaceVolumeTimer,60,nullptr);
|
||||
updateSpaceVolume(dialog,state);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
SetDlgItemTextW(dialog,spaceCapacity,L"Volume capacity unavailable");
|
||||
prepareSpaceScope(dialog,state);
|
||||
}
|
||||
SetFocus(tree);
|
||||
return FALSE;
|
||||
}
|
||||
const auto state=reinterpret_cast<SpaceAnalyzer *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!state) return FALSE;
|
||||
const auto tree=GetDlgItem(dialog,spaceTree);
|
||||
if(message==WM_DRAWITEM && wp==spaceMap)
|
||||
{
|
||||
const auto &paint=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
|
||||
if(state->display==SpaceDisplay::sunburst) paintSunburst(paint,*state);
|
||||
else paintSpaceMap(paint,*state);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_TIMER && wp==spaceVolumeTimer)
|
||||
{
|
||||
updateSpaceVolume(dialog,*state);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_TIMER && wp==spaceUpdateTimer)
|
||||
{
|
||||
updateSpaceTree(dialog,*state);
|
||||
@@ -315,8 +560,11 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l
|
||||
if(notification->code==TVN_SELCHANGEDW)
|
||||
{
|
||||
const auto selected=selectedSpaceNode(tree,*state);
|
||||
EnableWindow(GetDlgItem(dialog,spaceView),selected && !state->nodes[*selected].folder);
|
||||
EnableWindow(GetDlgItem(dialog,IDOK),selected.has_value());
|
||||
if(state->display==SpaceDisplay::tree)
|
||||
{
|
||||
EnableWindow(GetDlgItem(dialog,spaceView),selected && !state->nodes[*selected].folder);
|
||||
EnableWindow(GetDlgItem(dialog,IDOK),selected.has_value());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -330,6 +578,27 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l
|
||||
updateSpaceTree(dialog,*state);
|
||||
return TRUE;
|
||||
}
|
||||
if(command==spaceScope && IsWindowEnabled(GetDlgItem(dialog,spaceScope)))
|
||||
{
|
||||
state->volumeScope=!state->volumeScope;
|
||||
prepareSpaceScope(dialog,*state);
|
||||
return TRUE;
|
||||
}
|
||||
if(command==spaceMapButton || command==spaceSunburstButton)
|
||||
{
|
||||
const auto chart=command==spaceMapButton?SpaceDisplay::treemap:SpaceDisplay::sunburst;
|
||||
setSpaceDisplay(dialog,*state,state->display==chart?SpaceDisplay::tree:chart);
|
||||
if(state->run) updateSpaceTree(dialog,*state);
|
||||
return TRUE;
|
||||
}
|
||||
if(command==spaceSunburstList && state->display==SpaceDisplay::sunburst)
|
||||
{
|
||||
updateSunburstSelection(dialog,*state);
|
||||
if(HIWORD(wp)==LBN_DBLCLK)
|
||||
if(const auto selected=sunburstSelection(dialog,*state))
|
||||
finishSpaceSelection(dialog,*state,*selected,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
if(command==spaceRescan && IsWindowEnabled(GetDlgItem(dialog,spaceRescan)))
|
||||
{
|
||||
rescanSpace(dialog,*state);
|
||||
@@ -337,14 +606,9 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l
|
||||
}
|
||||
if(command==IDOK || command==spaceView)
|
||||
{
|
||||
if(const auto selected=selectedSpaceNode(tree,*state))
|
||||
{
|
||||
const auto &node=state->nodes[*selected];
|
||||
if(command==spaceView && node.folder) return TRUE;
|
||||
state->selected=node.path;
|
||||
state->selectedFolder=node.folder;
|
||||
FilesModalDialog::finish(dialog,command);
|
||||
}
|
||||
const auto selected=state->display==SpaceDisplay::sunburst?sunburstSelection(dialog,*state):
|
||||
state->display==SpaceDisplay::tree?selectedSpaceNode(tree,*state):std::nullopt;
|
||||
if(selected) finishSpaceSelection(dialog,*state,*selected,command);
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
@@ -357,6 +621,7 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l
|
||||
{
|
||||
if(state->run) state->run->stop.request_stop();
|
||||
KillTimer(dialog,spaceUpdateTimer);
|
||||
KillTimer(dialog,spaceVolumeTimer);
|
||||
}
|
||||
return paintCopyDialog(dialog,message,wp,lp,L" Space Analyzer ",false,{spaceFooter});
|
||||
}
|
||||
@@ -369,7 +634,7 @@ void openSpaceAnalyzer(HWND owner,Panel &panel)
|
||||
return;
|
||||
}
|
||||
const auto origin=static_cast<int>(&panel-panels);
|
||||
SpaceAnalyzer state{.root=panel.directory};
|
||||
SpaceAnalyzer state{.folder=folderPathWithoutSeparator(panel.directory),.root=folderPathWithoutSeparator(panel.directory)};
|
||||
const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(118),owner,
|
||||
spaceAnalyzerDialog,reinterpret_cast<LPARAM>(&state));
|
||||
if(answer==spaceView)
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
void finishSpaceSelection(HWND dialog,SpaceAnalyzer &state,size_t selected,int action)
|
||||
{
|
||||
if(selected>=state.nodes.size()) return;
|
||||
const auto &node=state.nodes[selected];
|
||||
if(action==spaceView && node.folder) return;
|
||||
state.selected=node.path;
|
||||
state.selectedFolder=node.folder;
|
||||
FilesModalDialog::finish(dialog,action);
|
||||
}
|
||||
|
||||
void divideSpaceTiles(std::span<const size_t> nodes,std::span<const long double> prefix,RECT bounds,
|
||||
LONG margin,std::vector<SpaceTile> &tiles)
|
||||
{
|
||||
const auto width=bounds.right-bounds.left, height=bounds.bottom-bounds.top;
|
||||
if(width<margin || height<margin || nodes.empty()) return;
|
||||
if(nodes.size()==1)
|
||||
{
|
||||
tiles.push_back({bounds,nodes.front()});
|
||||
return;
|
||||
}
|
||||
const auto total=prefix.back()-prefix.front();
|
||||
if(total<=0) return;
|
||||
const auto middle=prefix.front()+total/2;
|
||||
auto pivot=std::lower_bound(prefix.begin()+1,prefix.end()-1,middle);
|
||||
if(pivot==prefix.end()-1 ||
|
||||
(pivot>prefix.begin()+1 && middle-pivot[-1]<*pivot-middle)) --pivot;
|
||||
const auto offset=static_cast<size_t>(pivot-prefix.begin());
|
||||
const auto share=(*pivot-prefix.front())/total;
|
||||
auto first=bounds, second=bounds;
|
||||
if(width>=height)
|
||||
{
|
||||
const auto split=bounds.left+std::clamp(static_cast<LONG>(width*share+0.5L),1L,width-1);
|
||||
first.right=second.left=split;
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto split=bounds.top+std::clamp(static_cast<LONG>(height*share+0.5L),1L,height-1);
|
||||
first.bottom=second.top=split;
|
||||
}
|
||||
divideSpaceTiles(nodes.first(offset),prefix.first(offset+1),first,margin,tiles);
|
||||
divideSpaceTiles(nodes.subspan(offset),prefix.subspan(offset),second,margin,tiles);
|
||||
}
|
||||
|
||||
void layoutSpaceMap(HWND map,SpaceAnalyzer &state)
|
||||
{
|
||||
state.lastMapUpdate=GetTickCount64();
|
||||
const auto previous=state.selectedTile<state.tiles.size()?
|
||||
state.tiles[state.selectedTile].node:std::numeric_limits<size_t>::max();
|
||||
state.tiles.clear();
|
||||
state.selectedTile=0;
|
||||
if(state.mapFolder>=state.nodes.size()) return;
|
||||
std::vector<size_t> items;
|
||||
for(auto index:state.nodes[state.mapFolder].children)
|
||||
if(state.nodes[index].size.bytes) items.push_back(index);
|
||||
std::sort(items.begin(),items.end(),[&](size_t left,size_t right) {
|
||||
const auto a=state.nodes[left].size.bytes, b=state.nodes[right].size.bytes;
|
||||
return a!=b?a>b:left<right;
|
||||
});
|
||||
std::vector<long double> prefix{0};
|
||||
prefix.reserve(items.size()+1);
|
||||
for(auto index:items) prefix.push_back(prefix.back()+state.nodes[index].size.bytes);
|
||||
RECT bounds{};
|
||||
GetClientRect(map,&bounds);
|
||||
const auto minimum=std::max(4,MulDiv(8,GetDpiForWindow(map),96));
|
||||
divideSpaceTiles(items,prefix,bounds,minimum,state.tiles);
|
||||
for(size_t index=0;index<state.tiles.size();++index)
|
||||
if(state.tiles[index].node==previous)
|
||||
{
|
||||
state.selectedTile=index;
|
||||
break;
|
||||
}
|
||||
InvalidateRect(map,nullptr,FALSE);
|
||||
}
|
||||
|
||||
constexpr COLORREF spaceChartColors[]{RGB(158,203,218),RGB(167,205,172),RGB(230,198,142),
|
||||
RGB(197,179,211),RGB(226,178,173),RGB(177,190,225)};
|
||||
|
||||
void paintEmptySpaceChart(const DRAWITEMSTRUCT &paint)
|
||||
{
|
||||
auto bounds=paint.rcItem;
|
||||
SelectObject(paint.hDC,mono);
|
||||
SetBkMode(paint.hDC,TRANSPARENT);
|
||||
SetTextColor(paint.hDC,RGB(15,27,35));
|
||||
DrawTextW(paint.hDC,L"No measured space to display",-1,&bounds,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
|
||||
}
|
||||
|
||||
void paintSpaceMap(const DRAWITEMSTRUCT &paint,const SpaceAnalyzer &state)
|
||||
{
|
||||
FillRect(paint.hDC,&paint.rcItem,GetSysColorBrush(COLOR_WINDOW));
|
||||
SelectObject(paint.hDC,mono);
|
||||
SetBkMode(paint.hDC,TRANSPARENT);
|
||||
SetTextColor(paint.hDC,RGB(15,27,35));
|
||||
if(state.tiles.empty())
|
||||
{
|
||||
paintEmptySpaceChart(paint);
|
||||
return;
|
||||
}
|
||||
const auto brush=static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||||
const auto focused=GetFocus()==paint.hwndItem;
|
||||
for(size_t index=0;index<state.tiles.size();++index)
|
||||
{
|
||||
const auto &tile=state.tiles[index];
|
||||
if(!RectVisible(paint.hDC,&tile.box)) continue;
|
||||
const auto &node=state.nodes[tile.node];
|
||||
auto bounds=tile.box;
|
||||
SetDCBrushColor(paint.hDC,spaceChartColors[index%std::size(spaceChartColors)]);
|
||||
FillRect(paint.hDC,&bounds,brush);
|
||||
FrameRect(paint.hDC,&bounds,GetSysColorBrush(COLOR_WINDOW));
|
||||
if(focused && index==state.selectedTile)
|
||||
{
|
||||
InflateRect(&bounds,-2,-2);
|
||||
DrawFocusRect(paint.hDC,&bounds);
|
||||
bounds=tile.box;
|
||||
}
|
||||
InflateRect(&bounds,-std::max(3,cellWidth/2),-2);
|
||||
if(bounds.right-bounds.left>=3*cellWidth && bounds.bottom-bounds.top>=textHeight)
|
||||
{
|
||||
const auto name=node.path.filename().native();
|
||||
DrawTextW(paint.hDC,name.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
|
||||
bounds.top+=textHeight;
|
||||
if(bounds.bottom-bounds.top>=textHeight)
|
||||
{
|
||||
const auto logical=spaceLogicalSize(node);
|
||||
DrawTextW(paint.hDC,logical.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
|
||||
bounds.top+=textHeight;
|
||||
if(bounds.bottom-bounds.top>=textHeight)
|
||||
{
|
||||
const auto allocated=spaceAllocatedSize(node);
|
||||
DrawTextW(paint.hDC,allocated.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#include "files_space_sunburst.inl"
|
||||
|
||||
void refreshSpaceChart(HWND map,SpaceAnalyzer &state)
|
||||
{
|
||||
if(state.display==SpaceDisplay::sunburst) layoutSunburst(map,state);
|
||||
else layoutSpaceMap(map,state);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK spaceSunburstListKeys(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR payload)
|
||||
{
|
||||
auto &state=*reinterpret_cast<SpaceAnalyzer *>(payload);
|
||||
if(message==WM_GETDLGCODE && lp && wp==VK_RETURN)
|
||||
return DefSubclassProc(list,message,wp,lp)|DLGC_WANTMESSAGE;
|
||||
if(message==WM_KEYDOWN && wp==VK_RETURN)
|
||||
{
|
||||
const auto dialog=GetParent(list);
|
||||
if(const auto selected=sunburstSelection(dialog,state)) finishSpaceSelection(dialog,state,*selected,IDOK);
|
||||
return 0;
|
||||
}
|
||||
return DefSubclassProc(list,message,wp,lp);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK spaceMapInput(HWND map,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR payload)
|
||||
{
|
||||
auto &state=*reinterpret_cast<SpaceAnalyzer *>(payload);
|
||||
if(message==WM_SIZE && state.display!=SpaceDisplay::tree) refreshSpaceChart(map,state);
|
||||
if(message==WM_SETFOCUS || message==WM_KILLFOCUS) InvalidateRect(map,nullptr,FALSE);
|
||||
if(message==WM_LBUTTONDOWN)
|
||||
{
|
||||
SetFocus(map);
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_LBUTTONUP)
|
||||
{
|
||||
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
if(state.display==SpaceDisplay::sunburst)
|
||||
{
|
||||
if(const auto hit=hitSunburst(map,state,point))
|
||||
finishSpaceSelection(GetParent(map),state,state.sectors[*hit].node,IDOK);
|
||||
return 0;
|
||||
}
|
||||
for(const auto &tile:state.tiles)
|
||||
if(PtInRect(&tile.box,point))
|
||||
{
|
||||
finishSpaceSelection(GetParent(map),state,tile.node,IDOK);
|
||||
break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_GETDLGCODE)
|
||||
{
|
||||
const auto *key=reinterpret_cast<const MSG *>(lp);
|
||||
return DLGC_WANTARROWS|(key && key->message==WM_KEYDOWN && wp==VK_RETURN?DLGC_WANTMESSAGE:0);
|
||||
}
|
||||
if(message==WM_KEYDOWN && state.display==SpaceDisplay::treemap && !state.tiles.empty())
|
||||
{
|
||||
if(wp==VK_RETURN)
|
||||
{
|
||||
finishSpaceSelection(GetParent(map),state,state.tiles[state.selectedTile].node,IDOK);
|
||||
return 0;
|
||||
}
|
||||
if(wp==VK_DOWN || wp==VK_RIGHT || wp==VK_UP || wp==VK_LEFT)
|
||||
{
|
||||
auto &index=state.selectedTile;
|
||||
if(wp==VK_DOWN || wp==VK_RIGHT) index=(index+1)%state.tiles.size();
|
||||
else index=index?index-1:state.tiles.size()-1;
|
||||
InvalidateRect(map,nullptr,FALSE);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return DefSubclassProc(map,message,wp,lp);
|
||||
}
|
||||
|
||||
void setSpaceDisplay(HWND dialog,SpaceAnalyzer &state,SpaceDisplay display)
|
||||
{
|
||||
const auto tree=GetDlgItem(dialog,spaceTree), map=GetDlgItem(dialog,spaceMap);
|
||||
const auto list=GetDlgItem(dialog,spaceSunburstList);
|
||||
const bool showTree=display==SpaceDisplay::tree, showSunburst=display==SpaceDisplay::sunburst;
|
||||
const auto selection=selectedSpaceNode(tree,state);
|
||||
if(state.display==SpaceDisplay::tree && !showTree)
|
||||
{
|
||||
const auto index=selection.value_or(0);
|
||||
const auto &node=state.nodes[index];
|
||||
state.mapFolder=node.folder && !node.link?index:node.parent;
|
||||
}
|
||||
state.display=display;
|
||||
SetDlgItemTextW(dialog,spaceMapButton,display==SpaceDisplay::treemap?L"Tr&ee":L"Tree&map");
|
||||
SetDlgItemTextW(dialog,spaceSunburstButton,showSunburst?L"Tr&ee":L"S&unburst");
|
||||
layoutSpaceAnalyzer(dialog);
|
||||
ShowWindow(tree,showTree?SW_SHOW:SW_HIDE);
|
||||
ShowWindow(map,showTree?SW_HIDE:SW_SHOW);
|
||||
ShowWindow(GetDlgItem(dialog,spaceSunburstLabel),showSunburst?SW_SHOW:SW_HIDE);
|
||||
ShowWindow(list,showSunburst?SW_SHOW:SW_HIDE);
|
||||
if(!showSunburst)
|
||||
{
|
||||
EnableWindow(GetDlgItem(dialog,spaceView),showTree && selection && !state.nodes[*selection].folder);
|
||||
EnableWindow(GetDlgItem(dialog,IDOK),showTree && selection.has_value());
|
||||
}
|
||||
if(!showTree) refreshSpaceChart(map,state);
|
||||
SetFocus(showTree?tree:showSunburst?list:map);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
constexpr double fullCircle=2*std::numbers::pi_v<double>;
|
||||
constexpr unsigned sunburstRings=3;
|
||||
|
||||
double sunburstRingWidth(const RECT &bounds)
|
||||
{
|
||||
return std::max(0L,std::min(bounds.right-bounds.left,bounds.bottom-bounds.top)-4)/
|
||||
(2.0*(sunburstRings+0.5));
|
||||
}
|
||||
|
||||
void addSunburstRing(SpaceAnalyzer &state,size_t folder,unsigned ring,double start,double end)
|
||||
{
|
||||
if(ring>=sunburstRings || end-start<0.02) return;
|
||||
const auto &parent=state.nodes[folder];
|
||||
double total=0;
|
||||
for(auto index:parent.children) total+=static_cast<double>(state.nodes[index].size.bytes);
|
||||
if(total<=0) return;
|
||||
const auto span=end-start;
|
||||
auto cursor=start;
|
||||
for(auto index:parent.children)
|
||||
{
|
||||
const auto &item=state.nodes[index];
|
||||
if(!item.size.bytes) continue;
|
||||
const auto next=std::min(end,cursor+span*static_cast<double>(item.size.bytes)/total);
|
||||
if(next-cursor>=0.02)
|
||||
{
|
||||
state.sectors.push_back({index,ring,cursor,next});
|
||||
if(item.folder) addSunburstRing(state,index,ring+1,cursor,next);
|
||||
}
|
||||
cursor=next;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<size_t> sunburstSelectedSector(HWND dialog,const SpaceAnalyzer &state)
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,spaceSunburstList,LB_GETCURSEL,0,0);
|
||||
if(row==LB_ERR) return {};
|
||||
const auto sector=SendDlgItemMessageW(dialog,spaceSunburstList,LB_GETITEMDATA,row,0);
|
||||
if(sector==LB_ERR || static_cast<size_t>(sector)>=state.sectors.size()) return {};
|
||||
return static_cast<size_t>(sector);
|
||||
}
|
||||
|
||||
std::optional<size_t> sunburstSelection(HWND dialog,const SpaceAnalyzer &state)
|
||||
{
|
||||
const auto sector=sunburstSelectedSector(dialog,state);
|
||||
return sector?std::optional<size_t>(state.sectors[*sector].node):std::nullopt;
|
||||
}
|
||||
|
||||
void updateSunburstSelection(HWND dialog,SpaceAnalyzer &state)
|
||||
{
|
||||
state.selectedTile=sunburstSelectedSector(dialog,state).value_or(state.sectors.size());
|
||||
const auto selected=sunburstSelection(dialog,state);
|
||||
EnableWindow(GetDlgItem(dialog,spaceView),selected && !state.nodes[*selected].folder);
|
||||
EnableWindow(GetDlgItem(dialog,IDOK),selected.has_value());
|
||||
InvalidateRect(GetDlgItem(dialog,spaceMap),nullptr,FALSE);
|
||||
}
|
||||
|
||||
void layoutSunburst(HWND map,SpaceAnalyzer &state)
|
||||
{
|
||||
const auto dialog=GetParent(map);
|
||||
const auto list=GetDlgItem(dialog,spaceSunburstList);
|
||||
const auto selected=sunburstSelection(dialog,state);
|
||||
state.lastMapUpdate=GetTickCount64();
|
||||
state.sectors.clear();
|
||||
state.selectedTile=0;
|
||||
if(state.mapFolder<state.nodes.size())
|
||||
addSunburstRing(state,state.mapFolder,0,0,fullCircle);
|
||||
SendMessageW(list,WM_SETREDRAW,FALSE,0);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
SendMessageW(list,LB_INITSTORAGE,state.sectors.size(),0);
|
||||
LRESULT selection=0;
|
||||
size_t longest=0;
|
||||
for(size_t i=0;i<state.sectors.size();++i)
|
||||
{
|
||||
const auto §or=state.sectors[i];
|
||||
const auto &node=state.nodes[sector.node];
|
||||
const auto &root=state.nodes[state.mapFolder];
|
||||
const auto name=node.path.lexically_relative(root.path).native();
|
||||
const auto line=name+L" — "+spaceLogicalSize(node);
|
||||
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(line.c_str()));
|
||||
if(row>=0)
|
||||
{
|
||||
SendMessageW(list,LB_SETITEMDATA,row,i);
|
||||
if(selected==sector.node) selection=row;
|
||||
longest=std::max(longest,line.size());
|
||||
}
|
||||
}
|
||||
SendMessageW(list,LB_SETHORIZONTALEXTENT,(longest+1)*cellWidth,0);
|
||||
if(!state.sectors.empty()) SendMessageW(list,LB_SETCURSEL,selection,0);
|
||||
SendMessageW(list,WM_SETREDRAW,TRUE,0);
|
||||
InvalidateRect(list,nullptr,FALSE);
|
||||
updateSunburstSelection(dialog,state);
|
||||
}
|
||||
|
||||
std::optional<size_t> hitSunburst(HWND map,const SpaceAnalyzer &state,POINT point)
|
||||
{
|
||||
RECT bounds{};
|
||||
GetClientRect(map,&bounds);
|
||||
const auto width=sunburstRingWidth(bounds);
|
||||
if(width<=0) return {};
|
||||
const auto x=point.x-(bounds.left+bounds.right)/2.0;
|
||||
const auto y=point.y-(bounds.top+bounds.bottom)/2.0;
|
||||
const auto radius=std::hypot(x,y)/width-0.5;
|
||||
if(radius<0 || radius>=sunburstRings) return {};
|
||||
const auto ring=static_cast<unsigned>(radius);
|
||||
auto angle=std::atan2(x,-y);
|
||||
if(angle<0) angle+=fullCircle;
|
||||
for(size_t i=0;i<state.sectors.size();++i)
|
||||
{
|
||||
const auto §or=state.sectors[i];
|
||||
if(sector.ring==ring && angle>=sector.start && angle<sector.end) return i;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void paintSunburst(const DRAWITEMSTRUCT &paint,const SpaceAnalyzer &state)
|
||||
{
|
||||
auto bounds=paint.rcItem;
|
||||
FillRect(paint.hDC,&bounds,GetSysColorBrush(COLOR_WINDOW));
|
||||
if(state.sectors.empty())
|
||||
{
|
||||
paintEmptySpaceChart(paint);
|
||||
return;
|
||||
}
|
||||
const auto width=sunburstRingWidth(bounds);
|
||||
const auto x=(bounds.left+bounds.right)/2.0, y=(bounds.top+bounds.bottom)/2.0;
|
||||
const auto point=[&](double angle,double radius) {
|
||||
return POINT{std::lround(x+radius*std::sin(angle)),std::lround(y-radius*std::cos(angle))};
|
||||
};
|
||||
const auto oldBrush=SelectObject(paint.hDC,GetStockObject(DC_BRUSH));
|
||||
const auto oldPen=SelectObject(paint.hDC,GetStockObject(DC_PEN));
|
||||
for(size_t i=0;i<state.sectors.size();++i)
|
||||
{
|
||||
const auto §or=state.sectors[i];
|
||||
const auto segments=std::clamp(static_cast<int>((sector.end-sector.start)*26),2,164);
|
||||
const auto inner=(sector.ring+0.5)*width, outer=inner+width;
|
||||
std::array<POINT,330> points;
|
||||
for(int segment=0;segment<=segments;++segment)
|
||||
{
|
||||
const auto angle=sector.start+(sector.end-sector.start)*segment/segments;
|
||||
points[segment]=point(angle,outer);
|
||||
points[2*segments+1-segment]=point(angle,inner);
|
||||
}
|
||||
SetDCPenColor(paint.hDC,i==state.selectedTile?RGB(35,48,62):RGB(255,255,255));
|
||||
SetDCBrushColor(paint.hDC,spaceChartColors[i%std::size(spaceChartColors)]);
|
||||
Polygon(paint.hDC,points.data(),2*(segments+1));
|
||||
}
|
||||
SelectObject(paint.hDC,oldPen);
|
||||
SelectObject(paint.hDC,oldBrush);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
template<class Visitor>
|
||||
DWORD visitDirectoryRecords(HANDLE directory,const Visitor &visit)
|
||||
{
|
||||
alignas(FILE_ID_BOTH_DIR_INFO) std::array<unsigned char,64*1024> buffer;
|
||||
constexpr auto header=offsetof(FILE_ID_BOTH_DIR_INFO,FileName);
|
||||
while(GetFileInformationByHandleEx(directory,FileIdBothDirectoryInfo,buffer.data(),
|
||||
static_cast<DWORD>(buffer.size())))
|
||||
{
|
||||
for(size_t offset=0;;)
|
||||
{
|
||||
const auto remaining=buffer.size()-offset;
|
||||
if(remaining<header) return ERROR_INVALID_DATA;
|
||||
const auto &entry=*reinterpret_cast<const FILE_ID_BOTH_DIR_INFO *>(buffer.data()+offset);
|
||||
const auto size=entry.NextEntryOffset?entry.NextEntryOffset:remaining;
|
||||
if(size>remaining || size<header || entry.FileNameLength>size-header ||
|
||||
entry.FileNameLength%sizeof(wchar_t)) return ERROR_INVALID_DATA;
|
||||
const std::wstring_view name(entry.FileName,entry.FileNameLength/sizeof(wchar_t));
|
||||
if(name.empty() || name.find_first_of(L"/\\:")!=name.npos || name.find(L'\0')!=name.npos)
|
||||
return ERROR_INVALID_DATA;
|
||||
if(name!=L"." && name!=L"..")
|
||||
{
|
||||
const auto result=visit(entry,name);
|
||||
if(result!=ERROR_SUCCESS) return result;
|
||||
}
|
||||
if(!entry.NextEntryOffset) break;
|
||||
if(size%alignof(FILE_ID_BOTH_DIR_INFO)) return ERROR_INVALID_DATA;
|
||||
offset+=size;
|
||||
}
|
||||
}
|
||||
const auto error=GetLastError();
|
||||
return error==ERROR_NO_MORE_FILES?ERROR_SUCCESS:error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class FilesCommandsUi {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Point { public int X, Y; }
|
||||
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr window, IntPtr after, int x, int y, int width, int height, uint flags);
|
||||
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr window, int command);
|
||||
[DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
|
||||
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
[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", 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")]
|
||||
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text);
|
||||
public static bool Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return true;
|
||||
keybd_event(18, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(18, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
return GetForegroundWindow() == window;
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
function Wait-For([string]$Name, [scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 50; ++$attempt) {
|
||||
$value = & $Condition
|
||||
if ($value) { return $value }
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
throw "Timed out waiting for $Name."
|
||||
}
|
||||
|
||||
function Invoke-FilesCommand([IntPtr]$Window, [string]$LabelPattern) {
|
||||
[void][FilesCommandsUi]::Post($Window, 273, [IntPtr]132, [IntPtr]::Zero)
|
||||
$picker = [FilesCommandsUi]::GetDlgItem($Window, 121)
|
||||
[void](Wait-For 'the Commands menu' { [FilesCommandsUi]::IsWindowVisible($picker) })
|
||||
$count = [FilesCommandsUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64()
|
||||
for ($row = 0; $row -lt $count; ++$row) {
|
||||
$label = [Text.StringBuilder]::new(128)
|
||||
[void][FilesCommandsUi]::Read($picker, 393, [IntPtr]$row, $label)
|
||||
if ($label.ToString() -like $LabelPattern) {
|
||||
[void][FilesCommandsUi]::Send($picker, 390, [IntPtr]$row, [IntPtr]::Zero)
|
||||
[void][FilesCommandsUi]::Post($Window, 273, [IntPtr](0x20000 + 121), $picker)
|
||||
return
|
||||
}
|
||||
}
|
||||
throw "Missing Files command matching $LabelPattern."
|
||||
}
|
||||
@@ -2,50 +2,7 @@ param([Parameter(Mandatory)][string]$Executable)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class ComparisonSplitterUi {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Point { public int X, Y; }
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
|
||||
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
[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", 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")]
|
||||
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text);
|
||||
public static bool Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return true;
|
||||
keybd_event(18, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(18, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
return GetForegroundWindow() == window;
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
function Wait-For([string]$Name, [scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 50; ++$attempt) {
|
||||
$value = & $Condition
|
||||
if ($value) { return $value }
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
throw "Timed out waiting for $Name."
|
||||
}
|
||||
. "$PSScriptRoot/files_commands_ui.ps1"
|
||||
|
||||
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance'
|
||||
@@ -57,7 +14,7 @@ foreach ($name in $names) {
|
||||
}
|
||||
$temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
|
||||
$root = Join-Path $temp ('ks-files-splitter-' + [Guid]::NewGuid().ToString('N'))
|
||||
$dpi = [ComparisonSplitterUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
$process = $null
|
||||
try {
|
||||
$left = Join-Path $root 'left'
|
||||
@@ -78,52 +35,40 @@ try {
|
||||
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
|
||||
}
|
||||
foreach ($id in 102, 103) {
|
||||
$panel = [ComparisonSplitterUi]::GetDlgItem($main, $id)
|
||||
$panel = [FilesCommandsUi]::GetDlgItem($main, $id)
|
||||
[void](Wait-For 'the test file in the panel' {
|
||||
[ComparisonSplitterUi]::Send($panel, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64() -eq 2
|
||||
[FilesCommandsUi]::Send($panel, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64() -eq 2
|
||||
})
|
||||
[void][ComparisonSplitterUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero)
|
||||
[void][FilesCommandsUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero)
|
||||
}
|
||||
[void][ComparisonSplitterUi]::Post($main, 273, [IntPtr]132, [IntPtr]::Zero)
|
||||
$picker = [ComparisonSplitterUi]::GetDlgItem($main, 121)
|
||||
[void](Wait-For 'the Commands menu' { [ComparisonSplitterUi]::IsWindowVisible($picker) })
|
||||
$row = -1
|
||||
$count = [ComparisonSplitterUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64()
|
||||
for ($i = 0; $i -lt $count; ++$i) {
|
||||
$label = [Text.StringBuilder]::new(128)
|
||||
[void][ComparisonSplitterUi]::Read($picker, 393, [IntPtr]$i, $label)
|
||||
if ($label.ToString() -like 'Compare files*') { $row = $i; break }
|
||||
}
|
||||
if ($row -lt 0) { throw 'Missing Compare files command.' }
|
||||
[void][ComparisonSplitterUi]::Send($picker, 390, [IntPtr]$row, [IntPtr]::Zero)
|
||||
[void][ComparisonSplitterUi]::Post($main, 273, [IntPtr](0x20000 + 121), $picker)
|
||||
Invoke-FilesCommand $main 'Compare files*'
|
||||
$list = Wait-For 'the foreground comparison list' {
|
||||
$dialog = [IntPtr]::Zero
|
||||
while (($dialog = [ComparisonSplitterUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) {
|
||||
while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) {
|
||||
[uint32]$ownerPid = 0
|
||||
[void][ComparisonSplitterUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid)
|
||||
[void][FilesCommandsUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid)
|
||||
if ($ownerPid -ne $process.Id) { continue }
|
||||
$control = [ComparisonSplitterUi]::GetDlgItem($dialog, 402)
|
||||
if ([ComparisonSplitterUi]::IsWindowVisible($control) -and [ComparisonSplitterUi]::Activate($dialog)) {
|
||||
$control = [FilesCommandsUi]::GetDlgItem($dialog, 402)
|
||||
if ([FilesCommandsUi]::IsWindowVisible($control) -and [FilesCommandsUi]::Activate($dialog)) {
|
||||
return $control
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$bounds = [ComparisonSplitterUi+Rect]::new()
|
||||
[void][ComparisonSplitterUi]::GetClientRect($list, [ref]$bounds)
|
||||
$bounds = [FilesCommandsUi+Rect]::new()
|
||||
[void][FilesCommandsUi]::GetClientRect($list, [ref]$bounds)
|
||||
$middle = [int]($bounds.Right / 2)
|
||||
$destination = [int]($bounds.Right * 0.65)
|
||||
$mouseY = 30 -shl 16
|
||||
[void][ComparisonSplitterUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle))
|
||||
[void][FilesCommandsUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle))
|
||||
for ($x = $middle + 5; $x -lt $destination; $x += 5) {
|
||||
[void][ComparisonSplitterUi]::Send($list, 512, [IntPtr]1, [IntPtr]($mouseY -bor $x))
|
||||
[void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
|
||||
[void][FilesCommandsUi]::Send($list, 512, [IntPtr]1, [IntPtr]($mouseY -bor $x))
|
||||
[void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
|
||||
}
|
||||
[void][ComparisonSplitterUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination))
|
||||
[void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
|
||||
$origin = [ComparisonSplitterUi+Point]::new()
|
||||
[void][ComparisonSplitterUi]::ClientToScreen($list, [ref]$origin)
|
||||
[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)
|
||||
try {
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
@@ -146,7 +91,7 @@ try {
|
||||
else { $preferences.DeleteValue($name, $false) }
|
||||
}
|
||||
$preferences.Dispose()
|
||||
if ($dpi) { [void][ComparisonSplitterUi]::SetThreadDpiAwarenessContext($dpi) }
|
||||
if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) }
|
||||
if (Test-Path -LiteralPath $root) {
|
||||
$resolved = (Resolve-Path -LiteralPath $root).Path
|
||||
if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-files-splitter-*') {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
param([Parameter(Mandatory)][string]$Executable)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. "$PSScriptRoot/files_commands_ui.ps1"
|
||||
|
||||
$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
$process = $null
|
||||
try {
|
||||
$process = Start-Process -FilePath (Resolve-Path -LiteralPath $Executable) -PassThru
|
||||
$main = Wait-For 'the Files window' {
|
||||
$process.Refresh()
|
||||
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
|
||||
}
|
||||
[void][FilesCommandsUi]::ShowWindow($main, 9)
|
||||
$width = [int](350 * [FilesCommandsUi]::GetDpiForWindow($main) / 96)
|
||||
if (![FilesCommandsUi]::SetWindowPos($main, [IntPtr]::Zero, 0, 0, $width, 0, 22)) {
|
||||
throw 'Could not narrow the Files window.'
|
||||
}
|
||||
Invoke-FilesCommand $main 'Space Analyzer'
|
||||
$dialog = Wait-For 'the visible Space Analyzer' {
|
||||
$candidate = [IntPtr]::Zero
|
||||
while (($candidate = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $candidate, '#32770', 'Space Analyzer')) -ne [IntPtr]::Zero) {
|
||||
[uint32]$owner = 0
|
||||
[void][FilesCommandsUi]::GetWindowThreadProcessId($candidate, [ref]$owner)
|
||||
if ($owner -eq $process.Id -and [FilesCommandsUi]::IsWindowVisible($candidate)) { return $candidate }
|
||||
}
|
||||
}
|
||||
|
||||
$outer = [FilesCommandsUi+Rect]::new()
|
||||
if (![FilesCommandsUi]::GetWindowRect($dialog, [ref]$outer)) { throw 'Could not measure the Space Analyzer.' }
|
||||
$previousRight = $outer.Left
|
||||
$firstLeft = 0
|
||||
$midY = 0
|
||||
foreach ($id in 492, 493, 494, 1, 2) {
|
||||
$button = [FilesCommandsUi]::GetDlgItem($dialog, $id)
|
||||
$rect = [FilesCommandsUi+Rect]::new()
|
||||
if (![FilesCommandsUi]::IsWindowVisible($button) -or ![FilesCommandsUi]::GetWindowRect($button, [ref]$rect)) {
|
||||
throw "Space Analyzer footer button $id was unavailable."
|
||||
}
|
||||
if ($rect.Left -le $previousRight -or $rect.Right -ge $outer.Right -or $rect.Bottom -ge $outer.Bottom) {
|
||||
throw "Space Analyzer footer button $id was clipped or overlapped at narrow width."
|
||||
}
|
||||
if ($id -eq 492) {
|
||||
$firstLeft = $rect.Left
|
||||
$midY = $rect.Top + $rect.Bottom
|
||||
} elseif ([Math]::Abs($midY - $rect.Top - $rect.Bottom) -gt 1) {
|
||||
throw "Space Analyzer footer button $id was outside the shared button row."
|
||||
}
|
||||
$previousRight = $rect.Right
|
||||
}
|
||||
if ([Math]::Abs(($firstLeft + $previousRight) - ($outer.Left + $outer.Right)) -gt 2) {
|
||||
throw 'Space Analyzer footer buttons were off center.'
|
||||
}
|
||||
'Verified the full and centered Space Analyzer footer at narrow width.'
|
||||
} finally {
|
||||
# End this fixture without saving its temporary window dimensions.
|
||||
if ($process -and !$process.HasExited) {
|
||||
$process.Kill()
|
||||
$process.WaitForExit()
|
||||
}
|
||||
if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) }
|
||||
}
|
||||
Reference in new issue
Block a user