summaryrefslogtreecommitdiffstats
path: root/src/opengl/qwindowsurface_gl.cpp
blob: a59501c568a3a2a0a7066550dbfc411bb6d07395 (plain)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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
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
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
323
324
325
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
358
359
360
361
362
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
405
406
407
408
409
410
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
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights.  These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui/QApplication>
#include <QtGui/QColormap>
#include <QtGui/QDesktopWidget>
#include <QtGui/QPaintDevice>
#include <QtGui/QWidget>

#include <qglframebufferobject.h>
#include <qglpixelbuffer.h>
#include <qcolormap.h>
#include <qdesktopwidget.h>
#include "qdebug.h"

#ifdef Q_WS_X11
#include <private/qt_x11_p.h>
#include <qx11info_x11.h>
#include <private/qwidget_p.h>

#ifndef QT_OPENGL_ES
#include <GL/glx.h>
#include <X11/Xlib.h>
#endif
#endif //Q_WS_X11

#include <private/qglextensions_p.h>
#include <private/qwindowsurface_gl_p.h>

#include <private/qgl_p.h>

#include <private/qglpixelbuffer_p.h>
#include <private/qgraphicssystem_gl_p.h>

#include <private/qpaintengineex_opengl2_p.h>

#ifndef QT_OPENGL_ES_2
#include <private/qpaintengine_opengl_p.h>
#endif

#ifndef GLX_ARB_multisample
#define GLX_SAMPLE_BUFFERS_ARB  100000
#define GLX_SAMPLES_ARB         100001
#endif

#ifdef QT_OPENGL_ES_1_CL
#include "qgl_cl_p.h"
#endif

QT_BEGIN_NAMESPACE

//
// QGLGraphicsSystem
//
#ifdef Q_WS_WIN
extern Q_GUI_EXPORT bool qt_win_owndc_required;
#endif
QGLGraphicsSystem::QGLGraphicsSystem()
    : QGraphicsSystem()
{
#if defined(Q_WS_X11) && !defined(QT_OPENGL_ES)
    // only override the system defaults if the user hasn't already
    // picked a visual
    if (X11->visual == 0 && X11->visual_id == -1 && X11->visual_class == -1) {
        // find a double buffered, RGBA visual that supports OpenGL
        // and set that as the default visual for windows in Qt
        int i = 0;
        int spec[16];
        spec[i++] = GLX_RGBA;
        spec[i++] = GLX_DOUBLEBUFFER;

        if (!qgetenv("QT_GL_SWAPBUFFER_PRESERVE").isNull()) {
            spec[i++] = GLX_DEPTH_SIZE;
            spec[i++] = 8;
            spec[i++] = GLX_STENCIL_SIZE;
            spec[i++] = 8;
            spec[i++] = GLX_SAMPLE_BUFFERS_ARB;
            spec[i++] = 1;
            spec[i++] = GLX_SAMPLES_ARB;
            spec[i++] = 4;
        }

        spec[i++] = XNone;

        XVisualInfo *vi = glXChooseVisual(X11->display, X11->defaultScreen, spec);
        if (vi) {
            X11->visual_id = vi->visualid;
            X11->visual_class = vi->c_class;

            QGLFormat format;
            int res;
            glXGetConfig(X11->display, vi, GLX_LEVEL, &res);
            format.setPlane(res);
            glXGetConfig(X11->display, vi, GLX_DOUBLEBUFFER, &res);
            format.setDoubleBuffer(res);
            glXGetConfig(X11->display, vi, GLX_DEPTH_SIZE, &res);
            format.setDepth(res);
            if (format.depth())
                format.setDepthBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_RGBA, &res);
            format.setRgba(res);
            glXGetConfig(X11->display, vi, GLX_RED_SIZE, &res);
            format.setRedBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_GREEN_SIZE, &res);
            format.setGreenBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_BLUE_SIZE, &res);
            format.setBlueBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_ALPHA_SIZE, &res);
            format.setAlpha(res);
            if (format.alpha())
                format.setAlphaBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_ACCUM_RED_SIZE, &res);
            format.setAccum(res);
            if (format.accum())
                format.setAccumBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_STENCIL_SIZE, &res);
            format.setStencil(res);
            if (format.stencil())
                format.setStencilBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_STEREO, &res);
            format.setStereo(res);
            glXGetConfig(X11->display, vi, GLX_SAMPLE_BUFFERS_ARB, &res);
            format.setSampleBuffers(res);
            if (format.sampleBuffers()) {
                glXGetConfig(X11->display, vi, GLX_SAMPLES_ARB, &res);
                format.setSamples(res);
            }

            QGLWindowSurface::surfaceFormat = format;
            XFree(vi);

            printf("using visual class %x, id %x\n", X11->visual_class, X11->visual_id);
        }
    }
