main.cpp 34.3 KB
Newer Older
Andreas Pakulat's avatar
Andreas Pakulat committed
1
/***************************************************************************
2
 *   Copyright 2003-2009 Alexander Dymo <adymo@kdevelop.org>               *
Manuel Breugelmans's avatar
Manuel Breugelmans committed
3 4 5 6 7 8 9 10
 *   Copyright 2007 Ralf Habacker  <Ralf.Habacker@freenet.de>              *
 *   Copyright 2006-2007 Matt Rogers  <mattr@kde.org>                      *
 *   Copyright 2006-2007 Hamish Rodda <rodda@kde.org>                      *
 *   Copyright 2005-2007 Adam Treat <treat@kde.org>                        *
 *   Copyright 2003-2007 Jens Dagerbo <jens.dagerbo@swipnet.se>            *
 *   Copyright 2001-2002 Bernd Gehrmann <bernd@mail.berlios.de>            *
 *   Copyright 2001-2002 Matthias Hoelzer-Kluepfel <hoelzer@kde.org>       *
 *   Copyright 2003 Roberto Raggi <roberto@kdevelop.org>                   *
11
 *   Copyright 2010 Niko Sams <niko.sams@gmail.com>                        *
Kevin Funk's avatar
Kevin Funk committed
12
 *   Copyright 2015 Kevin Funk <kfunk@kde.org>                             *
Andreas Pakulat's avatar
Andreas Pakulat committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

30 31
#include <config.h>

32 33
#include "urlinfo.h"

34
#include <KLocalizedString>
Kevin Funk's avatar
Kevin Funk committed
35
#include <Kdelibs4ConfigMigrator>
36
#include <kaboutdata.h>
37
#include <kmessagebox.h>
38
#include <ktexteditor/cursor.h>
39
#include <kcrash.h>
40

41
#include <QApplication>
42
#include <QElapsedTimer>
43 44
#include <QCommandLineParser>
#include <QCommandLineOption>
45
#include <QFileInfo>
46
#include <QDir>
Kevin Funk's avatar
Kevin Funk committed
47
#include <QProcess>
48
#include <QSessionManager>
49
#include <QTextStream>
50 51
#include <QDBusInterface>
#include <QDBusReply>
Dāvis Mosāns's avatar
Dāvis Mosāns committed
52
#include <QLoggingCategory>
53

Dāvis Mosāns's avatar
Dāvis Mosāns committed
54 55
Q_DECLARE_LOGGING_CATEGORY(APP)
Q_LOGGING_CATEGORY(APP, "kdevelop.app")
56

57 58 59 60 61
#include <shell/core.h>
#include <shell/mainwindow.h>
#include <shell/projectcontroller.h>
#include <shell/documentcontroller.h>
#include <shell/plugincontroller.h>
62
#include <shell/sessioncontroller.h>
63 64 65 66 67
#include <shell/runcontroller.h>
#include <shell/launchconfiguration.h>
#include <shell/session.h>
#include <interfaces/ilauncher.h>
#include <interfaces/iproject.h>
Kevin Funk's avatar
Kevin Funk committed
68
#include <interfaces/launchconfigurationtype.h>
Milian Wolff's avatar
Milian Wolff committed
69
#include <util/path.h>
70 71

#include "kdevideextension.h"
72 73 74
#if KDEVELOP_SINGLE_APP
#include "qtsingleapplication.h"
#endif
75

Milian Wolff's avatar
Milian Wolff committed
76
#include <iostream>
77

René J.V. Bertin's avatar
OS X:  
René J.V. Bertin committed
78 79 80 81
#ifdef Q_OS_MAC
#include <CoreFoundation/CoreFoundation.h>
#endif

Milian Wolff's avatar
Milian Wolff committed
82
using namespace KDevelop;
83

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
namespace {

#if KDEVELOP_SINGLE_APP
QString serializeOpenFilesMessage(const QVector<UrlInfo> &infos)
{
    QByteArray message;
    QDataStream stream(&message, QIODevice::WriteOnly);
    stream << QByteArrayLiteral("open");
    stream << infos;
    return QString::fromLatin1(message.toHex());
}
#endif

void openFiles(const QVector<UrlInfo>& infos)
{
    foreach (const UrlInfo& file, infos) {
        if (!ICore::self()->documentController()->openDocument(file.url, file.cursor)) {
            qWarning() << i18n("Could not open %1", file.url.toDisplayString(QUrl::PreferLocalFile));
        }
    }
}

}

class KDevelopApplication:
109 110 111 112 113
#if KDEVELOP_SINGLE_APP
    public SharedTools::QtSingleApplication
#else
    public QApplication
#endif
114
{
115
public:
116
    explicit KDevelopApplication(int &argc, char **argv, bool GUIenabled = true)
117 118 119
#if KDEVELOP_SINGLE_APP
        : SharedTools::QtSingleApplication(QStringLiteral("KDevelop"), argc, argv)
#else
120
        : QApplication(argc, argv, GUIenabled)
121
#endif
122
        {
123 124 125 126
#if KDEVELOP_SINGLE_APP
            Q_UNUSED(GUIenabled);
#endif

127 128
            connect(this, &QGuiApplication::saveStateRequest, this, &KDevelopApplication::saveState);
        }
129

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
#if KDEVELOP_SINGLE_APP
public Q_SLOTS:
    void remoteArguments(const QString &message, QObject *socket)
    {
        Q_UNUSED(socket);

        QByteArray ba = QByteArray::fromHex(message.toLatin1());
        QDataStream stream(ba);
        QByteArray command;
        stream >> command;

        qCDebug(APP) << "Received remote command: " << command;

        if (command == "open") {
            QVector<UrlInfo> infos;
            stream >> infos;
            openFiles(infos);
        } else {
            qCWarning(APP) << "Unknown remote command: " << command;
        }
    }

    void fileOpenRequested(const QString &file)
    {
        openFiles({UrlInfo(file)});
    }
#endif

158
private Q_SLOTS:
159
    void saveState( QSessionManager& sm ) {
160 161
        if (KDevelop::Core::self() && KDevelop::Core::self()->sessionController()) {
            QString x11SessionId = QString("%1_%2").arg(sm.sessionId()).arg(sm.sessionKey());
162 163 164 165 166
            const auto activeSession = KDevelop::Core::self()->sessionController()->activeSession();
            if (!activeSession) {
                qWarning() << "No active session, can't save state";
                return;
            }
167

168
            QString kdevelopSessionId = activeSession->id().toString();
169 170
            sm.setRestartCommand(QStringList() << QCoreApplication::applicationFilePath() << "-session" << x11SessionId << "-s" << kdevelopSessionId);
        }
171 172 173
    }
};

174 175 176
/// Tries to find a session identified by @p data in @p sessions.
/// The @p data may be either a session's name or a string-representation of its UUID.
/// @return pointer to the session or NULL if nothing appropriate has been found
177
static const KDevelop::SessionInfo* findSessionInList( const SessionInfos& sessions, const QString& data )
178 179 180 181
{
    // We won't search a session without input data, since that could lead to false-positives
    // with unnamed sessions
    if( data.isEmpty() )
182
        return nullptr;
183

184
    for( auto it = sessions.constBegin(); it != sessions.constEnd(); ++it ) {
185 186 187 188 189
        if ( ( it->name == data ) || ( it->uuid.toString() == data ) ) {
            const KDevelop::SessionInfo& sessionRef = *it;
            return &sessionRef;
        }
    }
190
    return nullptr;
191 192
}

193 194
/// Performs a DBus call to open the given @p files in the running kdev instance identified by @p pid
/// Returns the exit status
195
static int openFilesInRunningInstance(const QVector<UrlInfo>& files, qint64 pid)
196
{
197 198
    const QString service = QString("org.kdevelop.kdevelop-%1").arg(pid);
    QDBusInterface iface(service, "/org/kdevelop/DocumentController", "org.kdevelop.DocumentController");
199 200

    QStringList urls;
201
    bool errors_occured = false;
202 203
    foreach ( const UrlInfo& file, files ) {
        QDBusReply<bool> result = iface.call("openDocumentSimple", file.url.toString(), file.cursor.line(), file.cursor.column());
204 205
        if ( ! result.value() ) {
            QTextStream err(stderr);
206
            err << i18n("Could not open file %1.", file.url.toDisplayString(QUrl::PreferLocalFile)) << "\n";
207 208
            errors_occured = true;
        }
209
    }
210 211
    // make the window visible
    QDBusMessage makeVisible = QDBusMessage::createMethodCall( service, "/kdevelop/MainWindow", "org.kdevelop.MainWindow",
212
                                                               "ensureVisible" );
213
    QDBusConnection::sessionBus().asyncCall( makeVisible );
214
    return errors_occured ? 1 : 0;
215 216 217 218
}

/// Gets the PID of a running KDevelop instance, eventually asking the user if there is more than one.
/// Returns -1 in case there are no running sessions.
219
static qint64 getRunningSessionPid()
220
{
221 222
    SessionInfos candidates;
    foreach( const KDevelop::SessionInfo& si, KDevelop::SessionController::availableSessionInfos() ) {
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        if( KDevelop::SessionController::isSessionRunning(si.uuid.toString()) ) {
            candidates << si;
        }
    }
    if ( candidates.isEmpty() ) {
        return -1;
    }

    QString sessionUuid;
    if ( candidates.size() == 1 ) {
        sessionUuid = candidates.first().uuid.toString();
    }
    else {
        const QString title = i18n("Select the session to open the document in");
        sessionUuid = KDevelop::SessionController::showSessionChooserDialog(title, true);
    }
    return KDevelop::SessionController::sessionRunInfo(sessionUuid).holderPid;
}

242
static QString findSessionId(const SessionInfos& availableSessionInfos, const QString& session)
243 244 245 246
{
    //If there is a session and a project with the same name, always open the session
    //regardless of the order encountered
    QString projectAsSession;
247
    foreach(const KDevelop::SessionInfo& si, availableSessionInfos)
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    {
        if ( session == si.name || session == si.uuid.toString() ) {
            return si.uuid.toString();
        } else if (projectAsSession.isEmpty()) {
            foreach(const QUrl& k, si.projects) {
                QString fn(k.fileName());
                fn = fn.left(fn.indexOf('.'));
                if ( session == fn ) {
                    projectAsSession = si.uuid.toString();
                }
            }
        }
    }

    if (projectAsSession.isEmpty())  {
        QTextStream qerr(stderr);
264
        qerr << endl << i18n("Cannot open unknown session %1. See `--list-sessions` switch for available sessions or use `-n` to create a new one.",
265 266 267 268 269 270 271 272 273 274 275
                             session) << endl;
    }
    return projectAsSession;
}

static qint64 findSessionPid(const QString &sessionId)
{
    KDevelop::SessionRunInfo sessionInfo = KDevelop::SessionController::sessionRunInfo( sessionId );
    return sessionInfo.holderPid;
}

Adam Treat's avatar
Adam Treat committed
276
int main( int argc, char *argv[] )
277
{
278 279 280
    QElapsedTimer timer;
    timer.start();

281 282
    // TODO: Maybe generalize, add KDEVELOP_STANDALONE build option
#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
Kevin Funk's avatar
Kevin Funk committed
283 284 285
    qputenv("KDE_FORK_SLAVES", "1"); // KIO slaves will be forked off instead of being started via DBus
#endif

Kevin Funk's avatar
Kevin Funk committed
286 287 288 289 290 291
    // Useful for valgrind runs, just `export KDEV_DISABLE_JIT=1`
    if (qEnvironmentVariableIsSet("KDEV_DISABLE_JIT")) {
        qputenv("KDEV_DISABLE_WELCOMEPAGE", "1");
        qputenv("QT_ENABLE_REGEXP_JIT", "0");
    }

292 293 294
    // Don't show any debug output by default.
    // If you need to enable additional logging for debugging use a rules file
    // as explained in the QLoggingCategory documentation:
295
    // https://doc.qt.io/qt-5/qloggingcategory.html#logging-rules
296
    QLoggingCategory::setFilterRules(QStringLiteral("*.debug=false\ndefault.debug=true\n"));
297
    KLocalizedString::setApplicationDomain("kdevelop");
298
    QCoreApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
299

René J.V. Bertin's avatar
OS X:  
René J.V. Bertin committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313
#ifdef Q_OS_MAC
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    if (mainBundle) {
        // get the application's Info Dictionary. For app bundles this would live in the bundle's Info.plist,
        // for regular executables it is obtained in another way.
        CFMutableDictionaryRef infoDict = (CFMutableDictionaryRef) CFBundleGetInfoDictionary(mainBundle);
        if (infoDict) {
            // Try to prevent App Nap on OS X. This can be tricky in practice, at least in 10.9 .
            CFDictionarySetValue(infoDict, CFSTR("NSAppSleepDisabled"), kCFBooleanTrue);
            CFDictionarySetValue(infoDict, CFSTR("NSSupportsAutomaticTermination"), kCFBooleanFalse);
        }
    }
#endif

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    //we can't use KCmdLineArgs as it doesn't allow arguments for the debugee
    //so lookup the --debug switch and eat everything behind by decrementing argc
    //debugArgs is filled with args after --debug <debuger>
    QStringList debugArgs;
    QString debugeeName;
    {
        bool debugFound = false;
        int c = argc;
        for (int i=0; i < c; ++i) {
            if (debugFound) {
                debugArgs << argv[i];
            } else if (qstrcmp(argv[i], "--debug") == 0 || qstrcmp(argv[i], "-d") == 0) {
                if (argc <= i+1) {
                    argc = i + 1;
                } else {
                    i++;
                    argc = i + 1;
                }
                debugFound = true;
            } else if (QString(argv[i]).startsWith("--debug=")) {
                argc = i + 1;
                debugFound = true;
            }
        }
    }

    KDevelopApplication app(argc, argv);

342
    static const char description[] = I18N_NOOP( "The KDevelop Integrated Development Environment" );
343
    KAboutData aboutData( "kdevelop", i18n( "KDevelop" ), QByteArray(VERSION), i18n(description), KAboutLicense::GPL,
Kevin Funk's avatar
Kevin Funk committed
344
                          i18n("Copyright 1999-2016, The KDevelop developers"), QString(), "http://www.kdevelop.org/");
345
    aboutData.setDesktopFileName(QStringLiteral("org.kde.kdevelop"));
346 347 348 349
    aboutData.addAuthor( i18n("Kevin Funk"), i18n( "Co-maintainer, C++/Clang, QA, Windows Support" ), "kfunk@kde.org" );
    aboutData.addAuthor( i18n("Sven Brauch"), i18n( "Co-maintainer, AppImage, Python Support, User Interface improvements" ), "svenbrauch@gmail.com" );
    aboutData.addAuthor( i18n("Aleix Pol Gonzalez"), i18n( "CMake Support, Run Support, Kross Support" ), "aleixpol@gmail.com" );
    aboutData.addAuthor( i18n("Milian Wolff"), i18n( "C++/Clang, Generic manager, Webdevelopment Plugins, Snippets, Performance" ), "mail@milianw.de" );
350
    aboutData.addAuthor( i18n("Olivier JG"), i18n( "C++/Clang, DUChain, Bug Fixes" ), "olivier.jg@gmail.com" );
351 352 353 354 355 356 357 358 359 360 361
    aboutData.addAuthor( i18n("Andreas Pakulat"), i18n( "Architecture, VCS Support, Project Management Support, QMake Projectmanager" ), "apaku@gmx.de" );
    aboutData.addAuthor( i18n("Alexander Dymo"), i18n( "Architecture, Sublime UI, Ruby support" ), "adymo@kdevelop.org" );
    aboutData.addAuthor( i18n("David Nolden"), i18n( "Definition-Use Chain, C++ Support, Code Navigation, Code Completion, Coding Assistance, Refactoring" ), "david.nolden.kdevelop@art-master.de" );
    aboutData.addAuthor( i18n("Vladimir Prus"), i18n( "GDB integration" ), "ghost@cs.msu.su" );
    aboutData.addAuthor( i18n("Hamish Rodda"), i18n( "Text editor integration, definition-use chain" ), "rodda@kde.org" );
    aboutData.addAuthor( i18n("Amilcar do Carmo Lucas"), i18n( "Website admin, API documentation, Doxygen and autoproject patches" ), "amilcar@kdevelop.org" );
    aboutData.addAuthor( i18n("Niko Sams"), i18n( "GDB integration, Webdevelopment Plugins" ), "niko.sams@gmail.com" );

    aboutData.addCredit( i18n("Matt Rogers"), QString(), "mattr@kde.org");
    aboutData.addCredit( i18n("Cédric Pasteur"), i18n("astyle and indent support"), "cedric.pasteur@free.fr" );
    aboutData.addCredit( i18n("Evgeniy Ivanov"), i18n("Distributed VCS, Git, Mercurial"), "powerfox@kde.ru" );
362
    // QTest integration is separate in playground currently.
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    //aboutData.addCredit( i18n("Manuel Breugelmanns"), i18n( "Veritas, QTest integration"), "mbr.nxi@gmail.com" );
    aboutData.addCredit( i18n("Robert Gruber") , i18n( "SnippetPart, debugger and usability patches" ), "rgruber@users.sourceforge.net" );
    aboutData.addCredit( i18n("Dukju Ahn"), i18n( "Subversion plugin, Custom Make Manager, Overall improvements" ), "dukjuahn@gmail.com" );
    aboutData.addCredit( i18n("Harald Fernengel"), i18n( "Ported to Qt 3, patches, valgrind, diff and perforce support" ), "harry@kdevelop.org" );
    aboutData.addCredit( i18n("Roberto Raggi"), i18n( "C++ parser" ), "roberto@kdevelop.org" );
    aboutData.addCredit( i18n("The KWrite authors"), i18n( "Kate editor component" ), "kwrite-devel@kde.org" );
    aboutData.addCredit( i18n("Nokia Corporation/Qt Software"), i18n( "Designer code" ), "qt-info@nokia.com" );

    aboutData.addCredit( i18n("Contributors to older versions:"), QString(), "" );
    aboutData.addCredit( i18n("Bernd Gehrmann"), i18n( "Initial idea, basic architecture, much initial source code" ), "bernd@kdevelop.org" );
    aboutData.addCredit( i18n("Caleb Tennis"), i18n( "KTabBar, bugfixes" ), "caleb@aei-tech.com" );
    aboutData.addCredit( i18n("Richard Dale"), i18n( "Java & Objective C support" ), "Richard_Dale@tipitina.demon.co.uk" );
    aboutData.addCredit( i18n("John Birch"), i18n( "Debugger frontend" ), "jbb@kdevelop.org" );
    aboutData.addCredit( i18n("Sandy Meier"), i18n( "PHP support, context menu stuff" ), "smeier@kdevelop.org" );
    aboutData.addCredit( i18n("Kurt Granroth"), i18n( "KDE application templates" ), "kurth@granroth.org" );
    aboutData.addCredit( i18n("Ian Reinhart Geiser"), i18n( "Dist part, bash support, application templates" ), "geiseri@yahoo.com" );
    aboutData.addCredit( i18n("Matthias Hoelzer-Kluepfel"), i18n( "Several components, htdig indexing" ), "hoelzer@kde.org" );
    aboutData.addCredit( i18n("Victor Roeder"), i18n( "Help with Automake manager and persistent class store" ), "victor_roeder@gmx.de" );
    aboutData.addCredit( i18n("Simon Hausmann"), i18n( "Help with KParts infrastructure" ), "hausmann@kde.org" );
    aboutData.addCredit( i18n("Oliver Kellogg"), i18n( "Ada support" ), "okellogg@users.sourceforge.net" );
    aboutData.addCredit( i18n("Jakob Simon-Gaarde"), i18n( "QMake projectmanager" ), "jsgaarde@tdcspace.dk" );
    aboutData.addCredit( i18n("Falk Brettschneider"), i18n( "MDI modes, QEditor, bugfixes" ), "falkbr@kdevelop.org" );
    aboutData.addCredit( i18n("Mario Scalas"), i18n( "PartExplorer, redesign of CvsPart, patches, bugs(fixes)" ), "mario.scalas@libero.it" );
    aboutData.addCredit( i18n("Jens Dagerbo"), i18n( "Replace, Bookmarks, FileList and CTags2 plugins. Overall improvements and patches" ), "jens.dagerbo@swipnet.se" );
    aboutData.addCredit( i18n("Julian Rockey"), i18n( "Filecreate part and other bits and patches" ), "linux@jrockey.com" );
    aboutData.addCredit( i18n("Ajay Guleria"), i18n( "ClearCase support" ), "ajay_guleria@yahoo.com" );
    aboutData.addCredit( i18n("Marek Janukowicz"), i18n( "Ruby support" ), "child@t17.ds.pwr.wroc.pl" );
    aboutData.addCredit( i18n("Robert Moniot"), i18n( "Fortran documentation" ), "moniot@fordham.edu" );
    aboutData.addCredit( i18n("Ka-Ping Yee"), i18n( "Python documentation utility" ), "ping@lfw.org" );
    aboutData.addCredit( i18n("Dimitri van Heesch"), i18n( "Doxygen wizard" ), "dimitri@stack.nl" );
    aboutData.addCredit( i18n("Hugo Varotto"), i18n( "Fileselector component" ), "hugo@varotto-usa.com" );
    aboutData.addCredit( i18n("Matt Newell"), i18n( "Fileselector component" ), "newellm@proaxis.com" );
    aboutData.addCredit( i18n("Daniel Engelschalt"), i18n( "C++ code completion, persistent class store" ), "daniel.engelschalt@gmx.net" );
    aboutData.addCredit( i18n("Stephane Ancelot"), i18n( "Patches" ), "sancelot@free.fr" );
    aboutData.addCredit( i18n("Jens Zurheide"), i18n( "Patches" ), "jens.zurheide@gmx.de" );
    aboutData.addCredit( i18n("Luc Willems"), i18n( "Help with Perl support" ), "Willems.luc@pandora.be" );
    aboutData.addCredit( i18n("Marcel Turino"), i18n( "Documentation index view" ), "M.Turino@gmx.de" );
    aboutData.addCredit( i18n("Yann Hodique"), i18n( "Patches" ), "Yann.Hodique@lifl.fr" );
    aboutData.addCredit( i18n("Tobias Gl\303\244\303\237er") , i18n( "Documentation Finder,  qmake projectmanager patches, usability improvements, bugfixes ... " ), "tobi.web@gmx.de" );
    aboutData.addCredit( i18n("Andreas Koepfle") , i18n( "QMake project manager patches" ), "koepfle@ti.uni-mannheim.de" );
    aboutData.addCredit( i18n("Sascha Cunz") , i18n( "Cleanup and bugfixes for qEditor, AutoMake and much other stuff" ), "mail@sacu.de" );
    aboutData.addCredit( i18n("Zoran Karavla"), i18n( "Artwork for the ruby language" ), "webmaster@the-error.net", "http://the-error.net" );
Adam Treat's avatar
Adam Treat committed
405

406 407
    KAboutData::setApplicationData(aboutData);
    // set icon for shells which do not use desktop file metadata
408 409
    // but without setting replacing an existing icon with an empty one!
    QApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("kdevelop"), QApplication::windowIcon()));
410

411 412
    KCrash::initialize();

413 414 415 416 417
    Kdelibs4ConfigMigrator migrator(QStringLiteral("kdevelop"));
    migrator.setConfigFiles({QStringLiteral("kdeveloprc")});
    migrator.setUiFiles({QStringLiteral("kdevelopui.rc")});
    migrator.migrate();

Kevin Funk's avatar
Kevin Funk committed
418 419 420
    // High DPI support
    app.setAttribute(Qt::AA_UseHighDpiPixmaps, true);

421
    qCDebug(APP) << "Startup";
Kevin Funk's avatar
Kevin Funk committed
422

423 424 425 426 427 428 429 430
    QCommandLineParser parser;
    parser.addVersionOption();
    parser.addHelpOption();
    aboutData.setupCommandLine(&parser);

    parser.addOption(QCommandLineOption{QStringList{"n", "new-session"}, i18n("Open KDevelop with a new session using the given name."), "name"});
    parser.addOption(QCommandLineOption{QStringList{"s", "open-session"}, i18n("Open KDevelop with the given session.\n"
                     "You can pass either hash or the name of the session." ), "session"});
431 432
    parser.addOption(QCommandLineOption{QStringList{"rm", "remove-session"}, i18n("Delete the given session.\n"
                     "You can pass either hash or the name of the session." ), "session"});
433 434 435 436 437 438 439 440 441
    parser.addOption(QCommandLineOption{QStringList{"ps", "pick-session"}, i18n("Shows all available sessions and lets you select one to open.")});
    parser.addOption(QCommandLineOption{QStringList{"pss", "pick-session-shell"}, i18n("List all available sessions on shell and lets you select one to open.")});
    parser.addOption(QCommandLineOption{QStringList{"l", "list-sessions"}, i18n("List available sessions and quit.")});
    parser.addOption(QCommandLineOption{QStringList{"p", "project"}, i18n("Open KDevelop and load the given project."), "project"});
    parser.addOption(QCommandLineOption{QStringList{"d", "debug"},
                     i18n("Start debugging an application in KDevelop with the given debugger.\n"
                     "The binary that should be debugged must follow - including arguments.\n"
                     "Example: kdevelop --debug gdb myapp --foo bar"), "debugger"});

442 443 444 445 446 447 448
    // this is used by the 'kdevelop!' script to retrieve the pid of a KDEVELOP
    // instance. When this is called, then we should just print the PID on the
    // standard-output. If a session is specified through open-session, then
    // we should return the PID of that session. Otherwise, if only a single
    // session is running, then we should just return the PID of that session.
    // Otherwise, we should print a command-line session-chooser dialog ("--pss"),
    // which only shows the running sessions, and the user can pick one.
449 450 451
    parser.addOption(QCommandLineOption{QStringList{"pid"}});

    parser.addPositionalArgument("files", i18n( "Files to load" ), "[FILE...]");
452

453 454
    // The session-controller needs to arguments to eventually pass them to newly opened sessions
    KDevelop::SessionController::setArguments(argc, argv);
455

456 457 458 459
    parser.process(app);
    aboutData.processCommandLine(&parser);

    if(parser.isSet("list-sessions"))
Milian Wolff's avatar
Milian Wolff committed
460 461
    {
        QTextStream qout(stdout);
462
        qout << endl << ki18n("Available sessions (use '-s HASH' or '-s NAME' to open a specific one):").toString() << endl << endl;
463
        qout << QString("%1").arg(ki18n("Hash").toString(), -38) << '\t' << ki18n("Name: Opened Projects").toString() << endl;
464
        foreach(const KDevelop::SessionInfo& si, KDevelop::SessionController::availableSessionInfos())
Milian Wolff's avatar
Milian Wolff committed
465
        {
466
            if ( si.name.isEmpty() && si.projects.isEmpty() ) {
467 468
                continue;
            }
469
            qout << si.uuid.toString() << '\t' << si.description;
470

471
            if(KDevelop::SessionController::isSessionRunning(si.uuid.toString()))
472
                qout << "     " << i18n("[running]");
473

474
            qout << endl;
Milian Wolff's avatar
Milian Wolff committed
475 476 477
        }
        return 0;
    }
478

479
    // Handle extra arguments, which stand for files to open
480
    QVector<UrlInfo> initialFiles;
481
    foreach (const QString &file, parser.positionalArguments()) {
482
        initialFiles.append(UrlInfo(file));
483
    }
484

485 486
    const auto availableSessionInfos = KDevelop::SessionController::availableSessionInfos();

487 488 489 490 491 492 493 494 495
    if (!initialFiles.isEmpty() && !parser.isSet("new-session")) {
#if KDEVELOP_SINGLE_APP
        if (app.isRunning()) {
            bool success = app.sendMessage(serializeOpenFilesMessage(initialFiles));
            if (success) {
                return 0;
            }
        }
#else
496
        qint64 pid = -1;
497
        if (parser.isSet("open-session")) {
498
            const QString session = findSessionId(availableSessionInfos, parser.value("open-session"));
499 500 501 502 503 504 505 506
            if (session.isEmpty()) {
                return 1;
            } else if (KDevelop::SessionController::isSessionRunning(session)) {
                pid = findSessionPid(session);
            }
        } else {
            pid = getRunningSessionPid();
        }
507 508 509 510
        if ( pid > 0 ) {
            return openFilesInRunningInstance(initialFiles, pid);
        }
        // else there are no running sessions, and the generated list of files will be opened below.
511
#endif
512 513
    }

514 515
    // if empty, restart kdevelop with last active session, see SessionController::defaultSessionId
    QString session;
516

517
    uint nRunningSessions = 0;
518
    foreach(const KDevelop::SessionInfo& si, availableSessionInfos)
519 520 521 522 523 524
        if(KDevelop::SessionController::isSessionRunning(si.uuid.toString()))
            ++nRunningSessions;

    // also show the picker dialog when a pid shall be retrieved and multiple
    // sessions are running.
    if(parser.isSet("pss") || (parser.isSet("pid") && !parser.isSet("open-session") && !parser.isSet("ps") && nRunningSessions > 1))
525 526
    {
        QTextStream qerr(stderr);
527
        SessionInfos candidates;
528
        foreach(const KDevelop::SessionInfo& si, availableSessionInfos)
529 530
            if( (!si.name.isEmpty() || !si.projects.isEmpty() || parser.isSet("pid")) &&
                (!parser.isSet("pid") || KDevelop::SessionController::isSessionRunning(si.uuid.toString())))
531
                candidates << si;
Dāvis Mosāns's avatar
Dāvis Mosāns committed
532

533 534 535 536 537
        if(candidates.size() == 0)
        {
            qerr << "no session available" << endl;
            return 1;
        }
Dāvis Mosāns's avatar
Dāvis Mosāns committed
538

539
        if(candidates.size() == 1 && parser.isSet("pid"))
540 541 542 543 544
        {
            session = candidates[0].uuid.toString();
        }else{
            for(int i = 0; i < candidates.size(); ++i)
                qerr << "[" << i << "]: " << candidates[i].description << endl;
Dāvis Mosāns's avatar
Dāvis Mosāns committed
545

546 547
            int chosen;
            std::cin >> chosen;
548
            if(std::cin.good() && (chosen >= 0 && chosen < candidates.size()))
549 550 551
            {
                session = candidates[chosen].uuid.toString();
            }else{
552
                qerr << "invalid selection" << endl;
553 554 555 556
                return 1;
            }
        }
    }
Dāvis Mosāns's avatar
Dāvis Mosāns committed
557

558
    if(parser.isSet("ps"))
559
    {
560
        bool onlyRunning = parser.isSet("pid");
561
        session = KDevelop::SessionController::showSessionChooserDialog(i18n("Select the session you would like to use"), onlyRunning);
562 563 564
        if(session.isEmpty())
            return 1;
    }
565

566
    if ( parser.isSet("debug") ) {
567 568
        if ( debugArgs.isEmpty() ) {
            QTextStream qerr(stderr);
569
            qerr << endl << i18nc("@info:shell", "Specify the binary you want to debug.") << endl;
570 571
            return 1;
        }
572 573 574 575 576 577

        QFileInfo binaryInfo(debugArgs.first());
        if (!binaryInfo.exists()) {
            binaryInfo = QStandardPaths::findExecutable(debugArgs.first());
            if (!binaryInfo.exists()) {
                QTextStream qerr(stderr);
Yuri Chornoivan's avatar
Yuri Chornoivan committed
578
                qerr << endl << i18nc("@info:shell", "Specified binary does not exist.") << endl;
579 580 581 582 583 584
                return 1;
            }
        }

        debugArgs.first() = binaryInfo.absoluteFilePath();
        debugeeName = i18n("Debug %1", binaryInfo.fileName());
585
        session = debugeeName;
586
    } else if ( parser.isSet("new-session") )
587
    {
588
        session = parser.value("new-session");
589
        foreach(const KDevelop::SessionInfo& si, availableSessionInfos)
590 591 592 593 594 595 596 597
        {
            if ( session == si.name ) {
                QTextStream qerr(stderr);
                qerr << endl << i18n("A session with the name %1 exists already. Use the -s switch to open it.", session) << endl;
                return 1;
            }
        }
        // session doesn't exist, we can create it
598
    } else if ( parser.isSet("open-session") ) {
599
        session = findSessionId(availableSessionInfos, parser.value("open-session"));
600 601
        if (session.isEmpty()) {
            return 1;
602
        }
603 604 605
    } else if ( parser.isSet("remove-session") )
    {
        session = parser.value("remove-session");
606
        auto si = findSessionInList(availableSessionInfos, session);
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
        if (!si) {
            QTextStream qerr(stderr);
            qerr << endl << i18n("No session with the name %1 exists.", session) << endl;
            return 1;
        }

        auto sessionLock = KDevelop::SessionController::tryLockSession(si->uuid.toString());
        if (!sessionLock.lock) {
            QTextStream qerr(stderr);
            qerr << endl << i18n("Could not lock session %1 for deletion.", session) << endl;
            return 1;
        }
        KDevelop::SessionController::deleteSessionFromDisk(sessionLock.lock);
        QTextStream qout(stdout);
        qout << endl << i18n("Session with name %1 was successfully removed.", session) << endl;
        return 0;
623
    }
624

625
    if(parser.isSet("pid")) {
626 627
        if (session.isEmpty())
        {   // just pick the first running session
628
            foreach(const KDevelop::SessionInfo& si, availableSessionInfos)
629 630 631
                if(KDevelop::SessionController::isSessionRunning(si.uuid.toString()))
                    session = si.uuid.toString();
        }
632
        const KDevelop::SessionInfo* sessionData = findSessionInList(availableSessionInfos, session);
633

634
        if( !sessionData ) {
Dāvis Mosāns's avatar
Dāvis Mosāns committed
635
            qCritical() << "session not given or does not exist";
636
            return 5;
637 638
        }

639 640
        const auto pid = findSessionPid(sessionData->uuid.toString());
        if (pid > 0) {
641
            // Print the PID and we're ready
642
            std::cout << pid << std::endl;
643
            return 0;
644 645 646
        } else {
            qCritical() << sessionData->uuid.toString() << sessionData->name << "is not running";
            return 5;
647
        }
648
    }
649

650
    KDevIDEExtension::init();
651

Kevin Funk's avatar
Kevin Funk committed
652
    if(!Core::initialize(nullptr, Core::Default, session))
653
        return 5;
654

655 656 657
    // register a DBUS service for this process, so that we can open files in it from other invocations
    QDBusConnection::sessionBus().registerService(QString("org.kdevelop.kdevelop-%1").arg(app.applicationPid()));

658
    Core* core = Core::self();
659
    if (!QProcessEnvironment::systemEnvironment().contains("KDEV_DISABLE_WELCOMEPAGE")) {
660
        core->pluginController()->loadPlugin("KDevWelcomePage");
661
    }
662

663
    QStringList projectNames = parser.values("project");
664 665 666 667 668 669 670 671
    if(!projectNames.isEmpty())
    {
        foreach(const QString& p, projectNames)
        {
            QFileInfo info( p );
            if( info.suffix() == "kdev4" ) {
                // make sure the project is not already opened by the session controller
                bool shouldOpen = true;
Milian Wolff's avatar
Milian Wolff committed
672
                Path path(info.absoluteFilePath());
673
                foreach(KDevelop::IProject* p, core->projectController()->projects()) {
Milian Wolff's avatar
Milian Wolff committed
674
                    if (p->projectFile() == path) {
675 676 677 678 679
                        shouldOpen = false;
                        break;
                    }
                }
                if (shouldOpen) {
Milian Wolff's avatar
Milian Wolff committed
680
                    core->projectController()->openProject( path.toUrl() );
681 682
                }
            }
Manuel Breugelmans's avatar
Manuel Breugelmans committed
683
        }
684
    }
685

686
    if ( parser.isSet("debug") ) {
687 688
        Q_ASSERT( !debugeeName.isEmpty() );
        QString launchName = debugeeName;
689

690
        KDevelop::LaunchConfiguration* launch = nullptr;
Dāvis Mosāns's avatar
Dāvis Mosāns committed
691
        qCDebug(APP) << launchName;
692
        foreach (KDevelop::LaunchConfiguration *l, core->runControllerInternal()->launchConfigurationsInternal()) {
Dāvis Mosāns's avatar
Dāvis Mosāns committed
693
            qCDebug(APP) << l->name();
694 695 696 697 698
            if (l->name() == launchName) {
                launch = l;
            }
        }

699
        KDevelop::LaunchConfigurationType *type = nullptr;
700
        foreach (KDevelop::LaunchConfigurationType *t, core->runController()->launchConfigurationTypes()) {
Dāvis Mosāns's avatar
Dāvis Mosāns committed
701
            qCDebug(APP) << t->id();
702 703 704 705 706 707 708 709 710 711 712
            if (t->id() == "Native Application") {
                type = t;
                break;
            }
        }
        if (!type) {
            QTextStream qerr(stderr);
            qerr << endl << i18n("Cannot find native launch configuration type") << endl;
            return 1;
        }

713 714
        if (launch && launch->type()->id() != "Native Application") launch = nullptr;
        if (launch && launch->launcherForMode("debug") != parser.value("debug")) launch = nullptr;
715
        if (!launch) {
Dāvis Mosāns's avatar
Dāvis Mosāns committed
716
            qCDebug(APP) << launchName << "not found, creating a new one";
717 718 719
            QPair<QString,QString> launcher;
            launcher.first = "debug";
            foreach (KDevelop::ILauncher *l, type->launchers()) {
720
                if (l->id() == parser.value("debug")) {
721 722 723 724 725 726 727
                    if (l->supportedModes().contains("debug")) {
                        launcher.second = l->id();
                    }
                }
            }
            if (launcher.second.isEmpty()) {
                QTextStream qerr(stderr);
728
                qerr << endl << i18n("Cannot find launcher %1", parser.value("debug")) << endl;
729 730
                return 1;
            }
731
            KDevelop::ILaunchConfiguration* ilaunch = core->runController()->createLaunchConfiguration(type, launcher, nullptr, launchName);
732 733 734 735 736 737 738 739 740
            launch = dynamic_cast<KDevelop::LaunchConfiguration*>(ilaunch);
        }

        type->configureLaunchFromCmdLineArguments(launch->config(), debugArgs);
        launch->config().writeEntry("Break on Start", true);
        core->runControllerInternal()->setDefaultLaunch(launch);

        core->runControllerInternal()->execute("debug", launch);
    } else {
741
        openFiles(initialFiles);
742
    }
743

744 745 746 747 748 749 750 751 752 753
#if KDEVELOP_SINGLE_APP
    // Set up remote arguments.
    QObject::connect(&app, &SharedTools::QtSingleApplication::messageReceived,
                     &app, &KDevelopApplication::remoteArguments);

    QObject::connect(&app, &SharedTools::QtSingleApplication::fileOpenRequest,
                     &app, &KDevelopApplication::fileOpenRequested);
#endif


754
#ifdef WITH_WELCOMEPAGE
755
    // make it possible to disable the welcome page, useful for valgrind runs e.g.
Kevin Funk's avatar
Kevin Funk committed
756
    if (!qEnvironmentVariableIsSet("KDEV_DISABLE_WELCOMEPAGE")) {
757 758
        trySetupWelcomePageView();
    }
759
#endif
760

761 762 763
    qCDebug(APP) << "Done startup" << "- took:" << timer.elapsed() << "ms";
    timer.invalidate();

764
    return app.exec();
765
}