In questa pagina

CPP minimale

Minimal CPP è un esempio che illustra come scrivere un compositore Wayland in C++.

Minimal CPP è un esempio minimalista di compositore che implementa un compositore completo ( Qt Wayland Compositor ) utilizzando il C++. L'API C++ di QtWaylandCompositor è di basso livello e destinata ad applicazioni specializzate, come il supporto di funzionalità hardware, oppure nel caso in cui Qt Quick non sia disponibile. L'API QML offre maggiore praticità e funzionalità. A titolo di confronto, l’esempio Minimal QML implementa più funzionalità con 30 righe di QML rispetto a quanto fa questo esempio in oltre 300 righe.

Finestra di composizione con più superfici client

Questo esempio è suddiviso in due parti. La logica relativa a Wayland è contenuta nella classe ` Compositor `, mentre l’interfaccia utente si trova nella classe ` Window `.

Finestra

La classe ` Window ` è piuttosto semplice. Per visualizzare le superfici Wayland, esegue un'iterazione sulle viste del compositore e le rende sullo schermo utilizzando ` QOpenGLTextureBlitter`:

void Window::paintGL()
{
    m_compositor->startRender();

    QOpenGLFunctions *functions = context()->functions();
    functions->glClearColor(.4f, .7f, .1f, 0.5f);
    functions->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    GLenum currentTarget = GL_TEXTURE_2D;
    m_textureBlitter.bind(currentTarget);
    functions->glEnable(GL_BLEND);
    functions->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    const auto views = m_compositor->views();
    for (View *view : views) {
        auto texture = view->getTexture();
        if (!texture)
            continue;
        if (texture->target() != currentTarget) {
            currentTarget = texture->target();
            m_textureBlitter.bind(currentTarget);
        }
        GLuint textureId = texture->textureId();
        QWaylandSurface *surface = view->surface();
        if (surface && surface->hasContent()) {
            QSize s = surface->destinationSize();
            view->initPosition(size(), s);
            QPointF pos = view->globalPosition();
            QRectF surfaceGeometry(pos, s);
            QOpenGLTextureBlitter::Origin surfaceOrigin =
                    view->currentBuffer().origin() == QWaylandSurface::OriginTopLeft
                    ? QOpenGLTextureBlitter::OriginTopLeft
                    : QOpenGLTextureBlitter::OriginBottomLeft;
            QMatrix4x4 targetTransform = QOpenGLTextureBlitter::targetTransform(surfaceGeometry, QRect(QPoint(), size()));
            m_textureBlitter.blit(textureId, targetTransform, surfaceOrigin);
        }
    }
    m_textureBlitter.release();
    m_compositor->endRender();
}

Tutti gli eventi di tastiera e mouse vengono inoltrati al compositore. Ad esempio:

void Window::mousePressEvent(QMouseEvent *event)
{
    m_compositor->handleMousePress(event->position().toPoint(), event->button());
}

Compositor

La classe ` Compositor ` è più complessa, poiché deve implementare gran parte della logica che in un compositore basato su QML sarebbe gestita da ` WaylandCompositor ` e ` WaylandQuickItem `.

La funzione ` create ` configura il compositore utilizzando ` IviApplication`, che rappresenta l'estensione della shell più basilare. La funzione viene chiamata dopo l'inizializzazione del contesto OpenGL:

void Compositor::create()
{
    QWaylandOutput *output = new QWaylandOutput(this, m_window);
    QWaylandOutputMode mode(m_window->size(), 60000);
    output->addMode(mode, true);
    QWaylandCompositor::create();
    output->setCurrentMode(mode);

    m_iviApplication = new QWaylandIviApplication(this);
    connect(m_iviApplication, &QWaylandIviApplication::iviSurfaceCreated, this, &Compositor::onIviSurfaceCreated);
}

Tutta la logica relativa agli eventi del mouse e al focus della tastiera deve essere implementata manualmente, compresi i "grab" impliciti del mouse (l'invio di tutti i movimenti del mouse alla superficie che ha ricevuto la pressione iniziale del mouse). Si noti che gli eventi di pressione del mouse nel protocollo Wayland non contengono la posizione del mouse, quindi dobbiamo sempre inviare un movimento del mouse quando riceviamo una pressione del mouse:

void Compositor::handleMousePress(const QPoint &position, Qt::MouseButton button)
{
    if (!m_mouseView) {
        if ((m_mouseView = viewAt(position)))
            raise(m_mouseView);
    }
    auto *seat = defaultSeat();
    seat->sendMouseMoveEvent(m_mouseView, mapToView(m_mouseView, position));
    seat->sendMousePressEvent(button);
}

Per il rilascio del mouse, terminiamo il "grab" implicito e notifichiamo alla superficie la posizione corrente del mouse:

void Compositor::handleMousePress(const QPoint &position, Qt::MouseButton button)
{
    if (!m_mouseView) {
        if ((m_mouseView = viewAt(position)))
            raise(m_mouseView);
    }
    auto *seat = defaultSeat();
    seat->sendMouseMoveEvent(m_mouseView, mapToView(m_mouseView, position));
    seat->sendMousePressEvent(button);
}

Quando riceviamo la notifica di una nuova superficie, creiamo un ` View ` per tenerne traccia e colleghiamo i segnali in modo da poter gestire gli aggiornamenti.

void Compositor::onIviSurfaceCreated(QWaylandIviSurface *iviSurface)
{
    View *view = new View(iviSurface->iviId());
    view->setSurface(iviSurface->surface());
    view->setOutput(outputFor(m_window));

    m_views << view;
    connect(view, &QWaylandView::surfaceDestroyed, this, &Compositor::viewSurfaceDestroyed);
    connect(iviSurface->surface(), &QWaylandSurface::redraw, this, &Compositor::triggerRender);
}

La classe ` View ` è una sottoclasse di ` QWaylandView`, che rappresenta una vista specifica di una superficie. La funzione ` advance ` aggiorna il buffer corrente della vista e restituisce `true` se è presente nuovo contenuto. La funzione ` getTexture ` rende il contenuto del buffer disponibile come texture OpenGL a beneficio della classe ` Window `:

QOpenGLTexture *View::getTexture() {
    if (advance())
        m_texture = currentBuffer().toOpenGLTexture();
    return m_texture;
}

Progetto di esempio su code.qt.io

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.