#elif defined(Q_WS_WIN)
    QGLWindowSurface::surfaceFormat.setDoubleBuffer(true);

    qt_win_owndc_required = true;
#endif
}

//
// QGLWindowSurface
//

class QGLGlobalShareWidget
{
public:
    QGLGlobalShareWidget() : widget(0), initializing(false) {}

    QGLWidget *shareWidget() {
        if (!initializing && !widget && !cleanedUp) {
            initializing = true;
            widget = new QGLWidget;
            initializing = false;
        }
        return widget;
    }

    void cleanup() {
        QGLWidget *w = widget;
        cleanedUp = true;
        widget = 0;
        delete w;
    }

    static bool cleanedUp;

private:
    QGLWidget *widget;
    bool initializing;
};

bool QGLGlobalShareWidget::cleanedUp = false;

static void qt_cleanup_gl_share_widget();
Q_GLOBAL_STATIC_WITH_INITIALIZER(QGLGlobalShareWidget, _qt_gl_share_widget,
                                 {
                                     qAddPostRoutine(qt_cleanup_gl_share_widget);
                                 })

static void qt_cleanup_gl_share_widget()
{
    _qt_gl_share_widget()->cleanup();
}

QGLWidget* qt_gl_share_widget()
{
    if (QGLGlobalShareWidget::cleanedUp)
        return 0;
    return _qt_gl_share_widget()->shareWidget();
}

struct QGLWindowSurfacePrivate
{
    QGLFramebufferObject *fbo;
    QGLPixelBuffer *pb;
    GLuint tex_id;
    GLuint pb_tex_id;

    int tried_fbo : 1;
    int tried_pb : 1;
    int destructive_swap_buffers : 1;

    QGLContext *ctx;

    QList<QGLContext **> contexts;

    QRegion paintedRegion;
    QSize size;

    QList<QImage> buffers;
};

QGLFormat QGLWindowSurface::surfaceFormat;

QGLWindowSurface::QGLWindowSurface(QWidget *window)
    : QWindowSurface(window), d_ptr(new QGLWindowSurfacePrivate)
{
    Q_ASSERT(window->isTopLevel());
    QGLExtensions::init();
    d_ptr->pb = 0;
    d_ptr->fbo = 0;
    d_ptr->ctx = 0;
    d_ptr->tried_fbo = false;
    d_ptr->tried_pb = false;
    d_ptr->destructive_swap_buffers = qgetenv("QT_GL_SWAPBUFFER_PRESERVE").isNull();
}

QGLWindowSurface::~QGLWindowSurface()
{
    if (d_ptr->ctx)
        glDeleteTextures(1, &d_ptr->tex_id);
    foreach(QGLContext **ctx, d_ptr->contexts) {
        delete *ctx;
        *ctx = 0;
    }

    delete d_ptr->pb;
    delete d_ptr->fbo;
    delete d_ptr;
}

