| 1 | // SPDX-FileCopyrightText: Nheko Contributors |
| 2 | // |
| 3 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 4 | |
| 5 | #include <iostream> |
| 6 | |
| 7 | #include <QApplication> |
| 8 | #include <QCommandLineParser> |
| 9 | #include <QDesktopServices> |
| 10 | #include <QDir> |
| 11 | #include <QFontDatabase> |
| 12 | #include <QLabel> |
| 13 | #include <QLibraryInfo> |
| 14 | #include <QMessageBox> |
| 15 | #include <QPoint> |
| 16 | #include <QQuickView> |
| 17 | #include <QScreen> |
| 18 | #include <QStandardPaths> |
| 19 | #include <QTranslator> |
| 20 | |
| 21 | // in theory we can enable this everywhere, but the header is missing on some of our CI systems and |
| 22 | // it is too much effort to install. |
| 23 | #if __has_include(<QtGui/qpa/qplatformwindow_p.h>) |
| 24 | #include <QtGui/qpa/qplatformwindow_p.h> |
| 25 | #endif |
| 26 | |
| 27 | #include <kdsingleapplication.h> |
| 28 | |
| 29 | #include "Cache.h" |
| 30 | #include "CallManager.h" |
| 31 | #include "ChatPage.h" |
| 32 | #include "Logging.h" |
| 33 | #include "MainWindow.h" |
| 34 | #include "MatrixClient.h" |
| 35 | #include "Utils.h" |
| 36 | #include "config/nheko.h" |
| 37 | |
| 38 | #if defined(Q_OS_MACOS) |
| 39 | #include "notifications/Manager.h" |
| 40 | #endif |
| 41 | |
| 42 | #ifdef GSTREAMER_AVAILABLE |
| 43 | #include <QAbstractEventDispatcher> |
| 44 | #include <gst/gst.h> |
| 45 | |
| 46 | #include "voip/CallDevices.h" |
| 47 | #endif |
| 48 | |
| 49 | #ifdef QML_DEBUGGING |
| 50 | #include <QQmlDebuggingEnabler> |
| 51 | QQmlTriviallyDestructibleDebuggingEnabler enabler; |
| 52 | #endif |
| 53 | |
| 54 | #if HAVE_BACKTRACE_SYMBOLS_FD |
| 55 | #include <csignal> |
| 56 | #include <execinfo.h> |
| 57 | #include <fcntl.h> |
| 58 | #include <unistd.h> |
| 59 | |
| 60 | void |
| 61 | stacktraceHandler(int signum) |
| 62 | { |
| 63 | std::signal(signum, SIG_DFL); |
| 64 | |
| 65 | // boost::stacktrace::safe_dump_to("./nheko-backtrace.dump"); |
| 66 | |
| 67 | // see |
| 68 | // https://stackoverflow.com/questions/77005/how-to-automatically-generate-a-stacktrace-when-my-program-crashes/77336#77336 |
| 69 | void *array[50]; |
| 70 | int size; |
| 71 | |
| 72 | // get void*'s for all entries on the stack |
| 73 | size = backtrace(array, 50); |
| 74 | |
| 75 | // print out all the frames to stderr |
| 76 | fprintf(stderr, "Error: signal %d:\n", signum); |
| 77 | backtrace_symbols_fd(array, size, STDERR_FILENO); |
| 78 | |
| 79 | int file = ::open("/tmp/nheko-crash.dump", |
| 80 | O_CREAT | O_WRONLY | O_TRUNC |
| 81 | #if defined(S_IWUSR) && defined(S_IRUSR) |
| 82 | , |
| 83 | S_IWUSR | S_IRUSR |
| 84 | #elif defined(S_IWRITE) && defined(S_IREAD) |
| 85 | , |
| 86 | S_IWRITE | S_IREAD |
| 87 | #endif |
| 88 | ); |
| 89 | if (file != -1) { |
| 90 | constexpr char header[] = "Error: signal\n"; |
| 91 | [[maybe_unused]] auto ret = write(file, header, std::size(header) - 1); |
| 92 | backtrace_symbols_fd(array, size, file); |
| 93 | close(file); |
| 94 | } |
| 95 | |
| 96 | std::raise(SIGABRT); |
| 97 | } |
| 98 | |
| 99 | void |
| 100 | registerSignalHandlers() |
| 101 | { |
| 102 | std::signal(SIGSEGV, &stacktraceHandler); |
| 103 | std::signal(SIGABRT, &stacktraceHandler); |
| 104 | } |
| 105 | |
| 106 | #else |
| 107 | |
| 108 | // No implementation for systems with no stacktrace support. |
| 109 | void |
| 110 | registerSignalHandlers() |
| 111 | { |
| 112 | } |
| 113 | |
| 114 | #endif |
| 115 | |
| 116 | #if defined(GSTREAMER_AVAILABLE) && (defined(Q_OS_MACOS) || defined(Q_OS_WINDOWS)) |
| 117 | GMainLoop *gloop = 0; |
| 118 | GThread *gthread = 0; |
| 119 | |
| 120 | extern "C" |
| 121 | { |
| 122 | static gpointer glibMainLoopThreadFunc(gpointer) |
| 123 | { |
| 124 | gloop = g_main_loop_new(0, false); |
| 125 | g_main_loop_run(gloop); |
| 126 | g_main_loop_unref(gloop); |
| 127 | gloop = 0; |
| 128 | return 0; |
| 129 | } |
| 130 | } // extern "C" |
| 131 | #endif |
| 132 | |
| 133 | QPoint |
| 134 | screenCenter(int width, int height) |
| 135 | { |
| 136 | // Deprecated in 5.13: QRect screenGeometry = QApplication::desktop()->screenGeometry(); |
| 137 | QRect screenGeometry = QGuiApplication::primaryScreen()->geometry(); |
| 138 | |
| 139 | int x = (screenGeometry.width() - width) / 2; |
| 140 | int y = (screenGeometry.height() - height) / 2; |
| 141 | |
| 142 | return QPoint(x, y); |
| 143 | } |
| 144 | |
| 145 | void |
| 146 | createStandardDirectory(QStandardPaths::StandardLocation path) |
| 147 | { |
| 148 | auto dir = QStandardPaths::writableLocation(path); |
| 149 | |
| 150 | if (!QDir().mkpath(dir)) { |
| 151 | throw std::runtime_error(("Unable to create state directory:" + dir).toStdString().c_str()); |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | int |
| 156 | main(int argc, char *argv[]) |
| 157 | { |
| 158 | QCoreApplication::setApplicationName(QStringLiteral("nheko")); |
| 159 | QCoreApplication::setApplicationVersion(nheko::version); |
| 160 | QCoreApplication::setOrganizationName(QStringLiteral("nheko")); |
| 161 | |
| 162 | // Disable the qml disk cache by default to prevent crashes on updates. See |
| 163 | // https://github.com/Nheko-Reborn/nheko/issues/1383 |
| 164 | if (qgetenv("NHEKO_ALLOW_QML_DISK_CACHE").size() == 0) { |
| 165 | qputenv("QML_DISABLE_DISK_CACHE", "1"); |
| 166 | } |
| 167 | |
| 168 | // this needs to be after setting the application name. Or how would we find our settings |
| 169 | // file then? |
| 170 | #if !defined(Q_OS_MACOS) |
| 171 | if (qgetenv("QT_SCALE_FACTOR").size() == 0) { |
| 172 | float factor = utils::scaleFactor(); |
| 173 | |
| 174 | if (factor != -1) |
| 175 | qputenv("QT_SCALE_FACTOR", QString::number(factor).toUtf8()); |
| 176 | } |
| 177 | #endif |
| 178 | |
| 179 | QString matrixUri; |
| 180 | for (int i = 1; i < argc; ++i) { |
| 181 | QString arg{argv[i]}; |
| 182 | if (arg.startsWith(QLatin1String("matrix:"))) { |
| 183 | matrixUri = arg; |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | QApplication app(argc, argv); |
| 188 | |
| 189 | QCommandLineParser parser; |
| 190 | parser.addHelpOption(); |
| 191 | parser.addVersionOption(); |
| 192 | QCommandLineOption debugOption(QStringLiteral("debug"), |
| 193 | QObject::tr("Alias for '--log-level trace'.")); |
| 194 | parser.addOption(debugOption); |
| 195 | QCommandLineOption logLevel( |
| 196 | QStringList() << QStringLiteral("l") << QStringLiteral("log-level"), |
| 197 | QObject::tr("Set the global log level, or a comma-separated list of <component>=<level> " |
| 198 | "pairs, or both. For example, to set the default log level to 'warn' but " |
| 199 | "disable logging for the 'ui' component, pass 'warn,ui=off'. " |
| 200 | "levels:{trace,debug,info,warning,error,critical,off} " |
| 201 | "components:{crypto,db,mtx,net,qml,ui}"), |
| 202 | QObject::tr("level")); |
| 203 | parser.addOption(logLevel); |
| 204 | QCommandLineOption logType( |
| 205 | QStringList() << QStringLiteral("L") << QStringLiteral("log-type"), |
| 206 | QObject::tr("Set the log output type. A comma-separated list is allowed. " |
| 207 | "The default is 'file,stderr'. types:{file,stderr,none}"), |
| 208 | QObject::tr("type")); |
| 209 | parser.addOption(logType); |
| 210 | QCommandLineOption compactDb( |
| 211 | QStringList() << QStringLiteral("C") << QStringLiteral("compact"), |
| 212 | QObject::tr("Recompacts the database which might improve performance.")); |
| 213 | parser.addOption(compactDb); |
| 214 | |
| 215 | // This option is not actually parsed via Qt due to the need to parse it before the app |
| 216 | // name is set. It only exists to keep Qt from complaining about the --profile/-p |
| 217 | // option and thereby crashing the app. |
| 218 | QCommandLineOption configName( |
| 219 | QStringList() << QStringLiteral("p") << QStringLiteral("profile"), |
| 220 | QCoreApplication::tr("Create a unique profile which allows you to log into several " |
| 221 | "accounts at the same time and start multiple instances of nheko."), |
| 222 | QCoreApplication::tr("profile"), |
| 223 | QCoreApplication::tr("profile name")); |
| 224 | parser.addOption(configName); |
| 225 | |
| 226 | parser.process(app); |
| 227 | |
| 228 | if (parser.isSet(compactDb)) |
| 229 | cache::setNeedsCompactFlag(); |
| 230 | |
| 231 | if (parser.isSet(configName)) |
| 232 | UserSettings::initialize(parser.value(configName)); |
| 233 | else |
| 234 | UserSettings::initialize(std::nullopt); |
| 235 | |
| 236 | auto settings = UserSettings::instance().toWeakRef(); |
| 237 | |
| 238 | auto profileName = settings.lock()->profile(); |
| 239 | |
| 240 | KDSingleApplication singleapp( |
| 241 | QStringLiteral("im.nheko.nheko-%1") |
| 242 | .arg(profileName == QLatin1String("default") ? QLatin1String("") : profileName)); |
| 243 | |
| 244 | // This check needs to happen _after_ process(), so that we actually print help for --help when |
| 245 | // Nheko is already running. |
| 246 | if (!singleapp.isPrimaryInstance()) { |
| 247 | auto token = qgetenv("XDG_ACTIVATION_TOKEN"); |
| 248 | |
| 249 | #if __has_include(<QtGui/qpa/qplatformwindow_p.h>) && \ |
| 250 | ((QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) && QT_CONFIG(wayland)) || \ |
| 251 | (QT_VERSION < QT_VERSION_CHECK(6, 7, 0) && defined(Q_OS_UNIX) && !defined(Q_OS_MACOS) \ |
| 252 | && !defined(Q_OS_HAIKU))) |
| 253 | // getting a valid activation token on wayland is a bit of a pain, it works most reliably |
| 254 | // when you have an actual window, that has the focus... |
| 255 | auto waylandApp = app.nativeInterface<QNativeInterface::QWaylandApplication>(); |
| 256 | // When the token is set in the env, use it by default as that's what we're supposed to do |
| 257 | // But leave a env knob so users can workaround terminal emulators that leak tokens |
| 258 | if (waylandApp && |
| 259 | (!qEnvironmentVariableIsEmpty("NHEKO_FORCE_ACTIVATION_SPLASH") || token.isEmpty())) { |
| 260 | QQuickView window; |
| 261 | window.setTitle("Activate main instance"); |
| 262 | window.setMaximumSize(QSize(100, 50)); |
| 263 | window.setMinimumSize(QSize(100, 50)); |
| 264 | window.setResizeMode(QQuickView::ResizeMode::SizeRootObjectToView); |
| 265 | window.setSource(QUrl(QStringLiteral("qrc:///resources/qml/ui/Spinner.qml"))); |
| 266 | window.show(); |
| 267 | auto waylandWindow = |
| 268 | window.nativeInterface<QNativeInterface::Private::QWaylandWindow>(); |
| 269 | if (waylandWindow) { |
| 270 | std::cout << "Launching temp window to activate main instance!\n"; |
| 271 | QObject::connect( |
| 272 | waylandWindow, |
| 273 | &QNativeInterface::Private::QWaylandWindow::xdgActivationTokenCreated, |
| 274 | waylandWindow, |
| 275 | [&token, &app](QString newToken) { // clazy:exclude=lambda-in-connect |
| 276 | token = newToken.toUtf8(); |
| 277 | app.exit(); |
| 278 | }, |
| 279 | Qt::SingleShotConnection); |
| 280 | QTimer::singleShot(100, waylandWindow, [waylandWindow, waylandApp] { |
| 281 | waylandWindow->requestXdgActivationToken(waylandApp->lastInputSerial()); |
| 282 | }); |
| 283 | app.exec(); |
| 284 | } |
| 285 | } |
| 286 | #endif |
| 287 | |
| 288 | std::cout << "Activating main app (instead of opening it a second time)." |
| 289 | << token.toStdString() << std::endl; |
| 290 | |
| 291 | // open uri in main instance |
| 292 | // TODO(Nico): Send also an activation token. |
| 293 | singleapp.sendMessage("activate" + token); |
| 294 | |
| 295 | if (!matrixUri.isEmpty()) { |
| 296 | std::cout << "Sending Matrix URL to main application: " << matrixUri.toStdString() |
| 297 | << std::endl; |
| 298 | // open uri in main instance |
| 299 | singleapp.sendMessage(matrixUri.toUtf8()); |
| 300 | } |
| 301 | |
| 302 | return 0; |
| 303 | } |
| 304 | |
| 305 | #if !defined(Q_OS_MACOS) |
| 306 | app.setWindowIcon(QIcon::fromTheme(QStringLiteral("nheko"), QIcon{":/logos/nheko.png"})); |
| 307 | #endif |
| 308 | #ifdef NHEKO_FLATPAK |
| 309 | app.setDesktopFileName(QStringLiteral("im.nheko.Nheko")); |
| 310 | #else |
| 311 | app.setDesktopFileName(QStringLiteral("nheko")); |
| 312 | #endif |
| 313 | |
| 314 | http::init(); |
| 315 | |
| 316 | createStandardDirectory(QStandardPaths::CacheLocation); |
| 317 | createStandardDirectory(QStandardPaths::AppDataLocation); |
| 318 | |
| 319 | registerSignalHandlers(); |
| 320 | |
| 321 | #if defined(GSTREAMER_AVAILABLE) && (defined(Q_OS_MACOS) || defined(Q_OS_WINDOWS)) |
| 322 | // If the version of Qt we're running in does not use GLib, we need to |
| 323 | // start a GMainLoop so that gstreamer can dispatch events. |
| 324 | const QMetaObject *mo = QAbstractEventDispatcher::instance(qApp->thread())->metaObject(); |
| 325 | if (gloop == 0 && strcmp(mo->className(), "QEventDispatcherGlib") != 0 && |
| 326 | strcmp(mo->superClass()->className(), "QEventDispatcherGlib") != 0) { |
| 327 | gthread = g_thread_new(0, glibMainLoopThreadFunc, 0); |
| 328 | } |
| 329 | #endif |
| 330 | |
| 331 | try { |
| 332 | QString level; |
| 333 | if (parser.isSet(logLevel)) { |
| 334 | level = parser.value(logLevel); |
| 335 | } else if (parser.isSet(debugOption)) { |
| 336 | level = "trace"; |
| 337 | } else { |
| 338 | level = qEnvironmentVariable("NHEKO_LOG_LEVEL"); |
| 339 | } |
| 340 | |
| 341 | QStringList targets = |
| 342 | (parser.isSet(logType) ? parser.value(logType) |
| 343 | : qEnvironmentVariable("NHEKO_LOG_TYPE", "file,stderr")) |
| 344 | .split(',', Qt::SkipEmptyParts); |
| 345 | targets.removeAll("none"); |
| 346 | bool to_stderr = bool(targets.removeAll("stderr")); |
| 347 | QString path = targets.removeAll("file") |
| 348 | ? QDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)) |
| 349 | .filePath("nheko.log") |
| 350 | : QLatin1String(""); |
| 351 | if (!targets.isEmpty()) { |
| 352 | std::cerr << "Invalid log type '" << targets.first().toStdString().c_str() << "'" |
| 353 | << std::endl; |
| 354 | std::exit(1); |
| 355 | } |
| 356 | |
| 357 | nhlog::init(level, path, to_stderr); |
| 358 | |
| 359 | } catch (const spdlog::spdlog_ex &ex) { |
| 360 | std::cerr << "Log initialization failed: " << ex.what() << std::endl; |
| 361 | std::exit(1); |
| 362 | } |
| 363 | |
| 364 | auto filter = new NhekoFixupPaletteEventFilter(&app); |
| 365 | app.installEventFilter(filter); |
| 366 | |
| 367 | QFont font; |
| 368 | QString userFontFamily = settings.lock()->font(); |
| 369 | if (!userFontFamily.isEmpty() && userFontFamily != QLatin1String("default")) { |
| 370 | font.setFamily(userFontFamily); |
| 371 | } |
| 372 | font.setPointSizeF(settings.lock()->fontSize()); |
| 373 | |
| 374 | app.setFont(font); |
| 375 | |
| 376 | #if QT_VERSION >= QT_VERSION_CHECK(6, 9, 0) |
| 377 | if (auto emojiFont = settings.lock()->emojiFont(); !emojiFont.isEmpty()) { |
| 378 | QFontDatabase::addApplicationEmojiFontFamily(emojiFont); |
| 379 | } |
| 380 | #endif |
| 381 | |
| 382 | settings.lock()->applyTheme(); |
| 383 | |
| 384 | if (QLocale().language() == QLocale::C) |
| 385 | QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedKingdom)); |
| 386 | |
| 387 | QTranslator qtTranslator; |
| 388 | if (qtTranslator.load(QLocale(), |
| 389 | QStringLiteral("qtbase"), |
| 390 | QStringLiteral("_"), |
| 391 | QLibraryInfo::path(QLibraryInfo::TranslationsPath))) { |
| 392 | app.installTranslator(&qtTranslator); |
| 393 | } else |
| 394 | qDebug() << "Failed to load qtbase translations: " |
| 395 | << QLibraryInfo::path(QLibraryInfo::TranslationsPath); |
| 396 | QTranslator qmlTranslator; |
| 397 | if (qmlTranslator.load(QLocale(), |
| 398 | QStringLiteral("qtdeclarative"), |
| 399 | QStringLiteral("_"), |
| 400 | QLibraryInfo::path(QLibraryInfo::TranslationsPath))) { |
| 401 | app.installTranslator(&qmlTranslator); |
| 402 | } else |
| 403 | qDebug() << "Failed to load qtdeclarative translations"; |
| 404 | |
| 405 | QTranslator appTranslator; |
| 406 | if (appTranslator.load(QLocale(), |
| 407 | QStringLiteral("nheko"), |
| 408 | QStringLiteral("_"), |
| 409 | QStringLiteral(":/translations"))) |
| 410 | app.installTranslator(&appTranslator); |
| 411 | else |
| 412 | qDebug() << "Failed to load nheko translations"; |
| 413 | |
| 414 | MainWindow w(nullptr); |
| 415 | // QQuickView w; |
| 416 | |
| 417 | // Move the MainWindow to the center |
| 418 | // w.move(screenCenter(w.width(), w.height())); |
| 419 | |
| 420 | if (!(settings.lock()->startInTray() && settings.lock()->tray())) |
| 421 | w.show(); |
| 422 | |
| 423 | QObject::connect(&app, &QApplication::aboutToQuit, &w, [&w]() { |
| 424 | ChatPage::instance()->removeAllNotifications(); |
| 425 | w.saveCurrentWindowSize(); |
| 426 | if (http::client() != nullptr) { |
| 427 | nhlog::net()->debug("shutting down all I/O threads & open connections"); |
| 428 | http::client()->close(true); |
| 429 | nhlog::net()->debug("bye"); |
| 430 | } |
| 431 | // This is required in order to destroy CallManager's QMediaPlayer, in turn allowing it |
| 432 | // to destroy its GstPipeline so that gst_deinit() can return. |
| 433 | ChatPage::instance()->callManager()->deleteLater(); |
| 434 | }); |
| 435 | |
| 436 | // It seems like handling the message in a blocking manner is a no-go. I have no idea how to |
| 437 | // fix that, so just use a queued connection for now... (ASAN does not cooperate and just |
| 438 | // hides the crash D:) |
| 439 | QObject::connect( |
| 440 | &singleapp, |
| 441 | &KDSingleApplication::messageReceived, |
| 442 | ChatPage::instance(), |
| 443 | [&](QByteArray message) { |
| 444 | if (message.isEmpty() || message.startsWith("activate")) { |
| 445 | auto token = message.remove(0, sizeof("activate") - 1); |
| 446 | if (!token.isEmpty()) { |
| 447 | nhlog::ui()->debug("Setting activation token to: {}", token.toStdString()); |
| 448 | qputenv("XDG_ACTIVATION_TOKEN", token); |
| 449 | } |
| 450 | w.show(); |
| 451 | w.raise(); |
| 452 | w.requestActivate(); |
| 453 | } else { |
| 454 | QString m = QString::fromUtf8(message); |
| 455 | ChatPage::instance()->handleMatrixUri(m); |
| 456 | } |
| 457 | }, |
| 458 | Qt::QueuedConnection); |
| 459 | |
| 460 | QMetaObject::Connection uriConnection; |
| 461 | if (singleapp.isPrimaryInstance() && !matrixUri.isEmpty()) { |
| 462 | uriConnection = QObject::connect(ChatPage::instance(), |
| 463 | &ChatPage::contentLoaded, |
| 464 | ChatPage::instance(), |
| 465 | [&uriConnection, matrixUri]() { |
| 466 | ChatPage::instance()->handleMatrixUri(matrixUri); |
| 467 | QObject::disconnect(uriConnection); |
| 468 | }); |
| 469 | } |
| 470 | QDesktopServices::setUrlHandler( |
| 471 | QStringLiteral("matrix"), ChatPage::instance(), "handleMatrixUri"); |
| 472 | |
| 473 | #if defined(Q_OS_MACOS) |
| 474 | // Need to set up notification delegate so users can respond to messages from within the |
| 475 | // notification itself. |
| 476 | NotificationsManager::attachToMacNotifCenter(); |
| 477 | #endif |
| 478 | |
| 479 | nhlog::ui()->info("starting nheko {}", nheko::version); |
| 480 | |
| 481 | auto returnvalue = app.exec(); |
| 482 | |
| 483 | #ifdef GSTREAMER_AVAILABLE |
| 484 | CallDevices::instance().deinit(); |
| 485 | |
| 486 | gst_deinit(); |
| 487 | #endif |
| 488 | |
| 489 | return returnvalue; |
| 490 | } |