sandbox.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #include "core/sandbox.h"
  8. #include "base/platform/base_platform_info.h"
  9. #include "platform/platform_specific.h"
  10. #include "mainwidget.h"
  11. #include "mainwindow.h"
  12. #include "storage/localstorage.h"
  13. #include "window/notifications_manager.h"
  14. #include "window/window_controller.h"
  15. #include "core/crash_reports.h"
  16. #include "core/crash_report_window.h"
  17. #include "core/application.h"
  18. #include "core/launcher.h"
  19. #include "core/local_url_handlers.h"
  20. #include "core/update_checker.h"
  21. #include "core/deadlock_detector.h"
  22. #include "base/timer.h"
  23. #include "base/concurrent_timer.h"
  24. #include "base/invoke_queued.h"
  25. #include "base/qthelp_url.h"
  26. #include "base/qthelp_regex.h"
  27. #include "ui/ui_utility.h"
  28. #include "ui/effects/animations.h"
  29. #include <QtCore/QLockFile>
  30. #include <QtGui/QSessionManager>
  31. #include <QtGui/QScreen>
  32. #include <QtGui/qpa/qplatformscreen.h>
  33. namespace Core {
  34. namespace {
  35. QChar _toHex(ushort v) {
  36. v = v & 0x000F;
  37. return QChar::fromLatin1((v >= 10) ? ('a' + (v - 10)) : ('0' + v));
  38. }
  39. ushort _fromHex(QChar c) {
  40. return ((c.unicode() >= uchar('a')) ? (c.unicode() - uchar('a') + 10) : (c.unicode() - uchar('0'))) & 0x000F;
  41. }
  42. QString _escapeTo7bit(const QString &str) {
  43. QString result;
  44. result.reserve(str.size() * 2);
  45. for (int i = 0, l = str.size(); i != l; ++i) {
  46. QChar ch(str.at(i));
  47. ushort uch(ch.unicode());
  48. if (uch < 32 || uch > 127 || uch == ushort(uchar('%'))) {
  49. result.append('%').append(_toHex(uch >> 12)).append(_toHex(uch >> 8)).append(_toHex(uch >> 4)).append(_toHex(uch));
  50. } else {
  51. result.append(ch);
  52. }
  53. }
  54. return result;
  55. }
  56. QString _escapeFrom7bit(const QString &str) {
  57. QString result;
  58. result.reserve(str.size());
  59. for (int i = 0, l = str.size(); i != l; ++i) {
  60. QChar ch(str.at(i));
  61. if (ch == QChar::fromLatin1('%') && i + 4 < l) {
  62. result.append(QChar(ushort((_fromHex(str.at(i + 1)) << 12) | (_fromHex(str.at(i + 2)) << 8) | (_fromHex(str.at(i + 3)) << 4) | _fromHex(str.at(i + 4)))));
  63. i += 4;
  64. } else {
  65. result.append(ch);
  66. }
  67. }
  68. return result;
  69. }
  70. } // namespace
  71. bool Sandbox::QuitOnStartRequested = false;
  72. Sandbox::Sandbox(int &argc, char **argv)
  73. : QApplication(argc, argv)
  74. , _mainThreadId(QThread::currentThreadId()) {
  75. }
  76. int Sandbox::start() {
  77. if (!Core::UpdaterDisabled()) {
  78. _updateChecker = std::make_unique<Core::UpdateChecker>();
  79. }
  80. {
  81. const auto d = QFile::encodeName(QDir(cWorkingDir()).absolutePath());
  82. char h[33] = { 0 };
  83. hashMd5Hex(d.constData(), d.size(), h);
  84. _localServerName = Platform::SingleInstanceLocalServerName(h);
  85. }
  86. {
  87. const auto d = QFile::encodeName(cExeDir() + cExeName());
  88. QByteArray h;
  89. h.resize(32);
  90. hashMd5Hex(d.constData(), d.size(), h.data());
  91. _lockFile = std::make_unique<QLockFile>(QDir::tempPath() + '/' + h + '-' + cGUIDStr());
  92. _lockFile->setStaleLockTime(0);
  93. if (!_lockFile->tryLock()
  94. && Launcher::Instance().customWorkingDir()) {
  95. // On Windows, QLockFile has problems detecting a stale lock
  96. // if the machine's hostname contains characters outside the US-ASCII character set.
  97. if constexpr (Platform::IsWindows()) {
  98. // QLockFile::removeStaleLockFile returns false on Windows,
  99. // when the application owning the lock is still running.
  100. if (!_lockFile->removeStaleLockFile()) {
  101. gManyInstance = true;
  102. }
  103. } else {
  104. gManyInstance = true;
  105. }
  106. }
  107. }
  108. #if defined Q_OS_LINUX && QT_VERSION >= QT_VERSION_CHECK(6, 2, 0)
  109. _localServer.setSocketOptions(QLocalServer::AbstractNamespaceOption);
  110. _localSocket.setSocketOptions(QLocalSocket::AbstractNamespaceOption);
  111. #endif // Q_OS_LINUX && Qt >= 6.2.0
  112. connect(
  113. &_localSocket,
  114. &QLocalSocket::connected,
  115. [=] { socketConnected(); });
  116. connect(
  117. &_localSocket,
  118. &QLocalSocket::disconnected,
  119. [=] { socketDisconnected(); });
  120. connect(
  121. &_localSocket,
  122. &QLocalSocket::errorOccurred,
  123. [=](QLocalSocket::LocalSocketError error) { socketError(error); });
  124. connect(
  125. &_localSocket,
  126. &QLocalSocket::bytesWritten,
  127. [=](qint64 bytes) { socketWritten(bytes); });
  128. connect(
  129. &_localSocket,
  130. &QLocalSocket::readyRead,
  131. [=] { socketReading(); });
  132. connect(
  133. &_localServer,
  134. &QLocalServer::newConnection,
  135. [=] { newInstanceConnected(); });
  136. crl::on_main(this, [=] { checkForQuit(); });
  137. connect(this, &QCoreApplication::aboutToQuit, [=] {
  138. customEnterFromEventLoop([&] {
  139. closeApplication();
  140. });
  141. });
  142. // https://github.com/telegramdesktop/tdesktop/issues/948
  143. // and https://github.com/telegramdesktop/tdesktop/issues/5022
  144. connect(this, &QGuiApplication::saveStateRequest, [](auto &manager) {
  145. manager.setRestartHint(QSessionManager::RestartNever);
  146. });
  147. LOG(("Connecting local socket to %1...").arg(_localServerName));
  148. _localSocket.connectToServer(_localServerName);
  149. if (QuitOnStartRequested) {
  150. closeApplication();
  151. return 0;
  152. }
  153. _started = true;
  154. return exec();
  155. }
  156. void Sandbox::QuitWhenStarted() {
  157. if (!QApplication::instance() || !Instance()._started) {
  158. QuitOnStartRequested = true;
  159. } else {
  160. quit();
  161. }
  162. }
  163. void Sandbox::launchApplication() {
  164. InvokeQueued(this, [=] {
  165. if (Quitting()) {
  166. quit();
  167. } else if (_application) {
  168. return;
  169. }
  170. setupScreenScale();
  171. #ifndef _DEBUG
  172. if (Logs::DebugEnabled()) {
  173. using DeadlockDetector::PingThread;
  174. _deadlockDetector = std::make_unique<PingThread>(this);
  175. }
  176. #endif // !_DEBUG
  177. _application = std::make_unique<Application>();
  178. // Ideally this should go to constructor.
  179. // But we want to catch all native events and Application installs
  180. // its own filter that can filter out some of them. So we install
  181. // our filter after the Application constructor installs his.
  182. installNativeEventFilter(this);
  183. _application->run();
  184. });
  185. }
  186. void Sandbox::setupScreenScale() {
  187. const auto ratio = devicePixelRatio();
  188. LOG(("Global devicePixelRatio: %1").arg(ratio));
  189. const auto logEnv = [](const char *name) {
  190. const auto value = qEnvironmentVariable(name);
  191. if (!value.isEmpty()) {
  192. LOG(("%1: %2").arg(name, value));
  193. }
  194. };
  195. logEnv("QT_DEVICE_PIXEL_RATIO");
  196. logEnv("QT_AUTO_SCREEN_SCALE_FACTOR");
  197. logEnv("QT_ENABLE_HIGHDPI_SCALING");
  198. logEnv("QT_SCALE_FACTOR");
  199. logEnv("QT_SCREEN_SCALE_FACTORS");
  200. logEnv("QT_SCALE_FACTOR_ROUNDING_POLICY");
  201. logEnv("QT_DPI_ADJUSTMENT_POLICY");
  202. logEnv("QT_USE_PHYSICAL_DPI");
  203. logEnv("QT_FONT_DPI");
  204. const auto useRatio = std::clamp(qCeil(ratio), 1, 3);
  205. style::SetDevicePixelRatio(useRatio);
  206. const auto screen = Sandbox::primaryScreen();
  207. const auto dpi = screen->logicalDotsPerInch();
  208. const auto basePair = screen->handle()->logicalBaseDpi();
  209. const auto base = (basePair.first + basePair.second) * 0.5;
  210. const auto screenScaleExact = dpi / base;
  211. const auto screenScale = int(base::SafeRound(screenScaleExact * 20)) * 5;
  212. LOG(("Primary screen DPI: %1, Base: %2.").arg(dpi).arg(base));
  213. LOG(("Computed screen scale: %1").arg(screenScale));
  214. if (Platform::IsMac()) {
  215. // 110% for Retina screens by default.
  216. cSetScreenScale((useRatio == 2) ? 110 : style::kScaleDefault);
  217. } else {
  218. cSetScreenScale(std::clamp(
  219. screenScale,
  220. style::kScaleMin,
  221. style::MaxScaleForRatio(useRatio)));
  222. }
  223. LOG(("DevicePixelRatio: %1").arg(useRatio));
  224. LOG(("ScreenScale: %1").arg(cScreenScale()));
  225. }
  226. Sandbox::~Sandbox() = default;
  227. bool Sandbox::event(QEvent *e) {
  228. if (e->type() == QEvent::Quit) {
  229. if (Quitting()) {
  230. return QCoreApplication::event(e);
  231. }
  232. Quit(QuitReason::QtQuitEvent);
  233. e->ignore();
  234. return false;
  235. } else if (e->type() == QEvent::Close) {
  236. Quit();
  237. } else if (e->type() == DeadlockDetector::PingPongEvent::Type()) {
  238. postEvent(
  239. static_cast<DeadlockDetector::PingPongEvent*>(e)->sender(),
  240. new DeadlockDetector::PingPongEvent(this));
  241. }
  242. return QApplication::event(e);
  243. }
  244. void Sandbox::socketConnected() {
  245. LOG(("Socket connected, this is not the first application instance, sending show command..."));
  246. _secondInstance = true;
  247. QString commands;
  248. const QStringList &lst(cSendPaths());
  249. for (QStringList::const_iterator i = lst.cbegin(), e = lst.cend(); i != e; ++i) {
  250. commands += u"SEND:"_q + _escapeTo7bit(*i) + ';';
  251. }
  252. if (qEnvironmentVariableIsSet("XDG_ACTIVATION_TOKEN")) {
  253. commands += u"XDG_ACTIVATION_TOKEN:"_q + _escapeTo7bit(qEnvironmentVariable("XDG_ACTIVATION_TOKEN")) + ';';
  254. }
  255. if (!cStartUrl().isEmpty()) {
  256. commands += u"OPEN:"_q + _escapeTo7bit(cStartUrl()) + ';';
  257. } else if (cQuit()) {
  258. commands += u"CMD:quit;"_q;
  259. } else {
  260. commands += u"CMD:show;"_q;
  261. }
  262. DEBUG_LOG(("Sandbox Info: writing commands %1").arg(commands));
  263. _localSocket.write(commands.toLatin1());
  264. }
  265. void Sandbox::socketWritten(qint64/* bytes*/) {
  266. if (_localSocket.state() != QLocalSocket::ConnectedState) {
  267. LOG(("Socket is not connected %1").arg(_localSocket.state()));
  268. return;
  269. }
  270. if (_localSocket.bytesToWrite()) {
  271. return;
  272. }
  273. LOG(("Show command written, waiting response..."));
  274. }
  275. void Sandbox::socketReading() {
  276. if (_localSocket.state() != QLocalSocket::ConnectedState) {
  277. LOG(("Socket is not connected %1").arg(_localSocket.state()));
  278. return;
  279. }
  280. _localSocketReadData.append(_localSocket.readAll());
  281. const auto m = QRegularExpression(u"RES:(\\d+)_(\\d+);"_q).match(
  282. _localSocketReadData);
  283. if (!m.hasMatch()) {
  284. return;
  285. }
  286. const auto processId = m.capturedView(1).toULongLong();
  287. const auto windowId = m.capturedView(2).toULongLong();
  288. if (windowId) {
  289. Platform::ActivateOtherProcess(processId, windowId);
  290. }
  291. LOG(("Show command response received, processId = %1, windowId = %2, "
  292. "activating and quitting..."
  293. ).arg(processId
  294. ).arg(windowId));
  295. return Quit();
  296. }
  297. void Sandbox::socketError(QLocalSocket::LocalSocketError e) {
  298. if (Quitting()) return;
  299. if (_secondInstance) {
  300. LOG(("Could not write show command, error %1, quitting...").arg(e));
  301. return Quit();
  302. }
  303. if (e == QLocalSocket::ServerNotFoundError) {
  304. LOG(("This is the only instance of Telegram, starting server and app..."));
  305. } else {
  306. LOG(("Socket connect error %1, starting server and app...").arg(e));
  307. }
  308. _localSocket.close();
  309. // Local server does not work in WinRT build.
  310. #ifndef Q_OS_WINRT
  311. psCheckLocalSocket(_localServerName);
  312. if (!_localServer.listen(_localServerName)) {
  313. LOG(("Failed to start listening to %1 server: %2").arg(_localServerName, _localServer.errorString()));
  314. return Quit();
  315. }
  316. #endif // !Q_OS_WINRT
  317. if (!Core::UpdaterDisabled()
  318. && !cNoStartUpdate()
  319. && Core::checkReadyUpdate()) {
  320. cSetRestartingUpdate(true);
  321. DEBUG_LOG(("Sandbox Info: installing update instead of starting app..."));
  322. return Quit();
  323. }
  324. if (cQuit()) {
  325. return Quit();
  326. }
  327. singleInstanceChecked();
  328. }
  329. void Sandbox::singleInstanceChecked() {
  330. if (cManyInstance()) {
  331. LOG(("App Info: Detected another instance"));
  332. }
  333. refreshGlobalProxy();
  334. if (!Logs::started() || !Logs::instanceChecked()) {
  335. new NotStartedWindow();
  336. return;
  337. }
  338. const auto result = CrashReports::Start();
  339. v::match(result, [&](CrashReports::Status status) {
  340. if (status == CrashReports::CantOpen) {
  341. new NotStartedWindow();
  342. } else {
  343. launchApplication();
  344. }
  345. }, [&](const QByteArray &crashdump) {
  346. // If crash dump is empty with that status it means that we
  347. // didn't close the application properly. Just ignore for now.
  348. if (crashdump.isEmpty()) {
  349. if (CrashReports::Restart() == CrashReports::CantOpen) {
  350. new NotStartedWindow();
  351. } else {
  352. launchApplication();
  353. }
  354. return;
  355. }
  356. _lastCrashDump = crashdump;
  357. auto window = new LastCrashedWindow(
  358. _lastCrashDump,
  359. [=] { launchApplication(); });
  360. window->proxyChanges(
  361. ) | rpl::start_with_next([=](MTP::ProxyData &&proxy) {
  362. _sandboxProxy = std::move(proxy);
  363. refreshGlobalProxy();
  364. }, window->lifetime());
  365. });
  366. }
  367. void Sandbox::socketDisconnected() {
  368. if (_secondInstance) {
  369. DEBUG_LOG(("Sandbox Error: socket disconnected before command response received, quitting..."));
  370. return Quit();
  371. }
  372. }
  373. void Sandbox::newInstanceConnected() {
  374. DEBUG_LOG(("Sandbox Info: new local socket connected"));
  375. for (auto client = _localServer.nextPendingConnection(); client; client = _localServer.nextPendingConnection()) {
  376. _localClients.push_back(LocalClient(client, QByteArray()));
  377. connect(
  378. client,
  379. &QLocalSocket::readyRead,
  380. [=] { readClients(); });
  381. connect(
  382. client,
  383. &QLocalSocket::disconnected,
  384. [=] { removeClients(); });
  385. }
  386. }
  387. void Sandbox::readClients() {
  388. // This method can be called before Application is constructed.
  389. QString startUrl;
  390. QStringList toSend;
  391. for (LocalClients::iterator i = _localClients.begin(), e = _localClients.end(); i != e; ++i) {
  392. i->second.append(i->first->readAll());
  393. if (i->second.size()) {
  394. QString cmds(QString::fromLatin1(i->second));
  395. int32 from = 0, l = cmds.length();
  396. for (int32 to = cmds.indexOf(QChar(';'), from); to >= from; to = (from < l) ? cmds.indexOf(QChar(';'), from) : -1) {
  397. auto cmd = base::StringViewMid(cmds, from, to - from);
  398. if (cmd.startsWith(u"CMD:"_q)) {
  399. const auto processId = QApplication::applicationPid();
  400. const auto windowId = execExternal(cmds.mid(from + 4, to - from - 4));
  401. const auto response = u"RES:%1_%2;"_q.arg(processId).arg(windowId).toLatin1();
  402. i->first->write(response.data(), response.size());
  403. } else if (cmd.startsWith(u"SEND:"_q)) {
  404. if (cSendPaths().isEmpty()) {
  405. toSend.append(_escapeFrom7bit(cmds.mid(from + 5, to - from - 5)));
  406. }
  407. } else if (cmd.startsWith(u"XDG_ACTIVATION_TOKEN:"_q)) {
  408. qputenv("XDG_ACTIVATION_TOKEN", _escapeFrom7bit(cmds.mid(from + 21, to - from - 21)).toUtf8());
  409. } else if (cmd.startsWith(u"OPEN:"_q)) {
  410. startUrl = _escapeFrom7bit(cmds.mid(from + 5, to - from - 5)).mid(0, 8192);
  411. const auto activationRequired = StartUrlRequiresActivate(startUrl);
  412. const auto processId = QApplication::applicationPid();
  413. const auto windowId = activationRequired
  414. ? execExternal("show")
  415. : 0;
  416. const auto response = u"RES:%1_%2;"_q.arg(processId).arg(windowId).toLatin1();
  417. i->first->write(response.data(), response.size());
  418. } else {
  419. LOG(("Sandbox Error: unknown command %1 passed in local socket").arg(cmd.toString()));
  420. }
  421. from = to + 1;
  422. }
  423. if (from > 0) {
  424. i->second = i->second.mid(from);
  425. }
  426. }
  427. }
  428. if (!toSend.isEmpty()) {
  429. QStringList paths(cSendPaths());
  430. paths.append(toSend);
  431. cSetSendPaths(paths);
  432. }
  433. if (_application) {
  434. _application->checkSendPaths();
  435. }
  436. if (!startUrl.isEmpty()) {
  437. cSetStartUrl(startUrl);
  438. }
  439. if (_application) {
  440. _application->checkStartUrl();
  441. }
  442. }
  443. void Sandbox::removeClients() {
  444. DEBUG_LOG(("Sandbox Info: remove clients slot called, clients %1"
  445. ).arg(_localClients.size()));
  446. for (auto i = _localClients.begin(), e = _localClients.end(); i != e;) {
  447. if (i->first->state() != QLocalSocket::ConnectedState) {
  448. DEBUG_LOG(("Sandbox Info: removing client"));
  449. i = _localClients.erase(i);
  450. e = _localClients.end();
  451. } else {
  452. ++i;
  453. }
  454. }
  455. }
  456. void Sandbox::checkForQuit() {
  457. if (Quitting()) {
  458. quit();
  459. }
  460. }
  461. void Sandbox::refreshGlobalProxy() {
  462. const auto proxy = !Core::IsAppLaunched()
  463. ? _sandboxProxy
  464. : Core::App().settings().proxy().isEnabled()
  465. ? Core::App().settings().proxy().selected()
  466. : MTP::ProxyData();
  467. if (proxy.type == MTP::ProxyData::Type::Socks5
  468. || proxy.type == MTP::ProxyData::Type::Http) {
  469. QNetworkProxy::setApplicationProxy(
  470. MTP::ToNetworkProxy(MTP::ToDirectIpProxy(proxy)));
  471. } else if (!Core::IsAppLaunched()
  472. || Core::App().settings().proxy().isSystem()) {
  473. QNetworkProxyFactory::setUseSystemConfiguration(true);
  474. } else {
  475. QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy);
  476. }
  477. }
  478. void Sandbox::checkForEmptyLoopNestingLevel() {
  479. // _loopNestingLevel == _eventNestingLevel means that we had a
  480. // native event in a nesting loop that didn't get a notify() call
  481. // after. That means we already have exited the nesting loop and
  482. // there must not be any postponed calls with that nesting level.
  483. if (_loopNestingLevel == _eventNestingLevel) {
  484. Assert(_postponedCalls.empty()
  485. || _postponedCalls.back().loopNestingLevel < _loopNestingLevel);
  486. Assert(!_previousLoopNestingLevels.empty());
  487. _loopNestingLevel = _previousLoopNestingLevels.back();
  488. _previousLoopNestingLevels.pop_back();
  489. }
  490. }
  491. void Sandbox::postponeCall(FnMut<void()> &&callable) {
  492. Expects(callable != nullptr);
  493. Expects(_eventNestingLevel >= _loopNestingLevel);
  494. checkForEmptyLoopNestingLevel();
  495. _postponedCalls.push_back({
  496. _loopNestingLevel,
  497. std::move(callable)
  498. });
  499. }
  500. void Sandbox::incrementEventNestingLevel() {
  501. ++_eventNestingLevel;
  502. }
  503. void Sandbox::decrementEventNestingLevel() {
  504. Expects(_eventNestingLevel >= _loopNestingLevel);
  505. if (_eventNestingLevel == _loopNestingLevel) {
  506. _loopNestingLevel = _previousLoopNestingLevels.back();
  507. _previousLoopNestingLevels.pop_back();
  508. }
  509. const auto processTillLevel = _eventNestingLevel - 1;
  510. processPostponedCalls(processTillLevel);
  511. checkForEmptyLoopNestingLevel();
  512. _eventNestingLevel = processTillLevel;
  513. Ensures(_eventNestingLevel >= _loopNestingLevel);
  514. }
  515. void Sandbox::registerEnterFromEventLoop() {
  516. Expects(_eventNestingLevel >= _loopNestingLevel);
  517. if (_eventNestingLevel > _loopNestingLevel) {
  518. _previousLoopNestingLevels.push_back(_loopNestingLevel);
  519. _loopNestingLevel = _eventNestingLevel;
  520. }
  521. }
  522. bool Sandbox::notifyOrInvoke(QObject *receiver, QEvent *e) {
  523. if (e->type() == base::InvokeQueuedEvent::Type()) {
  524. static_cast<base::InvokeQueuedEvent*>(e)->invoke();
  525. return true;
  526. }
  527. return QApplication::notify(receiver, e);
  528. }
  529. bool Sandbox::notify(QObject *receiver, QEvent *e) {
  530. if (QThread::currentThreadId() != _mainThreadId) {
  531. return notifyOrInvoke(receiver, e);
  532. }
  533. const auto wrap = createEventNestingLevel();
  534. if (e->type() == QEvent::UpdateRequest) {
  535. const auto weak = QPointer<QObject>(receiver);
  536. _widgetUpdateRequests.fire({});
  537. if (!weak) {
  538. return true;
  539. }
  540. }
  541. return notifyOrInvoke(receiver, e);
  542. }
  543. void Sandbox::processPostponedCalls(int level) {
  544. while (!_postponedCalls.empty()) {
  545. auto &last = _postponedCalls.back();
  546. if (last.loopNestingLevel != level) {
  547. break;
  548. }
  549. auto taken = std::move(last);
  550. _postponedCalls.pop_back();
  551. taken.callable();
  552. }
  553. }
  554. bool Sandbox::nativeEventFilter(
  555. const QByteArray &eventType,
  556. void *message,
  557. native_event_filter_result *result) {
  558. registerEnterFromEventLoop();
  559. return false;
  560. }
  561. rpl::producer<> Sandbox::widgetUpdateRequests() const {
  562. return _widgetUpdateRequests.events();
  563. }
  564. MTP::ProxyData Sandbox::sandboxProxy() const {
  565. return _sandboxProxy;
  566. }
  567. void Sandbox::closeApplication() {
  568. if (CurrentLaunchState() == LaunchState::QuitProcessed) {
  569. return;
  570. }
  571. SetLaunchState(LaunchState::QuitProcessed);
  572. _application = nullptr;
  573. _localServer.close();
  574. for (const auto &localClient : base::take(_localClients)) {
  575. localClient.first->close();
  576. }
  577. _localClients.clear();
  578. _localSocket.close();
  579. _updateChecker = nullptr;
  580. }
  581. uint64 Sandbox::execExternal(const QString &cmd) {
  582. DEBUG_LOG(("Sandbox Info: executing external command '%1'").arg(cmd));
  583. if (cmd == "show") {
  584. if (Core::IsAppLaunched() && Core::App().activePrimaryWindow()) {
  585. const auto window = Core::App().activePrimaryWindow();
  586. window->activate();
  587. return Platform::ActivationWindowId(window->widget());
  588. } else if (const auto window = PreLaunchWindow::instance()) {
  589. window->activate();
  590. return Platform::ActivationWindowId(window);
  591. }
  592. } else if (cmd == "quit") {
  593. Quit();
  594. }
  595. return 0;
  596. }
  597. } // namespace Core
  598. namespace crl {
  599. rpl::producer<> on_main_update_requests() {
  600. return Core::Sandbox::Instance().widgetUpdateRequests();
  601. }
  602. } // namespace crl