void QGLWindowSurface::deleted(QObject *object)
{
    QWidget *widget = qobject_cast<QWidget *>(object);
    if (widget) {
        QWidgetPrivate *widgetPrivate = widget->d_func();
        if (widgetPrivate->extraData()) {
            union { QGLContext **ctxPtr; void **voidPtr; };
            voidPtr = &widgetPrivate->extraData()->glContext;
            int index = d_ptr->contexts.indexOf(ctxPtr);
            if (index != -1) {
                delete *ctxPtr;
                *ctxPtr = 0;
                d_ptr->contexts.removeAt(index);
            }
        }
    }
}

void QGLWindowSurface::hijackWindow(QWidget *widget)
{
    QWidgetPrivate *widgetPrivate = widget->d_func();
    widgetPrivate->createExtra();
    if (widgetPrivate->extraData()->glContext)
        return;

    QGLContext *ctx = new QGLContext(surfaceFormat, widget);
    ctx->create(qt_gl_share_widget()->context());
#ifdef Q_WS_MAC
    ctx->updatePaintDevice();
#endif
    widgetPrivate->extraData()->glContext = ctx;

    union { QGLContext **ctxPtr; void **voidPtr; };

    connect(widget, SIGNAL(destroyed(QObject *)), this, SLOT(deleted(QObject *)));

    voidPtr = &widgetPrivate->extraData()->glContext;
    d_ptr->contexts << ctxPtr;
    qDebug() << "hijackWindow() context created for" << widget << d_ptr->contexts.size();
}

Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_gl_window_surface_2_engine)

#if !defined (QT_OPENGL_ES_2)
Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_gl_window_surface_engine)
#endif

/*! \reimp */
QPaintEngine *QGLWindowSurface::paintEngine() const
{
#if !defined(QT_OPENGL_ES_2)
    if (!qt_gl_preferGL2Engine())
        return qt_gl_window_surface_engine();
#endif
    return qt_gl_window_surface_2_engine();
}

int QGLWindowSurface::metric(PaintDeviceMetric m) const
{
    return window()->metric(m);
}

QGLContext *QGLWindowSurface::context() const
{
    return d_ptr->ctx;
}

QPaintDevice *QGLWindowSurface::paintDevice()
{
    updateGeometry();

    if (d_ptr->pb)
        return d_ptr->pb;

    if (d_ptr->ctx)
        return this;

    QGLContext *ctx = reinterpret_cast<QGLContext *>(window()->d_func()->extraData()->glContext);
    ctx->makeCurrent();
    return d_ptr->fbo;
}

static void drawTexture(const QRectF &rect, GLuint tex_id, const QSize &texSize, const QRectF &src = QRectF());

void QGLWindowSurface::beginPaint(const QRegion &)
{
    updateGeometry();
}

void QGLWindowSurface::endPaint(const QRegion &rgn)
{
    if (context())
        d_ptr->paintedRegion |= rgn;

    d_ptr->buffers.clear();
}

