Compare commits

..
10 changed files with 1046 additions and 98 deletions

No files matched your search

+5
View File
@@ -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
+20
View File
@@ -455,6 +455,26 @@ Warning і початковий фокус на No.
переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
з тією самою маскою й видимістю прихованих файлів.
- **Commands → Space Analyzer** показує місткість і вільне місце за даними
Windows перед скануванням. Volume вибирає корінь тому, Folder повертає
поточну локальну папку, Start запускає фоновий аналіз тим самим обходом,
що й підрахунок розмірів F3. Посилання на каталоги всередині області
сканування позначаються як link. Stop залишає часткові результати, а
Rescan повторює аналіз із початку.
- Дерево показує логічний розмір, зайняті байти та частку логічного розміру
від батьківської папки. Знак + позначає частковий підрахунок. Зайняті байти
підсумовуються за файловими записами, включно з окремими іменами для
жорстких посилань. Службові дані файлової системи в цей підсумок не входять.
Відсутні дані про зайняті байти позначаються в рядку стану.
- Treemap показує дочірні елементи вибраної папки прямокутниками,
пропорційними до їхнього логічного розміру. Дрібні елементи доступні в
дереві. Клік по плитці відкриває точний елемент у сусідній панелі. Стрілки
переводять фокус між плитками, Enter відкриває плитку у фокусі.
- View відкриває вибраний файл у спільному переглядачі Files. Show in
other panel відкриває вибрану папку або ставить курсор на файл у сусідній
панелі. Команди роботи з файлами доступні там. Якщо фільтр приховує
вибраний файл, панель показує його до зміни фільтра або переходу в іншу папку.
- Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів
у відкритих локальних папках. Фокус залишається там, де був, а курсор
лишається на поточному елементі, якщо той ще існує.
+20
View File
@@ -432,3 +432,23 @@ BEGIN
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17
END
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 "", 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 "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
END
+69 -22
View File
@@ -287,6 +287,12 @@ struct FolderSize
{
uint64_t bytes{};
bool partial{};
void add(uint64_t amount)
{
if(amount>UINT64_MAX-bytes) partial=true;
else bytes+=amount;
}
};
using FolderSizes=std::map<fs::path,FolderSize>;
@@ -305,8 +311,20 @@ struct FolderSizeJob
bool finished{};
};
using FolderMeasurementObserver=std::function<void(const fs::path &,const FileInfo *)>;
bool listMeasuredDirectory(FilesConnection &host,const fs::path &directory,const FileVisitor &visit,
std::stop_token stop)
{
const auto info=statFile(host,directory);
return info && (info->attributes&FILE_ATTRIBUTE_DIRECTORY) &&
!(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT) && !stop.stop_requested() &&
listFiles(host,directory,visit);
}
template<class ListDirectory>
FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDirectory &listDirectory)
FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDirectory &listDirectory,
const FolderMeasurementObserver &observe={})
{
FolderSize size;
std::vector<fs::path> pending{root};
@@ -314,20 +332,27 @@ FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDir
{
const auto directory=std::move(pending.back());
pending.pop_back();
bool complete=false;
try
{
if(!listDirectory(directory,[&](const fs::path &path,const FileInfo &entry)
complete=listDirectory(directory,[&](const fs::path &path,const FileInfo &entry)
{
if(stop.stop_requested()) return false;
if(observe) observe(path,&entry);
if(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT) return true;
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY) pending.push_back(path);
else if(entry.size>UINT64_MAX-size.bytes) size.partial=true;
else size.bytes+=entry.size;
else size.add(entry.size);
return true;
})) size.partial=true;
});
}
catch(const std::exception &) {}
if(!complete)
{
size.partial=true;
if(observe) observe(directory,nullptr);
}
catch(const std::exception &) {size.partial=true;}
}
if(stop.stop_requested()) size.partial=true;
return size;
}
@@ -404,6 +429,7 @@ struct PanelView
PanelSort sort{PanelSort::name};
bool descending{}, foldersFirst{true}, showHidden{true};
std::wstring mask;
fs::path revealedFile;
};
struct DirectoryRow
@@ -670,6 +696,7 @@ struct FilesNoticeOptions
};
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={});
void openMenu(HWND window, int index);
void openSpaceAnalyzer(HWND owner,Panel &panel);
void showFileDetails(const Panel &panel);
void updateSelectionSummary(const Panel &panel);
void editOptions(HWND owner);
@@ -2663,6 +2690,8 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti
std::optional<size_t> navigationPosition={})
{
if(directory.empty() && !ftp) return;
if(!panel.view.revealedFile.empty() &&
(peer || ftp || panel.view.revealedFile.parent_path()!=directory)) panel.view.revealedFile.clear();
if(directory!=panel.directory || !samePanelSource(panel,peer,ftp))
cancelFolderSizes(panel);
panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback),
@@ -2723,6 +2752,7 @@ bool panelViewAvailable(const Panel &panel)
void updatePanelView(Panel &panel)
{
panel.view.revealedFile.clear();
savePanelView(static_cast<int>(&panel-panels));
InvalidateRect(panel.heading,nullptr,FALSE);
if(panel.scanRequest)
@@ -2790,6 +2820,12 @@ LRESULT CALLBACK panelHeadingInput(HWND window,UINT message,WPARAM wp,LPARAM lp,
return DefSubclassProc(window,message,wp,lp);
}
void revealLocalFile(Panel &panel,const fs::path &path)
{
panel.view.revealedFile=path;
openOn(panel,path.parent_path(),false,{},path);
}
void showFtpProfiles(Panel &panel,fs::path selection={})
{
openOn(panel,ftpRoot,false,{},std::move(selection),{},FtpProfile{});
@@ -2915,10 +2951,7 @@ bool calculateFolderSizes(Panel &panel,LRESULT current)
FilesConnection host(peer?&*peer:nullptr);
measure([&](const fs::path &directory,const FileVisitor &visit)
{
const auto info=statFile(host,directory);
return info && (info->attributes&FILE_ATTRIBUTE_DIRECTORY) &&
!(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT) && !stop.stop_requested() &&
listFiles(host,directory,visit);
return listMeasuredDirectory(host,directory,visit,stop);
});
}
}
@@ -3126,6 +3159,7 @@ void selectDrive()
else if(menuIndex==2 && row==9) findLocalFiles(owner,panels[active]);
else if(menuIndex==2 && row==10) toggleQuickView(owner);
else if(menuIndex==2 && row==11) copyFullPanelPath(owner,panels[active]);
else if(menuIndex==2 && row==12) openSpaceAnalyzer(owner,panels[active]);
else
{
const int command=menuIndex==1?113+static_cast<int>(row):110+static_cast<int>(row);
@@ -3760,7 +3794,7 @@ void enter(Panel &panel)
auto target = panel.rows[row];
if(panel.findOrigin)
{
openOn(panel,target.parent_path(),false,{},target);
revealLocalFile(panel,target);
return;
}
if(panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") open(panel,target,true);
@@ -4012,26 +4046,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;
@@ -6890,6 +6932,7 @@ bool loadFilesPreferences(HWND window)
#include "files_find.inl"
#include "files_options.inl"
#include "files_space_analyzer.inl"
void openMenu(HWND window, int index)
{
@@ -6934,13 +6977,17 @@ void openMenu(HWND window, int index)
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4",
L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(),
L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q",
L"Copy full path\tCtrl+Shift+C"};
L"Copy full path\tCtrl+Shift+C",L"Space Analyzer"};
}
commandActions.clear();
if(index==2)
{
commandActions={0,3,11,-1,1,2,4,5,8};
if(!panels[active].peer && !panels[active].ftp) commandActions.insert(commandActions.begin()+1,9);
if(!panels[active].peer && !panels[active].ftp)
{
commandActions.insert(commandActions.begin()+1,9);
if(!terminalVisible) commandActions.insert(commandActions.begin()+2,12);
}
if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10);
if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7});
}
+1 -1
View File
@@ -31,7 +31,7 @@ void orderDirectoryRows(Panel::ScanResult &result,const PanelView &view)
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) rows.push_back({std::move(path),value,folder});
if(visible || path==view.revealedFile) rows.push_back({std::move(path),value,folder});
}
};
append(result.folders,true);
+594
View File
@@ -0,0 +1,594 @@
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 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;
};
struct SpaceEvent
{
fs::path path;
std::optional<FileInfo> item;
std::optional<uint64_t> allocated;
};
struct SpaceRun
{
std::stop_source stop;
std::mutex mutex;
std::deque<std::vector<SpaceEvent>> pending;
FolderSize result;
bool finished{}, stopped{};
};
std::shared_ptr<SpaceRun> startSpaceRun(const fs::path &root,bool volume)
{
auto run=std::make_shared<SpaceRun>();
std::thread([run,root,volume] {
std::vector<SpaceEvent> batch;
auto lastUpdate=GetTickCount64();
const auto publish=[&] {
if(batch.empty()) return;
std::lock_guard lock(run->mutex);
run->pending.push_back(std::move(batch));
batch.clear();
lastUpdate=GetTickCount64();
};
FolderSize total;
const auto stop=run->stop.get_token();
try
{
FilesConnection host(nullptr);
total=measureFolder(root,stop,[&](const fs::path &directory,const FileVisitor &visit) {
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) {
const auto allocate=info && !(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT));
batch.push_back({path,info?std::optional<FileInfo>(*info):std::nullopt,
allocate?allocatedFileBytes(path,info->attributes):std::nullopt});
if(batch.size()>=spaceBatchSize || GetTickCount64()-lastUpdate>=80) publish();
});
publish();
}
catch(const std::exception &) {total.partial=true;}
std::lock_guard lock(run->mutex);
run->result=total;
run->stopped=stop.stop_requested();
run->finished=true;
}).detach();
return run;
}
struct SpaceNode
{
fs::path path;
FolderSize size;
SpaceAllocation allocated;
size_t parent{};
std::vector<size_t> children;
HTREEITEM item{};
bool folder{}, link{}, expanded{};
};
struct SpaceAnalyzer
{
fs::path folder, root, selected;
SpaceVolume volume;
std::future<SpaceVolume> pendingVolume;
bool selectedFolder{}, volumeScope{}, mapVisible{};
std::shared_ptr<SpaceRun> run;
std::vector<SpaceNode> nodes;
std::map<fs::path,size_t> directories;
size_t files{}, mapFolder{}, selectedTile{};
std::vector<SpaceTile> tiles;
ULONGLONG lastMapUpdate{};
bool scanning{}, hasResults{};
};
void layoutSpaceAnalyzer(HWND dialog)
{
RECT bounds{};
GetClientRect(dialog,&bounds);
const auto frame=dialogFrameMetrics(GetDpiForWindow(dialog));
const auto inset=frame.content();
const auto width=std::max(1L,bounds.right-2*inset);
const auto place=[&](int id,int top,int height) {
SetWindowPos(GetDlgItem(dialog,id),nullptr,inset,top,width,height,SWP_NOZORDER|SWP_NOACTIVATE);
};
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})
{
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);
place(spaceMap,top,9*textHeight);
top+=9*textHeight+dialogRowGap();
place(spaceStatus,top,textHeight);
place(spaceFooter,top+textHeight+dialogRowGap(),1);
layoutDialogButtons(dialog,spaceFooter,spaceFooterButtons);
}
HTREEITEM insertSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index)
{
auto &node=state.nodes[index];
TVINSERTSTRUCTW insert{};
insert.hParent=index?state.nodes[node.parent].item:TVI_ROOT;
insert.hInsertAfter=TVI_LAST;
insert.item.mask=TVIF_TEXT|TVIF_PARAM|TVIF_CHILDREN;
insert.item.pszText=LPSTR_TEXTCALLBACKW;
insert.item.lParam=static_cast<LPARAM>(index);
insert.item.cChildren=node.folder && !node.link?I_CHILDRENCALLBACK:0;
node.item=TreeView_InsertItem(tree,&insert);
return node.item;
}
void expandSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index)
{
auto &node=state.nodes[index];
if(node.expanded) return;
node.expanded=true;
for(auto child:node.children) insertSpaceNode(tree,state,child);
}
void addSpaceEvent(HWND tree,SpaceAnalyzer &state,SpaceEvent event)
{
if(!event.item)
{
const auto directory=state.directories.find(event.path);
if(directory==state.directories.end()) return;
for(auto i=directory->second;;i=state.nodes[i].parent)
{
state.nodes[i].size.partial=true;
if(!i) break;
}
return;
}
const auto parent=state.directories.find(event.path.parent_path());
if(parent==state.directories.end()) return;
const auto index=state.nodes.size();
const bool folder=(event.item->attributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
const bool link=(event.item->attributes&FILE_ATTRIBUTE_REPARSE_POINT)!=0;
const auto bytes=folder || link?0:event.item->size;
if(folder) state.directories.emplace(event.path,index);
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)
{
insertSpaceNode(tree,state,index);
if(parentNode.children.size()==1) TreeView_Expand(tree,parentNode.item,TVE_EXPAND);
}
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];
const auto &parent=state.nodes[node.parent];
auto name=node.path.filename().native();
if(name.empty()) name=node.path.native();
if(name.size()>196)
{
name.resize(196);
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" — "+spaceLogicalSize(node)+L" · "+spaceAllocatedSize(node);
if(parent.size.bytes)
{
wchar_t share[48]{};
swprintf_s(share,L" (%.1f%%)",100.0*static_cast<double>(node.size.bytes)/static_cast<double>(parent.size.bytes));
result+=share;
}
return result;
}
std::optional<size_t> selectedSpaceNode(HWND tree,const SpaceAnalyzer &state)
{
TVITEMW item{};
item.mask=TVIF_PARAM;
item.hItem=TreeView_GetSelection(tree);
if(item.hItem && TreeView_GetItem(tree,&item) && static_cast<size_t>(item.lParam)<state.nodes.size())
return static_cast<size_t>(item.lParam);
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;
do
{
std::vector<SpaceEvent> batch;
{
std::lock_guard lock(state.run->mutex);
if(!state.run->pending.empty())
{
batch=std::move(state.run->pending.front());
state.run->pending.pop_front();
}
else if(state.run->finished)
{
finished=true;
stopped=state.run->stopped;
state.nodes[0].size.partial|=state.run->result.partial;
}
}
if(batch.empty()) break;
if(!changed) SendMessageW(tree,WM_SETREDRAW,FALSE,0);
changed=true;
for(auto &event:batch) addSpaceEvent(tree,state,std::move(event));
} while(GetTickCount64()<budget);
if(finished) state.scanning=false;
if(changed) SendMessageW(tree,WM_SETREDRAW,TRUE,0);
if(state.mapVisible && (finished || (changed && GetTickCount64()-state.lastMapUpdate>=200)))
layoutSpaceMap(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…";
const auto &allocation=state.nodes[0].allocated;
auto label=std::wstring(status)+L" · "+std::to_wstring(state.files)+L" files";
if(allocation.unavailable || allocation.known.partial) label+=L" · on-disk sizes partial";
else label+=state.mapVisible?L" · logical size by area":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() &&
!sameLocalFolder(state.volume.root,state.folder));
KillTimer(dialog,spaceUpdateTimer);
}
}
void resetSpaceResults(HWND dialog,SpaceAnalyzer &state,bool scanning)
{
const auto tree=GetDlgItem(dialog,spaceTree);
TreeView_DeleteAllItems(tree);
state.nodes.clear();
state.nodes.push_back({.path=state.root,.folder=true,.expanded=true});
state.directories.clear();
state.directories.emplace(state.root,0);
state.files=0;
state.mapFolder=0;
state.tiles.clear();
state.selectedTile=0;
state.scanning=scanning;
state.hasResults=scanning;
TreeView_SelectItem(tree,insertSpaceNode(tree,state,0));
if(state.mapVisible) layoutSpaceMap(GetDlgItem(dialog,spaceMap),state);
EnableWindow(GetDlgItem(dialog,spaceView),FALSE);
EnableWindow(GetDlgItem(dialog,IDOK),!state.mapVisible);
}
void prepareSpaceScope(HWND dialog,SpaceAnalyzer &state)
{
state.run.reset();
const auto scope=state.volumeScope?state.volume.root:state.folder;
state.root=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() && !sameLocalFolder(state.volume.root,state.folder));
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,state.volumeScope);
EnableWindow(GetDlgItem(dialog,spaceStop),TRUE);
SetTimer(dialog,spaceUpdateTimer,60,nullptr);
updateSpaceTree(dialog,state);
}
catch(const std::exception &)
{
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
state.scanning=false;
EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() &&
!sameLocalFolder(state.volume.root,state.folder));
SetDlgItemTextW(dialog,spaceStatus,L"Could not start space analysis.");
}
}
INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &state=*reinterpret_cast<SpaceAnalyzer *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
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));
TreeView_SetBkColor(tree,RGB(255,255,255));
TreeView_SetTextColor(tree,RGB(0,0,0));
layoutSpaceAnalyzer(dialog);
const auto inset=dialogFrameMetrics(GetDpiForWindow(dialog)).content();
// 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);
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)
{
paintSpaceMap(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),*state);
return TRUE;
}
if(message==WM_TIMER && wp==spaceVolumeTimer)
{
updateSpaceVolume(dialog,*state);
return TRUE;
}
if(message==WM_TIMER && wp==spaceUpdateTimer)
{
updateSpaceTree(dialog,*state);
return TRUE;
}
if(message==WM_NOTIFY)
{
const auto *notification=reinterpret_cast<const NMHDR *>(lp);
if(notification->hwndFrom==tree)
{
if(notification->code==TVN_GETDISPINFOW)
{
auto &item=reinterpret_cast<NMTVDISPINFOW *>(lp)->item;
const auto index=static_cast<size_t>(item.lParam);
if(index>=state->nodes.size()) return TRUE;
const auto &node=state->nodes[index];
if(item.mask&TVIF_CHILDREN) item.cChildren=node.folder && !node.link &&
(state->scanning || !node.children.empty())?1:0;
if((item.mask&TVIF_TEXT) && item.pszText && item.cchTextMax>0)
{
const auto text=spaceNodeText(*state,index);
lstrcpynW(item.pszText,text.c_str(),item.cchTextMax);
}
return TRUE;
}
if(notification->code==TVN_ITEMEXPANDINGW)
{
const auto &item=*reinterpret_cast<const NMTREEVIEWW *>(lp);
const auto index=static_cast<size_t>(item.itemNew.lParam);
if(item.action==TVE_EXPAND && index<state->nodes.size()) expandSpaceNode(tree,*state,index);
}
if(notification->code==TVN_SELCHANGEDW)
{
const auto selected=selectedSpaceNode(tree,*state);
EnableWindow(GetDlgItem(dialog,spaceView),!state->mapVisible && selected && !state->nodes[*selected].folder);
EnableWindow(GetDlgItem(dialog,IDOK),!state->mapVisible && selected.has_value());
}
}
}
if(message==WM_COMMAND)
{
const auto command=LOWORD(wp);
if(command==spaceStop && IsWindowEnabled(GetDlgItem(dialog,spaceStop)))
{
state->run->stop.request_stop();
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
updateSpaceTree(dialog,*state);
return TRUE;
}
if(command==spaceScope && IsWindowEnabled(GetDlgItem(dialog,spaceScope)))
{
state->volumeScope=!state->volumeScope;
prepareSpaceScope(dialog,*state);
return TRUE;
}
if(command==spaceMapButton)
{
showSpaceMap(dialog,*state,!state->mapVisible);
if(state->run) updateSpaceTree(dialog,*state);
return TRUE;
}
if(command==spaceRescan && IsWindowEnabled(GetDlgItem(dialog,spaceRescan)))
{
rescanSpace(dialog,*state);
return TRUE;
}
if(command==IDOK || command==spaceView)
{
if(!state->mapVisible)
if(const auto selected=selectedSpaceNode(tree,*state))
finishSpaceSelection(dialog,*state,*selected,command);
return TRUE;
}
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message==WM_DESTROY)
{
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});
}
void openSpaceAnalyzer(HWND owner,Panel &panel)
{
if(panel.peer || panel.ftp || panel.directory.empty())
{
setStatus(L"Space Analyzer requires an open local folder.");
return;
}
const auto origin=static_cast<int>(&panel-panels);
SpaceAnalyzer state{.folder=panel.directory,.root=panel.directory};
const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(118),owner,
spaceAnalyzerDialog,reinterpret_cast<LPARAM>(&state));
if(answer==spaceView)
{
ks::files::openTextWindow(owner,state.selected,false,textWindowDialogs(),nullptr);
return;
}
if(answer!=IDOK) return;
if(quickViewWindow) toggleQuickView(owner);
if(terminalVisible) showTerminal(owner,false);
const auto index=1-origin;
auto &other=panels[index];
activatePanel(index);
panelClipboardContext=true;
if(state.selectedFolder) openOn(other,state.selected,true,{});
else revealLocalFile(other,state.selected);
}
+190
View File
@@ -0,0 +1,190 @@
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);
}
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())
{
auto bounds=paint.rcItem;
DrawTextW(paint.hDC,L"No measured space to display",-1,&bounds,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
return;
}
constexpr COLORREF surfaces[]{RGB(158,203,218),RGB(167,205,172),RGB(230,198,142),
RGB(197,179,211),RGB(226,178,173),RGB(177,190,225)};
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,surfaces[index%std::size(surfaces)]);
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);
}
}
}
}
}
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.mapVisible) layoutSpaceMap(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)};
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.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 showSpaceMap(HWND dialog,SpaceAnalyzer &state,bool show)
{
const auto tree=GetDlgItem(dialog,spaceTree), map=GetDlgItem(dialog,spaceMap);
state.mapVisible=show;
if(show)
{
const auto index=selectedSpaceNode(tree,state).value_or(0);
const auto &node=state.nodes[index];
state.mapFolder=node.folder && !node.link?index:node.parent;
layoutSpaceMap(map,state);
}
ShowWindow(tree,show?SW_HIDE:SW_SHOW);
ShowWindow(map,show?SW_SHOW:SW_HIDE);
SetDlgItemTextW(dialog,spaceMapButton,show?L"Tr&ee":L"Tree&map");
const auto selection=selectedSpaceNode(tree,state);
EnableWindow(GetDlgItem(dialog,spaceView),!show && selection && !state.nodes[*selection].folder);
EnableWindow(GetDlgItem(dialog,IDOK),!show && selection.has_value());
SetFocus(show?map:tree);
}
+65
View File
@@ -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."
}
+20 -75
View File
@@ -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-*') {
+62
View File
@@ -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) }
}