main.cpp 34.2 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 408 409
    KAboutData::setApplicationData(aboutData);
    // set icon for shells which do not use desktop file metadata
    QApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("kdevelop")));

410 411
    KCrash::initialize();

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

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

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

422 423 424 425 426 427 428 429
    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"});
430 431
    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"});
432 433 434 435 436 437 438 439 440
    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"});

441 442 443 444 445 446 447
    // 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.
448 449 450
    parser.addOption(QCommandLineOption{QStringList{"pid"}});

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

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

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

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

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

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

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

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

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

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

516
    uint nRunningSessions = 0;
517
    foreach(const KDevelop::SessionInfo& si, availableSessionInfos)
518 519 520 521 522 523
        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))
524 525
    {
        QTextStream qerr(stderr);
526
        SessionInfos candidates;
527
        foreach(const KDevelop::SessionInfo& si, availableSessionInfos)
528 529
            if( (!si.name.isEmpty() || !si.projects.isEmpty() || parser.isSet("pid")) &&
                (!parser.isSet("pid") || KDevelop::SessionController::isSessionRunning(si.uuid.toString())))
530
                candidates << si;
Dāvis Mosāns's avatar
Dāvis Mosāns committed
531

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

538
        if(candidates.size() == 1 && parser.isSet("pid"))
539 540 541 542 543
        {
            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
544

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

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

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

        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
577
                qerr << endl << i18nc("@info:shell", "Specified binary does not exist.") << endl;
578 579 580 581 582 583
                return 1;
            }
        }

        debugArgs.first() = binaryInfo.absoluteFilePath();
        debugeeName = i18n("Debug %1", binaryInfo.fileName());
584
        session = debugeeName;
585
    } else if ( parser.isSet("new-session") )
586
    {
587
        session = parser.value("new-session");
588
        foreach(const KDevelop::SessionInfo& si, availableSessionInfos)
589 590 591 592 593 594 595 596
        {
            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
597
    } else if ( parser.isSet("open-session") ) {
598
        session = findSessionId(availableSessionInfos, parser.value("open-session"));
599 600
        if (session.isEmpty()) {
            return 1;
601
        }
602 603 604
    } else if ( parser.isSet("remove-session") )
    {
        session = parser.value("remove-session");
605
        auto si = findSessionInList(availableSessionInfos, session);
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
        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;
622
    }
623

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

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

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

649
    KDevIDEExtension::init();
650

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

654 655 656
    // 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()));

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

662
    QStringList projectNames = parser.values("project");
663 664 665 666 667 668 669 670
    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
671
                Path path(info.absoluteFilePath());
672
                foreach(KDevelop::IProject* p, core->projectController()->projects()) {
Milian Wolff's avatar
Milian Wolff committed
673
                    if (p->projectFile() == path) {
674 675 676 677 678
                        shouldOpen = false;
                        break;
                    }
                }
                if (shouldOpen) {
Milian Wolff's avatar
Milian Wolff committed
679
                    core->projectController()->openProject( path.toUrl() );
680 681
                }
            }
Manuel Breugelmans's avatar
Manuel Breugelmans committed
682
        }
683
    }
684

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

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

698
        KDevelop::LaunchConfigurationType *type = nullptr;
699
        foreach (KDevelop::LaunchConfigurationType *t, core->runController()->launchConfigurationTypes()) {
Dāvis Mosāns's avatar
Dāvis Mosāns committed
700
            qCDebug(APP) << t->id();
701 702 703 704 705 706 707 708 709 710 711
            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;
        }

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

743 744 745 746 747 748 749 750 751 752
#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


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

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

763
    return app.exec();
764
}