void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint &offset)
{
    QWidget *parent = widget->internalWinId() ? widget : widget->nativeParentWidget();
    Q_ASSERT(parent);

    if (!geometry().isValid())
        return;

    hijackWindow(parent);

    QRect br = rgn.boundingRect().translated(offset);
    br = br.intersected(window()->rect());
    QPoint wOffset = qt_qwidget_data(parent)->wrect.topLeft();
    QRect rect = br.translated(-offset - wOffset);

    const GLenum target = GL_TEXTURE_2D;

    if (context()) {
        context()->makeCurrent();

        if (context()->format().doubleBuffer()) {
#if !defined(QT_OPENGL_ES_2)
            if (d_ptr->destructive_swap_buffers) {
                glBindTexture(target, d_ptr->tex_id);

                QVector<QRect> rects = d_ptr->paintedRegion.rects();
                for (int i = 0; i < rects.size(); ++i) {
                    QRect br = rects.at(i);
                    if (br.isEmpty())
                        continue;

                    const uint bottom = window()->height() - (br.y() + br.height());
                    glCopyTexSubImage2D(target, 0, br.x(), bottom, br.x(), bottom, br.width(), br.height());
                }

                glBindTexture(target, 0);

                QRegion dirtyRegion = QRegion(window()->rect()) - d_ptr->paintedRegion;

                if (!dirtyRegion.isEmpty()) {
                    context()->makeCurrent();

                    glMatrixMode(GL_MODELVIEW);
                    glLoadIdentity();

                    glMatrixMode(GL_PROJECTION);
                    glLoadIdentity();
#ifndef QT_OPENGL_ES
                    glOrtho(0, window()->width(), window()->height(), 0, -999999, 999999);
#else
                    glOrthof(0, window()->width(), window()->height(), 0, -999999, 999999);
#endif
                    glViewport(0, 0, window()->width(), window()->height());

                    QVector<QRect> rects = dirtyRegion.rects();
                    glColor4f(1, 1, 1, 1);
                    for (int i = 0; i < rects.size(); ++i) {
                        QRect rect = rects.at(i);
                        if (rect.isEmpty())
                            continue;

                        drawTexture(rect, d_ptr->tex_id, window()->size(), rect);
                    }
                }
            }
#endif
            d_ptr->paintedRegion = QRegion();

            context()->swapBuffers();
        } else {
            glFlush();
        }

        return;
    }

    QGLContext *ctx = reinterpret_cast<QGLContext *>(parent->d_func()->extraData()->glContext);
    GLuint texture;
    if (d_ptr->fbo) {
        texture = d_ptr->fbo->texture();
    } else {
        d_ptr->pb->makeCurrent();
        glBindTexture(target, d_ptr->pb_tex_id);
        const uint bottom = window()->height() - (br.y() + br.height());
        glCopyTexSubImage2D(target, 0, br.x(), bottom, br.x(), bottom, br.width(), br.height());
        texture = d_ptr->pb_tex_id;
        glBindTexture(target, 0);
    }

    QSize size = widget->rect().size();
    if (d_ptr->destructive_swap_buffers && ctx->format().doubleBuffer()) {
        rect = parent->rect();
        br = rect.translated(wOffset);
        size = parent->size();
    }

    glDisable(GL_SCISSOR_TEST);

    if (d_ptr->fbo && QGLExtensions::glExtensions & QGLExtensions::FramebufferBlit) {
        const int h = d_ptr->fbo->height();

        const int x0 = rect.left();
        const int x1 = rect.left() + rect.width();
        const int y0 = h - (rect.top() + rect.height());
        const int y1 = h - rect.top();

        glBindFramebuffer(GL_DRAW_FRAMEBUFFER_EXT, 0);

        glBlitFramebufferEXT(x0, y0, x1, y1,
                x0, y0, x1, y1,
                GL_COLOR_BUFFER_BIT,
                GL_NEAREST);

        glBindFramebuffer(GL_DRAW_FRAMEBUFFER_EXT, d_ptr->fbo->handle());
    }
#if !defined(QT_OPENGL_ES_2)
    else {
        glDisable(GL_DEPTH_TEST);

        if (d_ptr->fbo) {
            d_ptr->fbo->release();
        } else {
            ctx->makeCurrent();
#ifdef Q_WS_MAC
            ctx->updatePaintDevice();
#endif
        }

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
#ifndef QT_OPENGL_ES
        glOrtho(0, size.width(), size.height(), 0, -999999, 999999);
#else
        glOrthof(0, size.width(), size.height(), 0, -999999, 999999);
#endif
        glViewport(0, 0, size.width(), size.height());

        glColor4f(1, 1, 1, 1);
        drawTexture(rect, texture, window()->size(), br);

        if (d_ptr->fbo)
            d_ptr->fbo->bind();
    }
#endif

    if (ctx->format().doubleBuffer())
        ctx->swapBuffers();
    else
        glFlush();
}

