-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
366 lines (310 loc) · 9.39 KB
/
main.cpp
File metadata and controls
366 lines (310 loc) · 9.39 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
#include <iostream>
#include <chrono>
#include <thread>
#include <sstream>
#include <queue>
#include <optional>
#include <X11/extensions/randr.h>
#include <X11/extensions/Xrandr.h>
#include <getopt.h>
#include "XWindow.h"
#include "RuntimeError.h"
struct WindowState
{
XWindow window;
Position position;
std::vector<unsigned long> state;
};
using timepoint = std::chrono::system_clock::time_point;
static std::vector<WindowState>
GetWinddowsState(XWindow& window, const std::vector<std::string>& exclude)
{
std::vector<WindowState> windows;
for (auto& e : window.Children())
{
try
{
if (std::find(exclude.begin(), exclude.end(), e.Title()) == exclude.end())
{
windows.emplace_back(WindowState{e, e.CurrentPosition(), e.WmState()});
}
}
catch (const std::exception& ex)
{
std::cerr << "Couldn't read state for window: " << e.WindowHandle()
<< ", " << ex.what() << std::endl;
}
}
return windows;
}
void RestoreWindows(std::vector<WindowState>& state)
{
for (auto& e : state)
{
try
{
std::cerr << "Restoring window: " << e.window.WindowHandle() << " ("
<< e.window.Title() << ") -> " << e.position << std::endl;
e.window.SetPosition(e.position);
}
catch (const std::exception& ex)
{
std::cerr << "Error while restoring window: " << e.window.WindowHandle()
<< ", " << ex.what() << std::endl;
}
}
}
void ConsumeEvents(Display* display,
size_t timeout_ms,
std::queue<XEvent>& events)
{
auto deadline =
std::chrono::system_clock::now() + std::chrono::milliseconds(timeout_ms);
while (std::chrono::system_clock::now() < deadline)
{
while (XEventsQueued(display, QueuedAlready) > 0)
{
events.emplace();
XNextEvent(display, &events.back());
deadline = std::chrono::system_clock::now() +
std::chrono::milliseconds(timeout_ms);
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
XEvent NextEvent(Display* display, std::queue<XEvent>& queue)
{
if (queue.empty())
{
XEvent event{};
XNextEvent(display, &event);
return event;
}
else
{
XEvent event = queue.front();
queue.pop();
return event;
}
}
void Run(Display* display,
XWindow root,
size_t period_ms,
size_t event_timeout_ms,
size_t resize_timeout_ms,
int original_x,
int original_y,
const std::vector<std::string>& exclude,
const std::optional<std::string>& foreground_when_lost,
std::optional<size_t> foreground_delay_ms)
{
if (XSelectInput(display, root.WindowHandle(), RRScreenChangeNotifyMask) == 0)
{
throw RuntimeError("XSelectInput failed");
}
XRRSelectInput(display, root.WindowHandle(), RRScreenChangeNotifyMask);
int rr_event_base = 0;
int rr_error_base = 0;
if (!XRRQueryExtension(display, &rr_event_base, &rr_error_base))
{
throw RuntimeError("X11 RR extension is not available");
}
std::vector<WindowState> state;
bool all_screens_present = true;
timepoint last_event_ts;
std::queue<XEvent> queued_events;
while (true)
{
/* Race condition: It's in theory possible that the resolution changed
* just after the last XPending() call. That's why we have this extra
* timeout check here*/
auto now = std::chrono::system_clock::now();
if (all_screens_present &&
(state.empty() ||
last_event_ts + std::chrono::milliseconds(event_timeout_ms) < now))
{
state = GetWinddowsState(root, exclude);
}
std::this_thread::sleep_for(std::chrono::milliseconds(period_ms));
while (!queued_events.empty() || XPending(display))
{
XEvent event = NextEvent(display, queued_events);
last_event_ts = std::chrono::system_clock::now();
if (event.type != rr_event_base + RRScreenChangeNotify)
{
continue;
}
const auto* screen_event =
reinterpret_cast<XRRScreenChangeNotifyEvent*>(&event);
bool original_screens = screen_event->width == original_x &&
screen_event->height == original_y;
if (!all_screens_present && original_screens)
{
std::cerr << "Original screens detected" << std::endl;
// Wait a fixed amount of time to make sure all events are received
ConsumeEvents(display, resize_timeout_ms, queued_events);
RestoreWindows(state);
}
else if (all_screens_present && !original_screens)
{
std::cerr << "Original screens lost (" << screen_event->width << ", "
<< screen_event->height << ")" << std::endl;
for (auto& e : state)
{
try
{
if (e.window.Title() == foreground_when_lost)
{
if (foreground_delay_ms.has_value())
{
std::this_thread::sleep_for(
std::chrono::milliseconds(foreground_delay_ms.value()));
}
e.window.Activate();
std::cerr << "Activated window: " << e.window.Title()
<< std::endl;
break;
}
}
catch (const std::exception& e)
{
std::cerr << "Failed to get window title, " << e.what()
<< std::endl;
}
}
}
all_screens_present = original_screens;
}
}
}
void Help(const char* name)
{
const char* help =
"Usage: %s -x screen_witdh -y screen_height [--screen-timeout timeout_ms] [--refresh refresh_ms] [--exclude window1,window2] [--foreground_when_lost window] [--foreground-delay delay_ms]\n\
Options: \n\
-x: The width, in pixels of the original screen area\n\
-y: The height, in pixels of the original screen area\n\
--screen_timeout: The timeout, in milliseconds, to wait for RRScreenChangeNotify events after a new screen is plugged / unplugged\n\
--exclude: A comma separated list of window titles to exclude when saving / restoring positions\n\
--refresh: The refresh rate at which windows are to be saved (in milliseconds)\n\
--foreground-when-lost: window to put to the foreground when screens are lost\n\
--foreground-delay: delay before moving window to foreground, in milliseconds\n\
--help: Display this message\n";
fprintf(stderr, help, name);
std::cerr << "Build time: " << __DATE__ << " " << __TIME__ << std::endl;
}
int OnX11Error(Display* display, XErrorEvent* error)
{
std::cerr << "Received X11 error:" << error->error_code << ", "
<< error->minor_code << std::endl;
char text[1024] = {0};
int result = XGetErrorText(display, error->error_code, text, sizeof(text));
if (result != 0)
{
std::cerr << "XGetErrorText failed, " << error << std::endl;
return 0;
}
std::cerr << text << std::endl;
return 0;
}
int main(int argc, char** argv)
{
option options[] = {{"x", required_argument, 0, 'x'},
{"y", required_argument, 0, 'y'},
{"refresh", required_argument, 0, 'r'},
{"screen-timeout", required_argument, 0, 's'},
{"exclude", required_argument, 0, 'e'},
{"foreground-when-lost", required_argument, 0, 'f'},
{"resize-timeout", required_argument, 0, 'i'},
{"foreground-delay", required_argument, 0, 'd'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}};
auto parse_int = [](const char* str)
{
try
{
return std::stoul(str);
}
catch (const std::exception& e)
{
std::cerr << "Invalid integer value: " << str << ", " << str << std::endl;
exit(1);
}
};
int x = -1;
int y = -1;
size_t refresh_timeout = 5000;
size_t resize_timeout = 2000;
size_t screen_timeout = 2000;
std::optional<std::string> foreground_when_lost;
std::optional<size_t> foreground_delay;
std::vector<std::string> exclude;
int arg = -1;
int index = -1;
while ((arg = getopt_long(argc, argv, "x:y:r:s:e:d:h", options, &index)) != -1)
{
switch (arg)
{
case 'x':
x = parse_int(optarg);
break;
case 'y':
y = parse_int(optarg);
break;
case 'r':
refresh_timeout = parse_int(optarg);
break;
case 's':
screen_timeout = parse_int(optarg);
break;
case 'd':
foreground_delay = parse_int(optarg);
break;
case 'h':
Help(argv[0]);
exit(1);
break;
case 'f':
foreground_when_lost = optarg;
break;
case 'i':
resize_timeout = parse_int(optarg);
break;
case 'e':
{
std::istringstream str(optarg);
std::string window;
while (std::getline(str, window, ','))
{
exclude.emplace_back(std::move(window));
}
break;
}
}
}
if (optind != argc || x == -1 || y == -1)
{
Help(argv[0]);
return 1;
}
auto* display = XOpenDisplay(nullptr);
if (display == nullptr)
{
std::cerr << "Failed to open display" << std::endl;
return 1;
}
XSetErrorHandler(OnX11Error);
Window root = XDefaultRootWindow(display);
Run(display,
XWindow{display, root},
refresh_timeout,
screen_timeout,
resize_timeout,
x,
y,
exclude,
foreground_when_lost,
foreground_delay);
XCloseDisplay(display);
return 0;
}