-
Notifications
You must be signed in to change notification settings - Fork 7.2k
Expand file tree
/
Copy pathsandbox.cpp
More file actions
773 lines (688 loc) · 22.6 KB
/
Copy pathsandbox.cpp
File metadata and controls
773 lines (688 loc) · 22.6 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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "core/sandbox.h"
#include "base/platform/base_platform_info.h"
#include "platform/platform_specific.h"
#include "mainwidget.h"
#include "mainwindow.h"
#include "storage/localstorage.h"
#include "window/notifications_manager.h"
#include "window/window_controller.h"
#include "core/crash_reports.h"
#include "core/crash_report_window.h"
#include "core/application.h"
#include "core/external_control.h"
#include "core/launcher.h"
#include "core/local_url_handlers.h"
#include "core/update_checker.h"
#include "core/deadlock_detector.h"
#include "base/timer.h"
#include "base/concurrent_timer.h"
#include "base/invoke_queued.h"
#include "base/options.h"
#include "base/qthelp_url.h"
#include "base/qthelp_regex.h"
#include "ui/ui_utility.h"
#include "ui/effects/animations.h"
#ifdef Q_OS_MAC
#include "platform/mac/global_menu_mac.h"
#endif // Q_OS_MAC
#include <QtCore/QLockFile>
#include <QtGui/QSessionManager>
#include <QtGui/QScreen>
#include <QtGui/qpa/qplatformscreen.h>
namespace Core {
namespace {
base::options::toggle OptionDeadlockDetector({
.id = kOptionDeadlockDetector,
.name = "Deadlock Detector",
.description = "Check once every 30 seconds that main thread is still responsive.",
});
constexpr auto kCleanupIpcTimeout = 10 * crl::time(1000);
constexpr auto kCleanupQuitTimeout = 30 * crl::time(1000);
} // namespace
const char kOptionDeadlockDetector[] = "deadlock-detector";
bool Sandbox::QuitOnStartRequested = false;
bool Sandbox::SystemShuttingDown = false;
Sandbox::Sandbox(int &argc, char **argv)
: QApplication(argc, argv)
, _mainThreadId(QThread::currentThreadId()) {
#ifdef Q_OS_MAC
Platform::CreateGlobalMenu();
#endif // Q_OS_MAC
}
int Sandbox::start() {
{
const auto d = QFile::encodeName(QDir(cWorkingDir()).absolutePath());
char h[33] = { 0 };
hashMd5Hex(d.constData(), d.size(), h);
_localServerName = Platform::SingleInstanceLocalServerName(h);
}
if (cLaunchMode() == LaunchModeCleanup) {
const auto result = stopRunningInstance();
psCleanup();
closeApplication();
return result;
}
if (!Core::UpdaterDisabled()) {
_updateChecker = std::make_unique<Core::UpdateChecker>();
}
{
const auto d = QFile::encodeName(cExeDir() + cExeName());
QByteArray h;
h.resize(32);
hashMd5Hex(d.constData(), d.size(), h.data());
_lockFile = std::make_unique<QLockFile>(QDir::tempPath() + '/' + h + '-' + cGUIDStr());
_lockFile->setStaleLockTime(0);
if (!_lockFile->tryLock()
&& Launcher::Instance().customWorkingDir()) {
// On Windows, QLockFile has problems detecting a stale lock
// if the machine's hostname contains characters outside the US-ASCII character set.
if constexpr (Platform::IsWindows()) {
// QLockFile::removeStaleLockFile returns false on Windows,
// when the application owning the lock is still running.
if (!_lockFile->removeStaleLockFile()) {
gManyInstance = true;
}
} else {
gManyInstance = true;
}
}
}
#if defined Q_OS_LINUX && QT_VERSION >= QT_VERSION_CHECK(6, 2, 0)
_localServer.setSocketOptions(QLocalServer::AbstractNamespaceOption);
_localSocket.setSocketOptions(QLocalSocket::AbstractNamespaceOption);
#endif // Q_OS_LINUX && Qt >= 6.2.0
connect(
&_localSocket,
&QLocalSocket::connected,
[=] { socketConnected(); });
connect(
&_localSocket,
&QLocalSocket::disconnected,
[=] { socketDisconnected(); });
connect(
&_localSocket,
&QLocalSocket::errorOccurred,
[=](QLocalSocket::LocalSocketError error) { socketError(error); });
connect(
&_localSocket,
&QLocalSocket::bytesWritten,
[=](qint64 bytes) { socketWritten(bytes); });
connect(
&_localSocket,
&QLocalSocket::readyRead,
[=] { socketReading(); });
connect(
&_localServer,
&QLocalServer::newConnection,
[=] { newInstanceConnected(); });
crl::on_main(this, [=] { checkForQuit(); });
connect(this, &QCoreApplication::aboutToQuit, [=] {
// On Windows, Qt emits aboutToQuit synchronously from its
// WM_ENDSESSION handler (QWindowsContext::windowsProc). Running
// closeApplication() there destroys QWindows mid-dispatch and
// later WM_ENDSESSION messages delivered to other top-level
// HWNDs crash on virtual dispatch through stale QWindow*. Detect
// that path and defer cleanup to the next main-loop tick so Qt
// finishes delivering shutdown messages on still-live windows.
// On a normal quit (Ctrl+Q etc.) aboutToQuit fires from the
// exec() epilogue after the event loop has exited and queued
// events would not run, so we keep the synchronous teardown.
if (SystemShuttingDown) {
QMetaObject::invokeMethod(this, [=] {
customEnterFromEventLoop([&] {
closeApplication();
});
}, Qt::QueuedConnection);
} else {
customEnterFromEventLoop([&] {
closeApplication();
});
}
});
// https://github.com/telegramdesktop/tdesktop/issues/948
// and https://github.com/telegramdesktop/tdesktop/issues/5022
connect(this, &QGuiApplication::saveStateRequest, [](auto &manager) {
manager.setRestartHint(QSessionManager::RestartNever);
});
LOG(("Connecting local socket to %1...").arg(_localServerName));
_localSocket.connectToServer(_localServerName);
if (QuitOnStartRequested) {
closeApplication();
return 0;
}
_started = true;
return exec();
}
int Sandbox::stopRunningInstance() {
LOG(("Cleanup: connecting to %1...").arg(_localServerName));
_localSocket.connectToServer(_localServerName);
if (!_localSocket.waitForConnected(int(kCleanupIpcTimeout))) {
if (_localSocket.error() == QLocalSocket::ServerNotFoundError) {
LOG(("Cleanup: no running instance found."));
return 0;
}
LOG(("Cleanup: connect error %1.").arg(_localSocket.error()));
return 1;
}
_localSocket.write("CMD:quit;");
if (!_localSocket.waitForBytesWritten(int(kCleanupIpcTimeout))) {
LOG(("Cleanup: could not send the quit command."));
return 1;
}
auto response = QByteArray();
const auto deadline = crl::now() + kCleanupIpcTimeout;
while (!response.contains(';')) {
const auto timeout = deadline - crl::now();
if (timeout <= 0 || !_localSocket.waitForReadyRead(int(timeout))) {
LOG(("Cleanup: no response to the quit command."));
return 1;
}
response.append(_localSocket.readAll());
}
const auto match = QRegularExpression(u"RES:(\\d+)_(\\d+);"_q).match(
QString::fromLatin1(response));
if (!match.hasMatch()) {
LOG(("Cleanup: bad response to the quit command."));
return 1;
}
const auto processId = match.capturedView(1).toULongLong();
LOG(("Cleanup: waiting for process %1 to quit...").arg(processId));
if (!Platform::WaitForProcessExit(processId, kCleanupQuitTimeout)) {
LOG(("Cleanup: the process did not quit in time."));
return 1;
}
LOG(("Cleanup: the running instance quit."));
return 0;
}
void Sandbox::NotifySystemShuttingDown() {
SystemShuttingDown = true;
}
void Sandbox::QuitWhenStarted() {
if (!QApplication::instance() || !Instance()._started) {
QuitOnStartRequested = true;
} else {
// Use exit(0) instead of quit() to avoid recursive
// [NSApp terminate:] on macOS. Since Qt 6.0, quit() routes
// through QCocoaIntegration::quit() -> [NSApp terminate:],
// which when called from within applicationShouldTerminate:
// causes a nested terminate that leads to exit() being called
// directly, bypassing normal cleanup. exit(0) properly exits
// event loops without going through the platform plugin.
QCoreApplication::exit(0);
}
}
void Sandbox::launchApplication() {
InvokeQueued(this, [=] {
if (Quitting()) {
quit();
} else if (_application) {
return;
}
setupScreenScale();
rpl::single(
rpl::empty
) | rpl::then(
OptionDeadlockDetector.changes()
) | rpl::on_next([=] {
using DeadlockDetector::PingThread;
// The test agent always wants a stuck main thread to crash with a
// report instead of hanging silently, so force it on for -testagent.
_deadlockDetector = (OptionDeadlockDetector.value() || cTestAgent())
? std::make_unique<PingThread>(this)
: nullptr;
}, _lifetime);
_application = std::make_unique<Application>();
// Ideally this should go to constructor.
// But we want to catch all native events and Application installs
// its own filter that can filter out some of them. So we install
// our filter after the Application constructor installs his.
installNativeEventFilter(this);
_application->run();
});
}
void Sandbox::setupScreenScale() {
const auto ratio = devicePixelRatio();
LOG(("Global devicePixelRatio: %1").arg(ratio));
const auto logEnv = [](const char *name) {
const auto value = qEnvironmentVariable(name);
if (!value.isEmpty()) {
LOG(("%1: %2").arg(name, value));
}
};
logEnv("QT_DEVICE_PIXEL_RATIO");
logEnv("QT_AUTO_SCREEN_SCALE_FACTOR");
logEnv("QT_ENABLE_HIGHDPI_SCALING");
logEnv("QT_SCALE_FACTOR");
logEnv("QT_SCREEN_SCALE_FACTORS");
logEnv("QT_SCALE_FACTOR_ROUNDING_POLICY");
logEnv("QT_DPI_ADJUSTMENT_POLICY");
logEnv("QT_USE_PHYSICAL_DPI");
logEnv("QT_FONT_DPI");
const auto useRatio = std::clamp(qCeil(ratio), 1, 3);
style::SetDevicePixelRatio(useRatio);
const auto screen = Sandbox::primaryScreen();
const auto dpi = screen->logicalDotsPerInch();
const auto basePair = screen->handle()->logicalBaseDpi();
const auto base = (basePair.first + basePair.second) * 0.5;
const auto screenScaleExact = dpi / base;
const auto screenScale = int(base::SafeRound(screenScaleExact * 20)) * 5;
LOG(("Primary screen DPI: %1, Base: %2.").arg(dpi).arg(base));
LOG(("Computed screen scale: %1").arg(screenScale));
if (Platform::IsMac()) {
// 110% for Retina screens by default.
cSetScreenScale((useRatio == 2) ? 110 : style::kScaleDefault);
} else {
cSetScreenScale(std::clamp(
screenScale,
style::kScaleMin,
style::MaxScaleForRatio(useRatio)));
}
LOG(("DevicePixelRatio: %1").arg(useRatio));
LOG(("ScreenScale: %1").arg(cScreenScale()));
}
Sandbox::~Sandbox() {
// When WM_ENDSESSION deferred closeApplication() to a main-loop
// tick that never came, the Application is still alive here and
// would be destroyed by member teardown at base nesting level,
// where Ui::PostponeCall bookkeeping is not allowed. Destroy it
// inside enter-from-event-loop instead, like a normal quit does.
customEnterFromEventLoop([&] {
closeApplication();
});
#ifdef Q_OS_MAC
Platform::DestroyGlobalMenu();
#endif // Q_OS_MAC
}
bool Sandbox::event(QEvent *e) {
if (e->type() == QEvent::Quit) {
if (Quitting()) {
return QCoreApplication::event(e);
}
Quit(QuitReason::QtQuitEvent);
e->ignore();
return false;
} else if (e->type() == QEvent::Close) {
Quit();
} else if (e->type() == DeadlockDetector::PingPongEvent::Type()) {
postEvent(
static_cast<DeadlockDetector::PingPongEvent*>(e)->sender(),
new DeadlockDetector::PingPongEvent(this));
}
return QApplication::event(e);
}
void Sandbox::socketConnected() {
LOG(("Socket connected, this is not the first application instance, sending show command..."));
_secondInstance = true;
QString commands;
if (qEnvironmentVariableIsSet("XDG_ACTIVATION_TOKEN")) {
commands += u"XDG_ACTIVATION_TOKEN:"_q + qgetenv("XDG_ACTIVATION_TOKEN").toBase64() + ';';
}
for (const auto &url : cRefStartUrls()) {
commands += u"OPEN:"_q + url.toString(QUrl::FullyEncoded) + ';';
}
if (cQuit()) {
commands += u"CMD:quit;"_q;
} else if (cRefStartUrls().isEmpty()) {
commands += u"CMD:show;"_q;
}
DEBUG_LOG(("Sandbox Info: writing commands %1").arg(commands));
_localSocket.write(commands.toLatin1());
}
void Sandbox::socketWritten(qint64/* bytes*/) {
if (_localSocket.state() != QLocalSocket::ConnectedState) {
LOG(("Socket is not connected %1").arg(_localSocket.state()));
return;
}
if (_localSocket.bytesToWrite()) {
return;
}
LOG(("Show command written, waiting response..."));
}
void Sandbox::socketReading() {
if (_localSocket.state() != QLocalSocket::ConnectedState) {
LOG(("Socket is not connected %1").arg(_localSocket.state()));
return;
}
_localSocketReadData.append(_localSocket.readAll());
const auto m = QRegularExpression(u"RES:(\\d+)_(\\d+);"_q).match(
_localSocketReadData);
if (!m.hasMatch()) {
return;
}
const auto processId = m.capturedView(1).toULongLong();
const auto windowId = m.capturedView(2).toULongLong();
if (windowId) {
Platform::ActivateOtherProcess(processId, windowId);
}
LOG(("Show command response received, processId = %1, windowId = %2, "
"activating and quitting..."
).arg(processId
).arg(windowId));
return Quit();
}
void Sandbox::socketError(QLocalSocket::LocalSocketError e) {
if (Quitting()) return;
if (_secondInstance) {
LOG(("Could not write show command, error %1, quitting...").arg(e));
return Quit();
}
if (e == QLocalSocket::ServerNotFoundError) {
LOG(("This is the only instance of Telegram, starting server and app..."));
} else {
LOG(("Socket connect error %1, starting server and app...").arg(e));
}
_localSocket.close();
// Local server does not work in WinRT build.
#ifndef Q_OS_WINRT
psCheckLocalSocket(_localServerName);
if (!_localServer.listen(_localServerName)) {
LOG(("Failed to start listening to %1 server: %2").arg(_localServerName, _localServer.errorString()));
return Quit();
}
#endif // !Q_OS_WINRT
if (!Core::UpdaterDisabled()
&& !cNoStartUpdate()
&& Core::checkReadyUpdate()) {
cSetRestartingUpdate(true);
DEBUG_LOG(("Sandbox Info: installing update instead of starting app..."));
return Quit();
}
if (cQuit()) {
return Quit();
}
singleInstanceChecked();
}
void Sandbox::singleInstanceChecked() {
if (cManyInstance()) {
LOG(("App Info: Detected another instance"));
}
refreshGlobalProxy();
if (!Logs::started() || !Logs::instanceChecked()) {
new NotStartedWindow();
return;
}
const auto result = CrashReports::Start();
v::match(result, [&](CrashReports::Status status) {
if (status == CrashReports::CantOpen) {
new NotStartedWindow();
} else {
launchApplication();
}
}, [&](const QByteArray &crashdump) {
// If crash dump is empty with that status it means that we
// didn't close the application properly. Just ignore for now.
if (crashdump.isEmpty()) {
if (CrashReports::Restart() == CrashReports::CantOpen) {
new NotStartedWindow();
} else {
launchApplication();
}
return;
}
_lastCrashDump = crashdump;
auto window = new LastCrashedWindow(
_lastCrashDump,
[=] { launchApplication(); });
window->proxyChanges(
) | rpl::on_next([=](MTP::ProxyData &&proxy) {
_sandboxProxy = std::move(proxy);
refreshGlobalProxy();
}, window->lifetime());
});
}
void Sandbox::socketDisconnected() {
if (_secondInstance) {
DEBUG_LOG(("Sandbox Error: socket disconnected before command response received, quitting..."));
return Quit();
}
}
void Sandbox::newInstanceConnected() {
DEBUG_LOG(("Sandbox Info: new local socket connected"));
for (auto client = _localServer.nextPendingConnection(); client; client = _localServer.nextPendingConnection()) {
_localClients.push_back(LocalClient(client, QByteArray()));
connect(
client,
&QLocalSocket::readyRead,
[=] { readClients(); });
connect(
client,
&QLocalSocket::disconnected,
[=] { removeClients(); });
}
}
void Sandbox::readClients() {
// This method can be called before Application is constructed.
QList<QUrl> startUrls;
for (LocalClients::iterator i = _localClients.begin(), e = _localClients.end(); i != e; ++i) {
i->second.append(i->first->readAll());
if (i->second.size()) {
bool activationRequired = false;
QString cmds(QString::fromLatin1(i->second));
int32 from = 0, l = cmds.length();
for (int32 to = cmds.indexOf(QChar(';'), from); to >= from; to = (from < l) ? cmds.indexOf(QChar(';'), from) : -1) {
auto cmd = base::StringViewMid(cmds, from, to - from);
if (cmd.startsWith(u"CMD:"_q)) {
const auto processId = QApplication::applicationPid();
const auto windowId = execExternal(cmds.mid(from + 4, to - from - 4));
const auto response = u"RES:%1_%2;"_q.arg(processId).arg(windowId).toLatin1();
i->first->write(response.data(), response.size());
} else if (cmd.startsWith(u"XDG_ACTIVATION_TOKEN:"_q)) {
qputenv("XDG_ACTIVATION_TOKEN", QByteArray::fromBase64(cmds.mid(from + 21, to - from - 21).toLatin1()));
} else if (cmd.startsWith(u"OPEN:"_q)) {
startUrls.append(cmds.mid(from + 5, to - from - 5).mid(0, 8192));
if (!activationRequired) {
activationRequired = StartUrlRequiresActivate(startUrls.back().toString());
}
} else if (cmd.startsWith(u"CTRL:"_q)) {
const auto payload = HandleExternalControl(
cmds.mid(from + 5, to - from - 5));
const auto response = QByteArray("DATA:")
+ payload.toBase64()
+ ';';
i->first->write(response);
} else {
LOG(("Sandbox Error: unknown command %1 passed in local socket").arg(cmd.toString()));
}
from = to + 1;
}
if (from > 0) {
i->second = i->second.mid(from);
}
const auto processId = QApplication::applicationPid();
const auto windowId = activationRequired
? execExternal("show")
: 0;
const auto response = u"RES:%1_%2;"_q.arg(processId).arg(windowId).toLatin1();
i->first->write(response.data(), response.size());
}
}
cRefStartUrls() << base::take(startUrls);
if (_application) {
_application->checkStartUrls();
}
}
void Sandbox::removeClients() {
DEBUG_LOG(("Sandbox Info: remove clients slot called, clients %1"
).arg(_localClients.size()));
for (auto i = _localClients.begin(), e = _localClients.end(); i != e;) {
if (i->first->state() != QLocalSocket::ConnectedState) {
DEBUG_LOG(("Sandbox Info: removing client"));
i = _localClients.erase(i);
e = _localClients.end();
} else {
++i;
}
}
}
void Sandbox::checkForQuit() {
if (Quitting()) {
quit();
}
}
void Sandbox::refreshGlobalProxy() {
const auto proxy = !Core::IsAppLaunched()
? _sandboxProxy
: Core::App().settings().proxy().isEnabled()
? Core::App().settings().proxy().selected()
: MTP::ProxyData();
if (proxy.type == MTP::ProxyData::Type::Socks5
|| proxy.type == MTP::ProxyData::Type::Http) {
QNetworkProxy::setApplicationProxy(
MTP::ToNetworkProxy(MTP::ToDirectIpProxy(proxy)));
} else if (!Core::IsAppLaunched()
|| Core::App().settings().proxy().isSystem()) {
QNetworkProxyFactory::setUseSystemConfiguration(true);
} else {
QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy);
}
}
void Sandbox::checkForEmptyLoopNestingLevel() {
// _loopNestingLevel == _eventNestingLevel means that we had a
// native event in a nesting loop that didn't get a notify() call
// after. That means we already have exited the nesting loop and
// there must not be any postponed calls with that nesting level.
if (_loopNestingLevel == _eventNestingLevel) {
Assert(_postponedCallsDeferred
|| _postponedCalls.empty()
|| _postponedCalls.back().loopNestingLevel < _loopNestingLevel);
Assert(!_previousLoopNestingLevels.empty());
_loopNestingLevel = _previousLoopNestingLevels.back();
_previousLoopNestingLevels.pop_back();
}
}
void Sandbox::postponeCall(FnMut<void()> &&callable) {
Expects(callable != nullptr);
Expects(_eventNestingLevel >= _loopNestingLevel);
checkForEmptyLoopNestingLevel();
_postponedCalls.push_back({
_loopNestingLevel,
std::move(callable)
});
}
void Sandbox::incrementEventNestingLevel() {
++_eventNestingLevel;
}
void Sandbox::decrementEventNestingLevel() {
Expects(_eventNestingLevel >= _loopNestingLevel);
if (_eventNestingLevel == _loopNestingLevel) {
_loopNestingLevel = _previousLoopNestingLevels.back();
_previousLoopNestingLevels.pop_back();
}
const auto processTillLevel = _eventNestingLevel - 1;
processPostponedCalls(processTillLevel);
checkForEmptyLoopNestingLevel();
_eventNestingLevel = processTillLevel;
Ensures(_eventNestingLevel >= _loopNestingLevel);
}
void Sandbox::registerEnterFromEventLoop() {
Expects(_eventNestingLevel >= _loopNestingLevel);
if (_eventNestingLevel > _loopNestingLevel) {
_previousLoopNestingLevels.push_back(_loopNestingLevel);
_loopNestingLevel = _eventNestingLevel;
}
}
bool Sandbox::notify(QObject *receiver, QEvent *e) {
if (QThread::currentThreadId() != _mainThreadId) {
return QApplication::notify(receiver, e);
}
const auto wrap = createEventNestingLevel();
if (e->type() == QEvent::UpdateRequest) {
const auto weak = QPointer<QObject>(receiver);
_widgetUpdateRequests.fire({});
if (!weak) {
return true;
}
}
return QApplication::notify(receiver, e);
}
void Sandbox::processPostponedCalls(int level) {
if (_postponedCallsDeferred) {
return;
}
while (!_postponedCalls.empty()) {
auto &last = _postponedCalls.back();
if (last.loopNestingLevel != level) {
break;
}
auto taken = std::move(last);
_postponedCalls.pop_back();
taken.callable();
}
}
void Sandbox::drainPostponedCalls() {
Expects(QThread::currentThreadId() == _mainThreadId);
if (!cTestAgent()) {
return;
}
const auto wasDeferred = std::exchange(_postponedCallsDeferred, true);
const auto guard = gsl::finally([&] {
_postponedCallsDeferred = wasDeferred;
});
while (!_postponedCalls.empty()) {
auto taken = std::move(_postponedCalls.back());
_postponedCalls.pop_back();
taken.callable();
}
}
void Sandbox::setPostponedCallsDeferred(bool deferred) {
Expects(QThread::currentThreadId() == _mainThreadId);
if (!cTestAgent()) {
return;
}
_postponedCallsDeferred = deferred;
}
bool Sandbox::nativeEventFilter(
const QByteArray &eventType,
void *message,
native_event_filter_result *result) {
registerEnterFromEventLoop();
return false;
}
rpl::producer<> Sandbox::widgetUpdateRequests() const {
return _widgetUpdateRequests.events();
}
MTP::ProxyData Sandbox::sandboxProxy() const {
return _sandboxProxy;
}
void Sandbox::closeApplication() {
if (CurrentLaunchState() == LaunchState::QuitProcessed) {
return;
}
SetLaunchState(LaunchState::QuitProcessed);
_application = nullptr;
_localServer.close();
for (const auto &localClient : base::take(_localClients)) {
localClient.first->close();
}
_localClients.clear();
_localSocket.close();
_updateChecker = nullptr;
}
uint64 Sandbox::execExternal(const QString &cmd) {
DEBUG_LOG(("Sandbox Info: executing external command '%1'").arg(cmd));
if (cmd == "show") {
if (Core::IsAppLaunched() && Core::App().activePrimaryWindow()) {
const auto window = Core::App().activePrimaryWindow();
window->activate();
return Platform::ActivationWindowId(window->widget());
} else if (const auto window = PreLaunchWindow::instance()) {
window->activate();
return Platform::ActivationWindowId(window);
}
} else if (cmd == "quit") {
Quit();
}
return 0;
}
} // namespace Core
namespace crl {
rpl::producer<> on_main_update_requests() {
return Core::Sandbox::Instance().widgetUpdateRequests();
}
} // namespace crl