void QGLWindowSurface::updateGeometry()
{
    QRect rect = QWindowSurface::geometry();

    const GLenum target = GL_TEXTURE_2D;

    if (rect.width() <= 0 || rect.height() <= 0)
        return;

    if (d_ptr->size == rect.size())
        return;

    d_ptr->size = rect.size();

    if (d_ptr->ctx) {
        if (d_ptr->destructive_swap_buffers) {
            glBindTexture(target, d_ptr->tex_id);
            glTexImage2D(target, 0, GL_RGBA, rect.width(), rect.height(), 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
            glBindTexture(target, 0);
        }
        return;
    }

    if (d_ptr->destructive_swap_buffers
        && (QGLExtensions::glExtensions & QGLExtensions::FramebufferObject)
#ifdef QT_OPENGL_ES_2
        && (QGLExtensions::glExtensions & QGLExtensions::FramebufferBlit)
#endif
        && (d_ptr->fbo || !d_ptr->tried_fbo))
    {
        d_ptr->tried_fbo = true;
        hijackWindow(window());
        QGLContext *ctx = reinterpret_cast<QGLContext *>(window()->d_func()->extraData()->glContext);
        ctx->d_ptr->internal_context = true;
        ctx->makeCurrent();
        delete d_ptr->fbo;

        QGLFramebufferObjectFormat format;
        format.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
        format.setInternalFormat(GL_RGBA);
        format.setTextureTarget(target);

        if (QGLExtensions::glExtensions & QGLExtensions::FramebufferBlit)
            format.setSamples(8);

        d_ptr->fbo = new QGLFramebufferObject(rect.size(), format);
        d_ptr->fbo->bind();
        if (d_ptr->fbo->isValid()) {
            qDebug() << "Created Window Surface FBO" << rect.size()
                     << "with samples" << d_ptr->fbo->format().samples();
            return;
        } else {
            qDebug() << "QGLWindowSurface: Failed to create valid FBO, falling back";
            delete d_ptr->fbo;
            d_ptr->fbo = 0;
        }
    }

#if !defined(QT_OPENGL_ES_2)
    if (d_ptr->destructive_swap_buffers && (d_ptr->pb || !d_ptr->tried_pb)) {
        d_ptr->tried_pb = true;

        if (d_ptr->pb) {
            d_ptr->pb->makeCurrent();
            glDeleteTextures(1, &d_ptr->pb_tex_id);
        }

        delete d_ptr->pb;

        d_ptr->pb = new QGLPixelBuffer(rect.width(), rect.height(),
                                        QGLFormat(QGL::SampleBuffers | QGL::StencilBuffer | QGL::DepthBuffer),
                                        qt_gl_share_widget());

        if (d_ptr->pb->isValid()) {
            qDebug() << "Created Window Surface Pixelbuffer, Sample buffers:" << d_ptr->pb->format().sampleBuffers();
            d_ptr->pb->makeCurrent();

            glGenTextures(1, &d_ptr->pb_tex_id);
            glBindTexture(target, d_ptr->pb_tex_id);
            glTexImage2D(target, 0, GL_RGBA, rect.width(), rect.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

            glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
            glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            glBindTexture(target, 0);

            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
#ifndef QT_OPENGL_ES
            glOrtho(0, d_ptr->pb->width(), d_ptr->pb->height(), 0, -999999, 999999);
#else
            glOrthof(0, d_ptr->pb->width(), d_ptr->pb->height(), 0, -999999, 999999);
#endif

            d_ptr->pb->d_ptr->qctx->d_func()->internal_context = true;
            return;
        } else {
            qDebug() << "QGLWindowSurface: Failed to create valid pixelbuffer, falling back";
            delete d_ptr->pb;
            d_ptr->pb = 0;
        }
    }
#endif // !defined(QT_OPENGL_ES_2)

    hijackWindow(window());
    QGLContext *ctx = reinterpret_cast<QGLContext *>(window()->d_func()->extraData()->glContext);
    ctx->makeCurrent();

    if (d_ptr->destructive_swap_buffers) {
        glGenTextures(1, &d_ptr->tex_id);
        glBindTexture(target, d_ptr->tex_id);
        glTexImage2D(target, 0, GL_RGBA, rect.width(), rect.height(), 0, GL_RGB, GL_UNSIGNED_BYTE, 0);

        glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glBindTexture(target, 0);
    }

    qDebug() << "QGLWindowSurface: Using plain widget as window surface" << this;;
    d_ptr->ctx = ctx;
    d_ptr->ctx->d_ptr->internal_context = true;
}

void QGLWindowSurface::setGeometry(const QRect &rect)
{
    QWindowSurface::setGeometry(rect);
}

bool QGLWindowSurface::scroll(const QRegion &area, int dx, int dy)
{
    // this code randomly fails currently for unknown reasons
    return false;

    if (!d_ptr->pb)
        return false;

    d_ptr->pb->makeCurrent();

    QRect br = area.boundingRect();

#if 0
    // ## workaround driver issue (scrolling by these deltas is unbearably slow for some reason)
    // ## maybe we should use glCopyTexSubImage insteadk
    if (dx == 1 || dx == -1 || dy == 1 || dy == -1 || dy == 2)
        return false;

    glRasterPos2i(br.x() + dx, br.y() + br.height() + dy);
    glCopyPixels(br.x(), d_ptr->pb->height() - (br.y() + br.height()), br.width(), br.height(), GL_COLOR);
    return true;
#endif

    const GLenum target = GL_TEXTURE_2D;

    glBindTexture(target, d_ptr->tex_id);
    glCopyTexImage2D(target, 0, GL_RGBA, br.x(), d_ptr->pb->height() - (br.y() + br.height()), br.width(), br.height(), 0);
    glBindTexture(target, 0);

    drawTexture(br.translated(dx, dy), d_ptr->tex_id, window()->size());

    return true;
}

static void drawTexture(const QRectF &rect, GLuint tex_id, const QSize &texSize, const QRectF &br)
{
    const GLenum target = GL_TEXTURE_2D;
    QRectF src = br.isEmpty()
        ? QRectF(QPointF(), texSize)
        : QRectF(QPointF(br.x(), texSize.height() - br.bottom()), br.size());

    if (target == GL_TEXTURE_2D) {
        qreal width = texSize.width();
        qreal height = texSize.height();

        src.setLeft(src.left() / width);
        src.setRight(src.right() / width);
        src.setTop(src.top() / height);
        src.setBottom(src.bottom() / height);
    }

    const q_vertexType tx1 = f2vt(src.left());
    const q_vertexType tx2 = f2vt(src.right());
    const q_vertexType ty1 = f2vt(src.top());
    const q_vertexType ty2 = f2vt(src.bottom());

    q_vertexType texCoordArray[4*2] = {
        tx1, ty2, tx2, ty2, tx2, ty1, tx1, ty1
    };

    q_vertexType vertexArray[4*2];
    extern void qt_add_rect_to_array(const QRectF &r, q_vertexType *array); // qpaintengine_opengl.cpp
    qt_add_rect_to_array(rect, vertexArray);

#if !defined(QT_OPENGL_ES_2)
    glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
    glTexCoordPointer(2, q_vertexTypeEnum, 0, texCoordArray);

    glBindTexture(target, tex_id);
    glEnable(target);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
#endif

    glDisable(target);
    glBindTexture(target, 0);
}

QImage *QGLWindowSurface::buffer(const QWidget *widget)
{
    QImage image;

    if (d_ptr->pb)
        image = d_ptr->pb->toImage();
    else if (d_ptr->fbo)
        image = d_ptr->fbo->toImage();

    if (image.isNull())
        return 0;

    QRect rect = widget->rect();
    rect.translate(widget->mapTo(widget->window(), QPoint()));

    QImage subImage = image.copy(rect);
    d_ptr->buffers << subImage;
    return &d_ptr->buffers.last();
}



QT_END_NAMESPACE