Repository navigation
Expand file tree
/
Copy pathArrangeInstances.cpp
More file actions
430 lines (377 loc) · 14.3 KB
/
Copy pathArrangeInstances.cpp
File metadata and controls
430 lines (377 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#include <Windows.h>
#include <dwmapi.h>
#include <shellapi.h>
#include <tlhelp32.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <iostream>
#include <optional>
#include <regex>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#pragma comment(lib, "Dwmapi.lib")
#pragma comment(lib, "Shell32.lib")
#pragma comment(lib, "User32.lib")
struct DwmAttrOverride {
DWMWINDOWATTRIBUTE attr;
DWORD target;
DWORD original;
bool applied = false;
};
static std::array<DwmAttrOverride, 3> MakeDwmDecorationOverrides() {
return {{
{DWMWA_NCRENDERING_POLICY, static_cast<DWORD>(DWMNCRP_DISABLED),
static_cast<DWORD>(DWMNCRP_USEWINDOWSTYLE)},
{DWMWA_WINDOW_CORNER_PREFERENCE, static_cast<DWORD>(DWMWCP_DONOTROUND),
static_cast<DWORD>(DWMWCP_DEFAULT)},
{DWMWA_BORDER_COLOR, static_cast<DWORD>(DWMWA_COLOR_NONE),
static_cast<DWORD>(DWMWA_COLOR_DEFAULT)},
}};
}
// Maps each HWND to its original styles and DWM decoration attributes.
struct StyleData {
LONG_PTR style;
LONG_PTR exStyle;
std::array<DwmAttrOverride, 3> dwmAttrs;
};
std::unordered_map<HWND, StyleData> savedStyles;
HANDLE exitEvent = NULL;
void CaptureStyle(HWND hWnd) {
StyleData data{GetWindowLongPtr(hWnd, GWL_STYLE),
GetWindowLongPtr(hWnd, GWL_EXSTYLE),
MakeDwmDecorationOverrides()};
for (auto& o : data.dwmAttrs) {
DWORD current = 0;
if (SUCCEEDED(DwmGetWindowAttribute(hWnd, o.attr, ¤t, sizeof(current)))) {
o.original = current;
}
}
savedStyles[hWnd] = data;
}
void RestoreStyle(HWND hWnd) {
auto it = savedStyles.find(hWnd);
// Never captured, nothing to do.
if (it == savedStyles.end()) {
return;
}
// Window was closed while we were running.
if (!IsWindow(hWnd)) {
savedStyles.erase(it);
return;
}
SetWindowLongPtr(hWnd, GWL_STYLE, it->second.style);
SetWindowLongPtr(hWnd, GWL_EXSTYLE, it->second.exStyle);
for (const auto& o : it->second.dwmAttrs) {
if (o.applied) {
DwmSetWindowAttribute(hWnd, o.attr, &o.original, sizeof(o.original));
}
}
SetWindowPos(hWnd, NULL, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
savedStyles.erase(it);
}
void RestoreAllStyles() {
std::vector<HWND> keys;
keys.reserve(savedStyles.size());
for (const auto& [hwnd, _] : savedStyles) {
keys.push_back(hwnd);
}
for (HWND hwnd : keys) {
RestoreStyle(hwnd);
}
}
void DisableStyle(HWND hWnd) {
// The Win32 styles to disable.
const LONG_PTR styleMask = WS_CAPTION | WS_BORDER | WS_DLGFRAME | WS_SYSMENU |
WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
LONG_PTR currentStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
SetWindowLongPtr(hWnd, GWL_STYLE, currentStyle & ~styleMask);
const LONG_PTR exStyleMask =
WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE | WS_EX_DLGMODALFRAME |
WS_EX_STATICEDGE;
LONG_PTR currentExStyle = GetWindowLongPtr(hWnd, GWL_EXSTYLE);
SetWindowLongPtr(hWnd, GWL_EXSTYLE, currentExStyle & ~exStyleMask);
// Disable modern DWM decorations (drop shadow, Win11 rounded corners, border).
auto it = savedStyles.find(hWnd);
if (it != savedStyles.end()) {
for (auto& o : it->second.dwmAttrs) {
if (SUCCEEDED(DwmSetWindowAttribute(hWnd, o.attr, &o.target, sizeof(o.target)))) {
o.applied = true;
}
}
}
}
void SetTaskbarAutoHide(bool enable) {
HWND hTaskbar = FindWindowW(L"Shell_TrayWnd", NULL);
if (!hTaskbar) return;
APPBARDATA abd = {};
abd.cbSize = sizeof(APPBARDATA);
abd.hWnd = hTaskbar;
abd.lParam = enable ? ABS_AUTOHIDE : 0;
SHAppBarMessage(ABM_SETSTATE, &abd);
ShowWindow(hTaskbar, enable ? SW_HIDE : SW_SHOWNOACTIVATE);
}
std::unordered_set<DWORD> GetExcludedProcessIds() {
std::unordered_set<DWORD> excluded;
// Ignore ancestors of the process calling this program.
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot != INVALID_HANDLE_VALUE) {
std::unordered_map<DWORD, DWORD> parentMap;
PROCESSENTRY32 pe = {};
pe.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hSnapshot, &pe)) {
do {
parentMap[pe.th32ProcessID] = pe.th32ParentProcessID;
} while (Process32Next(hSnapshot, &pe));
}
CloseHandle(hSnapshot);
DWORD current = GetCurrentProcessId();
while (true) {
auto it = parentMap.find(current);
if (it == parentMap.end() || it->second == 0 || it->second == current)
break;
excluded.insert(it->second);
current = it->second;
}
}
// Exclude conhost.
HWND hConsole = GetConsoleWindow();
if (hConsole) {
DWORD conhostPid = 0;
GetWindowThreadProcessId(hConsole, &conhostPid);
excluded.insert(conhostPid);
}
// Exclude the visible terminal host (e.g. Windows Terminal via ConPTY).
// ConPTY has no HWND ancestry relationship with conhost, so we locate the
// terminal window by matching its title against the current console title.
char consoleTitle[MAX_PATH] = {};
if (GetConsoleTitleA(consoleTitle, MAX_PATH) > 0) {
HWND hTerminal = FindWindowA(NULL, consoleTitle);
if (hTerminal) {
DWORD terminalPid = 0;
GetWindowThreadProcessId(hTerminal, &terminalPid);
excluded.insert(terminalPid); // Windows Terminal PID
}
}
return excluded;
}
std::string FormatFileTime(const FILETIME& ft) {
SYSTEMTIME st{};
FILETIME local{};
FileTimeToLocalFileTime(&ft, &local);
FileTimeToSystemTime(&local, &st);
char buf[32];
snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d", st.wYear,
st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return buf;
}
FILETIME GetWindowCreationTime(HWND hWnd) {
DWORD processId;
GetWindowThreadProcessId(hWnd, &processId);
HANDLE hProcess =
OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId);
if (hProcess == NULL) return FILETIME{};
FILETIME creationTime, exitTime, kernelTime, userTime;
if (!GetProcessTimes(hProcess, &creationTime, &exitTime, &kernelTime,
&userTime)) {
CloseHandle(hProcess);
return FILETIME{};
}
CloseHandle(hProcess);
return creationTime;
}
struct EnumWindowsParams {
EnumWindowsParams(const std::regex& regex)
: regex(regex), excludedPids(GetExcludedProcessIds()) {}
std::vector<HWND> matchingWindows;
const std::regex regex;
const std::unordered_set<DWORD> excludedPids;
};
std::string WindowTitle(HWND hWnd) {
int length = GetWindowTextLength(hWnd);
if (length == 0) return "";
std::vector<char> buffer(length + 1);
GetWindowTextA(hWnd, buffer.data(), length + 1);
return std::string(buffer.data());
}
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {
EnumWindowsParams* params = reinterpret_cast<EnumWindowsParams*>(lParam);
if (!params) return FALSE;
// Skip excluded windows.
DWORD windowPid;
GetWindowThreadProcessId(hWnd, &windowPid);
if (params->excludedPids.count(windowPid)) return TRUE;
// Check if the window title matches the regular expression.
std::string windowTitle = WindowTitle(hWnd);
if (std::regex_match(windowTitle, params->regex)) {
params->matchingWindows.push_back(hWnd);
}
return TRUE;
}
bool WindowOrderCmp(HWND hWnd1, HWND hWnd2) {
FILETIME ft1 = GetWindowCreationTime(hWnd1);
FILETIME ft2 = GetWindowCreationTime(hWnd2);
int cmp = CompareFileTime(&ft1, &ft2);
if (cmp != 0) return cmp < 0;
return WindowTitle(hWnd1) < WindowTitle(hWnd2);
}
void SortWindows(std::vector<HWND>& hWndVector) {
std::sort(hWndVector.begin(), hWndVector.end(), WindowOrderCmp);
}
std::vector<HWND> GetProcesses(const std::regex& regex) {
EnumWindowsParams params(regex);
EnumWindows(EnumWindowsProc, reinterpret_cast<LPARAM>(¶ms));
SortWindows(params.matchingWindows);
std::cout << "Found " << params.matchingWindows.size()
<< " matching windows:" << std::endl;
for (const auto window : params.matchingWindows) {
std::cout << window << "\t" << FormatFileTime(GetWindowCreationTime(window))
<< "\t" << WindowTitle(window) << std::endl;
}
return params.matchingWindows;
}
// Explanation of how the optimal tiling is found in constant time:
// Constraint: To display all instances, we want to have N instances tiled in a
// rows * columns grid, so:
// • rows * columns = N
// Constraint: To maximize screen usage, we want the number of columns and rows
// to reshape the effective instanceRatio to match the screen's ratio, so:
// • (columns / rows) * instanceRatio = screenRatio
// N, instanceRatio, and screenRatio are known.
// To find the optimal tiling, solve the system of equations.
// • rows * columns = N
// • columns = N/rows
// Substitution:
// • (columns / rows) * instanceRatio = screenRatio
// • (N / rows^2) * instanceRatio = screenRatio
// • N * instanceRatio = screenRatio * rows^2
// • rows^2 = N * instanceRatio / screenRatio
// • rows = sqrt(N * instanceRatio / screenRatio)
// Then, since we know the number of rows:
// • columns = N/rows
// Which solves for columns.
// If we could have fractional rows and columns, as the system of equations
// solves for, we would perfectly fill the screen every time. Since this is not
// possible, we use the fractional part of the rows and columns count to
// determine which needs an extra row/column to accommodate all instances.
// Whichever remainder is higher should work better.
// Sometimes it's still not enough and we must add both an extra row and an
// extra column.
std::tuple<std::size_t, std::size_t> GetOptimalTiling(
double screenRatio, double instanceRatio, std::size_t instanceCount) {
double targetRatio = screenRatio / instanceRatio;
double h = sqrt(instanceCount / targetRatio);
double w = instanceCount / h;
std::cout << "h: " << h << "\t"
<< "w: " << w << std::endl;
std::size_t numTall = static_cast<std::size_t>(h);
std::size_t numWide = static_cast<std::size_t>(w);
// Determine if rounding must occur.
double remTall = h - numTall;
double remWide = w - numWide;
std::cout << "numTall: " << numTall << "\t"
<< "numWide: " << numWide << std::endl;
std::cout << "remTall: " << remTall << "\t"
<< "remWide: " << remWide << std::endl;
// If we do not have enough space to fit all instances, add an extra row or
// column, whichever minimizes the violation of the target aspect ratio.
// Decrement the remainder to ensure we alternate between increasing the
// number of rows or columns until we can fit the desired instance count.
while (numTall * numWide < instanceCount) {
if (remTall > remWide) {
numTall++;
remTall--;
} else {
numWide++;
remWide--;
}
}
std::cout << "numTall: " << numTall << "\t"
<< "numWide: " << numWide << std::endl;
return {numWide, numTall};
}
std::tuple<int, int> GetDesktopResolution() {
RECT desktop;
const HWND hDesktop = GetDesktopWindow();
// Get the size of screen to the variable desktop
GetWindowRect(hDesktop, &desktop);
// The top left corner will have coordinates (0,0)
// and the bottom right corner will have coordinates
// (horizontal, vertical)
return {static_cast<int>(desktop.right), static_cast<int>(desktop.bottom)};
}
void PlaceWindows(const std::vector<HWND>& instances, double instanceRatio,
const std::optional<std::tuple<std::size_t, std::size_t>>&
tiling = std::nullopt) {
const auto [screenW, screenH] = GetDesktopResolution();
std::size_t numWide, numTall;
if (!tiling) {
double screenRatio =
static_cast<double>(screenW) / static_cast<double>(screenH);
std::tie(numWide, numTall) =
GetOptimalTiling(screenRatio, instanceRatio, instances.size());
} else {
std::tie(numWide, numTall) = tiling.value();
}
// Dimensions of each instance.
const int width = screenW / static_cast<int>(numWide);
const int height = screenH / static_cast<int>(numTall);
// Reposition each instance.
for (std::size_t i = 0; i < instances.size(); i++) {
const int xPos = static_cast<int>(i % numWide) * width;
const int yPos = static_cast<int>(i / numWide) * height;
SetWindowPos(instances[i], NULL, xPos, yPos, width, height,
SWP_SHOWWINDOW | SWP_FRAMECHANGED);
}
}
BOOL WINAPI ConsoleCtrlHandler(DWORD signal) {
if (signal == CTRL_C_EVENT || signal == CTRL_BREAK_EVENT ||
signal == CTRL_CLOSE_EVENT) {
// Signal the main to wake up and clean up, then stall this thread so the
// process isn't killed before main finishes.
SetEvent(exitEvent);
Sleep(3000);
return TRUE;
}
return FALSE;
}
int main(int argc, char* argv[]) {
if (argc <= 2) {
std::cout << "Usage: " << argv[0]
<< " <instanceRatio (width/height)> <ProcessRegEx>\n"
<< "\tExample: " << argv[0]
<< " 1.33333333333 \"Dolphin.* \\|.*\"" << std::endl
<< "\tExample: " << argv[0] << " 0.666666667 \".*melonDS .*\""
<< std::endl
<< "\tExample: " << argv[0]
<< " 1.77777777777 \"yuzu Mainline.*\"" << std::endl
<< "\tExample: " << argv[0] << " 1.5 \"mGBA.*\"" << std::endl;
return -1;
}
const double instanceRatio = std::stod(argv[1]);
const std::string procRegexStr = argv[2];
std::regex procRegex(procRegexStr, std::regex_constants::grep);
std::vector<HWND> instances = GetProcesses(procRegex);
if (instances.empty()) {
std::cout << "No matching windows found." << std::endl;
return 0;
}
exitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
for (const HWND hwnd : instances) {
CaptureStyle(hwnd);
DisableStyle(hwnd);
}
SetTaskbarAutoHide(true);
PlaceWindows(instances, instanceRatio);
std::cout << "Running. Close this window to restore and exit." << std::endl;
WaitForSingleObject(exitEvent, INFINITE);
std::cout << "\nCleaning up..." << std::endl;
SetTaskbarAutoHide(false);
RestoreAllStyles();
CloseHandle(exitEvent);
return 0;
}