summaryrefslogtreecommitdiffstats
path: root/lib/blinqpage.cpp
blob: 5c1011514aadea69863cf4f6490c7ce193dba491 (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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
#include "blinqpage.h"

// Needed to get access to content::GetContentClient()
#define CONTENT_IMPLEMENTATION

#include "content/public/browser/web_contents.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/web_contents_view.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/app/content_main_runner.h"
#include "content/public/app/content_main_delegate.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/main_function_params.h"
#include "net/url_request/url_request_context_getter.h"
#include "base/files/scoped_temp_dir.h"
#include "base/path_service.h"
#include "base/files/file_path.h"
#include "base/event_types.h"
#include "base/command_line.h"
#include "ui/gfx/insets.h"
#include "base/message_loop.h"
#include "ui/gfx/screen.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/rect_conversions.h"
#include "ui/surface/transport_dib.h"
#include "base/threading/thread_restrictions.h"
#include "content/common/view_messages.h"
#include "content/common/gpu/gpu_messages.h"
#include "content/shell/shell_browser_context.h"
#include "content/shell/shell_main_delegate.h"
#include "content/shell/shell_content_browser_client.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/browser/renderer_host/render_view_host_factory.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_gtk.h"
#include "content/browser/renderer_host/backing_store.h"
#include "content/browser/renderer_host/backing_store_gtk.h"
#include "webkit/user_agent/user_agent_util.h"
#include "skia/ext/platform_canvas.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebScreenInfo.h"

#include <QBackingStore>
#include <QByteArray>
#include <QWindow>
#include <QCoreApplication>
#include <QGuiApplication>
#include <qpa/qplatformwindow.h>
#include <QLabel>
#include <QPainter>
#include <QScreen>
#include <QResizeEvent>
#include <qpa/qplatformnativeinterface.h>

#include <X11/Xutil.h>

#define QT_NOT_YET_IMPLEMENTED fprintf(stderr, "function %s not implemented! - %s:%d\n", __func__, __FILE__, __LINE__);

namespace {

class Context;

void GetScreenInfoFromNativeWindow(QWindow* window, WebKit::WebScreenInfo* results)
{
    QScreen* screen = window->screen();

    WebKit::WebScreenInfo r;
    r.deviceScaleFactor = screen->devicePixelRatio();
    r.depthPerComponent = 8;
    r.depth = screen->depth();
    r.isMonochrome = (r.depth == 1);

    QRect virtualGeometry = screen->virtualGeometry();
    r.rect = WebKit::WebRect(virtualGeometry.x(), virtualGeometry.y(), virtualGeometry.width(), virtualGeometry.height());
    QRect available = screen->availableGeometry();
    r.availableRect = WebKit::WebRect(available.x(), available.y(), available.width(), available.height());
    *results = r;
}

class ResourceContext : public content::ResourceContext
{
public:
    ResourceContext(Context *ctx)
        : context(ctx)
    {}

    virtual net::HostResolver* GetHostResolver() { return 0; }

    inline virtual net::URLRequestContext* GetRequestContext();

private:
    Context *context;
};


static inline base::FilePath::StringType qStringToStringType(const QString &str)
{
#if defined(OS_POSIX)
    return str.toStdString();
#elif defined(OS_WIN)
    return str.toStdWString();
#endif
}

static QByteArray blinqProcessPath() {
    static bool initialized = false;
#ifdef BLINQ_PROCESS_PATH
    static QByteArray processPath(BLINQ_PROCESS_PATH);
#else
    static QByteArray processPath;
#endif
    if (initialized)
        return processPath;
    // Allow overriding at runtime for the time being.
    const QByteArray fromEnv = qgetenv("BLINQ_PROCESS_PATH");
    if (!fromEnv.isEmpty())
        processPath = fromEnv;
    if (processPath.isEmpty())
        qFatal("BLINQ_PROCESS_PATH environment variable not set or empty.");
    initialized = true;
    return processPath;
}

static void initializeBlinkPaths()
{
    static bool initialized = false;
    if (initialized)
        return;

    PathService::Override(content::CHILD_PROCESS_EXE, base::FilePath(qStringToStringType(QString(blinqProcessPath()))));
}

class Context : public content::BrowserContext
{
public:
   Context()
   {
       tempBasePath.CreateUniqueTempDir();
       resourceContext.reset(new ResourceContext(this));
   }
   virtual ~Context() {}

   virtual base::FilePath GetPath()
   {
       return tempBasePath.path();
   }

   virtual bool IsOffTheRecord() const
   {
       return false;
   }

   virtual net::URLRequestContextGetter* GetRequestContext()
   {
       return GetDefaultStoragePartition(this)->GetURLRequestContext();
   }
   virtual net::URLRequestContextGetter* GetRequestContextForRenderProcess(int) { return GetRequestContext(); }
   virtual net::URLRequestContextGetter* GetMediaRequestContext() { return GetRequestContext(); }
   virtual net::URLRequestContextGetter* GetMediaRequestContextForRenderProcess(int) { return GetRequestContext(); }
   virtual net::URLRequestContextGetter* GetMediaRequestContextForStoragePartition(const base::FilePath&, bool) { return GetRequestContext(); }

   virtual content::ResourceContext* GetResourceContext()
   {
       return resourceContext.get();
   }

   virtual content::DownloadManagerDelegate* GetDownloadManagerDelegate() { return 0; }
   virtual content::GeolocationPermissionContext* GetGeolocationPermissionContext() { return 0; }
   virtual content::SpeechRecognitionPreferences* GetSpeechRecognitionPreferences() { return 0; }
   virtual quota::SpecialStoragePolicy* GetSpecialStoragePolicy() { return 0; }

private:
    scoped_ptr<content::ResourceContext> resourceContext;
    base::ScopedTempDir tempBasePath; // ### Should become permanent location.

    DISALLOW_COPY_AND_ASSIGN(Context);
};

inline net::URLRequestContext* ResourceContext::GetRequestContext()
{
    return context->GetRequestContext()->GetURLRequestContext();
}

class RasterWindow : public QWindow
{
public:
    RasterWindow(QWindow *parent = 0)
        : QWindow(parent)
        , m_update_pending(false)
    {
        m_backingStore = new QBackingStore(this);
        create();
    }

    void blitPixmap(const QRect& rect, const QPixmap& pixmap)
    {
        if (!isExposed())
            return;

        m_backingStore->beginPaint(rect);
        QPaintDevice *device = m_backingStore->paintDevice();
        if (device) {
            QPainter painter(device);

            painter.drawPixmap(0, 0, width(), height(), pixmap);
        }
        m_backingStore->endPaint();
        m_backingStore->flush(rect);
    }

    void renderNow()
    {
        if (!isExposed())
            return;

    }

protected:
    bool event(QEvent *event)
    {
        if (event->type() == QEvent::UpdateRequest) {
            m_update_pending = false;
            renderNow();
            return true;
        }
        return QWindow::event(event);
    }

    void resizeEvent(QResizeEvent *resizeEvent)
    {
        m_backingStore->resize(resizeEvent->size());
        if (isExposed())
            renderNow();
    }
    
    void exposeEvent(QExposeEvent *)
    {
        if (isExposed()) {
            renderNow();
        }
    }
private:
    QPixmap m_pixmap;
    QBackingStore *m_backingStore;
    bool m_update_pending;
};

class BackingStoreQt : public QLabel
                     , public content::BackingStore
{
public:
    BackingStoreQt(content::RenderWidgetHost *host, const gfx::Size &size)
        : content::BackingStore(host, size)
        , m_pixelBuffer(size.width(), size.height())
    {
        // FIXME: remove QLabel inheritance
        resize(size.width(), size.height());
       // show();
        setWindowTitle(QStringLiteral("BackingStoreQt"));
        // FISME: remove QLabel inheritance
    }

    virtual void PaintToBackingStore(content::RenderProcessHost *process,
                                     TransportDIB::Id bitmap,
                                     const gfx::Rect &bitmap_rect,
                                     const std::vector<gfx::Rect> &copy_rects,
                                     float scale_factor,
                                     const base::Closure &completion_callback,
                                     bool *scheduled_completion_callback)
    {
        if (bitmap_rect.IsEmpty())
            return;

        *scheduled_completion_callback = false;
        TransportDIB* dib = process->GetTransportDIB(bitmap);
        if (!dib)
          return;

        // gfx::Rect pixel_bitmap_rect = gfx::ToEnclosedRect(gfx::ScaleRect(bitmap_rect, scale_factor));
        gfx::Rect pixel_bitmap_rect = bitmap_rect;


        uint8_t* bitmapData = static_cast<uint8_t*>(dib->memory());
        QImage img(bitmapData, pixel_bitmap_rect.width(), pixel_bitmap_rect.height(), QImage::Format_ARGB32);

        m_painter.begin(&m_pixelBuffer);

        for (size_t i = 0; i < copy_rects.size(); ++i) {
            gfx::Rect copy_rect = gfx::ToEnclosedRect(gfx::ScaleRect(copy_rects[i], scale_factor));

            QRect source = QRect( copy_rect.x() - pixel_bitmap_rect.x()
                                , copy_rect.y() - pixel_bitmap_rect.y()
                                , pixel_bitmap_rect.width()
                                , pixel_bitmap_rect.height());

            QRect destination = QRect( copy_rect.x()
                                     , copy_rect.y()
                                     , copy_rect.width()
                                     , copy_rect.height());

            m_painter.drawPixmap(destination, QPixmap::fromImage(img), source);
        }

        m_painter.end();

        // FIXME: remove QLabel inheritance
        setPixmap(m_pixelBuffer);
        repaint();
        // FIXME: remove QLabel inheritance
    }

    virtual void ScrollBackingStore(const gfx::Vector2d &delta, const gfx::Rect &clip_rect, const gfx::Size &view_size)
    {
        DCHECK(delta.x() == 0 || delta.y() == 0);

        m_pixelBuffer.scroll(delta.x(), delta.y(), clip_rect.x(), clip_rect.y(), clip_rect.width(), clip_rect.height());
    }

    virtual bool CopyFromBackingStore(const gfx::Rect &rect, skia::PlatformBitmap *output)
    {
        const int width = std::min(m_pixelBuffer.width(), rect.width());
        const int height = std::min(m_pixelBuffer.height(), rect.height());

        if (!output->Allocate(width, height, true))
            return false;

        // This code assumes a visual mode where a pixel is
        // represented using a 32-bit unsigned int, with a byte per component.
        const SkBitmap& bitmap = output->GetBitmap();
        SkAutoLockPixels alp(bitmap);

        QPixmap cpy = m_pixelBuffer.copy(rect.x(), rect.y(), rect.width(), rect.height());
        QImage img = cpy.toImage();

        // Convert the format and remove transparency.
        if (img.format() != QImage::Format_RGB32)
            img = img.convertToFormat(QImage::Format_RGB32);

        const uint8_t* src = img.bits();
        uint8_t* dst = reinterpret_cast<uint8_t*>(bitmap.getAddr32(0,0));
        memcpy(dst, src, width*height*32);

        return true;
    }

    void paintToQWindow(const gfx::Rect& r, QWindow* surface)
    {
        // OpenGL painting is currently not supported.
        if (surface->surfaceType() != QSurface::RasterSurface) {
            fprintf(stderr, "OpenGL painting is currently NOT supported.");
            return;
        }

        RasterWindow* rasterWindow = static_cast<RasterWindow*>(surface);
        rasterWindow->blitPixmap(QRect(r.x(), r.y(), r.width(), r.height()), m_pixelBuffer);
    }

private:
    QPainter m_painter;
    QPixmap m_pixelBuffer;
};

class RenderWidgetHostView
    : public content::RenderWidgetHostViewBase
{
public:
    RenderWidgetHostView(content::RenderWidgetHost* widget)
        : m_host(content::RenderWidgetHostImpl::From(widget))
        , m_view(0)
    {
    }

    virtual content::BackingStore *AllocBackingStore(const gfx::Size &size)
    {
        return new BackingStoreQt(m_host, size);
    }

    static RenderWidgetHostView* CreateViewForWidget(content::RenderWidgetHost* widget)
    {
        return new RenderWidgetHostView(widget);
    }

    virtual void InitAsChild(gfx::NativeView parent_view)
    {
        m_view = new RasterWindow;
    }

    virtual void InitAsPopup(content::RenderWidgetHostView*, const gfx::Rect&)
    {
        m_view = new RasterWindow;
    }

    virtual void InitAsFullscreen(content::RenderWidgetHostView*)
    {
        m_view = new RasterWindow;
    }

    virtual content::RenderWidgetHost* GetRenderWidgetHost() const
    {
        return m_host;
    }

    virtual void SetSize(const gfx::Size& size)
    {
        int width = size.width();
        int height = size.height();
        // int width = std::min(size.width(), kMaxWindowWidth);
        // int height = std::min(size.height(), kMaxWindowHeight);
        if (IsPopup()) {
            // We're a popup, honor the size request.
            m_view->resize(width,height);
        }

        if (m_requestedSize.width() != width ||
            m_requestedSize.height() != height) {
            m_requestedSize = gfx::Size(width, height);
            // m_host->SendScreenRects();
            m_host->WasResized();
        }
    }

    virtual void SetBounds(const gfx::Rect& rect)
    {
        // This is called when webkit has sent us a Move message.
        if (IsPopup())
            m_view->setGeometry(rect.x(), rect.y(), rect.width(), rect.height());

        SetSize(rect.size());
    }

    // FIXME: Should this really return a QWindow pointer?
    virtual gfx::NativeView GetNativeView() const
    {
        QT_NOT_YET_IMPLEMENTED
        // return m_view;
        return gfx::NativeView();
    }

    virtual QWindow* GetNativeViewQt() const OVERRIDE
    {
        return m_view;
    }

    virtual gfx::NativeViewId GetNativeViewId() const
    {
        QT_NOT_YET_IMPLEMENTED
        return gfx::NativeViewId();
    }

    virtual gfx::NativeViewAccessible GetNativeViewAccessible()
    {
        NOTIMPLEMENTED();
        return NULL;
    }

    // Set focus to the associated View component.
    virtual void Focus()
    {
        m_view->requestActivate();
    }

    virtual bool HasFocus() const
    {
        return m_view->isActive();
    }

    virtual bool IsSurfaceAvailableForCopy() const
    {
        return true;
    }

    virtual void Show()
    {
        m_view->show();
    }

    virtual void Hide()
    {
        m_view->hide();
    }

    virtual bool IsShowing()
    {
        return m_view->isVisible();
    }

    // Retrieve the bounds of the View, in screen coordinates.
    virtual gfx::Rect GetViewBounds() const
    {
        QRect rect = m_view->geometry();
        QPoint screenPos = m_view->mapToGlobal(QPoint(0,0));

        return gfx::Rect(screenPos.x(), screenPos.y(), rect.width(), rect.height());
    }

    // Subclasses should override this method to do what is appropriate to set
    // the custom background for their platform.
    virtual void SetBackground(const SkBitmap& background)
    {
        RenderWidgetHostViewBase::SetBackground(background);
        // Send(new ViewMsg_SetBackground(m_host->GetRoutingID(), background));
    }

    // Return value indicates whether the mouse is locked successfully or not.
    virtual bool LockMouse()
    {
        QT_NOT_YET_IMPLEMENTED
        return false;
    }
    virtual void UnlockMouse()
    {
        QT_NOT_YET_IMPLEMENTED
    }

    // Returns true if the mouse pointer is currently locked.
    virtual bool IsMouseLocked()
    {
        QT_NOT_YET_IMPLEMENTED
        return false;
    }

    // FIXME: remove TOOLKIT_GTK related things.
#if defined(TOOLKIT_GTK)
    // Gets the event for the last mouse down.
    virtual GdkEventButton* GetLastMouseDown()
    {
        return 0;
    }

    // Builds a submenu containing all the gtk input method commands.
    virtual gfx::NativeView BuildInputMethodsGtkMenu()
    {
    }
#endif  // defined(TOOLKIT_GTK)

    virtual void WasShown()
    {
        if (m_view->isVisible())
            return;

        m_host->WasShown();
    }

    virtual void WasHidden()
    {
        if (!m_view->isVisible())
            return;

        m_host->WasHidden();
    }

    virtual void MovePluginWindows(const gfx::Vector2d&, const std::vector<webkit::npapi::WebPluginGeometry>&)
    {
        QT_NOT_YET_IMPLEMENTED
    }

    virtual void Blur()
    {
        m_host->Blur();
    }

    virtual void UpdateCursor(const WebCursor&)
    {
        QT_NOT_YET_IMPLEMENTED
    }

    virtual void SetIsLoading(bool)
    {
        QT_NOT_YET_IMPLEMENTED
        // Give visual feedback for loading process.
    }

    virtual void TextInputStateChanged(const ViewHostMsg_TextInputState_Params&)
    {
        QT_NOT_YET_IMPLEMENTED
    }

    virtual void ImeCancelComposition()
    {
        QT_NOT_YET_IMPLEMENTED
    }

    virtual void ImeCompositionRangeChanged(const ui::Range&, const std::vector<gfx::Rect>&)
    {
        // FIXME: not implemented?
    }

    virtual void DidUpdateBackingStore(const gfx::Rect& scroll_rect, const gfx::Vector2d& scroll_delta, const std::vector<gfx::Rect>& copy_rects)
    {
        if (!m_view->isVisible())
            return;

        Paint(scroll_rect);

        for (size_t i = 0; i < copy_rects.size(); ++i) {
            gfx::Rect rect = gfx::SubtractRects(copy_rects[i], scroll_rect);
            if (rect.IsEmpty())
                continue;

            Paint(rect);
        }
    }

    virtual void RenderViewGone(base::TerminationStatus, int)
    {
        Destroy();
    }

    virtual void Destroy()
    {
        delete m_view;
        m_view = 0;
    }

    virtual void SetTooltipText(const string16&)
    {
        QT_NOT_YET_IMPLEMENTED
    }

    virtual void SelectionBoundsChanged(const ViewHostMsg_SelectionBounds_Params&)
    {
        QT_NOT_YET_IMPLEMENTED
    }

    virtual void ScrollOffsetChanged()
    {
        // FIXME: not implemented?
    }

    virtual void CopyFromCompositingSurface(const gfx::Rect& src_subrect, const gfx::Size& /* dst_size */, const base::Callback<void(bool, const SkBitmap&)>& callback)
    {
        // Grab the snapshot from the renderer as that's the only reliable way to
        // readback from the GPU for this platform right now.
        // FIXME: is this true?
        GetRenderWidgetHost()->GetSnapshotFromRenderer(src_subrect, callback);
    }

    virtual void CopyFromCompositingSurfaceToVideoFrame(const gfx::Rect& src_subrect, const scoped_refptr<media::VideoFrame>& target, const base::Callback<void(bool)>& callback)
    {
        NOTIMPLEMENTED();
        callback.Run(false);
    }

    virtual bool CanCopyToVideoFrame() const
    {
        return false;
    }

    virtual void OnAcceleratedCompositingStateChange()
    {
        // bool activated = m_host->is_accelerated_compositing_active();
        QT_NOT_YET_IMPLEMENTED
    }

    virtual void AcceleratedSurfaceBuffersSwapped(const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params, int gpu_host_id)
    {
        AcceleratedSurfaceMsg_BufferPresented_Params ack_params;
        ack_params.sync_point = 0;
        content::RenderWidgetHostImpl::AcknowledgeBufferPresent(params.route_id, gpu_host_id, ack_params);
    }

    virtual void AcceleratedSurfacePostSubBuffer(const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params, int gpu_host_id)
    {
        AcceleratedSurfaceMsg_BufferPresented_Params ack_params;
        ack_params.sync_point = 0;
        content::RenderWidgetHostImpl::AcknowledgeBufferPresent(params.route_id, gpu_host_id, ack_params);
    }

    virtual void AcceleratedSurfaceSuspend()
    {
        //FIXME: not implemented?
    }

    virtual void AcceleratedSurfaceRelease()
    {
        //FIXME: not implemented?
    }

    virtual bool HasAcceleratedSurface(const gfx::Size&)
    {
        return false;
    }

    virtual void GetScreenInfo(WebKit::WebScreenInfo* results)
    {
        GetScreenInfoFromNativeWindow(m_view, results);
    }

    virtual gfx::Rect GetBoundsInRootWindow()
    {
        QRect r = m_view->frameGeometry();
        return gfx::Rect(r.x(), r.y(), r.width(), r.height());
    }

    virtual gfx::GLSurfaceHandle GetCompositingSurface()
    {
        QT_NOT_YET_IMPLEMENTED
        return gfx::GLSurfaceHandle();
    }

    virtual void SetHasHorizontalScrollbar(bool) { }
    virtual void SetScrollOffsetPinning(bool, bool) { }
    virtual void OnAccessibilityNotifications(const std::vector<AccessibilityHostMsg_NotificationParams>&)
    {
        QT_NOT_YET_IMPLEMENTED
    }

private:
    void Paint(const gfx::Rect& scroll_rect)
    {
        bool force_create = !m_host->empty();
        BackingStoreQt* backing_store = static_cast<BackingStoreQt*>(m_host->GetBackingStore(force_create));
        if (backing_store && m_view)
            backing_store->paintToQWindow(scroll_rect, m_view);
    }

    bool IsPopup() const
    {
        return popup_type_ != WebKit::WebPopupTypeNone;
    }

    content::RenderWidgetHostImpl *m_host;
    QWindow *m_view;
    gfx::Size m_requestedSize;
};

class RenderViewHost : public content::RenderViewHostImpl
{
public:
    RenderViewHost(
        content::SiteInstance* instance,
        content::RenderViewHostDelegate* delegate,
        content::RenderWidgetHostDelegate* widget_delegate,
        int routing_id,
        bool swapped_out,
        content::SessionStorageNamespace* session_storage_namespace)
        : content::RenderViewHostImpl(instance, delegate, widget_delegate, routing_id, swapped_out, session_storage_namespace)
    {
        SetView(new RenderWidgetHostView(this));
    }
};

class ViewHostFactory : public content::RenderViewHostFactory
{
public:
    ViewHostFactory()
    {
        content::RenderViewHostFactory::RegisterFactory(this);
    }
    ~ViewHostFactory()
    {
        content::RenderViewHostFactory::UnregisterFactory();
    }

    virtual content::RenderViewHost *CreateRenderViewHost(content::SiteInstance *instance,
                                                          content::RenderViewHostDelegate *delegate,
                                                          content::RenderWidgetHostDelegate *widget_delegate,
                                                          int routing_id,
                                                          bool swapped_out,
                                                          content::SessionStorageNamespace *session_storage_namespace)
    {
        content::RenderViewHost *vh = new RenderViewHost(instance, delegate, widget_delegate, routing_id, swapped_out, session_storage_namespace);
        vh->GetView()->InitAsChild(0);

        return vh;
    }
};

// Return a timeout suitable for the glib loop, -1 to block forever,
// 0 to return right away, or a timeout in milliseconds from now.
int GetTimeIntervalMilliseconds(const base::TimeTicks& from) {
  if (from.is_null())
    return -1;

  // Be careful here.  TimeDelta has a precision of microseconds, but we want a
  // value in milliseconds.  If there are 5.5ms left, should the delay be 5 or
  // 6?  It should be 6 to avoid executing delayed work too early.
  int delay = static_cast<int>(
      ceil((from - base::TimeTicks::Now()).InMillisecondsF()));

  // If this value is negative, then we need to run delayed work soon.
  return delay < 0 ? 0 : delay;
}

#if 0
class MessagePump : public QObject,
                    public base::MessagePump
{
public:
    struct DelayedWorkEvent : public QEvent
    {
    public:
        DelayedWorkEvent(int msecs)
            : QEvent(static_cast<QEvent::Type>(QEvent::User + 1))
            , m_secs(msecs)
        {}

        int m_secs;
    };

    MessagePump()
        : m_delegate(0)
    {
    }

    virtual void Run(Delegate *delegate)
    {
        m_delegate = delegate;
        printf("RUN\n");
    }

    virtual void Quit()
    {
        printf("QUIT?!\n");
    }

    virtual void ScheduleWork()
    {
        QCoreApplication::postEvent(this, new QEvent(QEvent::User));
        printf("ScheduleWork\n");
    }

    virtual void ScheduleDelayedWork(const base::TimeTicks &delayed_work_time)
    {
        printf("Schedule Delayed Work %d\n", GetTimeIntervalMilliseconds(delayed_work_time));
//        QCoreApplication::postEvent(this, new DelayedWorkEvent(GetTimeIntervalMilliseconds(delayed_work_time)));
        QCoreApplication::postEvent(this, new QEvent(QEvent::User));
    }

protected:
    virtual void customEvent(QEvent *ev)
    {
        if (ev->type() == QEvent::User + 1) {
            startTimer(static_cast<DelayedWorkEvent*>(ev)->m_secs);
            return;
        }
        printf("customEvent\n");
        if (!m_delegate)
            return;
        if (m_delegate->DoWork())
            return;
        m_delegate->DoIdleWork();
    }

    virtual void timerEvent(QTimerEvent *ev)
    {
        printf("timerEvent\n");
        killTimer(ev->timerId());
        if (!m_delegate)
            return;
        base::TimeTicks next_delayed_work_time;
        if (!m_delegate->DoDelayedWork(&next_delayed_work_time))
            m_delegate->DoIdleWork();

        if (!next_delayed_work_time.is_null()) {
            QCoreApplication::postEvent(this, new QEvent(QEvent::User));
//            startTimer(GetTimeIntervalMilliseconds(next_delayed_work_time));
        }
    }

private:
    Delegate *m_delegate;
};

base::MessagePump* messagePumpFactory()
{
    return new MessagePump;
}
#endif

}

class BlinqPagePrivate
{
public:
    scoped_ptr<content::BrowserContext> context;
    scoped_ptr<content::WebContents> contents;
};

BlinqPage::BlinqPage(int argc, char **argv)
{
    {
        int myArgc = argc + 3;
        const char **myArgv = new const char *[myArgc];

        for (int i = 0; i < argc; ++i)
            myArgv[i] = argv[i];
        QByteArray subProcessPathOption("--browser-subprocess-path=");
        subProcessPathOption.append(blinqProcessPath());
        myArgv[argc] = subProcessPathOption.constData();
        myArgv[argc + 1] = "--no-sandbox";

        std::string ua = webkit_glue::BuildUserAgentFromProduct("Qrome/0.1");

        QByteArray userAgentParameter("--user-agent=");
        userAgentParameter.append(QString::fromStdString(ua).toUtf8());
        myArgv[argc + 2] = userAgentParameter.constData();

        CommandLine::Init(myArgc, myArgv);

        delete [] myArgv;

//        base::MessageLoop::InitMessagePumpForUIFactory(::messagePumpFactory);
    }

    static content::ContentMainRunner *runner = 0;
    if (!runner) {
        (void)new ViewHostFactory();

        runner = content::ContentMainRunner::Create();
        runner->Initialize(0, 0, new content::ShellMainDelegate);
    }

    initializeBlinkPaths();

    static content::BrowserMainRunner *browserRunner = 0;
    if (!browserRunner) {
        //CommandLine::Init(0, 0);

        browserRunner = content::BrowserMainRunner::Create();

        browserRunner->Initialize(content::MainFunctionParams(*CommandLine::ForCurrentProcess()));
    }

    base::ThreadRestrictions::SetIOAllowed(true);

    d.reset(new BlinqPagePrivate);

    d->context.reset(static_cast<content::ShellContentBrowserClient*>(content::GetContentClient()->browser())->browser_context());
    content::WebContents::CreateParams p(d->context.get());
//    d->contents.reset(content::WebContents::Create(p));

//    d->contents->GetController().LoadURL(GURL(std::string("http://qt-project.org/")),
//                                         content::Referrer(),
//                                         content::PAGE_TRANSITION_TYPED,
//                                         std::string());

    MessageLoopForUI::current()->Run();
}

BlinqPage::~BlinqPage()
{
}

QWindow *BlinqPage::window()
{
  return 0;
}