generator.cpp 43.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/********************************************************************
Copyright 2015  Martin Gräßlin <mgraesslin@kde.org>

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), which shall
act as a proxy defined in Section 6 of version 3 of the license.

This library 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
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*********************************************************************/
#include "generator.h"

#include <QCoreApplication>
#include <QCommandLineParser>
#include <QBuffer>
#include <QByteArray>
#include <QFutureWatcher>
#include <QMutexLocker>
#include <QDate>
#include <QProcess>
#include <QtConcurrent>
#include <QTextStream>
32 33 34
#include <QXmlStreamReader>

#include <QDebug>
35 36 37 38 39 40

namespace KWayland
{
namespace Tools
{

41 42
static QMap<QString, QString> s_clientClassNameMapping;

43 44 45 46 47 48 49 50 51 52 53
static QString toQtInterfaceName(const QString &wlInterface)
{
    auto it = s_clientClassNameMapping.constFind(wlInterface);
    if (it != s_clientClassNameMapping.constEnd()) {
        return it.value();
    } else {
        qWarning() << "Cannot find mapping for " << wlInterface;
    }
    return wlInterface;
}

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
static QString toCamelCase(const QString &underscoreName)
{
    const QStringList parts = underscoreName.split(QStringLiteral("_"));
    if (parts.count() < 2) {
        return underscoreName;
    }
    auto it = parts.constBegin();
    QString camelCase = (*it);
    it++;
    for (; it != parts.constEnd(); ++it) {
        camelCase.append((*it).left(1).toUpper());
        camelCase.append((*it).mid(1));
    }
    return camelCase;
}

70 71 72 73 74 75 76 77 78 79 80 81 82 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 109 110 111 112 113
Argument::Argument()
{
}

Argument::Argument(const QXmlStreamAttributes &attributes)
    : m_name(attributes.value(QStringLiteral("name")).toString())
    , m_type(parseType(attributes.value(QStringLiteral("type"))))
    , m_allowNull(attributes.hasAttribute(QStringLiteral("allow-null")))
    , m_inteface(attributes.value(QStringLiteral("interface")).toString())
{
}

Argument::~Argument() = default;

Argument::Type Argument::parseType(const QStringRef &type)
{
    if (type.compare(QLatin1String("new_id")) == 0) {
        return Type::NewId;
    }
    if (type.compare(QLatin1String("destructor")) == 0) {
        return Type::Destructor;
    }
    if (type.compare(QLatin1String("object")) == 0) {
        return Type::Object;
    }
    if (type.compare(QLatin1String("fd")) == 0) {
        return Type::FileDescriptor;
    }
    if (type.compare(QLatin1String("fixed")) == 0) {
        return Type::Fixed;
    }
    if (type.compare(QLatin1String("uint")) == 0) {
        return Type::Uint;
    }
    if (type.compare(QLatin1String("int")) == 0) {
        return Type::Int;
    }
    if (type.compare(QLatin1String("string")) == 0) {
        return Type::String;
    }

    return Type::Unknown;
}

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
QString Argument::typeAsQt() const
{
    switch (m_type) {
    case Type::Destructor:
        return QString();
    case Type::FileDescriptor:
        return QStringLiteral("int");
    case Type::Fixed:
        return QStringLiteral("qreal");
    case Type::Int:
        return QStringLiteral("qint32");
    case Type::NewId:
    case Type::Object:
        return toQtInterfaceName(m_inteface);
    case Type::String:
        return QStringLiteral("const QString &");
    case Type::Uint:
        return QStringLiteral("quint32");
    case Type::Unknown:
        return QString();
    default:
        Q_UNREACHABLE();
    }
}

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
QString Argument::typeAsServerWl() const
{
    switch (m_type) {
    case Type::Destructor:
        return QString();
    case Type::FileDescriptor:
        return QStringLiteral("int32_t");
    case Type::Fixed:
        return QStringLiteral("wl_fixed");
    case Type::Int:
        return QStringLiteral("int32_t");
    case Type::Object:
        return QStringLiteral("wl_resource *");
    case Type::String:
        return QStringLiteral("const char *");
    case Type::Uint:
    case Type::NewId:
        return QStringLiteral("uint32_t");
    case Type::Unknown:
        return QString();
    default:
        Q_UNREACHABLE();
    }
}

164 165 166 167 168 169 170 171 172 173 174
Request::Request()
{
}

Request::Request(const QString &name)
    : m_name(name)
{
}

Request::~Request() = default;

175 176 177 178 179 180 181 182 183 184
bool Request::isFactory() const
{
    for (const auto a: m_arguments) {
        if (a.type() == Argument::Type::NewId) {
            return true;
        }
    }
    return false;
}

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
Event::Event()
{
}

Event::Event(const QString &name)
    : m_name(name)
{
}

Event::~Event() = default;

Interface::Interface() = default;

Interface::Interface(const QXmlStreamAttributes &attributes)
    : m_name(attributes.value(QStringLiteral("name")).toString())
    , m_version(attributes.value(QStringLiteral("version")).toUInt())
201
    , m_factory(Q_NULLPTR)
202 203 204 205 206 207 208 209 210 211 212
{
    auto it = s_clientClassNameMapping.constFind(m_name);
    if (it != s_clientClassNameMapping.constEnd()) {
        m_clientName = it.value();
    } else {
        qWarning() << "Failed to map " << m_name << " to a KWayland name";
    }
}

Interface::~Interface() = default;

213 214 215 216 217 218 219 220 221 222 223 224
Generator::Generator(QObject *parent)
    : QObject(parent)
{
}

Generator::~Generator() = default;

void Generator::start()
{
    startAuthorNameProcess();
    startAuthorEmailProcess();

225 226
    startParseXml();

227 228
    startGenerateHeaderFile();
    startGenerateCppFile();
229 230
    startGenerateServerHeaderFile();
    startGenerateServerCppFile();
231 232
}

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
void Generator::startParseXml()
{
    if (m_xmlFileName.isEmpty()) {
        return;
    }
    QFile xmlFile(m_xmlFileName);
    xmlFile.open(QIODevice::ReadOnly);
    m_xmlReader.setDevice(&xmlFile);
    while (!m_xmlReader.atEnd()) {
        if (!m_xmlReader.readNextStartElement()) {
            continue;
        }
        if (m_xmlReader.qualifiedName().compare(QLatin1String("protocol")) == 0) {
            parseProtocol();
        }
    }

    auto findFactory = [this] (const QString interfaceName) -> Interface* {
        for (auto it = m_interfaces.begin(); it != m_interfaces.end(); ++it) {
            if ((*it).name().compare(interfaceName) == 0) {
                continue;
            }
            for (auto r: (*it).requests()) {
                for (auto a: r.arguments()) {
                    if (a.type() == Argument::Type::NewId && a.interface().compare(interfaceName) == 0) {
                        return &(*it);
                    }
                }
            }
        }
        return nullptr;
    };
    for (auto it = m_interfaces.begin(); it != m_interfaces.end(); ++it) {
        Interface *factory = findFactory((*it).name());
        if (factory) {
            qDebug() << (*it).name() << "gets factored by" << factory->kwaylandClientName();
            (*it).setFactory(factory);
        } else {
            qDebug() << (*it).name() << "considered as a global";
            (*it).markAsGlobal();
        }
    }
}

void Generator::parseProtocol()
{
    const auto attributes = m_xmlReader.attributes();
    const QString protocolName = attributes.value(QStringLiteral("name")).toString();

    if (m_baseFileName.isEmpty()) {
        m_baseFileName = protocolName.toLower();
    }

    while (!m_xmlReader.atEnd()) {
        if (!m_xmlReader.readNextStartElement()) {
            if (m_xmlReader.qualifiedName().compare(QLatin1String("protocol")) == 0) {
                return;
            }
            continue;
        }
        if (m_xmlReader.qualifiedName().compare(QLatin1String("interface")) == 0) {
            m_interfaces << parseInterface();
        }
    }
}

Interface Generator::parseInterface()
{
    Interface interface(m_xmlReader.attributes());
    while (!m_xmlReader.atEnd()) {
        if (!m_xmlReader.readNextStartElement()) {
            if (m_xmlReader.qualifiedName().compare(QLatin1String("interface")) == 0) {
                break;
            }
            continue;
        }
        if (m_xmlReader.qualifiedName().compare(QLatin1String("request")) == 0) {
            interface.addRequest(parseRequest());
        }
        if (m_xmlReader.qualifiedName().compare(QLatin1String("event")) == 0) {
            interface.addEvent(parseEvent());
        }
    }
    return interface;
}

Request Generator::parseRequest()
{
    const auto attributes = m_xmlReader.attributes();
    Request request(attributes.value(QStringLiteral("name")).toString());
323 324 325
    if (attributes.value(QStringLiteral("type")).toString().compare(QLatin1String("destructor")) == 0) {
        request.markAsDestructor();
    }
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    while (!m_xmlReader.atEnd()) {
        if (!m_xmlReader.readNextStartElement()) {
            if (m_xmlReader.qualifiedName().compare(QLatin1String("request")) == 0) {
                break;
            }
            continue;
        }
        if (m_xmlReader.qualifiedName().compare(QLatin1String("arg")) == 0) {
            request.addArgument(Argument(m_xmlReader.attributes()));
        }
    }
    return request;
}

Event Generator::parseEvent()
{
    const auto attributes = m_xmlReader.attributes();
    Event event(attributes.value(QStringLiteral("name")).toString());
    while (!m_xmlReader.atEnd()) {
        if (!m_xmlReader.readNextStartElement()) {
            if (m_xmlReader.qualifiedName().compare(QLatin1String("event")) == 0) {
                break;
            }
            continue;
        }
        if (m_xmlReader.qualifiedName().compare(QLatin1String("arg")) == 0) {
            event.addArgument(Argument(m_xmlReader.attributes()));
        }
    }
    return event;
}

358 359 360 361 362 363 364 365 366
void Generator::startGenerateHeaderFile()
{
    QFutureWatcher<void> *watcher = new QFutureWatcher<void>(this);
    connect(watcher, &QFutureWatcher<void>::finished, this, &Generator::checkEnd);
    m_finishedCounter++;
    watcher->setFuture(QtConcurrent::run([this] {
        QFile file(QStringLiteral("%1.h").arg(m_baseFileName));
        file.open(QIODevice::WriteOnly);
        m_stream.setLocalData(new QTextStream(&file));
367
        m_project.setLocalData(Project::Client);
368 369 370 371 372 373
        generateCopyrightHeader();
        generateStartIncludeGuard();
        generateHeaderIncludes();
        generateWaylandForwardDeclarations();
        generateStartNamespace();
        generateNamespaceForwardDeclarations();
374 375 376
        for (auto it = m_interfaces.constBegin(); it != m_interfaces.constEnd(); ++it) {
            generateClass(*it);
        }
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
        generateEndNamespace();
        generateEndIncludeGuard();

        m_stream.setLocalData(nullptr);
        file.close();
    }));
}

void Generator::startGenerateCppFile()
{
    QFutureWatcher<void> *watcher = new QFutureWatcher<void>(this);
    connect(watcher, &QFutureWatcher<void>::finished, this, &Generator::checkEnd);
    m_finishedCounter++;
    watcher->setFuture(QtConcurrent::run([this] {
        QFile file(QStringLiteral("%1.cpp").arg(m_baseFileName));
        file.open(QIODevice::WriteOnly);
        m_stream.setLocalData(new QTextStream(&file));
394
        m_project.setLocalData(Project::Client);
395 396 397
        generateCopyrightHeader();
        generateCppIncludes();
        generateStartNamespace();
398 399 400
        for (auto it = m_interfaces.constBegin(); it != m_interfaces.constEnd(); ++it) {
            generatePrivateClass(*it);
            generateClientCpp(*it);
401
            generateClientCppRequests(*it);
402
        }
403 404 405 406 407 408 409 410

        generateEndNamespace();

        m_stream.setLocalData(nullptr);
        file.close();
    }));
}

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
void Generator::startGenerateServerHeaderFile()
{
    QFutureWatcher<void> *watcher = new QFutureWatcher<void>(this);
    connect(watcher, &QFutureWatcher<void>::finished, this, &Generator::checkEnd);
    m_finishedCounter++;
    watcher->setFuture(QtConcurrent::run([this] {
        QFile file(QStringLiteral("%1_interface.h").arg(m_baseFileName));
        file.open(QIODevice::WriteOnly);
        m_stream.setLocalData(new QTextStream(&file));
        m_project.setLocalData(Project::Server);
        generateCopyrightHeader();
        generateStartIncludeGuard();
        generateHeaderIncludes();
        generateStartNamespace();
        generateNamespaceForwardDeclarations();
        for (auto it = m_interfaces.constBegin(); it != m_interfaces.constEnd(); ++it) {
            generateClass(*it);
        }
        generateEndNamespace();
        generateEndIncludeGuard();

        m_stream.setLocalData(nullptr);
        file.close();
    }));
}

void Generator::startGenerateServerCppFile()
{
    QFutureWatcher<void> *watcher = new QFutureWatcher<void>(this);
    connect(watcher, &QFutureWatcher<void>::finished, this, &Generator::checkEnd);
    m_finishedCounter++;
    watcher->setFuture(QtConcurrent::run([this] {
        QFile file(QStringLiteral("%1_interface.cpp").arg(m_baseFileName));
        file.open(QIODevice::WriteOnly);
        m_stream.setLocalData(new QTextStream(&file));
        m_project.setLocalData(Project::Server);
        generateCopyrightHeader();
        generateCppIncludes();
        generateStartNamespace();
        for (auto it = m_interfaces.constBegin(); it != m_interfaces.constEnd(); ++it) {
            generatePrivateClass(*it);
//             generateClientCpp(*it);
//             generateClientCppRequests(*it);
        }

        generateEndNamespace();

        m_stream.setLocalData(nullptr);
        file.close();
    }));
}

463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
void Generator::checkEnd()
{
    m_finishedCounter--;
    if (m_finishedCounter == 0) {
        QCoreApplication::quit();
    }
}

void Generator::startAuthorNameProcess()
{
    QProcess *git = new QProcess(this);
    git->setArguments(QStringList{
        QStringLiteral("config"),
        QStringLiteral("--get"),
        QStringLiteral("user.name")
    });
    git->setProgram(QStringLiteral("git"));
    connect(git, static_cast<void (QProcess::*)(int)>(&QProcess::finished), this,
        [this, git] {
            QMutexLocker locker(&m_mutex);
            m_authorName = QString::fromLocal8Bit(git->readAllStandardOutput()).trimmed();
            git->deleteLater();
            m_waitCondition.wakeAll();
        }
    );
    git->start();
}

void Generator::startAuthorEmailProcess()
{
    QProcess *git = new QProcess(this);
    git->setArguments(QStringList{
        QStringLiteral("config"),
        QStringLiteral("--get"),
        QStringLiteral("user.email")
    });
    git->setProgram(QStringLiteral("git"));
    connect(git, static_cast<void (QProcess::*)(int)>(&QProcess::finished), this,
        [this, git] {
            QMutexLocker locker(&m_mutex);
            m_authorEmail = QString::fromLocal8Bit(git->readAllStandardOutput()).trimmed();
            git->deleteLater();
            m_waitCondition.wakeAll();
        }
    );
    git->start();
}

void Generator::generateCopyrightHeader()
{
    m_mutex.lock();
    while (m_authorEmail.isEmpty() || m_authorName.isEmpty()) {
        m_waitCondition.wait(&m_mutex);
    }
    m_mutex.unlock();
    const QString templateString = QStringLiteral(
"/****************************************************************************\n"
"Copyright %1  %2 <%3>\n"
"\n"
"This library is free software; you can redistribute it and/or\n"
"modify it under the terms of the GNU Lesser General Public\n"
"License as published by the Free Software Foundation; either\n"
"version 2.1 of the License, or (at your option) version 3, or any\n"
"later version accepted by the membership of KDE e.V. (or its\n"
"successor approved by the membership of KDE e.V.), which shall\n"
"act as a proxy defined in Section 6 of version 3 of the license.\n"
"\n"
"This library is distributed in the hope that it will be useful,\n"
"but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
"Lesser General Public License for more details.\n"
"\n"
"You should have received a copy of the GNU Lesser General Public\n"
"License along with this library.  If not, see <http://www.gnu.org/licenses/>.\n"
"****************************************************************************/\n"
);
    QDate date = QDate::currentDate();
    *m_stream.localData() << templateString.arg(date.year()).arg(m_authorName).arg(m_authorEmail);
}

void Generator::generateEndIncludeGuard()
{
    *m_stream.localData() << QStringLiteral("#endif\n");
}

void Generator::generateStartIncludeGuard()
{
    const QString templateString = QStringLiteral(
"#ifndef KWAYLAND_%1_%2_H\n"
"#define KWAYLAND_%1_%2_H\n\n");

554
    *m_stream.localData() << templateString.arg(projectToName().toUpper()).arg(m_baseFileName.toUpper());
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
}

void Generator::generateStartNamespace()
{
    const QString templateString = QStringLiteral(
"namespace KWayland\n"
"{\n"
"namespace %1\n"
"{\n\n");
    *m_stream.localData() << templateString.arg(projectToName());
}

void Generator::generateEndNamespace()
{
    *m_stream.localData() << QStringLiteral("\n}\n}\n\n");
}

void Generator::generateHeaderIncludes()
{
574
    switch (m_project.localData()) {
575 576 577 578
    case Project::Client:
        *m_stream.localData() << QStringLiteral("#include <QObject>\n\n");
        break;
    case Project::Server:
579 580 581
        *m_stream.localData() << QStringLiteral(
"#include \"global.h\"\n"
"#include \"resource.h\"\n\n");
582 583 584 585 586 587 588 589 590
        break;
    default:
        Q_UNREACHABLE();
    }
    *m_stream.localData() << QStringLiteral("#include <KWayland/%1/kwayland%2_export.h>\n\n").arg(projectToName()).arg(projectToName().toLower());
}

void Generator::generateCppIncludes()
{
591
    switch (m_project.localData()) {
592
    case Project::Client:
593
        *m_stream.localData() << QStringLiteral("#include \"%1.h\"\n").arg(m_baseFileName.toLower());
594
        *m_stream.localData() << QStringLiteral("#include \"event_queue.h\"\n");
595
        *m_stream.localData() << QStringLiteral("#include \"wayland_pointer_p.h\"\n\n");
596 597
        break;
    case Project::Server:
598 599 600 601 602
        *m_stream.localData() << QStringLiteral("#include \"%1_interface.h\"\n").arg(m_baseFileName.toLower());
        *m_stream.localData() << QStringLiteral(
"#include \"display.h\"\n"
"#include \"global_p.h\"\n"
"#include \"resource_p.h\"\n\n");
603 604 605 606 607 608
        break;
    default:
        Q_UNREACHABLE();
    }
}

609
void Generator::generateClass(const Interface &interface)
610
{
611
    switch (m_project.localData()) {
612
    case Project::Client:
613 614 615 616 617
        if (interface.isGlobal()) {
            generateClientGlobalClass(interface);
        } else {
            generateClientResourceClass(interface);
        }
618 619
        break;
    case Project::Server:
620 621 622 623 624
        if (interface.isGlobal()) {
            generateServerGlobalClass(interface);
        } else {
            generateServerResourceClass(interface);
        }
625 626 627 628 629 630
        break;
    default:
        Q_UNREACHABLE();
    }
}

631 632 633 634 635 636 637 638 639
void Generator::generateClientGlobalClass(const Interface &interface)
{
    generateClientGlobalClassDoxy(interface);
    generateClientClassQObjectDerived(interface);
    generateClientGlobalClassCtor(interface);
    generateClientClassDtor(interface);
    generateClientGlobalClassSetup(interface);
    generateClientClassReleaseDestroy(interface);
    generateClientClassStart(interface);
640
    generateClientClassRequests(interface);
641 642 643 644 645 646 647 648 649 650 651
    generateClientClassCasts(interface);
    generateClientClassSignals(interface);
    generateClientGlobalClassEnd(interface);
}

void Generator::generateClientResourceClass(const Interface &interface)
{
    generateClientClassQObjectDerived(interface);
    generateClientClassDtor(interface);
    generateClientResourceClassSetup(interface);
    generateClientClassReleaseDestroy(interface);
652
    generateClientClassRequests(interface);
653 654 655 656
    generateClientClassCasts(interface);
    generateClientResourceClassEnd(interface);
}

657 658 659 660 661 662 663 664 665 666 667 668 669
void Generator::generateServerGlobalClass(const Interface &interface)
{
    const QString templateString = QStringLiteral(
"class KWAYLANDSERVER_EXPORT %1 : public Global\n"
"{\n"
"    Q_OBJECT\n"
"public:\n"
"    virtual ~%1();\n"
"\n"
"private:\n"
"    explicit %1(Display *display, QObject *parent = nullptr);\n"
"    friend class Display;\n"
"    class Private;\n"
670
"};\n"
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
"\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandServerName());
}

void Generator::generateServerResourceClass(const Interface &interface)
{
    const QString templateString = QStringLiteral(
"class KWAYLANDSERVER_EXPORT %1 : public Resource\n"
"{\n"
"    Q_OBJECT\n"
"public:\n"
"    virtual ~%1();\n"
"\n"
"private:\n"
"    explicit %1(%2 *parent, wl_resource *parentResource);\n"
"    friend class %2;\n"
"\n"
"    class Private;\n"
"    Private *d_func() const;\n"
690
"};\n"
691 692 693 694
"\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandServerName()).arg(interface.factory()->kwaylandServerName());
}

695
void Generator::generatePrivateClass(const Interface &interface)
696
{
697
    switch (m_project.localData()) {
698
    case Project::Client:
699
        generateClientPrivateClass(interface);
700 701
        break;
    case Project::Server:
702 703 704 705 706
        if (interface.isGlobal()) {
            generateServerPrivateGlobalClass(interface);
        } else {
            generateServerPrivateResourceClass(interface);
        }
707 708 709 710 711 712
        break;
    default:
        Q_UNREACHABLE();
    }
}

713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
void Generator::generateServerPrivateGlobalClass(const Interface &interface)
{
    QString templateString = QStringLiteral(
"class %1::Private : public Global::Private\n"
"{\n"
"public:\n"
"    Private(%1 *q, Display *d);\n"
"\n"
"private:\n"
"    void bind(wl_client *client, uint32_t version, uint32_t id) override;\n"
"\n"
"    static void unbind(wl_resource *resource);\n"
"    static Private *cast(wl_resource *r) {\n"
"        return reinterpret_cast<Private*>(wl_resource_get_user_data(r));\n"
"    }\n"
"\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandServerName());

    generateServerPrivateCallbackDefinitions(interface);

    templateString = QStringLiteral(
"    %1 *q;\n"
"    static const struct %2_interface s_interface;\n"
736
"    static const quint32 s_version;\n"
737
"};\n"
738 739
"\n"
"const quint32 %1::Private::s_version = %3;\n"
740 741 742 743 744 745 746 747 748 749
"\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandServerName()).arg(interface.name()).arg(interface.version());
    generateServerPrivateInterfaceClass(interface);
    generateServerPrivateCallbackImpl(interface);
    generateServerPrivateGlobalCtorBindClass(interface);
}

void Generator::generateServerPrivateCallbackDefinitions(const Interface &interface)
{
    for (const auto &r: interface.requests()) {
750 751 752
        if (r.isDestructor() && !interface.isGlobal()) {
            continue;
        }
753 754 755 756 757 758 759 760 761 762 763 764
        *m_stream.localData() << QStringLiteral("    static void %1Callback(wl_client *client, wl_resource *resource").arg(toCamelCase(r.name()));
        for (const auto &a: r.arguments()) {
            *m_stream.localData() << QStringLiteral(", %1 %2").arg(a.typeAsServerWl()).arg(a.name());
        }
        *m_stream.localData() << QStringLiteral(");\n");
    }
    *m_stream.localData() << QStringLiteral("\n");
}

void Generator::generateServerPrivateCallbackImpl(const Interface &interface)
{
    for (const auto &r: interface.requests()) {
765 766 767
        if (r.isDestructor() && !interface.isGlobal()) {
            continue;
        }
768 769 770 771 772 773
        *m_stream.localData() << QStringLiteral("void %2::Private::%1Callback(wl_client *client, wl_resource *resource").arg(toCamelCase(r.name())).arg(interface.kwaylandServerName());
        for (const auto &a: r.arguments()) {
            *m_stream.localData() << QStringLiteral(", %1 %2").arg(a.typeAsServerWl()).arg(a.name());
        }
        *m_stream.localData() << QStringLiteral(
")\n"
774 775 776 777 778 779 780 781 782
"{\n");
        if (r.isDestructor()) {
            *m_stream.localData() << QStringLiteral(
"    Q_UNUSED(client)\n"
"    wl_resource_destroy(resource);\n");
        } else {
            *m_stream.localData() << QStringLiteral("    // TODO: implement\n");
        }
        *m_stream.localData() << QStringLiteral(
783 784 785 786 787 788 789 790 791
"}\n"
"\n");
    }
}

void Generator::generateServerPrivateGlobalCtorBindClass(const Interface &interface)
{
    QString templateString = QStringLiteral(
"%1::Private::Private(%1 *q, Display *d)\n"
792
"    : Global::Private(d, &%2_interface, s_version)\n"
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
"    , q(q)\n"
"{\n"
"}\n"
"\n"
"void %1::Private::bind(wl_client *client, uint32_t version, uint32_t id)\n"
"{\n"
"    auto c = display->getConnection(client);\n"
"    wl_resource *resource = c->createResource(&%2_interface, qMin(version, s_version), id);\n"
"    if (!resource) {\n"
"        wl_client_post_no_memory(client);\n"
"        return;\n"
"    }\n"
"    wl_resource_set_implementation(resource, &s_interface, this, unbind);\n"
"    // TODO: should we track?\n"
"}\n"
"\n"
"void %1::Private::unbind(wl_resource *resource)\n"
"{\n"
"    Q_UNUSED(resource)\n"
"    // TODO: implement?\n"
"}\n"
"\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandServerName()).arg(interface.name());
}

void Generator::generateServerPrivateResourceClass(const Interface &interface)
{
    QString templateString = QStringLiteral(
"class %1::Private : public Resource::Private\n"
"{\n"
"public:\n"
"    Private(%1 *q, %2 *c, wl_resource *parentResource);\n"
"    ~Private();\n"
"\n"
"private:\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandServerName()).arg(interface.factory()->kwaylandServerName());

    generateServerPrivateCallbackDefinitions(interface);

    templateString = QStringLiteral(
"    %1 *q_func() {\n"
"        return reinterpret_cast<%1 *>(q);\n"
"    }\n"
"\n"
"    static const struct %2_interface s_interface;\n"
838
"};\n"
839 840 841 842 843 844 845 846 847 848
"\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandServerName()).arg(interface.name());

    generateServerPrivateInterfaceClass(interface);
    generateServerPrivateCallbackImpl(interface);
    generateServerPrivateResourceCtorDtorClass(interface);
}

void Generator::generateServerPrivateInterfaceClass(const Interface &interface)
{
Martin Flöser's avatar
Martin Flöser committed
849
    *m_stream.localData() << QStringLiteral("#ifndef DOXYGEN_SHOULD_SKIP_THIS\n");
850 851 852 853 854 855 856 857
    *m_stream.localData() << QStringLiteral("const struct %2_interface %1::Private::s_interface = {\n").arg(interface.kwaylandServerName()).arg(interface.name());
    bool first = true;
    for (auto r: interface.requests()) {
        if (!first) {
            *m_stream.localData() << QStringLiteral(",\n");
        } else {
            first = false;
        }
858 859 860 861 862
        if (r.isDestructor() && !interface.isGlobal()) {
            *m_stream.localData() << QStringLiteral("    resourceDestroyedCallback");
        } else {
            *m_stream.localData() << QStringLiteral("    %1Callback").arg(toCamelCase(r.name()));
        }
863
    }
Martin Flöser's avatar
Martin Flöser committed
864
    *m_stream.localData() << QStringLiteral("\n};\n#endif\n\n");
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
}

void Generator::generateServerPrivateResourceCtorDtorClass(const Interface &interface)
{
    QString templateString = QStringLiteral(
"%1::Private::Private(%1 *q, %2 *c, wl_resource *parentResource)\n"
"    : Resource::Private(q, c, parentResource, &%3_interface, &s_interface)\n"
"{\n"
"}\n"
"\n"
"%1::Private::~Private()\n"
"{\n"
"    if (resource) {\n"
"        wl_resource_destroy(resource);\n"
"        resource = nullptr;\n"
"    }\n"
"}\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandServerName()).arg(interface.factory()->kwaylandServerName()).arg(interface.name());
}

885
void Generator::generateClientPrivateClass(const Interface &interface)
886 887 888 889 890 891 892 893 894
{
    if (interface.isGlobal()) {
        generateClientPrivateGlobalClass(interface);
    } else {
        generateClientPrivateResourceClass(interface);
    }
}

void Generator::generateClientPrivateResourceClass(const Interface &interface)
895 896 897 898 899
{
    const QString templateString = QStringLiteral(
"class %1::Private\n"
"{\n"
"public:\n"
900
"    Private(%1 *q);\n"
901
"\n"
902 903 904
"    void setup(%2 *arg);\n"
"\n"
"    WaylandPointer<%2, %2_destroy> %3;\n"
905 906 907
"\n"
"private:\n"
"    %1 *q;\n"
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
"};\n\n");

    *m_stream.localData() << templateString.arg(interface.kwaylandClientName()).arg(interface.name()).arg(interface.kwaylandClientName().toLower());
}

void Generator::generateClientPrivateGlobalClass(const Interface &interface)
{
    const QString templateString = QStringLiteral(
"class %1::Private\n"
"{\n"
"public:\n"
"    Private() = default;\n"
"\n"
"    void setup(%2 *arg);\n"
"\n"
"    WaylandPointer<%2, %2_destroy> %3;\n"
"    EventQueue *queue = nullptr;\n"
"};\n\n");
926

927
    *m_stream.localData() << templateString.arg(interface.kwaylandClientName()).arg(interface.name()).arg(interface.kwaylandClientName().toLower());
928 929
}

930
void Generator::generateClientCpp(const Interface &interface)
931
{
932 933 934
    if (interface.isGlobal()) {
        // generate ctor without this pointer to Private
        const QString templateString = QStringLiteral(
935 936 937 938
"%1::%1(QObject *parent)\n"
"    : QObject(parent)\n"
"    , d(new Private)\n"
"{\n"
939 940 941 942 943 944 945 946
"}\n");
        *m_stream.localData() << templateString.arg(interface.kwaylandClientName());
    } else {
        // Private ctor
        const QString templateString = QStringLiteral(
"%1::Private::Private(%1 *q)\n"
"    : q(q)\n"
"{\n"
947 948
"}\n"
"\n"
949 950 951 952 953 954 955 956 957
"%1::%1(QObject *parent)\n"
"    : QObject(parent)\n"
"    , d(new Private(this))\n"
"{\n"
"}\n");
        *m_stream.localData() << templateString.arg(interface.kwaylandClientName());
    }
    const QString templateString = QStringLiteral(
"\n"
958 959 960 961 962
"%1::~%1()\n"
"{\n"
"    release();\n"
"}\n"
"\n"
963 964 965 966 967 968 969
"void %1::Private::setup(%3 *arg)\n"
"{\n"
"    Q_ASSERT(arg);\n"
"    Q_ASSERT(!%2);\n"
"    %2.setup(arg);\n"
"}\n"
"\n"
970 971
"void %1::setup(%3 *%2)\n"
"{\n"
972
"    d->setup(%2);\n"
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
"}\n"
"\n"
"void %1::release()\n"
"{\n"
"    d->%2.release();\n"
"}\n"
"\n"
"void %1::destroy()\n"
"{\n"
"    d->%2.destroy();\n"
"}\n"
"\n"
"%1::operator %3*() {\n"
"    return d->%2;\n"
"}\n"
"\n"
"%1::operator %3*() const {\n"
"    return d->%2;\n"
"}\n"
"\n"
"bool %1::isValid() const\n"
"{\n"
"    return d->%2.isValid();\n"
"}\n\n");

998 999 1000
    *m_stream.localData() << templateString.arg(interface.kwaylandClientName())
                                           .arg(interface.kwaylandClientName().toLower())
                                           .arg(interface.name());
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    if (interface.isGlobal()) {
        const QString templateStringGlobal = QStringLiteral(
"void %1::setEventQueue(EventQueue *queue)\n"
"{\n"
"    d->queue = queue;\n"
"}\n"
"\n"
"EventQueue *%1::eventQueue()\n"
"{\n"
"    return d->queue;\n"
"}\n\n"
        );
        *m_stream.localData() << templateStringGlobal.arg(interface.kwaylandClientName());
    }
1015 1016
}

1017
void Generator::generateClientGlobalClassDoxy(const Interface &interface)
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
{
    const QString templateString = QStringLiteral(
"/**\n"
" * @short Wrapper for the %2 interface.\n"
" *\n"
" * This class provides a convenient wrapper for the %2 interface.\n"
" *\n"
" * To use this class one needs to interact with the Registry. There are two\n"
" * possible ways to create the %1 interface:\n"
" * @code\n"
" * %1 *c = registry->create%1(name, version);\n"
" * @endcode\n"
" *\n"
" * This creates the %1 and sets it up directly. As an alternative this\n"
" * can also be done in a more low level way:\n"
" * @code\n"
" * %1 *c = new %1;\n"
" * c->setup(registry->bind%1(name, version));\n"
" * @endcode\n"
" *\n"
" * The %1 can be used as a drop-in replacement for any %2\n"
" * pointer as it provides matching cast operators.\n"
" *\n"
" * @see Registry\n"
1042 1043 1044 1045 1046 1047 1048 1049
" **/\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandClientName()).arg(interface.name());
}

void Generator::generateClientClassQObjectDerived(const Interface &interface)
{
    const QString templateString = QStringLiteral(
"class KWAYLANDCLIENT_EXPORT %1 : public QObject\n"
1050 1051
"{\n"
"    Q_OBJECT\n"
1052 1053 1054 1055 1056 1057 1058
"public:\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandClientName());
}

void Generator::generateClientGlobalClassCtor(const Interface &interface)
{
    const QString templateString = QStringLiteral(
1059 1060 1061 1062 1063 1064
"    /**\n"
"     * Creates a new %1.\n"
"     * Note: after constructing the %1 it is not yet valid and one needs\n"
"     * to call setup. In order to get a ready to use %1 prefer using\n"
"     * Registry::create%1.\n"
"     **/\n"
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
"    explicit %1(QObject *parent = nullptr);\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandClientName());
}

void Generator::generateClientClassDtor(const Interface &interface)
{
    *m_stream.localData() << QStringLiteral("    virtual ~%1();\n\n").arg(interface.kwaylandClientName());
}

void Generator::generateClientClassReleaseDestroy(const Interface &interface)
{
    const QString templateString = QStringLiteral(
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
"    /**\n"
"     * @returns @c true if managing a %2.\n"
"     **/\n"
"    bool isValid() const;\n"
"    /**\n"
"     * Releases the %2 interface.\n"
"     * After the interface has been released the %1 instance is no\n"
"     * longer valid and can be setup with another %2 interface.\n"
"     **/\n"
"    void release();\n"
"    /**\n"
Martin Flöser's avatar
Martin Flöser committed
1088
"     * Destroys the data held by this %1.\n"
1089
"     * This method is supposed to be used when the connection to the Wayland\n"
Martin Flöser's avatar
Martin Flöser committed
1090 1091
"     * server goes away. If the connection is not valid anymore, it's not\n"
"     * possible to call release anymore as that calls into the Wayland\n"
1092
"     * connection and the call would fail. This method cleans up the data, so\n"
Martin Flöser's avatar
Martin Flöser committed
1093
"     * that the instance can be deleted or set up to a new %2 interface\n"
1094 1095 1096 1097
"     * once there is a new connection available.\n"
"     *\n"
"     * It is suggested to connect this method to ConnectionThread::connectionDied:\n"
"     * @code\n"
1098
"     * connect(connection, &ConnectionThread::connectionDied, %3, &%1::destroy);\n"
1099 1100 1101 1102 1103
"     * @endcode\n"
"     *\n"
"     * @see release\n"
"     **/\n"
"    void destroy();\n"
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
"\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandClientName()).arg(interface.name()).arg(interface.kwaylandClientName().toLower());
}

void Generator::generateClientGlobalClassSetup(const Interface &interface)
{
    const QString templateString = QStringLiteral(
"    /**\n"
"     * Setup this %1 to manage the @p %3.\n"
"     * When using Registry::create%1 there is no need to call this\n"
"     * method.\n"
"     **/\n"
"    void setup(%2 *%3);\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandClientName()).arg(interface.name()).arg(interface.kwaylandClientName().toLower());
}

void Generator::generateClientResourceClassSetup(const Interface &interface)
{
    const QString templateString = QStringLiteral(
"    /**\n"
"     * Setup this %1 to manage the @p %3.\n"
"     * When using %4::create%1 there is no need to call this\n"
"     * method.\n"
"     **/\n"
"    void setup(%2 *%3);\n");
    *m_stream.localData() << templateString.arg(interface.kwaylandClientName())
                                           .arg(interface.name())
                                           .arg(interface.kwaylandClientName().toLower())
                                           .arg(interface.factory()->kwaylandClientName());

}

void Generator::generateClientClassStart(const Interface &interface)
{
    const QString templateString = QStringLiteral(
1139 1140 1141 1142 1143 1144 1145 1146
"    /**\n"
"     * Sets the @p queue to use for creating objects with this %1.\n"
"     **/\n"
"    void setEventQueue(EventQueue *queue);\n"
"    /**\n"
"     * @returns The event queue to use for creating objects with this %1.\n"
"     **/\n"
"    EventQueue *eventQueue();\n\n");
1147
    *m_stream.localData() << templateString.arg(interface.kwaylandClientName());
1148 1149
}

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
void Generator::generateClientClassRequests(const Interface &interface)
{
    const auto requests = interface.requests();
    const QString templateString = QStringLiteral("    void %1(%2);\n\n");
    const QString factoryTemplateString = QStringLiteral("    %1 *%2(%3);\n\n");
    for (const auto &r: requests) {
        if (r.isDestructor()) {
            continue;
        }
        QString arguments;
        bool first = true;
        QString factored;
        for (const auto &a: r.arguments()) {
            if (a.type() == Argument::Type::NewId) {
                factored = a.interface();
                continue;
            }
            if (!first) {
                arguments.append(QStringLiteral(", "));
            } else {
                first = false;
            }
            if (a.type() == Argument::Type::Object) {
1173
                arguments.append(QStringLiteral("%1 *%2").arg(a.typeAsQt()).arg(toCamelCase(a.name())));
1174
            } else {
1175
                arguments.append(QStringLiteral("%1 %2").arg(a.typeAsQt()).arg(toCamelCase(a.name())));
1176 1177 1178
            }
        }
        if (factored.isEmpty()) {
1179
            *m_stream.localData() << templateString.arg(toCamelCase((r.name()))).arg(arguments);
1180 1181 1182 1183 1184
        } else {
            if (!first) {
                arguments.append(QStringLiteral(", "));
            }
            arguments.append(QStringLiteral("QObject *parent = nullptr"));
1185
            *m_stream.localData() << factoryTemplateString.arg(toQtInterfaceName(factored)).arg(toCamelCase(r.name())).arg(arguments);
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
        }
    }
}

void Generator::generateClientCppRequests(const Interface &interface)
{
    const auto requests = interface.requests();
    const QString templateString = QStringLiteral("void %1::%2(%3)\n");
    const QString factoryTemplateString = QStringLiteral("%2 *%1::%3(%4)\n");
    for (const auto &r: requests) {
        if (r.isDestructor()) {
            continue;
        }
        QString arguments;
        bool first = true;
        QString factored;
        for (const auto &a: r.arguments()) {
            if (a.type() == Argument::Type::NewId) {
                factored = a.interface();
                continue;
            }
            if (!first) {
                arguments.append(QStringLiteral(", "));
            } else {
                first = false;
            }
            if (a.type() == Argument::Type::Object) {
1213
                arguments.append(QStringLiteral("%1 *%2").arg(a.typeAsQt()).arg(toCamelCase(a.name())));
1214
            } else {
1215
                arguments.append(QStringLiteral("%1 %2").arg(a.typeAsQt()).arg(toCamelCase(a.name())));
1216 1217 1218
            }
        }
        if (factored.isEmpty()) {
1219
            *m_stream.localData() << templateString.arg(interface.kwaylandClientName()).arg(toCamelCase(r.name())).arg(arguments);
1220 1221 1222 1223 1224
        } else {
            if (!first) {
                arguments.append(QStringLiteral(", "));
            }
            arguments.append(QStringLiteral("QObject *parent"));
1225
            *m_stream.localData() << factoryTemplateString.arg(interface.kwaylandClientName()).arg(toQtInterfaceName(factored)).arg(toCamelCase(r.name())).arg(arguments);
1226 1227 1228 1229 1230
        }
        *m_stream.localData() << QStringLiteral("{\n}\n\n");
    }
}

1231
void Generator::generateClientClassCasts(const Interface &interface)
1232 1233 1234 1235
{
    const QString templateString = QStringLiteral(
"    operator %1*();\n"
"    operator %1*() const;\n\n");
1236
    *m_stream.localData() << templateString.arg(interface.name());
1237 1238
}

1239
void Generator::generateClientGlobalClassEnd(const Interface &interface)
1240
{
1241 1242 1243 1244 1245 1246 1247 1248 1249
    Q_UNUSED(interface)
    *m_stream.localData() << QStringLiteral("private:\n");
    generateClientClassDptr(interface);
    *m_stream.localData() << QStringLiteral("};\n\n");
}

void Generator::generateClientClassDptr(const Interface &interface)
{
    Q_UNUSED(interface)
1250 1251
    *m_stream.localData() << QStringLiteral(
"    class Private;\n"
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
"    QScopedPointer<Private> d;\n");
}

void Generator::generateClientResourceClassEnd(const Interface &interface)
{
    *m_stream.localData() << QStringLiteral(
"private:\n"
"    friend class %2;\n"
"    explicit %1(QObject *parent = nullptr);\n"
    ).arg(interface.kwaylandClientName()).arg(interface.factory()->kwaylandClientName());
    generateClientClassDptr(interface);
    *m_stream.localData() << QStringLiteral("};\n\n");
1264 1265 1266 1267
}

void Generator::generateWaylandForwardDeclarations()
{
1268 1269 1270 1271
    for (auto it = m_interfaces.constBegin(); it != m_interfaces.constEnd(); ++it) {
        *m_stream.localData() << QStringLiteral("struct %1;\n").arg((*it).name());
    }
    *m_stream.localData() << "\n";
1272 1273 1274 1275
}

void Generator::generateNamespaceForwardDeclarations()
{
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
    QSet<QString> referencedObjects;
    for (auto it = m_interfaces.constBegin(); it != m_interfaces.constEnd(); ++it) {
        const auto events = (*it).events();
        const auto requests = (*it).requests();
        for (const auto &e: events) {
            const auto args = e.arguments();
            for (const auto &a: args) {
                if (a.type() != Argument::Type::Object && a.type() != Argument::Type::NewId) {
                    continue;
                }
                referencedObjects << a.interface();
            }
        }
        for (const auto &r: requests) {
            const auto args = r.arguments();
            for (const auto &a: args) {
                if (a.type() != Argument::Type::Object && a.type() != Argument::Type::NewId) {
                    continue;
                }
                referencedObjects << a.interface();
            }
        }
    }

1300
    switch (m_project.localData()) {
1301
    case Project::Client:
1302 1303 1304 1305 1306 1307
        *m_stream.localData() << QStringLiteral("class EventQueue;\n");
        for (const auto &o : referencedObjects) {
            auto it = s_clientClassNameMapping.constFind(o);
            if (it != s_clientClassNameMapping.constEnd()) {
                *m_stream.localData() << QStringLiteral("class %1;\n").arg(it.value());
            } else {
1308
                qWarning() << "Cannot forward declare KWayland class for interface " << o;
1309 1310 1311
            }
        }
        *m_stream.localData() << QStringLiteral("\n");
1312 1313
        break;
    case Project::Server:
1314
        *m_stream.localData() << QStringLiteral("class Display;\n\n");
1315 1316 1317 1318 1319 1320
        break;
    default:
        Q_UNREACHABLE();
    }
}

1321
void Generator::generateClientClassSignals(const Interface &interface)
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
{
    const QString templateString = QStringLiteral(
"Q_SIGNALS:\n"
"    /**\n"
"     * The corresponding global for this interface on the Registry got removed.\n"
"     *\n"
"     * This signal gets only emitted if the %1 got created by\n"
"     * Registry::create%1\n"
"     **/\n"
"    void removed();\n\n");
1332
    *m_stream.localData() << templateString.arg(interface.kwaylandClientName());
1333 1334 1335 1336
}

QString Generator::projectToName() const
{
1337
    switch (m_project.localData()) {
1338 1339 1340 1341 1342 1343 1344 1345 1346
    case Project::Client:
        return QStringLiteral("Client");
    case Project::Server:
        return QStringLiteral("Server");
    default:
        Q_UNREACHABLE();
    }
}

1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
static void parseMapping()
{
    QFile mappingFile(QStringLiteral(MAPPING_FILE));
    mappingFile.open(QIODevice::ReadOnly);
    QTextStream stream(&mappingFile);
    while (!stream.atEnd()) {
        QString line = stream.readLine();
        if (line.startsWith(QLatin1String("#")) || line.isEmpty()) {
            continue;
        }
        const QStringList parts = line.split(QStringLiteral(";"));
        if (parts.count() < 2) {
            continue;
        }
        s_clientClassNameMapping.insert(parts.first(), parts.at(1));
    }
}

1365 1366 1367 1368 1369 1370
}
}

int main(int argc, char **argv)
{
    using namespace KWayland::Tools;
1371 1372 1373

    parseMapping();

1374 1375 1376
    QCoreApplication app(argc, argv);

    QCommandLineParser parser;
1377 1378 1379
    QCommandLineOption xmlFile(QStringList{QStringLiteral("x"), QStringLiteral("xml")},
                               QStringLiteral("The wayland protocol to parse."),
                               QStringLiteral("FileName"));
1380
    QCommandLineOption fileName(QStringList{QStringLiteral("f"), QStringLiteral("file")},
1381 1382
                                QStringLiteral("The base name of files to be generated. E.g. for \"foo\" the files \"foo.h\" and \"foo.cpp\" are generated."
                                               "If not provided the base name gets derived from the xml protocol name"),
1383 1384 1385
                                QStringLiteral("FileName"));

    parser.addHelpOption();
1386
    parser.addOption(xmlFile);
1387 1388 1389 1390 1391
    parser.addOption(fileName);

    parser.process(app);

    Generator generator(&app);
1392
    generator.setXmlFileName(parser.value(xmlFile));
1393 1394 1395 1396 1397
    generator.setBaseFileName(parser.value(fileName));
    generator.start();

    return app.exec();
}