From 1d23d5ab9f7582f88ef4566c447c7fc61fb4a03b Mon Sep 17 00:00:00 2001 From: Julien Wadel Date: Tue, 29 Apr 2025 15:05:49 +0200 Subject: [PATCH] Clang format --- .clang-format | 31 ++ linphone-app/src/app/App.cpp | 892 +++++++++++++++---------------- linphone-app/src/app/App.hpp | 241 ++++----- linphone-app/src/app/cli/Cli.cpp | 406 +++++++------- linphone-app/src/app/cli/Cli.hpp | 115 ++-- 5 files changed, 818 insertions(+), 867 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..fe663f18f --- /dev/null +++ b/.clang-format @@ -0,0 +1,31 @@ +# Copyright (c) 2010-2023 Belledonne Communications SARL. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + +--- +Language: Cpp +BasedOnStyle: LLVM +AccessModifierOffset: -4 +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: AllIfsAndElse +AlwaysBreakTemplateDeclarations: Yes +BinPackParameters: false +ColumnLimit: 120 +PointerAlignment: Right +IndentCaseLabels: true +IndentWidth: 4 +Standard: c++14 +TabWidth: 4 +UseTab: ForIndentation +... diff --git a/linphone-app/src/app/App.cpp b/linphone-app/src/app/App.cpp index d4ac51f79..40ceb8ed3 100644 --- a/linphone-app/src/app/App.cpp +++ b/linphone-app/src/app/App.cpp @@ -30,42 +30,42 @@ #include #include #include -#include #include +#include #include #include #include #include -#include "config.h" #include "cli/Cli.hpp" #include "components/Components.hpp" +#include "components/history/CallHistoryModel.hpp" +#include "components/history/CallHistoryProxyModel.hpp" +#include "components/other/date/DateModel.hpp" +#include "components/other/desktop-tools/DesktopTools.hpp" +#include "components/other/spell-checker/SpellChecker.hpp" +#include "config.h" #include "logger/Logger.hpp" #include "paths/Paths.hpp" #include "providers/AvatarProvider.hpp" -#include "providers/ImageProvider.hpp" #include "providers/ExternalImageProvider.hpp" +#include "providers/ImageProvider.hpp" #include "providers/QRCodeProvider.hpp" -#include "providers/ThumbnailProvider.hpp" #include "providers/ScreenProvider.hpp" +#include "providers/ThumbnailProvider.hpp" #include "translator/DefaultTranslator.hpp" -#include "utils/Utils.hpp" #include "utils/Constants.hpp" -#include "components/history/CallHistoryModel.hpp" -#include "components/history/CallHistoryProxyModel.hpp" -#include "components/other/desktop-tools/DesktopTools.hpp" -#include "components/other/date/DateModel.hpp" -#include "components/other/spell-checker/SpellChecker.hpp" +#include "utils/Utils.hpp" #include "components/screen/ScreenProxyModel.hpp" #include "components/settings/EmojisSettingsModel.hpp" -#include "components/timeline/TimelineModel.hpp" #include "components/timeline/TimelineListModel.hpp" +#include "components/timeline/TimelineModel.hpp" #include "components/timeline/TimelineProxyModel.hpp" -#include "components/participant/ParticipantModel.hpp" #include "components/participant/ParticipantListModel.hpp" +#include "components/participant/ParticipantModel.hpp" #include "components/participant/ParticipantProxyModel.hpp" #include "components/videoSource/VideoSourceDescriptorModel.hpp" @@ -82,20 +82,18 @@ const QString IconsDirectory(QDir::homePath().append(QStringLiteral("/.local/sha #elif defined(Q_OS_MACOS) const QString OsascriptExecutable(QStringLiteral("osascript")); #else -const QString AutoStartSettingsFilePath( - QStringLiteral("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run") - ); +const QString + AutoStartSettingsFilePath(QStringLiteral("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run")); #endif // ifdef Q_OS_LINUX -} +} // namespace // ----------------------------------------------------------------------------- #ifdef Q_OS_LINUX -bool App::autoStartEnabled () { +bool App::autoStartEnabled() { const QString confPath(AutoStartDirectory + EXECUTABLE_NAME ".desktop"); QFile file(confPath); - if(!QDir(AutoStartDirectory).exists() || !file.exists()) - return false; + if (!QDir(AutoStartDirectory).exists() || !file.exists()) return false; if (!file.open(QFile::ReadOnly)) { qWarning() << "Unable to open autostart file in read only: `" << confPath << "`."; return false; @@ -110,8 +108,10 @@ bool App::autoStartEnabled () { QString autoStartConf = in.readAll(); int index = -1; - // check if the Exec part of the autostart ini file not corresponding to our executable (old desktop entry with wrong version in filename) - if (autoStartConf.indexOf(QString("Exec=" + exec+ " ")) < 0) {// On autostart, there is the option --iconified so there is one space. + // check if the Exec part of the autostart ini file not corresponding to our executable (old desktop entry with + // wrong version in filename) + if (autoStartConf.indexOf(QString("Exec=" + exec + " ")) < + 0) { // On autostart, there is the option --iconified so there is one space. // replace file setAutoStart(true); } @@ -119,38 +119,39 @@ bool App::autoStartEnabled () { return true; } #elif defined(Q_OS_MACOS) -static inline QString getMacOsBundlePath () { +static inline QString getMacOsBundlePath() { QDir dir(QCoreApplication::applicationDirPath()); - if (dir.dirName() != QLatin1String("MacOS")) - return QString(); - + if (dir.dirName() != QLatin1String("MacOS")) return QString(); + dir.cdUp(); dir.cdUp(); - + QString path(dir.path()); - if (path.length() > 0 && path.right(1) == "/") - path.chop(1); + if (path.length() > 0 && path.right(1) == "/") path.chop(1); return path; } -static inline QString getMacOsBundleName () { +static inline QString getMacOsBundleName() { return QFileInfo(getMacOsBundlePath()).baseName(); } -bool App::autoStartEnabled () { +bool App::autoStartEnabled() { const QByteArray expectedWord(getMacOsBundleName().toUtf8()); if (expectedWord.isEmpty()) { qInfo() << QStringLiteral("Application is not installed. Autostart unavailable."); return false; } - + QProcess process; - process.start(OsascriptExecutable, { "-e", "tell application \"System Events\" to get the name of every login item" }); + process.start(OsascriptExecutable, + {"-e", "tell application \"System Events\" to get the name of every login item"}); if (!process.waitForFinished()) { - qWarning() << QStringLiteral("Unable to execute properly: `%1` (%2).").arg(OsascriptExecutable).arg(process.errorString()); + qWarning() << QStringLiteral("Unable to execute properly: `%1` (%2).") + .arg(OsascriptExecutable) + .arg(process.errorString()); return false; } - + // TODO: Move in utils? const QByteArray buf(process.readAll()); for (const char *p = buf.data(), *word = p, *end = p + buf.length(); p <= end; ++p) { @@ -161,121 +162,117 @@ bool App::autoStartEnabled () { case '\t': case '\0': if (word != p) { - if (!strncmp(word, expectedWord, size_t(p - word))) - return true; + if (!strncmp(word, expectedWord, size_t(p - word))) return true; word = p + 1; } default: break; } } - + return false; } #else -bool App::autoStartEnabled () { +bool App::autoStartEnabled() { return QSettings(AutoStartSettingsFilePath, QSettings::NativeFormat).value(EXECUTABLE_NAME).isValid(); } #endif // ifdef Q_OS_LINUX // ----------------------------------------------------------------------------- -static inline bool installLocale (App &app, QTranslator &translator, const QLocale &locale) { +static inline bool installLocale(App &app, QTranslator &translator, const QLocale &locale) { bool ok = translator.load(locale, Constants::LanguagePath) && app.installTranslator(&translator); - if(ok) - QLocale::setDefault(locale); + if (ok) QLocale::setDefault(locale); return ok; } -static inline string getConfigPathIfExists (const QCommandLineParser &parser) { +static inline string getConfigPathIfExists(const QCommandLineParser &parser) { QString filePath = parser.isSet("config") ? parser.value("config") : ""; string configPath; - if(!QUrl(filePath).isRelative()){ - configPath = Utils::appStringToCoreString(FileDownloader::synchronousDownload(filePath, Utils::coreStringToAppString(Paths::getConfigDirPath(false)), true)); + if (!QUrl(filePath).isRelative()) { + configPath = Utils::appStringToCoreString(FileDownloader::synchronousDownload( + filePath, Utils::coreStringToAppString(Paths::getConfigDirPath(false)), true)); } - if( configPath == "") - configPath = Paths::getConfigFilePath(filePath, false); - if( configPath == "" ) - configPath = Paths::getConfigFilePath("", false); + if (configPath == "") configPath = Paths::getConfigFilePath(filePath, false); + if (configPath == "") configPath = Paths::getConfigFilePath("", false); return configPath; } -QString App::getFetchConfig (QString filePath, bool * error) { +QString App::getFetchConfig(QString filePath, bool *error) { *error = false; - if( !filePath.isEmpty()){ - if(QUrl(filePath).isRelative()){// this is a file path + if (!filePath.isEmpty()) { + if (QUrl(filePath).isRelative()) { // this is a file path filePath = Utils::coreStringToAppString(Paths::getConfigFilePath(filePath, false)); - if(!filePath.isEmpty()) - filePath = "file://"+filePath; + if (!filePath.isEmpty()) filePath = "file://" + filePath; } - if(filePath.isEmpty()){ - qWarning() <<"Remote provisionning cannot be retrieved. Command have beend cleaned"; + if (filePath.isEmpty()) { + qWarning() << "Remote provisionning cannot be retrieved. Command have beend cleaned"; *error = true; } } return filePath; } -QString App::getFetchConfig (QCommandLineParser *parser) { +QString App::getFetchConfig(QCommandLineParser *parser) { QString filePath = parser->value("fetch-config"); bool error = false; filePath = getFetchConfig(filePath, &error); - if(error) { - qWarning() <<"Remote provisionning cannot be retrieved. Command have beend cleaned"; + if (error) { + qWarning() << "Remote provisionning cannot be retrieved. Command have beend cleaned"; createParser(); - }else if( !filePath.isEmpty()) - mParser->process(cleanParserKeys(mParser, QStringList("fetch-config")));// Remove this parameter from the parser + } else if (!filePath.isEmpty()) + mParser->process( + cleanParserKeys(mParser, QStringList("fetch-config"))); // Remove this parameter from the parser return filePath; } -void App::useFetchConfig(const QString& filePath){ - if( !filePath.isEmpty()){ - if(CoreManager::getInstance()->isInitialized()) { - if(CoreManager::getInstance()->getSettingsModel()->getAutoApplyProvisioningConfigUriHandlerEnabled()) +void App::useFetchConfig(const QString &filePath) { + if (!filePath.isEmpty()) { + if (CoreManager::getInstance()->isInitialized()) { + if (CoreManager::getInstance()->getSettingsModel()->getAutoApplyProvisioningConfigUriHandlerEnabled()) setFetchConfig(filePath); - else - emit requestFetchConfig(filePath); - }else{ - QObject * context = new QObject(); - connect(CoreManager::getInstance(), &CoreManager::coreManagerInitialized, context, [context, filePath, this](){ - useFetchConfig(filePath); - context->deleteLater(); - }); + else emit requestFetchConfig(filePath); + } else { + QObject *context = new QObject(); + connect(CoreManager::getInstance(), &CoreManager::coreManagerInitialized, context, + [context, filePath, this]() { + useFetchConfig(filePath); + context->deleteLater(); + }); } } } -bool App::setFetchConfig (QString filePath) { +bool App::setFetchConfig(QString filePath) { bool fetched = false; qDebug() << "setFetchConfig with " << filePath; - if(!filePath.isEmpty()){ + if (!filePath.isEmpty()) { auto instance = CoreManager::getInstance(); - if(instance){ + if (instance) { auto core = instance->getCore(); - if(core){ - filePath.replace('\\','/'); + if (core) { + filePath.replace('\\', '/'); fetched = core->setProvisioningUri(Utils::appStringToCoreString(filePath)) == 0; } } } - if(!fetched){ - qWarning() <<"Remote provisionning cannot be retrieved. Command have beend cleaned"; - }else - restart(); + if (!fetched) { + qWarning() << "Remote provisionning cannot be retrieved. Command have beend cleaned"; + } else restart(); return fetched; } // ----------------------------------------------------------------------------- - - -App::App (int &argc, char *argv[]) : SingleApplication(argc, argv, true, Mode::User | Mode::ExcludeAppPath | Mode::ExcludeAppVersion) { +App::App(int &argc, char *argv[]) + : SingleApplication(argc, argv, true, Mode::User | Mode::ExcludeAppPath | Mode::ExcludeAppVersion) { // Ignore vertical sync. This way, we avoid blinking on resizes(and other refresh steps like layouts etc.). auto ignoreVSync = QSurfaceFormat::defaultFormat(); ignoreVSync.setSwapInterval(0); QSurfaceFormat::setDefaultFormat(ignoreVSync); //------------------- - connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)), this, SLOT(stateChanged(Qt::ApplicationState))); - + connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)), this, + SLOT(stateChanged(Qt::ApplicationState))); + setWindowIcon(QIcon(Constants::WindowIconPath)); #ifdef Q_OS_WIN @@ -312,48 +309,53 @@ App::App (int &argc, char *argv[]) : SingleApplication(argc, argv, true, Mode::U createParser(); mParser->parse(this->arguments()); -// Get configuration for translators - shared_ptr config = Utils::getConfigIfExists (QString::fromStdString(getConfigPathIfExists(*mParser))); - + // Get configuration for translators + shared_ptr config = + Utils::getConfigIfExists(QString::fromStdString(getConfigPathIfExists(*mParser))); + // Init locale. mTranslator = new DefaultTranslator(this); mDefaultTranslator = new DefaultTranslator(this); initLocale(config); Logger::init(config); - - createParser();// Recreate parser in order to use translations from config. + + createParser(); // Recreate parser in order to use translations from config. mParser->process(*this); - - if (mParser->isSet("verbose")) - Logger::getInstance()->setVerbose(true); - if (mParser->isSet("qt-logs-only")) - Logger::getInstance()->enableQtOnly(true); - + + if (mParser->isSet("verbose")) Logger::getInstance()->setVerbose(true); + if (mParser->isSet("qt-logs-only")) Logger::getInstance()->enableQtOnly(true); + // List available locales. for (const auto &locale : QDir(Constants::LanguagePath).entryList()) mAvailableLocales << QLocale(locale); - + if (mParser->isSet("help")) { mParser->showHelp(); } - + if (mParser->isSet("cli-help")) { Cli::showHelp(); ::exit(EXIT_SUCCESS); } - - if (mParser->isSet("version")) - mParser->showVersion(); + + if (mParser->isSet("version")) mParser->showVersion(); mAutoStart = false; mAutoStart = autoStartEnabled(); - - qInfo() << QStringLiteral("Starting application " APPLICATION_NAME " (bin: " EXECUTABLE_NAME "). Version:%1 Os:%2 Qt:%3") - .arg(applicationVersion()).arg(Utils::getOsProduct()).arg(qVersion()); - qInfo() << QStringLiteral("Use locale: %1 with language: %2").arg(mLocale.name()).arg(QLocale::languageToString(mLocale.language())); - qInfo() << QStringLiteral("System timezone: code=%1 / country=%2 / Offset=%3 / ID=%4").arg(QTimeZone::systemTimeZone().country()).arg(Utils::getCountryName(QTimeZone::systemTimeZone().country())) - .arg(QTimeZone::systemTimeZone().standardTimeOffset(QDateTime::currentDateTime())) - .arg(QString(QTimeZone::systemTimeZoneId())); - + + qInfo() << QStringLiteral("Starting application " APPLICATION_NAME " (bin: " EXECUTABLE_NAME + "). Version:%1 Os:%2 Qt:%3") + .arg(applicationVersion()) + .arg(Utils::getOsProduct()) + .arg(qVersion()); + qInfo() << QStringLiteral("Use locale: %1 with language: %2") + .arg(mLocale.name()) + .arg(QLocale::languageToString(mLocale.language())); + qInfo() << QStringLiteral("System timezone: code=%1 / country=%2 / Offset=%3 / ID=%4") + .arg(QTimeZone::systemTimeZone().country()) + .arg(Utils::getCountryName(QTimeZone::systemTimeZone().country())) + .arg(QTimeZone::systemTimeZone().standardTimeOffset(QDateTime::currentDateTime())) + .arg(QString(QTimeZone::systemTimeZoneId())); + // Deal with received messages and CLI. QObject::connect(this, &App::receivedMessage, this, [](int, const QByteArray &byteArray) { QString command(byteArray); @@ -363,75 +365,70 @@ App::App (int &argc, char *argv[]) : SingleApplication(argc, argv, true, Mode::U mCheckForUpdateUserInitiated = false; } -App::~App () { +App::~App() { qInfo() << QStringLiteral("Destroying app..."); } -void App::stop(){ +void App::stop() { qInfo() << QStringLiteral("Stopping app..."); - if( mEngine ){ + if (mEngine) { delete mEngine; processEvents(QEventLoop::AllEvents); } CoreManager::uninit(); - processEvents(QEventLoop::AllEvents); // Process all needed events on engine deletion. - if( mParser) - delete mParser; + processEvents(QEventLoop::AllEvents); // Process all needed events on engine deletion. + if (mParser) delete mParser; } // ----------------------------------------------------------------------------- -QStringList App::cleanParserKeys(QCommandLineParser * parser, QStringList keys){ +QStringList App::cleanParserKeys(QCommandLineParser *parser, QStringList keys) { QStringList oldArguments = parser->optionNames(); QStringList parameters; parameters << "dummy"; - for(int i = 0 ; i < oldArguments.size() ; ++i){ - if( !keys.contains(oldArguments[i])){ - if( mParser->value(oldArguments[i]).isEmpty()) - parameters << "--"+oldArguments[i]; - else - parameters << "--"+oldArguments[i]+"="+parser->value(oldArguments[i]); + for (int i = 0; i < oldArguments.size(); ++i) { + if (!keys.contains(oldArguments[i])) { + if (mParser->value(oldArguments[i]).isEmpty()) parameters << "--" + oldArguments[i]; + else parameters << "--" + oldArguments[i] + "=" + parser->value(oldArguments[i]); } } return parameters; } -void App::processArguments(QHash args){ +void App::processArguments(QHash args) { QList keys = args.keys(); QStringList parameters = cleanParserKeys(mParser, keys); - for(auto i = keys.begin() ; i != keys.end() ; ++i){ - parameters << "--"+(*i)+"="+args.value(*i); + for (auto i = keys.begin(); i != keys.end(); ++i) { + parameters << "--" + (*i) + "=" + args.value(*i); } - if(!mParser->parse(parameters)) - qWarning() << "Parsing error : " << mParser->errorText(); + if (!mParser->parse(parameters)) qWarning() << "Parsing error : " << mParser->errorText(); } -static QQuickWindow *createSubWindow (QQmlApplicationEngine *engine, const char *path) { +static QQuickWindow *createSubWindow(QQmlApplicationEngine *engine, const char *path) { QString qPath(path); qInfo() << QStringLiteral("Creating subwindow: `%1`.").arg(path); - + QQmlComponent component(engine, QUrl(path)); if (component.isError()) { qWarning() << component.errors(); abort(); } qInfo() << QStringLiteral("Subwindow status: `%1`.").arg(component.status()); - + QObject *object = component.create(); Q_ASSERT(object); - + QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership); object->setParent(engine); - - + int totalDuration = 0; int loops = 0; QElapsedTimer timer; timer.start(); auto window = qobject_cast(object); - QObject::connect(window, &QQuickWindow::beforeRendering, [totalDuration, loops, timer, path]() mutable{ + QObject::connect(window, &QQuickWindow::beforeRendering, [totalDuration, loops, timer, path]() mutable { totalDuration += timer.elapsed(); ++loops; - if (totalDuration > 10*1000) { + if (totalDuration > 10 * 1000) { qDebug() << path << " : " << (1000.0 * loops) / totalDuration << "fps"; totalDuration = 0; loops = 0; @@ -443,21 +440,21 @@ static QQuickWindow *createSubWindow (QQmlApplicationEngine *engine, const char // ----------------------------------------------------------------------------- -void App::initContentApp () { +void App::initContentApp() { std::string configPath; shared_ptr config; bool mustBeIconified = false; bool needRestart = true; - + // Destroy qml components and linphone core if necessary. if (mEngine) { needRestart = false; setOpened(false); qInfo() << QStringLiteral("Restarting app..."); - + delete mEngine; - + mNotifier = nullptr; // CoreManager::uninit(); @@ -468,7 +465,7 @@ void App::initContentApp () { mTranslator = new DefaultTranslator(this); mDefaultTranslator = new DefaultTranslator(this); configPath = getConfigPathIfExists(*mParser); - config = Utils::getConfigIfExists (QString::fromStdString(configPath)); + config = Utils::getConfigIfExists(QString::fromStdString(configPath)); initLocale(config); } else { configPath = getConfigPathIfExists(*mParser); @@ -476,48 +473,45 @@ void App::initContentApp () { // Update and download codecs. VideoCodecsModel::updateCodecs(); VideoCodecsModel::downloadUpdatableCodecs(this); - + // Don't quit if last window is closed!!! setQuitOnLastWindowClosed(false); - - - + #ifndef Q_OS_MACOS mustBeIconified = mParser->isSet("iconified"); #endif // ifndef Q_OS_MACOS mColorListModel = new ColorListModel(); mImageListModel = new ImageListModel(); } - + // Change colors if necessary. mColorListModel->useConfig(config); mImageListModel->useConfig(config); -// There is no more database for callback. Setting it in the configuration before starting the core will do migration. -// When the migration is done by SDK, further migrations on call logs will do nothing. It is safe to use . + // There is no more database for callback. Setting it in the configuration before starting the core will do + // migration. When the migration is done by SDK, further migrations on call logs will do nothing. It is safe to use + // . config->setString("storage", "call_logs_db_uri", Paths::getCallHistoryFilePath()); - + // Init core. CoreManager::init(this, Utils::coreStringToAppString(configPath)); - - + // Init engine content. mEngine = new QQmlApplicationEngine(this); - + // Provide `+custom` folders for custom components and `5.9` for old components. { QStringList selectors("custom"); const QVersionNumber &version = QLibraryInfo::version(); - if (version.majorVersion() == 5 && version.minorVersion() == 9) - selectors.push_back("5.9"); + if (version.majorVersion() == 5 && version.minorVersion() == 9) selectors.push_back("5.9"); (new QQmlFileSelector(mEngine, mEngine))->setExtraSelectors(selectors); } qInfo() << QStringLiteral("Activated selectors:") << QQmlFileSelector::get(mEngine)->selector()->allSelectors(); - + // Set modules paths. mEngine->addImportPath(":/ui/modules"); mEngine->addImportPath(":/ui/scripts"); mEngine->addImportPath(":/ui/views"); - + // Provide avatars/thumbnails providers. mEngine->addImageProvider(AvatarProvider::ProviderId, new AvatarProvider()); mEngine->addImageProvider(ImageProvider::ProviderId, new ImageProvider()); @@ -526,7 +520,7 @@ void App::initContentApp () { mEngine->addImageProvider(ThumbnailProvider::ProviderId, new ThumbnailProvider()); mEngine->addImageProvider(ScreenProvider::ProviderId, new ScreenProvider()); mEngine->addImageProvider(WindowProvider::ProviderId, new WindowProvider()); - + mEngine->rootContext()->setContextProperty("applicationName", APPLICATION_NAME); mEngine->rootContext()->setContextProperty("executableName", EXECUTABLE_NAME); @@ -535,7 +529,7 @@ void App::initContentApp () { #else mEngine->rootContext()->setContextProperty("applicationUrl", ""); #endif - + #ifdef APPLICATION_VENDOR mEngine->rootContext()->setContextProperty("applicationVendor", APPLICATION_VENDOR); #else @@ -552,60 +546,54 @@ void App::initContentApp () { mEngine->rootContext()->setContextProperty("applicationLicenceUrl", ""); #endif - #ifdef COPYRIGHT_RANGE_DATE - mEngine->rootContext()->setContextProperty("copyrightRangeDate", COPYRIGHT_RANGE_DATE); + mEngine->rootContext()->setContextProperty("copyrightRangeDate", COPYRIGHT_RANGE_DATE); #else mEngine->rootContext()->setContextProperty("copyrightRangeDate", ""); #endif mEngine->rootContext()->setContextProperty("Colors", mColorListModel->getQmlData()); mEngine->rootContext()->setContextProperty("Images", mImageListModel->getQmlData()); - - mEngine->rootContext()->setContextProperty("qtIsNewer_5_15_0", QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) ); - + + mEngine->rootContext()->setContextProperty("qtIsNewer_5_15_0", QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)); + registerTypes(); registerSharedTypes(); registerToolTypes(); registerSharedToolTypes(); registerUninstalledModules(); - + // Enable notifications. mNotifier = new Notifier(mEngine); // Load main view. qInfo() << QStringLiteral("Loading main view..."); mEngine->load(QUrl(Constants::QmlViewMainWindow)); - if (mEngine->rootObjects().isEmpty()) - qFatal("Unable to open main window."); - - QObject::connect( - CoreManager::getInstance(), - &CoreManager::coreManagerInitialized, CoreManager::getInstance(), - [this, mustBeIconified]() mutable { - if(CoreManager::getInstance()->started()) { - openAppAfterInit(mustBeIconified); - } - } - ); + if (mEngine->rootObjects().isEmpty()) qFatal("Unable to open main window."); + + QObject::connect(CoreManager::getInstance(), &CoreManager::coreManagerInitialized, CoreManager::getInstance(), + [this, mustBeIconified]() mutable { + if (CoreManager::getInstance()->started()) { + openAppAfterInit(mustBeIconified); + } + }); // Execute command argument if needed - // Commands are executed only once. clearPsitionalArguments doesn't work as its name suggest : getPositionalArguments still retrieve user arguments. - // So execute the command only once. + // Commands are executed only once. clearPsitionalArguments doesn't work as its name suggest : + // getPositionalArguments still retrieve user arguments. So execute the command only once. static bool firstRun = false; - if(!firstRun){ + if (!firstRun) { firstRun = true; const QString commandArgument = getCommandArgument(); if (!commandArgument.isEmpty()) { Cli::CommandFormat format; Cli::executeCommand(commandArgument, &format); - if (format == Cli::UriFormat || format == Cli::UrlFormat ) - mustBeIconified = true; + if (format == Cli::UriFormat || format == Cli::UrlFormat) mustBeIconified = true; } } } // ----------------------------------------------------------------------------- -QString App::getCommandArgument () { +QString App::getCommandArgument() { const QStringList &arguments = mParser->positionalArguments(); return arguments.empty() ? QString("") : arguments[0]; } @@ -614,21 +602,20 @@ QString App::getCommandArgument () { #ifdef Q_OS_MACOS -bool App::event (QEvent *event) { +bool App::event(QEvent *event) { if (event->type() == QEvent::FileOpen) { const QString url = static_cast(event)->url().toString(); if (isSecondary()) { sendMessage(url.toLocal8Bit(), -1); ::exit(EXIT_SUCCESS); } - + Cli::executeCommand(url); - }else if(event->type() == QEvent::ApplicationStateChange){ - auto state = static_cast(event); - if( state->applicationState() == Qt::ApplicationActive) - smartShowWindow(getMainWindow()); + } else if (event->type() == QEvent::ApplicationStateChange) { + auto state = static_cast(event); + if (state->applicationState() == Qt::ApplicationActive) smartShowWindow(getMainWindow()); } - + return SingleApplication::event(event); } @@ -636,155 +623,147 @@ bool App::event (QEvent *event) { // ----------------------------------------------------------------------------- -QQuickWindow *App::getCallsWindow () const { - if (CoreManager::getInstance()->getCore()->getConfig()->getInt( - SettingsModel::UiSection, "disable_calls_window", 0 - )) +QQuickWindow *App::getCallsWindow() const { + if (CoreManager::getInstance()->getCore()->getConfig()->getInt(SettingsModel::UiSection, "disable_calls_window", 0)) return nullptr; - + return mCallsWindow; } -QQuickWindow *App::getMainWindow () const { - return qobject_cast( - const_cast(mEngine)->rootObjects().at(0) - ); +QQuickWindow *App::getMainWindow() const { + return qobject_cast(const_cast(mEngine)->rootObjects().at(0)); } -QQuickWindow *App::getSettingsWindow () const { +QQuickWindow *App::getSettingsWindow() const { return mSettingsWindow; } // ----------------------------------------------------------------------------- -void App::smartShowWindow (QQuickWindow *window) { - if (!window) - return; +void App::smartShowWindow(QQuickWindow *window) { + if (!window) return; window->setVisible(true); // Force show, maybe redundant with setVisible - if(window->visibility() == QWindow::Maximized)// Avoid to change visibility mode + if (window->visibility() == QWindow::Maximized) // Avoid to change visibility mode window->showMaximized(); - else - window->show(); - window->raise();// Raise ensure to get focus on Mac + else window->show(); + window->raise(); // Raise ensure to get focus on Mac window->requestActivate(); } // ----------------------------------------------------------------------------- -bool App::hasFocus () const { +bool App::hasFocus() const { return getMainWindow()->isActive() || (mCallsWindow && mCallsWindow->isActive()); } void App::stateChanged(Qt::ApplicationState pState) { DesktopTools::applicationStateChanged(pState); auto core = CoreManager::getInstance(); - if(core) - core->stateChanged(pState); + if (core) core->stateChanged(pState); } // ----------------------------------------------------------------------------- -void App::createParser () { +void App::createParser() { delete mParser; - + mParser = new QCommandLineParser(); mParser->setApplicationDescription(tr("applicationDescription")); - mParser->addPositionalArgument("command", tr("commandLineDescription").replace("%1", APPLICATION_NAME), "[command]"); + mParser->addPositionalArgument("command", tr("commandLineDescription").replace("%1", APPLICATION_NAME), + "[command]"); mParser->addOptions({ - { { "h", "help" }, tr("commandLineOptionHelp") }, - { "cli-help", tr("commandLineOptionCliHelp").replace("%1", APPLICATION_NAME) }, - { { "v", "version" }, tr("commandLineOptionVersion") }, - { "config", tr("commandLineOptionConfig").replace("%1", EXECUTABLE_NAME), tr("commandLineOptionConfigArg") }, - { "fetch-config", tr("commandLineOptionFetchConfig").replace("%1", EXECUTABLE_NAME), tr("commandLineOptionFetchConfigArg") }, - { { "c", "call" }, tr("commandLineOptionCall").replace("%1", EXECUTABLE_NAME),tr("commandLineOptionCallArg") }, - #ifndef Q_OS_MACOS - { "iconified", tr("commandLineOptionIconified") }, - #endif // ifndef Q_OS_MACOS - { { "V", "verbose" }, tr("commandLineOptionVerbose") }, - { "qt-logs-only", tr("commandLineOptionQtLogsOnly") }, - }); + {{"h", "help"}, tr("commandLineOptionHelp")}, + {"cli-help", tr("commandLineOptionCliHelp").replace("%1", APPLICATION_NAME)}, + {{"v", "version"}, tr("commandLineOptionVersion")}, + {"config", tr("commandLineOptionConfig").replace("%1", EXECUTABLE_NAME), tr("commandLineOptionConfigArg")}, + {"fetch-config", tr("commandLineOptionFetchConfig").replace("%1", EXECUTABLE_NAME), + tr("commandLineOptionFetchConfigArg")}, + {{"c", "call"}, tr("commandLineOptionCall").replace("%1", EXECUTABLE_NAME), tr("commandLineOptionCallArg")}, +#ifndef Q_OS_MACOS + {"iconified", tr("commandLineOptionIconified")}, +#endif // ifndef Q_OS_MACOS + {{"V", "verbose"}, tr("commandLineOptionVerbose")}, + {"qt-logs-only", tr("commandLineOptionQtLogsOnly")}, + }); } // ----------------------------------------------------------------------------- -template -static QObject *makeSharedSingleton (QQmlEngine *, QJSEngine *) { +template +static QObject *makeSharedSingleton(QQmlEngine *, QJSEngine *) { QObject *object = (*function)(); QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership); return object; } -template -static inline void registerSharedSingletonType (const char *name) { +template +static inline void registerSharedSingletonType(const char *name) { qmlRegisterSingletonType(Constants::MainQmlUri, 1, 0, name, makeSharedSingleton); } -template -static QObject *makeSharedSingleton (QQmlEngine *, QJSEngine *) { +template +static QObject *makeSharedSingleton(QQmlEngine *, QJSEngine *) { QObject *object = (CoreManager::getInstance()->*function)(); QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership); return object; } - -template -static QObject *makeSharedSingleton (QQmlEngine *, QJSEngine *) { +template +static QObject *makeSharedSingleton(QQmlEngine *, QJSEngine *) { QObject *object = (CoreManager::getInstance()->*function)(); QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership); return object; } -template -static inline void registerSharedSingletonType (const char *name) { +template +static inline void registerSharedSingletonType(const char *name) { qmlRegisterSingletonType(Constants::MainQmlUri, 1, 0, name, makeSharedSingleton); } -template -static inline void registerSharedSingletonType (const char *name) { +template +static inline void registerSharedSingletonType(const char *name) { qmlRegisterSingletonType(Constants::MainQmlUri, 1, 0, name, makeSharedSingleton); } -template -static inline void registerUncreatableType (const char *name) { +template +static inline void registerUncreatableType(const char *name) { qmlRegisterUncreatableType(Constants::MainQmlUri, 1, 0, name, QLatin1String("Uncreatable")); } -template -static inline void registerSingletonType (const char *name) { - qmlRegisterSingletonType(Constants::MainQmlUri, 1, 0, name, [](QQmlEngine *engine, QJSEngine *) -> QObject *{ - return new T(engine); - }); +template +static inline void registerSingletonType(const char *name) { + qmlRegisterSingletonType(Constants::MainQmlUri, 1, 0, name, + [](QQmlEngine *engine, QJSEngine *) -> QObject * { return new T(engine); }); } -template -static inline void registerType (const char *name) { +template +static inline void registerType(const char *name) { qmlRegisterType(Constants::MainQmlUri, 1, 0, name); } -template -static inline void registerToolType (const char *name, const int &major_version = 1 , const int &minor_version = 0) { - qmlRegisterSingletonType(name, major_version, minor_version, name, [](QQmlEngine *engine, QJSEngine *) -> QObject *{ - return new T(engine); - }); +template +static inline void registerToolType(const char *name, const int &major_version = 1, const int &minor_version = 0) { + qmlRegisterSingletonType(name, major_version, minor_version, name, + [](QQmlEngine *engine, QJSEngine *) -> QObject * { return new T(engine); }); } -template -static QObject *makeSharedTool (QQmlEngine *, QJSEngine *) { +template +static QObject *makeSharedTool(QQmlEngine *, QJSEngine *) { QObject *object = (Owner::getInstance()->*function)(); QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership); return object; } -template -static inline void registerSharedToolType (const char *name) { +template +static inline void registerSharedToolType(const char *name) { qmlRegisterSingletonType(name, 1, 0, name, makeSharedTool); } -void App::registerTypes () { +void App::registerTypes() { qInfo() << QStringLiteral("Registering types..."); - + qRegisterMetaType>(); qRegisterMetaType(); qRegisterMetaType>(); - qRegisterMetaType > >(); + qRegisterMetaType>>(); qRegisterMetaType>(); qRegisterMetaType>(); qRegisterMetaType>(); @@ -793,9 +772,9 @@ void App::registerTypes () { qRegisterMetaType>(); qRegisterMetaType>(); qRegisterMetaType>(); - //qRegisterMetaType>(); + // qRegisterMetaType>(); LinphoneEnums::registerMetaTypes(); - + registerType("AssistantModel"); registerType("AuthenticationNotifier"); registerType("CallsListProxyModel"); @@ -822,7 +801,7 @@ void App::registerTypes () { registerType("TemporaryFile"); registerType("TimeZoneProxyModel"); registerType("VideoSourceDescriptorModel"); - + registerType("CallHistoryProxyModel"); registerType("ColorProxyModel"); registerType("ImageColorsProxyModel"); @@ -834,15 +813,14 @@ void App::registerTypes () { registerType("TelephoneNumbersModel"); registerType("ScreenProxyModel"); registerType("SpellChecker"); - + registerSingletonType("AudioCodecsModel"); registerSingletonType("OwnPresenceModel"); registerSingletonType("Presence"); - //registerSingletonType("TimelineModel"); + // registerSingletonType("TimelineModel"); registerSingletonType("UrlHandlers"); registerSingletonType("VideoCodecsModel"); - - + registerUncreatableType("CallModel"); registerUncreatableType("CallHistoryModel"); registerUncreatableType("ChatCallModel"); @@ -863,7 +841,7 @@ void App::registerTypes () { registerUncreatableType("LdapModel"); registerUncreatableType("RecorderModel"); registerUncreatableType("SearchResultModel"); - registerUncreatableType("SipAddressObserver"); + registerUncreatableType("SipAddressObserver"); registerUncreatableType("VcardModel"); registerUncreatableType("TimelineModel"); registerUncreatableType("TunnelModel"); @@ -875,36 +853,36 @@ void App::registerTypes () { registerUncreatableType("ParticipantDeviceListModel"); registerUncreatableType("ParticipantImdnStateModel"); registerUncreatableType("ParticipantImdnStateListModel"); - - - - qmlRegisterUncreatableMetaObject(LinphoneEnums::staticMetaObject, "LinphoneEnums", 1, 0, "LinphoneEnums", "Only enums"); + + qmlRegisterUncreatableMetaObject(LinphoneEnums::staticMetaObject, "LinphoneEnums", 1, 0, "LinphoneEnums", + "Only enums"); } -void App::registerSharedTypes () { +void App::registerSharedTypes() { qInfo() << QStringLiteral("Registering shared types..."); - + registerSharedSingletonType("App"); registerSharedSingletonType("CoreManager"); registerSharedSingletonType("SettingsModel"); registerSharedSingletonType("EmojisSettingsModel"); registerSharedSingletonType("AccountSettingsModel"); - registerSharedSingletonType("SipAddressesModel"); + registerSharedSingletonType("SipAddressesModel"); registerSharedSingletonType("CallsListModel"); registerSharedSingletonType("ContactsListModel"); - registerSharedSingletonType("ContactsImporterListModel"); + registerSharedSingletonType( + "ContactsImporterListModel"); registerSharedSingletonType("LdapListModel"); registerSharedSingletonType("TimelineListModel"); registerSharedSingletonType("RecorderManager"); - - //qmlRegisterSingletonType(Constants::MainQmlUri, 1, 0, "ColorList", mColorListModel); - - //registerSharedSingletonType("ColorCpp"); + + // qmlRegisterSingletonType(Constants::MainQmlUri, 1, 0, "ColorList", mColorListModel); + + // registerSharedSingletonType("ColorCpp"); } -void App::registerToolTypes () { +void App::registerToolTypes() { qInfo() << QStringLiteral("Registering tool types..."); - + registerToolType("Clipboard"); registerToolType("DesktopTools"); registerToolType("TextToSpeech"); @@ -914,144 +892,132 @@ void App::registerToolTypes () { registerToolType("ConstantsCpp"); } -void App::registerSharedToolTypes () { +void App::registerSharedToolTypes() { qInfo() << QStringLiteral("Registering shared tool types..."); - - registerSharedToolType("ColorsList"); + + registerSharedToolType("ColorsList"); } void App::registerUninstalledModules() { - if(!isPdfAvailable()) - qmlRegisterModule("QtQuick.Pdf",5,15); + if (!isPdfAvailable()) qmlRegisterModule("QtQuick.Pdf", 5, 15); } // ----------------------------------------------------------------------------- -void App::setTrayIcon () { +void App::setTrayIcon() { QQuickWindow *root = getMainWindow(); - QSystemTrayIcon* systemTrayIcon = (mSystemTrayIcon?mSystemTrayIcon : new QSystemTrayIcon(nullptr));// Workaround : QSystemTrayIcon cannot be deleted because of setContextMenu (indirectly) - + QSystemTrayIcon *systemTrayIcon = + (mSystemTrayIcon + ? mSystemTrayIcon + : new QSystemTrayIcon( + nullptr)); // Workaround : QSystemTrayIcon cannot be deleted because of setContextMenu (indirectly) + // trayIcon: Right click actions. QAction *settingsAction = new QAction(tr("settings"), root); - root->connect(settingsAction, &QAction::triggered, root, [this] { - App::smartShowWindow(getSettingsWindow()); - }); - + root->connect(settingsAction, &QAction::triggered, root, [this] { App::smartShowWindow(getSettingsWindow()); }); + QAction *updateCheckAction = nullptr; - if(SettingsModel::isCheckForUpdateAvailable()){ + if (SettingsModel::isCheckForUpdateAvailable()) { updateCheckAction = new QAction(tr("checkForUpdates"), root); - root->connect(updateCheckAction, &QAction::triggered, root, [this] { - checkForUpdates(true); - }); + root->connect(updateCheckAction, &QAction::triggered, root, [this] { checkForUpdates(true); }); } - + QAction *aboutAction = new QAction(tr("about"), root); root->connect(aboutAction, &QAction::triggered, root, [root] { App::smartShowWindow(root); - QMetaObject::invokeMethod( - root, Constants::AttachVirtualWindowMethodName, Qt::DirectConnection, - Q_ARG(QVariant, QUrl(Constants::AboutPath)), Q_ARG(QVariant, QVariant()), Q_ARG(QVariant, QVariant()) - ); + QMetaObject::invokeMethod(root, Constants::AttachVirtualWindowMethodName, Qt::DirectConnection, + Q_ARG(QVariant, QUrl(Constants::AboutPath)), Q_ARG(QVariant, QVariant()), + Q_ARG(QVariant, QVariant())); }); - + QAction *restoreAction = new QAction(tr("restore"), root); - root->connect(restoreAction, &QAction::triggered, root, [root] { - smartShowWindow(root); - }); - + root->connect(restoreAction, &QAction::triggered, root, [root] { smartShowWindow(root); }); + QAction *quitAction = new QAction(tr("quit"), root); root->connect(quitAction, &QAction::triggered, this, &App::quit); - + // trayIcon: Left click actions. - static QMenu *menu = new QMenu();// Static : Workaround about a bug with setContextMenu where it cannot be called more than once. - root->connect(systemTrayIcon, &QSystemTrayIcon::activated, [root]( - QSystemTrayIcon::ActivationReason reason - ) { + static QMenu *menu = + new QMenu(); // Static : Workaround about a bug with setContextMenu where it cannot be called more than once. + root->connect(systemTrayIcon, &QSystemTrayIcon::activated, [root](QSystemTrayIcon::ActivationReason reason) { if (reason == QSystemTrayIcon::Trigger) { - if (root->visibility() == QWindow::Hidden) - smartShowWindow(root); - else - root->hide(); + if (root->visibility() == QWindow::Hidden) smartShowWindow(root); + else root->hide(); } }); menu->setTitle(APPLICATION_NAME); // Build trayIcon menu. menu->addAction(settingsAction); - if(updateCheckAction) - menu->addAction(updateCheckAction); + if (updateCheckAction) menu->addAction(updateCheckAction); menu->addAction(aboutAction); menu->addSeparator(); menu->addAction(restoreAction); menu->addSeparator(); menu->addAction(quitAction); - if(!mSystemTrayIcon) - systemTrayIcon->setContextMenu(menu);// This is a Qt bug. We cannot call setContextMenu more than once. So we have to keep an instance of the menu. + if (!mSystemTrayIcon) + systemTrayIcon->setContextMenu(menu); // This is a Qt bug. We cannot call setContextMenu more than once. So we + // have to keep an instance of the menu. systemTrayIcon->setIcon(QIcon(Constants::WindowIconPath)); systemTrayIcon->setToolTip(APPLICATION_NAME); systemTrayIcon->show(); - if(!mSystemTrayIcon) - mSystemTrayIcon = systemTrayIcon; - if(!QSystemTrayIcon::isSystemTrayAvailable()) - qInfo() << "System tray is not available"; + if (!mSystemTrayIcon) mSystemTrayIcon = systemTrayIcon; + if (!QSystemTrayIcon::isSystemTrayAvailable()) qInfo() << "System tray is not available"; } // ----------------------------------------------------------------------------- -void App::initLocale (const shared_ptr &config) { +void App::initLocale(const shared_ptr &config) { // Try to use preferred locale. QString locale; - + // Use english. This default translator is used if there are no found translations in others loads mLocale = QLocale(Constants::DefaultLocale); - if (!installLocale(*this, *mDefaultTranslator, mLocale)) - qFatal("Unable to install default translator."); - - if (config) - locale = Utils::coreStringToAppString(config->getString(SettingsModel::UiSection, "locale", "")); - + if (!installLocale(*this, *mDefaultTranslator, mLocale)) qFatal("Unable to install default translator."); + + if (config) locale = Utils::coreStringToAppString(config->getString(SettingsModel::UiSection, "locale", "")); + if (!locale.isEmpty() && installLocale(*this, *mTranslator, QLocale(locale))) { mLocale = QLocale(locale); return; } - -// Try to use system locale. -//#ifdef Q_OS_MACOS -// Use this workaround if there is still an issue about detecting wrong language from system on Mac. Qt doesn't use the current system language on QLocale::system(). So we need to get it from user settings and overwrite its Locale. -// QSettings settings; -// QString preferredLanguage = settings.value("AppleLanguages").toStringList().first(); -// QStringList qtLocale = QLocale::system().name().split('_'); -// if(qtLocale[0] != preferredLanguage){ -// qInfo() << "Override Qt language from " << qtLocale[0] << " to the preferred language : " << preferredLanguage; -// qtLocale[0] = preferredLanguage; -// } -// QLocale sysLocale = QLocale(qtLocale.join('_')); -//#else - QLocale sysLocale(QLocale::system().name());// Use Locale from name because Qt has a bug where it didn't use the QLocale::language (aka : translator.language != locale.language) on Mac. -//#endif + + // Try to use system locale. + // #ifdef Q_OS_MACOS + // Use this workaround if there is still an issue about detecting wrong language from system on Mac. Qt doesn't use + // the current system language on QLocale::system(). So we need to get it from user settings and overwrite its + // Locale. + // QSettings settings; + // QString preferredLanguage = settings.value("AppleLanguages").toStringList().first(); + // QStringList qtLocale = QLocale::system().name().split('_'); + // if(qtLocale[0] != preferredLanguage){ + // qInfo() << "Override Qt language from " << qtLocale[0] << " to the preferred language : " << + //preferredLanguage; qtLocale[0] = preferredLanguage; + // } + // QLocale sysLocale = QLocale(qtLocale.join('_')); + // #else + QLocale sysLocale( + QLocale::system().name()); // Use Locale from name because Qt has a bug where it didn't use the + // QLocale::language (aka : translator.language != locale.language) on Mac. + // #endif if (installLocale(*this, *mTranslator, sysLocale)) { mLocale = sysLocale; return; } - } -QString App::getConfigLocale () const { +QString App::getConfigLocale() const { return Utils::coreStringToAppString( - CoreManager::getInstance()->getCore()->getConfig()->getString( - SettingsModel::UiSection, "locale", "" - ) - ); + CoreManager::getInstance()->getCore()->getConfig()->getString(SettingsModel::UiSection, "locale", "")); } -void App::setConfigLocale (const QString &locale) { - CoreManager::getInstance()->getCore()->getConfig()->setString( - SettingsModel::UiSection, "locale", Utils::appStringToCoreString(locale) - ); - +void App::setConfigLocale(const QString &locale) { + CoreManager::getInstance()->getCore()->getConfig()->setString(SettingsModel::UiSection, "locale", + Utils::appStringToCoreString(locale)); + emit configLocaleChanged(locale); } -QLocale App::getLocale () const { +QLocale App::getLocale() const { return mLocale; } @@ -1059,60 +1025,56 @@ QLocale App::getLocale () const { #ifdef Q_OS_LINUX -void App::setAutoStart (bool enabled) { - if (enabled == mAutoStart) - return; - +void App::setAutoStart(bool enabled) { + if (enabled == mAutoStart) return; + QDir dir(AutoStartDirectory); if (!dir.exists() && !dir.mkpath(AutoStartDirectory)) { qWarning() << QStringLiteral("Unable to build autostart dir path: `%1`.").arg(AutoStartDirectory); return; } - + const QString confPath(AutoStartDirectory + EXECUTABLE_NAME ".desktop"); - if(generateDesktopFile(confPath, !enabled, true)) { + if (generateDesktopFile(confPath, !enabled, true)) { mAutoStart = enabled; emit autoStartChanged(enabled); } } -void App::exportDesktopFile(){ +void App::exportDesktopFile() { QDir dir(ApplicationsDirectory); if (!dir.exists() && !dir.mkpath(ApplicationsDirectory)) { qWarning() << QStringLiteral("Unable to build applications dir path: `%1`.").arg(ApplicationsDirectory); return; } - + const QString confPath(ApplicationsDirectory + EXECUTABLE_NAME ".desktop"); - if(generateDesktopFile(confPath, true, false)) - generateDesktopFile(confPath, false, false); + if (generateDesktopFile(confPath, true, false)) generateDesktopFile(confPath, false, false); } -QString App::getApplicationPath() const{ +QString App::getApplicationPath() const { const QString binPath(QCoreApplication::applicationFilePath()); - + // Check if installation is done via Flatpak, AppImage, or classic package // in order to rewrite a correct exec path for autostart QString exec; qDebug() << "binpath=" << binPath; - if (binPath.startsWith("/app")) { //Flatpak + if (binPath.startsWith("/app")) { // Flatpak exec = QStringLiteral("flatpak run " APPLICATION_ID); qDebug() << "exec path autostart set flatpak=" << exec; - } - else if (binPath.startsWith("/tmp/.mount")) { //Appimage + } else if (binPath.startsWith("/tmp/.mount")) { // Appimage exec = QProcessEnvironment::systemEnvironment().value(QStringLiteral("APPIMAGE")); qDebug() << "exec path autostart set appimage=" << exec; - } - else { //classic package + } else { // classic package exec = binPath; qDebug() << "exec path autostart set classic package=" << exec; } return exec; } -bool App::generateDesktopFile(const QString& confPath, bool remove, bool openInBackground){ +bool App::generateDesktopFile(const QString &confPath, bool remove, bool openInBackground) { qInfo() << QStringLiteral("Updating `%1`...").arg(confPath); QFile file(confPath); - + if (remove) { if (file.exists() && !file.remove()) { qWarning() << QLatin1String("Unable to remove autostart file: `" EXECUTABLE_NAME ".desktop`."); @@ -1120,89 +1082,86 @@ bool App::generateDesktopFile(const QString& confPath, bool remove, bool openInB } return true; } - + if (!file.open(QFile::WriteOnly)) { qWarning() << "Unable to open autostart file: `" EXECUTABLE_NAME ".desktop`."; return false; } - + QString exec = getApplicationPath(); - + QDir dir; QString iconPath; bool haveIcon = false; - if(!dir.mkpath(IconsDirectory)) // Scalable icons folder may be created + if (!dir.mkpath(IconsDirectory)) // Scalable icons folder may be created qWarning() << "Cannot create scalable icon path at " << IconsDirectory; - else{ - iconPath = IconsDirectory + EXECUTABLE_NAME +".svg"; + else { + iconPath = IconsDirectory + EXECUTABLE_NAME + ".svg"; QFile icon(Constants::WindowIconPath); - if(!QFile(iconPath).exists()) {// Keep old icon but copy if it doesn't exist + if (!QFile(iconPath).exists()) { // Keep old icon but copy if it doesn't exist haveIcon = icon.copy(iconPath); - if(!haveIcon) - qWarning() << "Couldn't copy icon svg into " << iconPath; - else {// Update permissions + if (!haveIcon) qWarning() << "Couldn't copy icon svg into " << iconPath; + else { // Update permissions QFile icon(iconPath); icon.setPermissions(icon.permissions() | QFileDevice::WriteOwner); } - }else { + } else { qInfo() << "Icon already exists in " << IconsDirectory << ". It is not replaced."; haveIcon = true; } } - - QTextStream(&file) << QString( - "[Desktop Entry]\n" - "Name=" APPLICATION_NAME "\n" - "GenericName=SIP Phone\n" - "Comment=" APPLICATION_DESCRIPTION "\n" - "Type=Application\n") - << (openInBackground ? "Exec=" + exec + " --iconified %u\n" : "Exec=" + exec + " %u\n") - << (haveIcon ? "Icon=" +iconPath + "\n" : "Icon=" EXECUTABLE_NAME "\n") - << "Terminal=false\n" - "Categories=Network;Telephony;\n" - "MimeType=x-scheme-handler/sip-" EXECUTABLE_NAME ";x-scheme-handler/sip;x-scheme-handler/sips-" EXECUTABLE_NAME ";x-scheme-handler/sips;x-scheme-handler/tel;x-scheme-handler/callto;x-scheme-handler/" EXECUTABLE_NAME "-config;\n" - "X-PulseAudio-Properties=media.role=phone\n"; - - return true; + + QTextStream(&file) + << QString("[Desktop Entry]\n" + "Name=" APPLICATION_NAME "\n" + "GenericName=SIP Phone\n" + "Comment=" APPLICATION_DESCRIPTION "\n" + "Type=Application\n") + << (openInBackground ? "Exec=" + exec + " --iconified %u\n" : "Exec=" + exec + " %u\n") + << (haveIcon ? "Icon=" + iconPath + "\n" : "Icon=" EXECUTABLE_NAME "\n") + << "Terminal=false\n" + "Categories=Network;Telephony;\n" + "MimeType=x-scheme-handler/sip-" EXECUTABLE_NAME + ";x-scheme-handler/sip;x-scheme-handler/sips-" EXECUTABLE_NAME + ";x-scheme-handler/sips;x-scheme-handler/tel;x-scheme-handler/callto;x-scheme-handler/" EXECUTABLE_NAME + "-config;\n" + "X-PulseAudio-Properties=media.role=phone\n"; + + return true; } #elif defined(Q_OS_MACOS) -void App::setAutoStart (bool enabled) { - if (enabled == mAutoStart) - return; - +void App::setAutoStart(bool enabled) { + if (enabled == mAutoStart) return; + if (getMacOsBundlePath().isEmpty()) { qWarning() << QStringLiteral("Application is not installed. Unable to change autostart state."); return; } - + if (enabled) - QProcess::execute(OsascriptExecutable, { - "-e", "tell application \"System Events\" to make login item at end with properties" - "{ path: \"" + getMacOsBundlePath() + "\", hidden: false }" - }); + QProcess::execute(OsascriptExecutable, + {"-e", "tell application \"System Events\" to make login item at end with properties" + "{ path: \"" + + getMacOsBundlePath() + "\", hidden: false }"}); else - QProcess::execute(OsascriptExecutable, { - "-e", "tell application \"System Events\" to delete login item \"" + getMacOsBundleName() + "\"" - }); - + QProcess::execute(OsascriptExecutable, {"-e", "tell application \"System Events\" to delete login item \"" + + getMacOsBundleName() + "\""}); + mAutoStart = enabled; emit autoStartChanged(enabled); } #else -void App::setAutoStart (bool enabled) { - if (enabled == mAutoStart) - return; - +void App::setAutoStart(bool enabled) { + if (enabled == mAutoStart) return; + QSettings settings(AutoStartSettingsFilePath, QSettings::NativeFormat); - if (enabled) - settings.setValue(EXECUTABLE_NAME, QDir::toNativeSeparators(applicationFilePath())); - else - settings.remove(EXECUTABLE_NAME); - + if (enabled) settings.setValue(EXECUTABLE_NAME, QDir::toNativeSeparators(applicationFilePath())); + else settings.remove(EXECUTABLE_NAME); + mAutoStart = enabled; emit autoStartChanged(enabled); } @@ -1211,7 +1170,7 @@ void App::setAutoStart (bool enabled) { // ----------------------------------------------------------------------------- -void App::openAppAfterInit (bool mustBeIconified) { +void App::openAppAfterInit(bool mustBeIconified) { qInfo() << QStringLiteral("Open " APPLICATION_NAME " app."); auto coreManager = CoreManager::getInstance(); coreManager->getSettingsModel()->updateCameraMode(); @@ -1225,83 +1184,79 @@ void App::openAppAfterInit (bool mustBeIconified) { core->setNatPolicy(core->getNatPolicy()); } }); - + QQuickWindow *mainWindow = getMainWindow(); - + #ifndef __APPLE__ // Enable TrayIconSystem. - if (!QSystemTrayIcon::isSystemTrayAvailable()) - qWarning("System tray not found on this system."); - else - setTrayIcon(); + if (!QSystemTrayIcon::isSystemTrayAvailable()) qWarning("System tray not found on this system."); + else setTrayIcon(); #endif // ifndef __APPLE__ - + // Display Assistant if it does not exist proxy config. if (coreManager->getAccountList().empty()) - QMetaObject::invokeMethod(mainWindow, "setView", Q_ARG(QVariant, Constants::AssistantViewName), Q_ARG(QVariant, QString("")), Q_ARG(QVariant, QString(""))); - + QMetaObject::invokeMethod(mainWindow, "setView", Q_ARG(QVariant, Constants::AssistantViewName), + Q_ARG(QVariant, QString("")), Q_ARG(QVariant, QString(""))); + #ifdef ENABLE_UPDATE_CHECK QTimer *timer = new QTimer(mEngine); timer->setInterval(Constants::VersionUpdateCheckInterval); - + QObject::connect(timer, &QTimer::timeout, this, &App::checkForUpdate); timer->start(); - + checkForUpdates(); #endif // ifdef ENABLE_UPDATE_CHECK // Launch call if wanted and clean parser - if( mParser->isSet("call") && coreManager->isLastRemoteProvisioningGood()){ + if (mParser->isSet("call") && coreManager->isLastRemoteProvisioningGood()) { QString sipAddress = mParser->value("call"); - mParser->parse(cleanParserKeys(mParser, QStringList("call")));// Clean call from parser - if(coreManager->started()){ + mParser->parse(cleanParserKeys(mParser, QStringList("call"))); // Clean call from parser + if (coreManager->started()) { coreManager->getCallsListModel()->launchAudioCall(sipAddress); - }else{ - QObject * context = new QObject(); - QObject::connect(CoreManager::getInstance(), &CoreManager::coreManagerInitialized,context, - [sipAddress,coreManager, context]() mutable { - if(context){ - delete context; - context = nullptr; - coreManager->getCallsListModel()->launchAudioCall(sipAddress); - } - }); + } else { + QObject *context = new QObject(); + QObject::connect(CoreManager::getInstance(), &CoreManager::coreManagerInitialized, context, + [sipAddress, coreManager, context]() mutable { + if (context) { + delete context; + context = nullptr; + coreManager->getCallsListModel()->launchAudioCall(sipAddress); + } + }); } } QString fetchFilePath = getFetchConfig(mParser); mustBeIconified = mustBeIconified && fetchFilePath.isEmpty(); #ifndef __APPLE__ - if (!mustBeIconified) - smartShowWindow(mainWindow); + if (!mustBeIconified) smartShowWindow(mainWindow); #else Q_UNUSED(mustBeIconified); smartShowWindow(mainWindow); #endif setOpened(true); useFetchConfig(fetchFilePath); - + QString lastRunningVersion = CoreManager::getInstance()->getSettingsModel()->getLastRunningVersionOfApp(); if (lastRunningVersion != "unknown" && lastRunningVersion != applicationVersion()) { - emit CoreManager::getInstance()->userInitiatedVersionUpdateCheckResult(3, "", ""); + emit CoreManager::getInstance() -> userInitiatedVersionUpdateCheckResult(3, "", ""); } CoreManager::getInstance()->getSettingsModel()->setLastRunningVersionOfApp(applicationVersion()); } // ----------------------------------------------------------------------------- -QString App::getStrippedApplicationVersion(){// x.y.z but if 'z-*' then x.y.z-1 +QString App::getStrippedApplicationVersion() { // x.y.z but if 'z-*' then x.y.z-1 QString currentVersion = applicationVersion(); QStringList versions = currentVersion.split('.'); - if(versions.size() >=3){ - currentVersion = versions[0]+"."+versions[1]+"."; + if (versions.size() >= 3) { + currentVersion = versions[0] + "." + versions[1] + "."; QStringList patchVersions = versions[2].split('-'); - if( patchVersions.size() > 1 ) { + if (patchVersions.size() > 1) { bool ok; patchVersions[1].toInt(&ok); - if( !ok) // Second part of patch is not a number (ie: alpha, beta, pre). Reduce version. - currentVersion += QString::number(patchVersions[0].toInt()-1); - else - currentVersion += patchVersions[0]; - } else - currentVersion += patchVersions[0]; + if (!ok) // Second part of patch is not a number (ie: alpha, beta, pre). Reduce version. + currentVersion += QString::number(patchVersions[0].toInt() - 1); + else currentVersion += patchVersions[0]; + } else currentVersion += patchVersions[0]; } return currentVersion; } @@ -1309,14 +1264,13 @@ void App::checkForUpdate() { checkForUpdates(false); } void App::checkForUpdates(bool force) { - if(force || CoreManager::getInstance()->getSettingsModel()->isCheckForUpdateEnabled()) { + if (force || CoreManager::getInstance()->getSettingsModel()->isCheckForUpdateEnabled()) { getInstance()->mCheckForUpdateUserInitiated = force; - CoreManager::getInstance()->getCore()->checkForUpdate( - Utils::appStringToCoreString(applicationVersion())); + CoreManager::getInstance()->getCore()->checkForUpdate(Utils::appStringToCoreString(applicationVersion())); } } -bool App::isPdfAvailable(){ +bool App::isPdfAvailable() { #ifdef PDF_ENABLED return true; #else @@ -1324,7 +1278,7 @@ bool App::isPdfAvailable(){ #endif } -bool App::isLinux(){ +bool App::isLinux() { #ifdef Q_OS_LINUX return true; #else diff --git a/linphone-app/src/app/App.hpp b/linphone-app/src/app/App.hpp index 6668cf164..eadfa4844 100644 --- a/linphone-app/src/app/App.hpp +++ b/linphone-app/src/app/App.hpp @@ -35,7 +35,7 @@ class QQuickWindow; class QSystemTrayIcon; namespace linphone { - class Config; +class Config; } class ColorListModel; @@ -43,174 +43,175 @@ class DefaultTranslator; class ImageListModel; class Notifier; - class App : public SingleApplication { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(QString configLocale READ getConfigLocale WRITE setConfigLocale NOTIFY configLocaleChanged) - Q_PROPERTY(QLocale locale READ getLocale CONSTANT) - Q_PROPERTY(QVariantList availableLocales READ getAvailableLocales CONSTANT) - Q_PROPERTY(QString qtVersion READ getQtVersion CONSTANT) + Q_PROPERTY(QString configLocale READ getConfigLocale WRITE setConfigLocale NOTIFY configLocaleChanged) + Q_PROPERTY(QLocale locale READ getLocale CONSTANT) + Q_PROPERTY(QVariantList availableLocales READ getAvailableLocales CONSTANT) + Q_PROPERTY(QString qtVersion READ getQtVersion CONSTANT) - Q_PROPERTY(bool autoStart READ getAutoStart WRITE setAutoStart NOTIFY autoStartChanged) + Q_PROPERTY(bool autoStart READ getAutoStart WRITE setAutoStart NOTIFY autoStartChanged) public: - App (int &argc, char *argv[]); - ~App (); + App(int &argc, char *argv[]); + ~App(); - void stop(); - void initContentApp (); - QStringList cleanParserKeys(QCommandLineParser * parser, QStringList keys);// Get all options from parser and remove the selected keys. Return the result that can be passed to parser process. - void processArguments(QHash args); + void stop(); + void initContentApp(); + QStringList cleanParserKeys(QCommandLineParser *parser, + QStringList keys); // Get all options from parser and remove the selected keys. Return + // the result that can be passed to parser process. + void processArguments(QHash args); - QString getCommandArgument (); + QString getCommandArgument(); - QString getFetchConfig (QString filePath, bool * error); - QString getFetchConfig (QCommandLineParser *parser);// Return file path of fetch-config - void useFetchConfig(const QString& filePath); // Check if the fetch is auto or not and make gui request if needed. - Q_INVOKABLE bool setFetchConfig (QString filePath); // return true if filepath has been set. + QString getFetchConfig(QString filePath, bool *error); + QString getFetchConfig(QCommandLineParser *parser); // Return file path of fetch-config + void useFetchConfig(const QString &filePath); // Check if the fetch is auto or not and make gui request if needed. + Q_INVOKABLE bool setFetchConfig(QString filePath); // return true if filepath has been set. - #ifdef Q_OS_MACOS - bool event (QEvent *event) override; - #endif // ifdef Q_OS_MACOS +#ifdef Q_OS_MACOS + bool event(QEvent *event) override; +#endif // ifdef Q_OS_MACOS - QQmlApplicationEngine *getEngine () { - return mEngine; - } - - Notifier *getNotifier () const { - return mNotifier; - } - - ColorListModel *getColorListModel () const { - return mColorListModel; + QQmlApplicationEngine *getEngine() { + return mEngine; } - ImageListModel *getImageListModel () const { - return mImageListModel; + + Notifier *getNotifier() const { + return mNotifier; } - - QLocale getLocale () const; - - //static ColorListModel *getColorListModel () const { - //return App::getInstance()-getColorListModel(); - //} - QSystemTrayIcon *getSystemTrayIcon () const { - return mSystemTrayIcon; - } + ColorListModel *getColorListModel() const { + return mColorListModel; + } + ImageListModel *getImageListModel() const { + return mImageListModel; + } - QQuickWindow *getMainWindow () const; + QLocale getLocale() const; - bool hasFocus () const; + // static ColorListModel *getColorListModel () const { + // return App::getInstance()-getColorListModel(); + //} - bool isOpened () const { - return mIsOpened; - } + QSystemTrayIcon *getSystemTrayIcon() const { + return mSystemTrayIcon; + } - static App *getInstance () { - return static_cast(QApplication::instance()); - } + QQuickWindow *getMainWindow() const; - static constexpr int RestartCode = 1000; - static constexpr int DeleteDataCode = 1001; + bool hasFocus() const; - Q_INVOKABLE void restart () { - exit(RestartCode); - } + bool isOpened() const { + return mIsOpened; + } - Q_INVOKABLE QQuickWindow *getCallsWindow () const; - Q_INVOKABLE QQuickWindow *getSettingsWindow () const; + static App *getInstance() { + return static_cast(QApplication::instance()); + } - Q_INVOKABLE static void smartShowWindow (QQuickWindow *window); - bool mCheckForUpdateUserInitiated; - Q_INVOKABLE static void checkForUpdates(bool force = false); + static constexpr int RestartCode = 1000; + static constexpr int DeleteDataCode = 1001; -// Check module availability when no dependencies are needed (else use SettingsModel) - Q_INVOKABLE static bool isPdfAvailable(); - Q_INVOKABLE static bool isLinux(); - bool autoStartEnabled(); + Q_INVOKABLE void restart() { + exit(RestartCode); + } + + Q_INVOKABLE QQuickWindow *getCallsWindow() const; + Q_INVOKABLE QQuickWindow *getSettingsWindow() const; + + Q_INVOKABLE static void smartShowWindow(QQuickWindow *window); + bool mCheckForUpdateUserInitiated; + Q_INVOKABLE static void checkForUpdates(bool force = false); + + // Check module availability when no dependencies are needed (else use SettingsModel) + Q_INVOKABLE static bool isPdfAvailable(); + Q_INVOKABLE static bool isLinux(); + bool autoStartEnabled(); #ifdef Q_OS_LINUX - Q_INVOKABLE void exportDesktopFile(); - - QString getApplicationPath() const; - bool generateDesktopFile(const QString& confPath, bool remove, bool openInBackground); + Q_INVOKABLE void exportDesktopFile(); + + QString getApplicationPath() const; + bool generateDesktopFile(const QString &confPath, bool remove, bool openInBackground); #endif - + public slots: - void stateChanged(Qt::ApplicationState); + void stateChanged(Qt::ApplicationState); signals: - void configLocaleChanged (const QString &locale); + void configLocaleChanged(const QString &locale); - void autoStartChanged (bool enabled); + void autoStartChanged(bool enabled); + + void opened(bool status); + void requestFetchConfig(QString filePath); - void opened (bool status); - void requestFetchConfig(QString filePath); - private: - void createParser (); + void createParser(); - void registerTypes (); - void registerSharedTypes (); - void registerToolTypes (); - void registerSharedToolTypes (); - void registerUninstalledModules (); + void registerTypes(); + void registerSharedTypes(); + void registerToolTypes(); + void registerSharedToolTypes(); + void registerUninstalledModules(); - void setTrayIcon (); - void createNotifier (); + void setTrayIcon(); + void createNotifier(); - void initLocale (const std::shared_ptr &config); + void initLocale(const std::shared_ptr &config); - QString getConfigLocale () const; - void setConfigLocale (const QString &locale); + QString getConfigLocale() const; + void setConfigLocale(const QString &locale); - QVariantList getAvailableLocales () const { - return mAvailableLocales; - } + QVariantList getAvailableLocales() const { + return mAvailableLocales; + } - bool getAutoStart () const { - return mAutoStart; - } + bool getAutoStart() const { + return mAutoStart; + } - void setAutoStart (bool enabled); + void setAutoStart(bool enabled); - void openAppAfterInit (bool mustBeIconified = false); + void openAppAfterInit(bool mustBeIconified = false); - void setOpened (bool status) { - if (mIsOpened != status) { - mIsOpened = status; - emit opened(mIsOpened); - } - } - static QString getStrippedApplicationVersion();// x.y.z but if 'z-*' then x.y.z-1 - static void checkForUpdate (); + void setOpened(bool status) { + if (mIsOpened != status) { + mIsOpened = status; + emit opened(mIsOpened); + } + } + static QString getStrippedApplicationVersion(); // x.y.z but if 'z-*' then x.y.z-1 + static void checkForUpdate(); - static QString getQtVersion () { - return qVersion(); - } + static QString getQtVersion() { + return qVersion(); + } - QVariantList mAvailableLocales; - QLocale mLocale; + QVariantList mAvailableLocales; + QLocale mLocale; - bool mAutoStart = false; + bool mAutoStart = false; - QCommandLineParser *mParser = nullptr; + QCommandLineParser *mParser = nullptr; - QQmlApplicationEngine *mEngine = nullptr; + QQmlApplicationEngine *mEngine = nullptr; - DefaultTranslator *mTranslator = nullptr; - DefaultTranslator *mDefaultTranslator = nullptr; - Notifier *mNotifier = nullptr; + DefaultTranslator *mTranslator = nullptr; + DefaultTranslator *mDefaultTranslator = nullptr; + Notifier *mNotifier = nullptr; - QQuickWindow *mCallsWindow = nullptr; - QQuickWindow *mSettingsWindow = nullptr; + QQuickWindow *mCallsWindow = nullptr; + QQuickWindow *mSettingsWindow = nullptr; - ColorListModel * mColorListModel; - ImageListModel * mImageListModel; + ColorListModel *mColorListModel; + ImageListModel *mImageListModel; - QSystemTrayIcon *mSystemTrayIcon = nullptr; + QSystemTrayIcon *mSystemTrayIcon = nullptr; - bool mIsOpened = false; + bool mIsOpened = false; }; #endif // APP_H_ diff --git a/linphone-app/src/app/cli/Cli.cpp b/linphone-app/src/app/cli/Cli.cpp index 6cb9c0619..479d0ab9e 100644 --- a/linphone-app/src/app/cli/Cli.cpp +++ b/linphone-app/src/app/cli/Cli.cpp @@ -41,67 +41,64 @@ using namespace std; // API. // ============================================================================= -static void cliShow (QHash &args) { +static void cliShow(QHash &args) { App *app = App::getInstance(); - if( args.size() > 0){ + if (args.size() > 0) { app->processArguments(args); app->initContentApp(); } app->smartShowWindow(app->getMainWindow()); } -static void cliCall (QHash &args) { +static void cliCall(QHash &args) { QString addressToCall = args["sip-address"]; - if(args.size() > 1){// Call with options + if (args.size() > 1) { // Call with options App *app = App::getInstance(); - args["call"] = args["sip-address"];// Swap cli def to parser + args["call"] = args["sip-address"]; // Swap cli def to parser args.remove("sip-address"); app->processArguments(args); app->initContentApp(); - }else - CoreManager::getInstance()->getCallsListModel()->launchAudioCall(args["sip-address"], ""); + } else CoreManager::getInstance()->getCallsListModel()->launchAudioCall(args["sip-address"], ""); } -static void cliAccept (QHash &args) { +static void cliAccept(QHash &args) { auto currentCall = CoreManager::getInstance()->getCore()->getCurrentCall(); App *app = App::getInstance(); - if( args.size() > 0){ + if (args.size() > 0) { app->processArguments(args); app->initContentApp(); } - if(currentCall){ + if (currentCall) { currentCall->accept(); } } -static void cliDecline (QHash &args) { +static void cliDecline(QHash &args) { auto currentCall = CoreManager::getInstance()->getCore()->getCurrentCall(); App *app = App::getInstance(); - if( args.size() > 0){ + if (args.size() > 0) { app->processArguments(args); app->initContentApp(); } - if(currentCall){ + if (currentCall) { currentCall->decline(linphone::Reason::Declined); } } -static void cliBye (QHash &args) { +static void cliBye(QHash &args) { auto currentCall = CoreManager::getInstance()->getCore()->getCurrentCall(); - if(args.size() > 0) { - if( args["sip-address"] == "*")// Call with options + if (args.size() > 0) { + if (args["sip-address"] == "*") // Call with options CoreManager::getInstance()->getCallsListModel()->terminateAllCalls(); - else if( args["sip-address"] == ""){ - if(currentCall) - currentCall->terminate(); - }else - CoreManager::getInstance()->getCallsListModel()->terminateCall(args["sip-address"]); - }else if(currentCall){ + else if (args["sip-address"] == "") { + if (currentCall) currentCall->terminate(); + } else CoreManager::getInstance()->getCallsListModel()->terminateCall(args["sip-address"]); + } else if (currentCall) { currentCall->terminate(); } } -static void cliJoinConference (QHash &args) { +static void cliJoinConference(QHash &args) { const QString sipAddress = args.take("sip-address"); CoreManager *coreManager = CoreManager::getInstance(); @@ -117,14 +114,14 @@ static void cliJoinConference (QHash &args) { coreManager->getCallsListModel()->launchAudioCall(sipAddress, "", args); } -static void cliJoinConferenceAs (QHash &args) { +static void cliJoinConferenceAs(QHash &args) { const QString fromSipAddress = args.take("guest-sip-address"); const QString toSipAddress = args.take("sip-address"); CoreManager *coreManager = CoreManager::getInstance(); /*shared_ptr proxyConfig = coreManager->getCore()->getDefaultProxyConfig(); if (!proxyConfig) { - qWarning() << QStringLiteral("You have no proxy config."); - return; + qWarning() << QStringLiteral("You have no proxy config."); + return; } const shared_ptr currentSipAddress = proxyConfig->getIdentityAddress(); @@ -136,12 +133,10 @@ static void cliJoinConferenceAs (QHash &args) { } const shared_ptr currentSipAddress = account->getParams()->getIdentityAddress(); - const shared_ptr askedSipAddress = linphone::Factory::get()->createAddress( - Utils::appStringToCoreString(fromSipAddress) - ); + const shared_ptr askedSipAddress = + linphone::Factory::get()->createAddress(Utils::appStringToCoreString(fromSipAddress)); if (!currentSipAddress->weakEqual(askedSipAddress)) { - qWarning() << QStringLiteral("Guest sip address `%1` doesn't match with default account.") - .arg(fromSipAddress); + qWarning() << QStringLiteral("Guest sip address `%1` doesn't match with default account.").arg(fromSipAddress); return; } @@ -149,7 +144,7 @@ static void cliJoinConferenceAs (QHash &args) { coreManager->getCallsListModel()->launchAudioCall(toSipAddress, "", args); } -static void cliInitiateConference (QHash &args) { +static void cliInitiateConference(QHash &args) { shared_ptr core = CoreManager::getInstance()->getCore(); // Check identity. @@ -168,8 +163,8 @@ static void cliInitiateConference (QHash &args) { } if (!account->getParams()->getIdentityAddress()->weakEqual(address)) { qWarning() << QStringLiteral("Received different sip address from identity : `%1 != %2`.") - .arg(Utils::coreStringToAppString(account->getParams()->getIdentityAddress()->asString())) - .arg(Utils::coreStringToAppString(address->asString())); + .arg(Utils::coreStringToAppString(account->getParams()->getIdentityAddress()->asString())) + .arg(Utils::coreStringToAppString(address->asString())); return; } @@ -178,26 +173,24 @@ static void cliInitiateConference (QHash &args) { auto updateCallsWindow = []() { QQuickWindow *callsWindow = App::getInstance()->getCallsWindow(); - if (!callsWindow) - return; + if (!callsWindow) return; // TODO: Set the view to the "waiting call view". if (CoreManager::getInstance()->getSettingsModel()->getKeepCallsWindowInBackground()) { - if (!callsWindow->isVisible()) - callsWindow->showMinimized(); - } else - App::smartShowWindow(callsWindow); + if (!callsWindow->isVisible()) callsWindow->showMinimized(); + } else App::smartShowWindow(callsWindow); }; if (conference) { - qInfo() << QStringLiteral("Conference `%1` already exists.").arg(Utils::coreStringToAppString(conference->getConferenceAddress()->asString())); + qInfo() << QStringLiteral("Conference `%1` already exists.") + .arg(Utils::coreStringToAppString(conference->getConferenceAddress()->asString())); updateCallsWindow(); return; } qInfo() << QStringLiteral("Create conference with id: `%1`.").arg(id); auto confParameters = core->createConferenceParams(conference); - confParameters->enableVideo(false);// Video is not yet fully supported by the application in conference + confParameters->enableVideo(false); // Video is not yet fully supported by the application in conference conference = core->createConferenceWithParams(confParameters); if (conference->enter() == -1) { @@ -212,7 +205,7 @@ static void cliInitiateConference (QHash &args) { // Helpers. // ============================================================================= -static QString splitWord (QString word, int &curPos, const int lineLength, const QString &padding) { +static QString splitWord(QString word, int &curPos, const int lineLength, const QString &padding) { QString out; out += word.mid(0, lineLength - curPos) + "\n" + padding; curPos = padding.length(); @@ -227,7 +220,7 @@ static QString splitWord (QString word, int &curPos, const int lineLength, const return out; } -static QString indentedWord (QString word, int &curPos, const int lineLength, const QString &padding) { +static QString indentedWord(QString word, int &curPos, const int lineLength, const QString &padding) { QString out; if (curPos + word.length() > lineLength) { if (padding.length() + word.length() > lineLength) { @@ -244,7 +237,7 @@ static QString indentedWord (QString word, int &curPos, const int lineLength, co return out; } -static string multilineIndent (const QString &str, int indentationNumber = 0) { +static string multilineIndent(const QString &str, int indentationNumber = 0) { constexpr int lineLength(80); static const QRegExp spaceRegexp("(\\s)"); @@ -262,23 +255,23 @@ static string multilineIndent (const QString &str, int indentationNumber = 0) { word = str.mid(wordPos, spacePos - wordPos); out += indentedWord(word, indentedTextCurPos, lineLength, padding); switch (str[spacePos].unicode()) { - case '\n': - out += "\n" + padding; - indentedTextCurPos = padding.length(); - break; - case '\t': // TAB as space. - case ' ': - if (indentedTextCurPos == lineLength) { + case '\n': out += "\n" + padding; indentedTextCurPos = padding.length(); - } else { - out += " "; - indentedTextCurPos += 1; - } - break; + break; + case '\t': // TAB as space. + case ' ': + if (indentedTextCurPos == lineLength) { + out += "\n" + padding; + indentedTextCurPos = padding.length(); + } else { + out += " "; + indentedTextCurPos += 1; + } + break; - default: - break; + default: + break; } spacePos += 1; wordPos = spacePos; @@ -292,25 +285,21 @@ static string multilineIndent (const QString &str, int indentationNumber = 0) { // ============================================================================= -Cli::Command::Command ( - const QString &functionName, - const char *functionDescription, - Cli::Function function, - const QHash &argsScheme, - const bool &genericArguments - ) : - mFunctionName(functionName), - mFunctionDescription(functionDescription), - mFunction(function), - mArgsScheme(argsScheme), - mGenericArguments(genericArguments) {} +Cli::Command::Command(const QString &functionName, + const char *functionDescription, + Cli::Function function, + const QHash &argsScheme, + const bool &genericArguments) + : mFunctionName(functionName), mFunctionDescription(functionDescription), mFunction(function), + mArgsScheme(argsScheme), mGenericArguments(genericArguments) { +} -void Cli::Command::execute (QHash &args) const { - if(!mGenericArguments){// Check arguments validity. +void Cli::Command::execute(QHash &args) const { + if (!mGenericArguments) { // Check arguments validity. for (const auto &argName : args.keys()) { if (!mArgsScheme.contains(argName)) { - qWarning() << QStringLiteral("Command with invalid argument: `%1 (%2)`.") - .arg(mFunctionName).arg(argName); + qWarning() + << QStringLiteral("Command with invalid argument: `%1 (%2)`.").arg(mFunctionName).arg(argName); return; } @@ -319,8 +308,7 @@ void Cli::Command::execute (QHash &args) const { // Check missing arguments. for (const auto &argName : mArgsScheme.keys()) { if (!mArgsScheme[argName].isOptional && (!args.contains(argName) || args[argName].isEmpty())) { - qWarning() << QStringLiteral("Missing argument for command: `%1 (%2)`.") - .arg(mFunctionName).arg(argName); + qWarning() << QStringLiteral("Missing argument for command: `%1 (%2)`.").arg(mFunctionName).arg(argName); return; } } @@ -332,33 +320,29 @@ void Cli::Command::execute (QHash &args) const { (*mFunction)(args); } else { Function f = mFunction; - QObject * context = new QObject(); - QObject::connect(app, &App::opened, - [f, args, context]()mutable { - if(context){ + QObject *context = new QObject(); + QObject::connect(app, &App::opened, [f, args, context]() mutable { + if (context) { delete context; context = nullptr; qInfo() << QStringLiteral("Execute deferred command:") << args; QHash fuckConst = args; (*f)(fuckConst); } - } - ); + }); } } -void Cli::Command::executeUri (QString address, QHash args) const { +void Cli::Command::executeUri(QString address, QHash args) const { QUrl url(address); QString query = url.query(); QStringList parameters = query.split('&'); - for(int i = 0 ; i < parameters.size() ; ++i){ + for (int i = 0; i < parameters.size(); ++i) { QStringList parameter = parameters[i].split('='); - if( parameter[0]!="" && parameter[0] != "method"){ - if(parameter.size() > 1) - args[parameter[0]] = QByteArray::fromBase64(parameter[1].toUtf8() ); - else - args[parameter[0]] = ""; + if (parameter[0] != "" && parameter[0] != "method") { + if (parameter.size() > 1) args[parameter[0]] = QByteArray::fromBase64(parameter[1].toUtf8()); + else args[parameter[0]] = ""; } } @@ -367,43 +351,40 @@ void Cli::Command::executeUri (QString address, QHash args) co } // pUrl can be `anytoken?p1=x&p2=y` or `p1=x&p2=y`. It will only use p1 and p2 -void Cli::Command::executeUrl (const QString &pUrl) const { +void Cli::Command::executeUrl(const QString &pUrl) const { QHash args; QStringList urlParts = pUrl.split('?'); - QString query = (urlParts.size()>1?urlParts[1]:urlParts[0]); - QString authority = (urlParts.size()>1 && urlParts[0].contains(':')?urlParts[0].split(':')[1]:""); + QString query = (urlParts.size() > 1 ? urlParts[1] : urlParts[0]); + QString authority = (urlParts.size() > 1 && urlParts[0].contains(':') ? urlParts[0].split(':')[1] : ""); QStringList parameters = query.split('&'); - for(int i = 0 ; i < parameters.size() ; ++i){ + for (int i = 0; i < parameters.size(); ++i) { QStringList parameter = parameters[i].split('='); - if( parameter[0] != "method"){ - if(parameter.size() > 1) - args[parameter[0]] = QByteArray::fromBase64(parameter[1].toUtf8() ); - else - args[parameter[0]] = ""; + if (parameter[0] != "method") { + if (parameter.size() > 1) args[parameter[0]] = QByteArray::fromBase64(parameter[1].toUtf8()); + else args[parameter[0]] = ""; } } - if(!authority.isEmpty()) - args["sip-address"] = authority; + if (!authority.isEmpty()) args["sip-address"] = authority; execute(args); } -QString Cli::Command::getFunctionSyntax () const { +QString Cli::Command::getFunctionSyntax() const { QString functionSyntax; functionSyntax += QStringLiteral("\""); functionSyntax += mFunctionName; - for (auto &argName : mArgsScheme.keys()){ + for (auto &argName : mArgsScheme.keys()) { functionSyntax += QStringLiteral(" "); functionSyntax += mArgsScheme[argName].isOptional ? QStringLiteral("[") : QStringLiteral(""); functionSyntax += argName; functionSyntax += QStringLiteral("=<"); switch (mArgsScheme[argName].type) { - case String: - functionSyntax += QStringLiteral("str"); - break; - default: - functionSyntax += QStringLiteral("value"); - break; + case String: + functionSyntax += QStringLiteral("str"); + break; + default: + functionSyntax += QStringLiteral("value"); + break; } functionSyntax += QString(">"); functionSyntax += mArgsScheme[argName].isOptional ? QStringLiteral("]") : QStringLiteral(""); @@ -420,140 +401,135 @@ QRegExp Cli::mRegExpArgs("(?:(?:([\\w-]+)\\s*)=\\s*(?:\"([^\"\\\\]*(?:\\\\.[^\"\ QRegExp Cli::mRegExpFunctionName("^\\s*([a-z-]+)\\s*"); QMap Cli::mCommands = { - createCommand("show", QT_TR_NOOP("showFunctionDescription"), cliShow, QHash(), true), - createCommand("call", QT_TR_NOOP("callFunctionDescription"), cliCall, { - { "sip-address", {} } - }, true), - createCommand("initiate-conference", QT_TR_NOOP("initiateConferenceFunctionDescription"), cliInitiateConference, { - { "sip-address", {} }, { "conference-id", {} } - }), - createCommand("join-conference", QT_TR_NOOP("joinConferenceFunctionDescription"), cliJoinConference, { - { "sip-address", {} }, { "conference-id", {} }, { "display-name", {} } - }), - createCommand("join-conference-as", QT_TR_NOOP("joinConferenceAsFunctionDescription"), cliJoinConferenceAs, { - { "sip-address", {} }, { "conference-id", {} }, { "guest-sip-address", {} } - }), - createCommand("bye", QT_TR_NOOP("byeFunctionDescription"), cliBye, QHash(), true), - createCommand("accept", QT_TR_NOOP("acceptFunctionDescription"), cliAccept, QHash(), true), - createCommand("decline", QT_TR_NOOP("declineFunctionDescription"), cliDecline, QHash(), true), + createCommand("show", QT_TR_NOOP("showFunctionDescription"), cliShow, QHash(), true), + createCommand("call", QT_TR_NOOP("callFunctionDescription"), cliCall, {{"sip-address", {}}}, true), + createCommand("initiate-conference", + QT_TR_NOOP("initiateConferenceFunctionDescription"), + cliInitiateConference, + {{"sip-address", {}}, {"conference-id", {}}}), + createCommand("join-conference", + QT_TR_NOOP("joinConferenceFunctionDescription"), + cliJoinConference, + {{"sip-address", {}}, {"conference-id", {}}, {"display-name", {}}}), + createCommand("join-conference-as", + QT_TR_NOOP("joinConferenceAsFunctionDescription"), + cliJoinConferenceAs, + {{"sip-address", {}}, {"conference-id", {}}, {"guest-sip-address", {}}}), + createCommand("bye", QT_TR_NOOP("byeFunctionDescription"), cliBye, QHash(), true), + createCommand("accept", QT_TR_NOOP("acceptFunctionDescription"), cliAccept, QHash(), true), + createCommand("decline", QT_TR_NOOP("declineFunctionDescription"), cliDecline, QHash(), true), }; // ----------------------------------------------------------------------------- /* string Cli::getScheme(const QString& address){ - QStringList tempSipAddress = address->split(':'); - if( tempSipAddress.size() > 0) - return tempSipAddress[0].toStdString(); - else - return ""; + QStringList tempSipAddress = address->split(':'); + if( tempSipAddress.size() > 0) + return tempSipAddress[0].toStdString(); + else + return ""; } bool Cli::changeScheme(QString * address){ - QStringList tempSipAddress = address->split(':'); - string scheme; - bool ok = false; - if(tempSipAddress.size() > 1) { - scheme = tempSipAddress[0].toStdString(); - for (const string &validScheme : { string("sip"), "sip-"+string(EXECUTABLE_NAME), string("sips"), "sips-"+string(EXECUTABLE_NAME), string("tel"), string("callto"), string(EXECUTABLE_NAME)+ "-config" }) - if (scheme == validScheme) - ok = true; - if( !ok){ - qWarning() << QStringLiteral("Not a valid uri: `%1` Unsupported scheme: `%2`.").arg(*address).arg(Utils::coreStringToAppString(scheme)); - }else{ - tempSipAddress[0] = "sip";// In order to pass bellesip parsing. - *address = tempSipAddress.join(':'); - } - } - return ok; + QStringList tempSipAddress = address->split(':'); + string scheme; + bool ok = false; + if(tempSipAddress.size() > 1) { + scheme = tempSipAddress[0].toStdString(); + for (const string &validScheme : { string("sip"), "sip-"+string(EXECUTABLE_NAME), string("sips"), +"sips-"+string(EXECUTABLE_NAME), string("tel"), string("callto"), string(EXECUTABLE_NAME)+ "-config" }) if (scheme == +validScheme) ok = true; if( !ok){ qWarning() << QStringLiteral("Not a valid uri: `%1` Unsupported scheme: +`%2`.").arg(*address).arg(Utils::coreStringToAppString(scheme)); }else{ tempSipAddress[0] = "sip";// In order to pass +bellesip parsing. *address = tempSipAddress.join(':'); + } + } + return ok; } */ -void Cli::executeCommand (const QString &command, CommandFormat *format) { +void Cli::executeCommand(const QString &command, CommandFormat *format) { -// Detect if command is a CLI by testing commands + // Detect if command is a CLI by testing commands const QString &functionName = parseFunctionName(command); - const std::string configURI = string(EXECUTABLE_NAME)+"-config"; - if(!functionName.isEmpty()){// It is a CLI + const std::string configURI = string(EXECUTABLE_NAME) + "-config"; + if (!functionName.isEmpty()) { // It is a CLI qInfo() << QStringLiteral("Detecting cli command: `%1`...").arg(command); QHash args = parseArgs(command); mCommands[functionName].execute(args); - if (format) - *format = CliFormat; + if (format) *format = CliFormat; return; - }else{// It is a URI + } else { // It is a URI QStringList tempSipAddress = command.split(':'); - string scheme="sip"; - QString transformedCommand; // In order to pass bellesip parsing, set scheme to 'sip:'. - if( tempSipAddress.size() == 1){ - transformedCommand = "sip:"+command; - }else{ + string scheme = "sip"; + QString transformedCommand; // In order to pass bellesip parsing, set scheme to 'sip:'. + if (tempSipAddress.size() == 1) { + transformedCommand = "sip:" + command; + } else { scheme = tempSipAddress[0].toStdString(); bool ok = false; - for (const string &validScheme : { string("sip"), "sip-"+string(EXECUTABLE_NAME), string("sips"), "sips-"+string(EXECUTABLE_NAME), string("tel"), string("callto"), configURI }) - if (scheme == validScheme) - ok = true; - if( !ok){ - qWarning() << QStringLiteral("Not a valid URI: `%1` Unsupported scheme: `%2`.").arg(command).arg(Utils::coreStringToAppString(scheme)); + for (const string &validScheme : + {string("sip"), "sip-" + string(EXECUTABLE_NAME), string("sips"), "sips-" + string(EXECUTABLE_NAME), + string("tel"), string("callto"), configURI}) + if (scheme == validScheme) ok = true; + if (!ok) { + qWarning() << QStringLiteral("Not a valid URI: `%1` Unsupported scheme: `%2`.") + .arg(command) + .arg(Utils::coreStringToAppString(scheme)); return; } tempSipAddress[0] = "sip"; transformedCommand = tempSipAddress.join(':'); } - if( scheme == configURI ){ + if (scheme == configURI) { QHash args = parseArgs(command); QString fetchUrl; - if(args.contains("fetch-config")) - fetchUrl = QByteArray::fromBase64(args["fetch-config"].toUtf8() ); + if (args.contains("fetch-config")) fetchUrl = QByteArray::fromBase64(args["fetch-config"].toUtf8()); else { - QUrl url(command.mid(configURI.size()+1));// Remove 'exec-config:' - if(url.scheme().isEmpty()) - url.setScheme("https"); + QUrl url(command.mid(configURI.size() + 1)); // Remove 'exec-config:' + if (url.scheme().isEmpty()) url.setScheme("https"); fetchUrl = url.toString(); } - if (format) - *format = CliFormat; + if (format) *format = CliFormat; QHash dummy; - mCommands["show"].execute(dummy);// Just open the app. + mCommands["show"].execute(dummy); // Just open the app. App::getInstance()->useFetchConfig(fetchUrl); - }else{ + } else { shared_ptr address; QString qAddress = transformedCommand; - if(Utils::isUsername(transformedCommand)){ - address = linphone::Factory::get()->createAddress(Utils::appStringToCoreString(transformedCommand+"@to.remove")); + if (Utils::isUsername(transformedCommand)) { + address = linphone::Factory::get()->createAddress( + Utils::appStringToCoreString(transformedCommand + "@to.remove")); address->setDomain(""); qAddress = Utils::coreStringToAppString(address->asString()); - if(address && qAddress.isEmpty()) - qAddress = transformedCommand; - }else - address = linphone::Factory::get()->createAddress(Utils::appStringToCoreString(transformedCommand));// Test if command is an address - if (format) - *format = UriFormat; + if (address && qAddress.isEmpty()) qAddress = transformedCommand; + } else + address = linphone::Factory::get()->createAddress( + Utils::appStringToCoreString(transformedCommand)); // Test if command is an address + if (format) *format = UriFormat; qInfo() << QStringLiteral("Detecting URI command: `%1`...").arg(command); QString functionName; - if( address) { + if (address) { functionName = Utils::coreStringToAppString(address->getHeader("method")).isEmpty() - ? QStringLiteral("call") - : Utils::coreStringToAppString(address->getHeader("method")); - }else{ + ? QStringLiteral("call") + : Utils::coreStringToAppString(address->getHeader("method")); + } else { QStringList fields = command.split('?'); - if(fields.size() >1){ + if (fields.size() > 1) { fields = fields[1].split('&'); - for(int i = 0 ; i < fields.size() && functionName.isEmpty(); ++i){ + for (int i = 0; i < fields.size() && functionName.isEmpty(); ++i) { QStringList data = fields[i].split('='); - if( data[0] == "method" && data.size() >1) - functionName = data[1]; + if (data[0] == "method" && data.size() > 1) functionName = data[1]; } - if(functionName.isEmpty()) - functionName = "call"; + if (functionName.isEmpty()) functionName = "call"; } } functionName = functionName.toLower(); - if( functionName.isEmpty()){ + if (functionName.isEmpty()) { qWarning() << QStringLiteral("There is no method set in `%1`.").arg(command); return; - }else if( !mCommands.contains(functionName)) { + } else if (!mCommands.contains(functionName)) { qWarning() << QStringLiteral("This command doesn't exist: `%1`.").arg(functionName); return; } - if(address){ + if (address) { // TODO: check if there is too much headers. QHash headers; for (const auto &argName : mCommands[functionName].mArgsScheme.keys()) { @@ -561,43 +537,37 @@ void Cli::executeCommand (const QString &command, CommandFormat *format) { headers[argName] = QByteArray::fromBase64(QByteArray(header.c_str(), int(header.length()))); } mCommands[functionName].executeUri(qAddress, headers); - }else - mCommands[functionName].executeUrl(command); + } else mCommands[functionName].executeUrl(command); } } } -void Cli::showHelp () { - cout << multilineIndent(tr("appCliDescription").arg(APPLICATION_NAME), 0) << - endl << - "Usage: " << - endl << - multilineIndent(tr("uriCommandLineSyntax").arg(EXECUTABLE_NAME), 0) << - multilineIndent(tr("cliCommandLineSyntax").arg(EXECUTABLE_NAME), 0) << - endl << - multilineIndent(tr("commandsName")) << endl; +void Cli::showHelp() { + cout << multilineIndent(tr("appCliDescription").arg(APPLICATION_NAME), 0) << endl + << "Usage: " << endl + << multilineIndent(tr("uriCommandLineSyntax").arg(EXECUTABLE_NAME), 0) + << multilineIndent(tr("cliCommandLineSyntax").arg(EXECUTABLE_NAME), 0) << endl + << multilineIndent(tr("commandsName")) << endl; for (const auto &method : mCommands.keys()) - cout << multilineIndent(mCommands[method].getFunctionSyntax(), 1) << - multilineIndent(tr(mCommands[method].getFunctionDescription()), 2) << - endl; + cout << multilineIndent(mCommands[method].getFunctionSyntax(), 1) + << multilineIndent(tr(mCommands[method].getFunctionDescription()), 2) << endl; } // ----------------------------------------------------------------------------- -pair Cli::createCommand ( - const QString &functionName, - const char *functionDescription, - Function function, - const QHash &argsScheme, - const bool &genericArguments - ) { - return { functionName.toLower(), Cli::Command(functionName.toLower(), functionDescription, function, argsScheme, genericArguments) }; +pair Cli::createCommand(const QString &functionName, + const char *functionDescription, + Function function, + const QHash &argsScheme, + const bool &genericArguments) { + return {functionName.toLower(), + Cli::Command(functionName.toLower(), functionDescription, function, argsScheme, genericArguments)}; } // ----------------------------------------------------------------------------- -QString Cli::parseFunctionName (const QString &command) { +QString Cli::parseFunctionName(const QString &command) { mRegExpFunctionName.indexIn(command.toLower()); if (mRegExpFunctionName.pos(1) == -1) { qWarning() << QStringLiteral("Unable to parse function name of command: `%1`.").arg(command); @@ -615,7 +585,7 @@ QString Cli::parseFunctionName (const QString &command) { return functionName; } -QHash Cli::parseArgs (const QString &command) { +QHash Cli::parseArgs(const QString &command) { QHash args; int pos = 0; diff --git a/linphone-app/src/app/cli/Cli.hpp b/linphone-app/src/app/cli/Cli.hpp index 6df664671..2b7011558 100644 --- a/linphone-app/src/app/cli/Cli.hpp +++ b/linphone-app/src/app/cli/Cli.hpp @@ -30,88 +30,83 @@ // ============================================================================= namespace linphone { - class Address; +class Address; } class Cli : public QObject { - Q_OBJECT; + Q_OBJECT - typedef void (*Function)(QHash &); + typedef void (*Function)(QHash &); - enum ArgumentType { - String - }; + enum ArgumentType { String }; - struct Argument { - Argument (ArgumentType type = String, bool isOptional = false) { - this->type = type; - this->isOptional = isOptional; - } + struct Argument { + Argument(ArgumentType type = String, bool isOptional = false) { + this->type = type; + this->isOptional = isOptional; + } - ArgumentType type; - bool isOptional; - }; + ArgumentType type; + bool isOptional; + }; - class Command { - public: - Command () = default; - Command ( - const QString &functionName, - const char *functionDescription, - Function function, - const QHash &argsScheme, - const bool &genericArguments=false - ); + class Command { + public: + Command() = default; + Command(const QString &functionName, + const char *functionDescription, + Function function, + const QHash &argsScheme, + const bool &genericArguments = false); - void execute (QHash &args) const; - void executeUri (QString address, QHash args) const; - void executeUrl (const QString &url) const; + void execute(QHash &args) const; + void executeUri(QString address, QHash args) const; + void executeUrl(const QString &url) const; - const char *getFunctionDescription () const { - return mFunctionDescription; - } + const char *getFunctionDescription() const { + return mFunctionDescription; + } - QString getFunctionSyntax () const ; + QString getFunctionSyntax() const; - QHash mArgsScheme; - - private: - QString mFunctionName; - const char *mFunctionDescription; - Function mFunction = nullptr; - bool mGenericArguments=false;// Used to avoid check on arguments - }; + QHash mArgsScheme; + + private: + QString mFunctionName; + const char *mFunctionDescription; + Function mFunction = nullptr; + bool mGenericArguments = false; // Used to avoid check on arguments + }; public: - enum CommandFormat { - UnknownFormat, - CliFormat, - UriFormat, // Parameters are in base64 - UrlFormat - }; + enum CommandFormat { + UnknownFormat, + CliFormat, + UriFormat, // Parameters are in base64 + UrlFormat + }; - static void executeCommand (const QString &command, CommandFormat *format = nullptr); + static void executeCommand(const QString &command, CommandFormat *format = nullptr); - static void showHelp (); + static void showHelp(); private: - Cli (); + Cli(); - static std::pair createCommand ( - const QString &functionName, - const char *functionDescription, - Function function, - const QHash &argsScheme = QHash(), - const bool &genericArguments=false - ); + static std::pair + createCommand(const QString &functionName, + const char *functionDescription, + Function function, + const QHash &argsScheme = QHash(), + const bool &genericArguments = false); - static QString parseFunctionName (const QString &command); - static QHash parseArgs (const QString &command); + static QString parseFunctionName(const QString &command); + static QHash parseArgs(const QString &command); - static QMap mCommands; + static QMap mCommands; - static QRegExp mRegExpArgs; - static QRegExp mRegExpFunctionName; + static QRegExp mRegExpArgs; + static QRegExp mRegExpFunctionName; }; #endif // CLI_H_