Sync translations from Transifex and run lupdate
[qBittorrent.git] / src / app / main.cpp
blob719f1926c83273dd03b4600dee566a418ddb9591
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2014 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * In addition, as a special exception, the copyright holders give permission to
21 * link this program with the OpenSSL project's "OpenSSL" library (or with
22 * modified versions of it that use the same license as the "OpenSSL" library),
23 * and distribute the linked executables. You must obey the GNU General Public
24 * License in all respects for all of the code used other than "OpenSSL". If you
25 * modify file(s), you may extend this exception to your version of the file(s),
26 * but you are not obligated to do so. If you do not wish to do so, delete this
27 * exception statement from your version.
30 #include <QtGlobal>
32 #include <chrono>
33 #include <cstdlib>
34 #include <memory>
36 #ifdef Q_OS_UNIX
37 #include <sys/resource.h>
38 #endif
40 #ifndef Q_OS_WIN
41 #ifndef Q_OS_HAIKU
42 #include <unistd.h>
43 #endif // Q_OS_HAIKU
44 #elif defined DISABLE_GUI
45 #include <io.h>
46 #endif
48 #include <QDebug>
49 #include <QThread>
51 #ifndef DISABLE_GUI
52 // GUI-only includes
53 #include <QFont>
54 #include <QMessageBox>
55 #include <QPainter>
56 #include <QPen>
57 #include <QPushButton>
58 #include <QSplashScreen>
59 #include <QTimer>
61 #ifdef QBT_STATIC_QT
62 #include <QtPlugin>
63 Q_IMPORT_PLUGIN(QICOPlugin)
64 #endif // QBT_STATIC_QT
66 #else // DISABLE_GUI
67 #include <cstdio>
68 #endif // DISABLE_GUI
70 #include "base/global.h"
71 #include "base/preferences.h"
72 #include "base/profile.h"
73 #include "base/version.h"
74 #include "application.h"
75 #include "cmdoptions.h"
76 #include "signalhandler.h"
77 #include "upgrade.h"
79 #ifndef DISABLE_GUI
80 #include "gui/utils.h"
81 #endif
83 using namespace std::chrono_literals;
85 void displayVersion();
86 bool userAgreesWithLegalNotice();
87 void displayBadArgMessage(const QString &message);
89 #ifndef DISABLE_GUI
90 void showSplashScreen();
91 #endif // DISABLE_GUI
93 #ifdef Q_OS_UNIX
94 void adjustFileDescriptorLimit();
95 #endif
97 // Main
98 int main(int argc, char *argv[])
100 #ifdef Q_OS_UNIX
101 adjustFileDescriptorLimit();
102 #endif
104 // We must save it here because QApplication constructor may change it
105 bool isOneArg = (argc == 2);
107 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && !defined(DISABLE_GUI)
108 // Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created
109 if (qgetenv("QT_ENABLE_HIGHDPI_SCALING").isEmpty() && qgetenv("QT_AUTO_SCREEN_SCALE_FACTOR").isEmpty())
110 Application::setAttribute(Qt::AA_EnableHighDpiScaling, true);
111 // HighDPI scale factor policy must be set before QGuiApplication is created
112 if (qgetenv("QT_SCALE_FACTOR_ROUNDING_POLICY").isEmpty())
113 Application::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
114 #endif
118 // Create Application
119 auto app = std::make_unique<Application>(argc, argv);
121 #ifdef Q_OS_WIN
122 // QCoreApplication::applicationDirPath() needs an Application object instantiated first
123 // Let's hope that there won't be a crash before this line
124 const char *envName = "_NT_SYMBOL_PATH";
125 const QString envValue = qEnvironmentVariable(envName);
126 if (envValue.isEmpty())
127 qputenv(envName, Application::applicationDirPath().toLocal8Bit());
128 else
129 qputenv(envName, u"%1;%2"_qs.arg(envValue, Application::applicationDirPath()).toLocal8Bit());
130 #endif
132 const QBtCommandLineParameters params = app->commandLineArgs();
133 if (!params.unknownParameter.isEmpty())
135 throw CommandLineParameterError(QObject::tr("%1 is an unknown command line parameter.",
136 "--random-parameter is an unknown command line parameter.")
137 .arg(params.unknownParameter));
139 #if !defined(Q_OS_WIN) || defined(DISABLE_GUI)
140 if (params.showVersion)
142 if (isOneArg)
144 displayVersion();
145 return EXIT_SUCCESS;
147 throw CommandLineParameterError(QObject::tr("%1 must be the single command line parameter.")
148 .arg(u"-v (or --version)"_qs));
150 #endif
151 if (params.showHelp)
153 if (isOneArg)
155 displayUsage(QString::fromLocal8Bit(argv[0]));
156 return EXIT_SUCCESS;
158 throw CommandLineParameterError(QObject::tr("%1 must be the single command line parameter.")
159 .arg(u"-h (or --help)"_qs));
162 const bool firstTimeUser = !Preferences::instance()->getAcceptedLegal();
163 if (firstTimeUser)
165 #ifndef DISABLE_GUI
166 if (!userAgreesWithLegalNotice())
167 return EXIT_SUCCESS;
168 #elif defined(Q_OS_WIN)
169 if (_isatty(_fileno(stdin))
170 && _isatty(_fileno(stdout))
171 && !userAgreesWithLegalNotice())
172 return EXIT_SUCCESS;
173 #else
174 if (!params.shouldDaemonize
175 && isatty(fileno(stdin))
176 && isatty(fileno(stdout))
177 && !userAgreesWithLegalNotice())
178 return EXIT_SUCCESS;
179 #endif
181 setCurrentMigrationVersion();
184 // Check if qBittorrent is already running for this user
185 if (app->isRunning())
187 #if defined(DISABLE_GUI) && !defined(Q_OS_WIN)
188 if (params.shouldDaemonize)
190 throw CommandLineParameterError(QObject::tr("You cannot use %1: qBittorrent is already running for this user.")
191 .arg(u"-d (or --daemon)"_qs));
193 #endif
195 QThread::msleep(300);
196 app->callMainInstance();
198 return EXIT_SUCCESS;
201 #ifdef Q_OS_WIN
202 // This affects only Windows apparently and Qt5.
203 // When QNetworkAccessManager is instantiated it regularly starts polling
204 // the network interfaces to see what's available and their status.
205 // This polling creates jitter and high ping with wifi interfaces.
206 // So here we disable it for lack of better measure.
207 // It will also spew this message in the console: QObject::startTimer: Timers cannot have negative intervals
208 // For more info see:
209 // 1. https://github.com/qbittorrent/qBittorrent/issues/4209
210 // 2. https://bugreports.qt.io/browse/QTBUG-40332
211 // 3. https://bugreports.qt.io/browse/QTBUG-46015
213 qputenv("QT_BEARER_POLL_TIMEOUT", QByteArray::number(-1));
214 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && !defined(DISABLE_GUI)
215 // this is the default in Qt6
216 app->setAttribute(Qt::AA_DisableWindowContextHelpButton);
217 #endif
218 #endif // Q_OS_WIN
220 #ifdef Q_OS_MACOS
221 // Since Apple made difficult for users to set PATH, we set here for convenience.
222 // Users are supposed to install Homebrew Python for search function.
223 // For more info see issue #5571.
224 QByteArray path = "/usr/local/bin:";
225 path += qgetenv("PATH");
226 qputenv("PATH", path.constData());
228 // On OS X the standard is to not show icons in the menus
229 app->setAttribute(Qt::AA_DontShowIconsInMenus);
230 #else
231 if (!Preferences::instance()->iconsInMenusEnabled())
232 app->setAttribute(Qt::AA_DontShowIconsInMenus);
233 #endif
235 #if defined(DISABLE_GUI) && !defined(Q_OS_WIN)
236 if (params.shouldDaemonize)
238 app.reset(); // Destroy current application
239 if (daemon(1, 0) == 0)
241 app = std::make_unique<Application>(argc, argv);
242 if (app->isRunning())
244 // Another instance had time to start.
245 return EXIT_FAILURE;
248 else
250 qCritical("Something went wrong while daemonizing, exiting...");
251 return EXIT_FAILURE;
254 #elif !defined(DISABLE_GUI)
255 if (!(params.noSplash || Preferences::instance()->isSplashScreenDisabled()))
256 showSplashScreen();
257 #endif
259 registerSignalHandlers();
261 return app->exec();
263 catch (const CommandLineParameterError &er)
265 displayBadArgMessage(er.message());
266 return EXIT_FAILURE;
268 catch (const RuntimeError &er)
270 qDebug() << er.message();
271 return EXIT_FAILURE;
275 #if !defined(DISABLE_GUI)
276 void showSplashScreen()
278 QPixmap splashImg(u":/icons/splash.png"_qs);
279 QPainter painter(&splashImg);
280 const auto version = QStringLiteral(QBT_VERSION);
281 painter.setPen(QPen(Qt::white));
282 painter.setFont(QFont(u"Arial"_qs, 22, QFont::Black));
283 painter.drawText(224 - painter.fontMetrics().horizontalAdvance(version), 270, version);
284 QSplashScreen *splash = new QSplashScreen(splashImg);
285 splash->show();
286 QTimer::singleShot(1500ms, splash, &QObject::deleteLater);
287 qApp->processEvents();
289 #endif // DISABLE_GUI
291 void displayVersion()
293 printf("%s %s\n", qUtf8Printable(qApp->applicationName()), QBT_VERSION);
296 void displayBadArgMessage(const QString &message)
298 const QString help = QObject::tr("Run application with -h option to read about command line parameters.");
299 #if defined(Q_OS_WIN) && !defined(DISABLE_GUI)
300 QMessageBox msgBox(QMessageBox::Critical, QObject::tr("Bad command line"),
301 (message + u'\n' + help), QMessageBox::Ok);
302 msgBox.show(); // Need to be shown or to moveToCenter does not work
303 msgBox.move(Utils::Gui::screenCenter(&msgBox));
304 msgBox.exec();
305 #else
306 const QString errMsg = QObject::tr("Bad command line: ") + u'\n'
307 + message + u'\n'
308 + help + u'\n';
309 fprintf(stderr, "%s", qUtf8Printable(errMsg));
310 #endif
313 bool userAgreesWithLegalNotice()
315 Preferences *const pref = Preferences::instance();
316 Q_ASSERT(!pref->getAcceptedLegal());
318 #ifdef DISABLE_GUI
319 const QString eula = u"\n*** %1 ***\n"_qs.arg(QObject::tr("Legal Notice"))
320 + QObject::tr("qBittorrent is a file sharing program. When you run a torrent, its data will be made available to others by means of upload. Any content you share is your sole responsibility.") + u"\n\n"
321 + QObject::tr("No further notices will be issued.") + u"\n\n"
322 + QObject::tr("Press %1 key to accept and continue...").arg(u"'y'"_qs) + u'\n';
323 printf("%s", qUtf8Printable(eula));
325 const char ret = getchar(); // Read pressed key
326 if ((ret == 'y') || (ret == 'Y'))
328 // Save the answer
329 pref->setAcceptedLegal(true);
330 return true;
332 #else
333 QMessageBox msgBox;
334 msgBox.setText(QObject::tr("qBittorrent is a file sharing program. When you run a torrent, its data will be made available to others by means of upload. Any content you share is your sole responsibility.\n\nNo further notices will be issued."));
335 msgBox.setWindowTitle(QObject::tr("Legal notice"));
336 msgBox.addButton(QObject::tr("Cancel"), QMessageBox::RejectRole);
337 const QAbstractButton *agreeButton = msgBox.addButton(QObject::tr("I Agree"), QMessageBox::AcceptRole);
338 msgBox.show(); // Need to be shown or to moveToCenter does not work
339 msgBox.move(Utils::Gui::screenCenter(&msgBox));
340 msgBox.exec();
341 if (msgBox.clickedButton() == agreeButton)
343 // Save the answer
344 pref->setAcceptedLegal(true);
345 return true;
347 #endif // DISABLE_GUI
349 return false;
352 #ifdef Q_OS_UNIX
353 void adjustFileDescriptorLimit()
355 rlimit limit {};
357 if (getrlimit(RLIMIT_NOFILE, &limit) != 0)
358 return;
360 limit.rlim_cur = limit.rlim_max;
361 setrlimit(RLIMIT_NOFILE, &limit);
363 #endif