a9619d1694e0f61e58fa50abc5bb3e0da8be1065
[WebKit-https.git] / Source / WebKit / UIProcess / API / gtk / WebKitWebViewBase.cpp
1 /*
2  * Copyright (C) 2010 Apple Inc. All rights reserved.
3  * Portions Copyright (c) 2010 Motorola Mobility, Inc.  All rights reserved.
4  * Copyright (C) 2011 Igalia S.L.
5  * Copyright (C) 2013 Gustavo Noronha Silva <gns@gnome.org>.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
18  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
26  * THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include "config.h"
30 #include "WebKitWebViewBase.h"
31
32 #include "APIPageConfiguration.h"
33 #include "AcceleratedBackingStore.h"
34 #include "DrawingAreaProxyCoordinatedGraphics.h"
35 #include "InputMethodFilter.h"
36 #include "KeyBindingTranslator.h"
37 #include "NativeWebKeyboardEvent.h"
38 #include "NativeWebMouseEvent.h"
39 #include "NativeWebWheelEvent.h"
40 #include "PageClientImpl.h"
41 #include "ViewGestureController.h"
42 #include "WebEventFactory.h"
43 #include "WebInspectorProxy.h"
44 #include "WebKit2Initialize.h"
45 #include "WebKitWebViewBaseAccessible.h"
46 #include "WebKitWebViewBasePrivate.h"
47 #include "WebPageGroup.h"
48 #include "WebPageProxy.h"
49 #include "WebPreferences.h"
50 #include "WebProcessPool.h"
51 #include "WebUserContentControllerProxy.h"
52 #include <WebCore/ActivityState.h>
53 #include <WebCore/CairoUtilities.h>
54 #include <WebCore/GUniquePtrGtk.h>
55 #include <WebCore/GtkUtilities.h>
56 #include <WebCore/GtkVersioning.h>
57 #include <WebCore/NotImplemented.h>
58 #include <WebCore/PasteboardHelper.h>
59 #include <WebCore/PlatformDisplay.h>
60 #include <WebCore/RefPtrCairo.h>
61 #include <WebCore/Region.h>
62 #include <gdk/gdk.h>
63 #include <gdk/gdkkeysyms.h>
64 #include <glib/gi18n-lib.h>
65 #include <memory>
66 #include <pal/system/SleepDisabler.h>
67 #include <wtf/Compiler.h>
68 #include <wtf/HashMap.h>
69 #include <wtf/glib/GRefPtr.h>
70 #include <wtf/glib/WTFGType.h>
71 #include <wtf/text/CString.h>
72
73 #if ENABLE(FULLSCREEN_API)
74 #include "WebFullScreenManagerProxy.h"
75 #endif
76
77 #if PLATFORM(X11)
78 #include <gdk/gdkx.h>
79 #endif
80
81 // gtk_widget_get_scale_factor() appeared in GTK 3.10, but we also need
82 // to make sure we have cairo new enough to support cairo_surface_set_device_scale
83 #define HAVE_GTK_SCALE_FACTOR HAVE_CAIRO_SURFACE_SET_DEVICE_SCALE && GTK_CHECK_VERSION(3, 10, 0)
84
85 using namespace WebKit;
86 using namespace WebCore;
87
88 struct ClickCounter {
89 public:
90     void reset()
91     {
92         currentClickCount = 0;
93         previousClickPoint = IntPoint();
94         previousClickTime = 0;
95         previousClickButton = 0;
96     }
97
98     int currentClickCountForGdkButtonEvent(GdkEvent* event)
99     {
100         int doubleClickDistance = 250;
101         int doubleClickTime = 5;
102         g_object_get(gtk_settings_get_for_screen(gdk_event_get_screen(event)),
103             "gtk-double-click-distance", &doubleClickDistance, "gtk-double-click-time", &doubleClickTime, nullptr);
104
105         // GTK+ only counts up to triple clicks, but WebCore wants to know about
106         // quadruple clicks, quintuple clicks, ad infinitum. Here, we replicate the
107         // GDK logic for counting clicks.
108         guint32 eventTime = gdk_event_get_time(event);
109         if (!eventTime) {
110             // Real events always have a non-zero time, but events synthesized
111             // by the WTR do not and we must calculate a time manually. This time
112             // is not calculated in the WTR, because GTK+ does not work well with
113             // anything other than GDK_CURRENT_TIME on synthesized events.
114             GTimeVal timeValue;
115             g_get_current_time(&timeValue);
116             eventTime = (timeValue.tv_sec * 1000) + (timeValue.tv_usec / 1000);
117         }
118
119         if ((event->type == GDK_2BUTTON_PRESS || event->type == GDK_3BUTTON_PRESS)
120             || ((std::abs(event->button.x - previousClickPoint.x()) < doubleClickDistance)
121                 && (std::abs(event->button.y - previousClickPoint.y()) < doubleClickDistance)
122                 && (eventTime - previousClickTime < static_cast<unsigned>(doubleClickTime))
123                 && (event->button.button == previousClickButton)))
124             currentClickCount++;
125         else
126             currentClickCount = 1;
127
128         double x, y;
129         gdk_event_get_coords(event, &x, &y);
130         previousClickPoint = IntPoint(x, y);
131         previousClickButton = event->button.button;
132         previousClickTime = eventTime;
133
134         return currentClickCount;
135     }
136
137 private:
138     int currentClickCount;
139     IntPoint previousClickPoint;
140     unsigned previousClickButton;
141     int previousClickTime;
142 };
143
144 typedef HashMap<GtkWidget*, IntRect> WebKitWebViewChildrenMap;
145 typedef HashMap<uint32_t, GUniquePtr<GdkEvent>> TouchEventsMap;
146
147 struct _WebKitWebViewBasePrivate {
148     _WebKitWebViewBasePrivate()
149         : updateActivityStateTimer(RunLoop::main(), this, &_WebKitWebViewBasePrivate::updateActivityStateTimerFired)
150     {
151     }
152
153     void updateActivityStateTimerFired()
154     {
155         if (!pageProxy)
156             return;
157         pageProxy->activityStateDidChange(activityStateFlagsToUpdate);
158         activityStateFlagsToUpdate = { };
159     }
160
161     WebKitWebViewChildrenMap children;
162     std::unique_ptr<PageClientImpl> pageClient;
163     RefPtr<WebPageProxy> pageProxy;
164     bool shouldForwardNextKeyEvent { false };
165     bool shouldForwardNextWheelEvent { false };
166     ClickCounter clickCounter;
167     CString tooltipText;
168     IntRect tooltipArea;
169     GRefPtr<AtkObject> accessible;
170     GtkWidget* dialog { nullptr };
171     GtkWidget* inspectorView { nullptr };
172     AttachmentSide inspectorAttachmentSide { AttachmentSide::Bottom };
173     unsigned inspectorViewSize { 0 };
174     GUniquePtr<GdkEvent> contextMenuEvent;
175     WebContextMenuProxyGtk* activeContextMenuProxy { nullptr };
176     InputMethodFilter inputMethodFilter;
177     KeyBindingTranslator keyBindingTranslator;
178     TouchEventsMap touchEvents;
179     IntSize contentsSize;
180
181     GtkWindow* toplevelOnScreenWindow { nullptr };
182     unsigned long toplevelFocusInEventID { 0 };
183     unsigned long toplevelFocusOutEventID { 0 };
184     unsigned long toplevelWindowStateEventID { 0 };
185     unsigned long toplevelWindowRealizedID { 0 };
186
187     // View State.
188     OptionSet<ActivityState::Flag> activityState;
189     OptionSet<ActivityState::Flag> activityStateFlagsToUpdate;
190     RunLoop::Timer<WebKitWebViewBasePrivate> updateActivityStateTimer;
191
192 #if ENABLE(FULLSCREEN_API)
193     bool fullScreenModeActive { false };
194     std::unique_ptr<PAL::SleepDisabler> sleepDisabler;
195 #endif
196
197     std::unique_ptr<AcceleratedBackingStore> acceleratedBackingStore;
198
199 #if ENABLE(DRAG_SUPPORT)
200     std::unique_ptr<DragAndDropHandler> dragAndDropHandler;
201 #endif
202
203 #if HAVE(GTK_GESTURES)
204     std::unique_ptr<GestureController> gestureController;
205 #endif
206     std::unique_ptr<ViewGestureController> viewGestureController;
207 };
208
209 WEBKIT_DEFINE_TYPE(WebKitWebViewBase, webkit_web_view_base, GTK_TYPE_CONTAINER)
210
211 static void webkitWebViewBaseScheduleUpdateActivityState(WebKitWebViewBase* webViewBase, OptionSet<ActivityState::Flag> flagsToUpdate)
212 {
213     WebKitWebViewBasePrivate* priv = webViewBase->priv;
214     priv->activityStateFlagsToUpdate.add(flagsToUpdate);
215     if (priv->updateActivityStateTimer.isActive())
216         return;
217
218     priv->updateActivityStateTimer.startOneShot(0_s);
219 }
220
221 static gboolean toplevelWindowFocusInEvent(GtkWidget* widget, GdkEventFocus*, WebKitWebViewBase* webViewBase)
222 {
223     // Spurious focus in events can occur when the window is hidden.
224     if (!gtk_widget_get_visible(widget))
225         return FALSE;
226
227     WebKitWebViewBasePrivate* priv = webViewBase->priv;
228     if (priv->activityState & ActivityState::WindowIsActive)
229         return FALSE;
230
231     priv->activityState.add(ActivityState::WindowIsActive);
232     webkitWebViewBaseScheduleUpdateActivityState(webViewBase, ActivityState::WindowIsActive);
233
234     return FALSE;
235 }
236
237 static gboolean toplevelWindowFocusOutEvent(GtkWidget*, GdkEventFocus*, WebKitWebViewBase* webViewBase)
238 {
239     WebKitWebViewBasePrivate* priv = webViewBase->priv;
240     if (!(priv->activityState & ActivityState::WindowIsActive))
241         return FALSE;
242
243     priv->activityState.remove(ActivityState::WindowIsActive);
244     webkitWebViewBaseScheduleUpdateActivityState(webViewBase, ActivityState::WindowIsActive);
245
246     return FALSE;
247 }
248
249 static gboolean toplevelWindowStateEvent(GtkWidget*, GdkEventWindowState* event, WebKitWebViewBase* webViewBase)
250 {
251     WebKitWebViewBasePrivate* priv = webViewBase->priv;
252     if (!(event->changed_mask & GDK_WINDOW_STATE_ICONIFIED))
253         return FALSE;
254
255     bool visible = !(event->new_window_state & GDK_WINDOW_STATE_ICONIFIED);
256     if ((visible && priv->activityState & ActivityState::IsVisible) || (!visible && !(priv->activityState & ActivityState::IsVisible)))
257         return FALSE;
258
259     if (visible)
260         priv->activityState.add(ActivityState::IsVisible);
261     else
262         priv->activityState.remove(ActivityState::IsVisible);
263     webkitWebViewBaseScheduleUpdateActivityState(webViewBase, ActivityState::IsVisible);
264
265     return FALSE;
266 }
267
268 static void toplevelWindowRealized(WebKitWebViewBase* webViewBase)
269 {
270     gtk_widget_realize(GTK_WIDGET(webViewBase));
271
272     WebKitWebViewBasePrivate* priv = webViewBase->priv;
273     if (priv->toplevelWindowRealizedID) {
274         g_signal_handler_disconnect(priv->toplevelOnScreenWindow, priv->toplevelWindowRealizedID);
275         priv->toplevelWindowRealizedID = 0;
276     }
277 }
278
279 static void webkitWebViewBaseSetToplevelOnScreenWindow(WebKitWebViewBase* webViewBase, GtkWindow* window)
280 {
281     WebKitWebViewBasePrivate* priv = webViewBase->priv;
282     if (priv->toplevelOnScreenWindow == window)
283         return;
284
285     if (priv->toplevelFocusInEventID) {
286         g_signal_handler_disconnect(priv->toplevelOnScreenWindow, priv->toplevelFocusInEventID);
287         priv->toplevelFocusInEventID = 0;
288     }
289     if (priv->toplevelFocusOutEventID) {
290         g_signal_handler_disconnect(priv->toplevelOnScreenWindow, priv->toplevelFocusOutEventID);
291         priv->toplevelFocusOutEventID = 0;
292     }
293     if (priv->toplevelWindowStateEventID) {
294         g_signal_handler_disconnect(priv->toplevelOnScreenWindow, priv->toplevelWindowStateEventID);
295         priv->toplevelWindowStateEventID = 0;
296     }
297     if (priv->toplevelWindowRealizedID) {
298         g_signal_handler_disconnect(priv->toplevelOnScreenWindow, priv->toplevelWindowRealizedID);
299         priv->toplevelWindowRealizedID = 0;
300     }
301
302     priv->toplevelOnScreenWindow = window;
303
304     if (!priv->toplevelOnScreenWindow) {
305         OptionSet<ActivityState::Flag> flagsToUpdate;
306         if (priv->activityState & ActivityState::IsInWindow) {
307             priv->activityState.remove(ActivityState::IsInWindow);
308             flagsToUpdate.add(ActivityState::IsInWindow);
309         }
310         if (priv->activityState & ActivityState::WindowIsActive) {
311             priv->activityState.remove(ActivityState::WindowIsActive);
312             flagsToUpdate.add(ActivityState::IsInWindow);
313         }
314         if (flagsToUpdate)
315             webkitWebViewBaseScheduleUpdateActivityState(webViewBase, flagsToUpdate);
316
317         return;
318     }
319
320     priv->toplevelFocusInEventID =
321         g_signal_connect(priv->toplevelOnScreenWindow, "focus-in-event",
322                          G_CALLBACK(toplevelWindowFocusInEvent), webViewBase);
323     priv->toplevelFocusOutEventID =
324         g_signal_connect(priv->toplevelOnScreenWindow, "focus-out-event",
325                          G_CALLBACK(toplevelWindowFocusOutEvent), webViewBase);
326     priv->toplevelWindowStateEventID =
327         g_signal_connect(priv->toplevelOnScreenWindow, "window-state-event", G_CALLBACK(toplevelWindowStateEvent), webViewBase);
328
329     if (gtk_widget_get_realized(GTK_WIDGET(window)))
330         gtk_widget_realize(GTK_WIDGET(webViewBase));
331     else
332         priv->toplevelWindowRealizedID = g_signal_connect_swapped(window, "realize", G_CALLBACK(toplevelWindowRealized), webViewBase);
333 }
334
335 static void webkitWebViewBaseRealize(GtkWidget* widget)
336 {
337     WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(widget);
338     WebKitWebViewBasePrivate* priv = webView->priv;
339
340     gtk_widget_set_realized(widget, TRUE);
341
342     GtkAllocation allocation;
343     gtk_widget_get_allocation(widget, &allocation);
344
345     GdkWindowAttr attributes;
346     attributes.window_type = GDK_WINDOW_CHILD;
347     attributes.x = allocation.x;
348     attributes.y = allocation.y;
349     attributes.width = allocation.width;
350     attributes.height = allocation.height;
351     attributes.wclass = GDK_INPUT_OUTPUT;
352     attributes.visual = gtk_widget_get_visual(widget);
353     attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK
354         | GDK_EXPOSURE_MASK
355         | GDK_BUTTON_PRESS_MASK
356         | GDK_BUTTON_RELEASE_MASK
357         | GDK_SCROLL_MASK
358         | GDK_SMOOTH_SCROLL_MASK
359         | GDK_POINTER_MOTION_MASK
360         | GDK_ENTER_NOTIFY_MASK
361         | GDK_LEAVE_NOTIFY_MASK
362         | GDK_KEY_PRESS_MASK
363         | GDK_KEY_RELEASE_MASK
364         | GDK_BUTTON_MOTION_MASK
365         | GDK_BUTTON1_MOTION_MASK
366         | GDK_BUTTON2_MOTION_MASK
367         | GDK_BUTTON3_MOTION_MASK
368         | GDK_TOUCH_MASK;
369 #if HAVE(GTK_GESTURES)
370     attributes.event_mask |= GDK_TOUCHPAD_GESTURE_MASK;
371 #endif
372
373     gint attributesMask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL;
374
375     GdkWindow* window = gdk_window_new(gtk_widget_get_parent_window(widget), &attributes, attributesMask);
376     gtk_widget_set_window(widget, window);
377     gdk_window_set_user_data(window, widget);
378
379 #if USE(TEXTURE_MAPPER_GL) && PLATFORM(X11) && !USE(REDIRECTED_XCOMPOSITE_WINDOW)
380     if (PlatformDisplay::sharedDisplay().type() == PlatformDisplay::Type::X11) {
381         if (auto* drawingArea = static_cast<DrawingAreaProxyCoordinatedGraphics*>(priv->pageProxy->drawingArea()))
382             drawingArea->setNativeSurfaceHandleForCompositing(GDK_WINDOW_XID(window));
383     }
384 #endif
385
386     gtk_im_context_set_client_window(priv->inputMethodFilter.context(), window);
387 }
388
389 static void webkitWebViewBaseUnrealize(GtkWidget* widget)
390 {
391     WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(widget);
392 #if USE(TEXTURE_MAPPER_GL) && PLATFORM(X11) && !USE(REDIRECTED_XCOMPOSITE_WINDOW)
393     if (PlatformDisplay::sharedDisplay().type() == PlatformDisplay::Type::X11) {
394         if (auto* drawingArea = static_cast<DrawingAreaProxyCoordinatedGraphics*>(webView->priv->pageProxy->drawingArea()))
395             drawingArea->destroyNativeSurfaceHandleForCompositing();
396     }
397 #endif
398     gtk_im_context_set_client_window(webView->priv->inputMethodFilter.context(), nullptr);
399
400     GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->unrealize(widget);
401 }
402
403 static bool webkitWebViewChildIsInternalWidget(WebKitWebViewBase* webViewBase, GtkWidget* widget)
404 {
405     WebKitWebViewBasePrivate* priv = webViewBase->priv;
406     return widget == priv->inspectorView || widget == priv->dialog;
407 }
408
409 static void webkitWebViewBaseContainerAdd(GtkContainer* container, GtkWidget* widget)
410 {
411     WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(container);
412     WebKitWebViewBasePrivate* priv = webView->priv;
413
414     // Internal widgets like the web inspector and authentication dialog have custom
415     // allocations so we don't need to add them to our list of children.
416     if (!webkitWebViewChildIsInternalWidget(webView, widget)) {
417         GtkAllocation childAllocation;
418         gtk_widget_get_allocation(widget, &childAllocation);
419         priv->children.set(widget, childAllocation);
420     }
421
422     gtk_widget_set_parent(widget, GTK_WIDGET(container));
423 }
424
425 void webkitWebViewBaseAddDialog(WebKitWebViewBase* webViewBase, GtkWidget* dialog)
426 {
427     WebKitWebViewBasePrivate* priv = webViewBase->priv;
428     priv->dialog = dialog;
429     gtk_container_add(GTK_CONTAINER(webViewBase), dialog);
430     gtk_widget_show(dialog);
431
432     // We need to draw the shadow over the widget.
433     gtk_widget_queue_draw(GTK_WIDGET(webViewBase));
434 }
435
436 void webkitWebViewBaseAddWebInspector(WebKitWebViewBase* webViewBase, GtkWidget* inspector, AttachmentSide attachmentSide)
437 {
438     if (webViewBase->priv->inspectorView == inspector && webViewBase->priv->inspectorAttachmentSide == attachmentSide)
439         return;
440
441     webViewBase->priv->inspectorAttachmentSide = attachmentSide;
442
443     if (webViewBase->priv->inspectorView == inspector) {
444         gtk_widget_queue_resize(GTK_WIDGET(webViewBase));
445         return;
446     }
447
448     webViewBase->priv->inspectorView = inspector;
449     gtk_container_add(GTK_CONTAINER(webViewBase), inspector);
450 }
451
452 static void webkitWebViewBaseContainerRemove(GtkContainer* container, GtkWidget* widget)
453 {
454     WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(container);
455     WebKitWebViewBasePrivate* priv = webView->priv;
456     GtkWidget* widgetContainer = GTK_WIDGET(container);
457
458     gboolean wasVisible = gtk_widget_get_visible(widget);
459     gtk_widget_unparent(widget);
460
461     if (priv->inspectorView == widget) {
462         priv->inspectorView = 0;
463         priv->inspectorViewSize = 0;
464     } else if (priv->dialog == widget) {
465         priv->dialog = nullptr;
466         if (gtk_widget_get_visible(widgetContainer))
467             gtk_widget_grab_focus(widgetContainer);
468     } else {
469         ASSERT(priv->children.contains(widget));
470         priv->children.remove(widget);
471     }
472     if (wasVisible && gtk_widget_get_visible(widgetContainer))
473         gtk_widget_queue_resize(widgetContainer);
474 }
475
476 static void webkitWebViewBaseContainerForall(GtkContainer* container, gboolean includeInternals, GtkCallback callback, gpointer callbackData)
477 {
478     WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(container);
479     WebKitWebViewBasePrivate* priv = webView->priv;
480
481     for (const auto& child : copyToVector(priv->children.keys())) {
482         if (priv->children.contains(child))
483             (*callback)(child, callbackData);
484     }
485
486     if (includeInternals && priv->inspectorView)
487         (*callback)(priv->inspectorView, callbackData);
488
489     if (includeInternals && priv->dialog)
490         (*callback)(priv->dialog, callbackData);
491 }
492
493 void webkitWebViewBaseChildMoveResize(WebKitWebViewBase* webView, GtkWidget* child, const IntRect& childRect)
494 {
495     const IntRect& geometry = webView->priv->children.get(child);
496     if (geometry == childRect)
497         return;
498
499     webView->priv->children.set(child, childRect);
500     gtk_widget_queue_resize_no_redraw(GTK_WIDGET(webView));
501 }
502
503 static void webkitWebViewBaseDispose(GObject* gobject)
504 {
505     WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(gobject);
506     webkitWebViewBaseSetToplevelOnScreenWindow(webView, nullptr);
507     webView->priv->pageProxy->close();
508     webView->priv->acceleratedBackingStore = nullptr;
509     webView->priv->sleepDisabler = nullptr;
510     G_OBJECT_CLASS(webkit_web_view_base_parent_class)->dispose(gobject);
511 }
512
513 static void webkitWebViewBaseConstructed(GObject* object)
514 {
515     G_OBJECT_CLASS(webkit_web_view_base_parent_class)->constructed(object);
516
517     GtkWidget* viewWidget = GTK_WIDGET(object);
518     gtk_widget_set_can_focus(viewWidget, TRUE);
519     gtk_drag_dest_set(viewWidget, static_cast<GtkDestDefaults>(0), nullptr, 0,
520         static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_LINK | GDK_ACTION_PRIVATE));
521     gtk_drag_dest_set_target_list(viewWidget, PasteboardHelper::singleton().targetList());
522
523     WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(object)->priv;
524     priv->pageClient = std::make_unique<PageClientImpl>(viewWidget);
525     priv->dialog = nullptr;
526 }
527
528 static gboolean webkitWebViewBaseDraw(GtkWidget* widget, cairo_t* cr)
529 {
530     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
531     auto* drawingArea = static_cast<DrawingAreaProxyCoordinatedGraphics*>(webViewBase->priv->pageProxy->drawingArea());
532     if (!drawingArea)
533         return FALSE;
534
535     GdkRectangle clipRect;
536     if (!gdk_cairo_get_clip_rectangle(cr, &clipRect))
537         return FALSE;
538
539     bool showingNavigationSnapshot = webViewBase->priv->pageProxy->isShowingNavigationGestureSnapshot();
540     if (showingNavigationSnapshot)
541         cairo_push_group(cr);
542
543     if (webViewBase->priv->acceleratedBackingStore && drawingArea->isInAcceleratedCompositingMode())
544         webViewBase->priv->acceleratedBackingStore->paint(cr, clipRect);
545     else {
546         WebCore::Region unpaintedRegion; // This is simply unused.
547         drawingArea->paint(cr, clipRect, unpaintedRegion);
548     }
549
550     if (showingNavigationSnapshot) {
551         ViewGestureController& controller = webkitWebViewBaseViewGestureController(webViewBase);
552         RefPtr<cairo_pattern_t> group = adoptRef(cairo_pop_group(cr));
553         controller.draw(cr, group.get());
554     }
555
556     GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->draw(widget, cr);
557
558     return FALSE;
559 }
560
561 static void webkitWebViewBaseChildAllocate(GtkWidget* child, gpointer userData)
562 {
563     if (!gtk_widget_get_visible(child))
564         return;
565
566     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(userData);
567     WebKitWebViewBasePrivate* priv = webViewBase->priv;
568     const IntRect& geometry = priv->children.get(child);
569     if (geometry.isEmpty())
570         return;
571
572     GtkAllocation childAllocation = geometry;
573     gtk_widget_size_allocate(child, &childAllocation);
574     priv->children.set(child, IntRect());
575 }
576
577 static void webkitWebViewBaseSizeAllocate(GtkWidget* widget, GtkAllocation* allocation)
578 {
579     GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->size_allocate(widget, allocation);
580
581     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
582     gtk_container_foreach(GTK_CONTAINER(webViewBase), webkitWebViewBaseChildAllocate, webViewBase);
583
584     IntRect viewRect(allocation->x, allocation->y, allocation->width, allocation->height);
585     WebKitWebViewBasePrivate* priv = webViewBase->priv;
586     if (priv->inspectorView) {
587         GtkAllocation childAllocation = viewRect;
588
589         if (priv->inspectorAttachmentSide == AttachmentSide::Bottom) {
590             int inspectorViewHeight = std::min(static_cast<int>(priv->inspectorViewSize), allocation->height);
591             childAllocation.x = 0;
592             childAllocation.y = allocation->height - inspectorViewHeight;
593             childAllocation.height = inspectorViewHeight;
594             viewRect.setHeight(std::max(allocation->height - inspectorViewHeight, 1));
595         } else {
596             int inspectorViewWidth = std::min(static_cast<int>(priv->inspectorViewSize), allocation->width);
597             childAllocation.y = 0;
598             childAllocation.x = allocation->width - inspectorViewWidth;
599             childAllocation.width = inspectorViewWidth;
600             viewRect.setWidth(std::max(allocation->width - inspectorViewWidth, 1));
601         }
602
603         gtk_widget_size_allocate(priv->inspectorView, &childAllocation);
604     }
605
606     // The dialogs are centered in the view rect, which means that it
607     // never overlaps the web inspector. Thus, we need to calculate the allocation here
608     // after calculating the inspector allocation.
609     if (priv->dialog) {
610         GtkRequisition minimumSize;
611         gtk_widget_get_preferred_size(priv->dialog, &minimumSize, nullptr);
612
613         GtkAllocation childAllocation = { 0, 0, std::max(minimumSize.width, viewRect.width()), std::max(minimumSize.height, viewRect.height()) };
614         gtk_widget_size_allocate(priv->dialog, &childAllocation);
615     }
616
617     if (auto* drawingArea = static_cast<DrawingAreaProxyCoordinatedGraphics*>(priv->pageProxy->drawingArea()))
618         drawingArea->setSize(viewRect.size());
619 }
620
621 static void webkitWebViewBaseGetPreferredWidth(GtkWidget* widget, gint* minimumSize, gint* naturalSize)
622 {
623     WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv;
624     *minimumSize = 0;
625     *naturalSize = priv->contentsSize.width();
626 }
627
628 static void webkitWebViewBaseGetPreferredHeight(GtkWidget* widget, gint* minimumSize, gint* naturalSize)
629 {
630     WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv;
631     *minimumSize = 0;
632     *naturalSize = priv->contentsSize.height();
633 }
634
635 static void webkitWebViewBaseMap(GtkWidget* widget)
636 {
637     GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->map(widget);
638
639     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
640     WebKitWebViewBasePrivate* priv = webViewBase->priv;
641     OptionSet<ActivityState::Flag> flagsToUpdate;
642     if (!(priv->activityState & ActivityState::IsVisible))
643         flagsToUpdate.add(ActivityState::IsVisible);
644     if (priv->toplevelOnScreenWindow) {
645         if (!(priv->activityState & ActivityState::IsInWindow))
646             flagsToUpdate.add(ActivityState::IsInWindow);
647         if (gtk_window_is_active(GTK_WINDOW(priv->toplevelOnScreenWindow)) && !(priv->activityState & ActivityState::WindowIsActive))
648             flagsToUpdate.add(ActivityState::WindowIsActive);
649     }
650     if (!flagsToUpdate)
651         return;
652
653     priv->activityState.add(flagsToUpdate);
654     webkitWebViewBaseScheduleUpdateActivityState(webViewBase, flagsToUpdate);
655 }
656
657 static void webkitWebViewBaseUnmap(GtkWidget* widget)
658 {
659     GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->unmap(widget);
660
661     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
662     WebKitWebViewBasePrivate* priv = webViewBase->priv;
663     if (!(priv->activityState & ActivityState::IsVisible))
664         return;
665
666     priv->activityState.remove(ActivityState::IsVisible);
667     webkitWebViewBaseScheduleUpdateActivityState(webViewBase, ActivityState::IsVisible);
668 }
669
670 static gboolean webkitWebViewBaseFocusInEvent(GtkWidget* widget, GdkEventFocus* event)
671 {
672     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
673     webkitWebViewBaseSetFocus(webViewBase, true);
674     webViewBase->priv->inputMethodFilter.notifyFocusedIn();
675
676     return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->focus_in_event(widget, event);
677 }
678
679 static gboolean webkitWebViewBaseFocusOutEvent(GtkWidget* widget, GdkEventFocus* event)
680 {
681     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
682     webkitWebViewBaseSetFocus(webViewBase, false);
683     webViewBase->priv->inputMethodFilter.notifyFocusedOut();
684
685     return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->focus_out_event(widget, event);
686 }
687
688 static gboolean webkitWebViewBaseKeyPressEvent(GtkWidget* widget, GdkEventKey* keyEvent)
689 {
690     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
691     WebKitWebViewBasePrivate* priv = webViewBase->priv;
692
693 #if ENABLE(DEVELOPER_MODE) && OS(LINUX)
694     if ((keyEvent->state & GDK_CONTROL_MASK) && (keyEvent->state & GDK_SHIFT_MASK) && keyEvent->keyval == GDK_KEY_G) {
695         auto& preferences = priv->pageProxy->preferences();
696         preferences.setResourceUsageOverlayVisible(!preferences.resourceUsageOverlayVisible());
697         priv->shouldForwardNextKeyEvent = FALSE;
698         return GDK_EVENT_STOP;
699     }
700 #endif
701
702     if (priv->dialog)
703         return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->key_press_event(widget, keyEvent);
704
705 #if ENABLE(FULLSCREEN_API)
706     if (priv->fullScreenModeActive) {
707         switch (keyEvent->keyval) {
708         case GDK_KEY_Escape:
709         case GDK_KEY_f:
710         case GDK_KEY_F:
711             priv->pageProxy->fullScreenManager()->requestExitFullScreen();
712             return GDK_EVENT_STOP;
713         default:
714             break;
715         }
716     }
717 #endif
718
719     // Since WebProcess key event handling is not synchronous, handle the event in two passes.
720     // When WebProcess processes the input event, it will call PageClientImpl::doneWithKeyEvent
721     // with event handled status which determines whether to pass the input event to parent or not
722     // using gtk_main_do_event().
723     if (priv->shouldForwardNextKeyEvent) {
724         priv->shouldForwardNextKeyEvent = FALSE;
725         return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->key_press_event(widget, keyEvent);
726     }
727
728     // We need to copy the event as otherwise it could be destroyed before we reach the lambda body.
729     GUniquePtr<GdkEvent> event(gdk_event_copy(reinterpret_cast<GdkEvent*>(keyEvent)));
730     priv->inputMethodFilter.filterKeyEvent(keyEvent, [priv, event = WTFMove(event)](const WebCore::CompositionResults& compositionResults, InputMethodFilter::EventFakedForComposition faked) {
731         priv->pageProxy->handleKeyboardEvent(NativeWebKeyboardEvent(event.get(), compositionResults, faked,
732             !compositionResults.compositionUpdated() ? priv->keyBindingTranslator.commandsForKeyEvent(&event->key) : Vector<String>()));
733     });
734
735     return GDK_EVENT_STOP;
736 }
737
738 static gboolean webkitWebViewBaseKeyReleaseEvent(GtkWidget* widget, GdkEventKey* keyEvent)
739 {
740     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
741     WebKitWebViewBasePrivate* priv = webViewBase->priv;
742
743     if (priv->shouldForwardNextKeyEvent) {
744         priv->shouldForwardNextKeyEvent = FALSE;
745         return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->key_release_event(widget, keyEvent);
746     }
747
748     // We need to copy the event as otherwise it could be destroyed before we reach the lambda body.
749     GUniquePtr<GdkEvent> event(gdk_event_copy(reinterpret_cast<GdkEvent*>(keyEvent)));
750     priv->inputMethodFilter.filterKeyEvent(keyEvent, [priv, event = WTFMove(event)](const WebCore::CompositionResults& compositionResults, InputMethodFilter::EventFakedForComposition faked) {
751         priv->pageProxy->handleKeyboardEvent(NativeWebKeyboardEvent(event.get(), compositionResults, faked, { }));
752     });
753
754     return GDK_EVENT_STOP;
755 }
756
757 static void webkitWebViewBaseHandleMouseEvent(WebKitWebViewBase* webViewBase, GdkEvent* event)
758 {
759     WebKitWebViewBasePrivate* priv = webViewBase->priv;
760     ASSERT(!priv->dialog);
761
762     int clickCount = 0;
763
764     switch (event->type) {
765     case GDK_BUTTON_PRESS:
766     case GDK_2BUTTON_PRESS:
767     case GDK_3BUTTON_PRESS: {
768         // For double and triple clicks GDK sends both a normal button press event
769         // and a specific type (like GDK_2BUTTON_PRESS). If we detect a special press
770         // coming up, ignore this event as it certainly generated the double or triple
771         // click. The consequence of not eating this event is two DOM button press events
772         // are generated.
773         GUniquePtr<GdkEvent> nextEvent(gdk_event_peek());
774         if (nextEvent && (nextEvent->any.type == GDK_2BUTTON_PRESS || nextEvent->any.type == GDK_3BUTTON_PRESS))
775             return;
776
777         priv->inputMethodFilter.notifyMouseButtonPress();
778
779         // If it's a right click event save it as a possible context menu event.
780         if (event->button.button == GDK_BUTTON_SECONDARY)
781             priv->contextMenuEvent.reset(gdk_event_copy(event));
782
783         clickCount = priv->clickCounter.currentClickCountForGdkButtonEvent(event);
784     }
785         FALLTHROUGH;
786     case GDK_BUTTON_RELEASE:
787         gtk_widget_grab_focus(GTK_WIDGET(webViewBase));
788         break;
789     case GDK_MOTION_NOTIFY:
790     case GDK_ENTER_NOTIFY:
791     case GDK_LEAVE_NOTIFY:
792         break;
793     default:
794         ASSERT_NOT_REACHED();
795     }
796
797     priv->pageProxy->handleMouseEvent(NativeWebMouseEvent(event, clickCount));
798 }
799
800 static gboolean webkitWebViewBaseButtonPressEvent(GtkWidget* widget, GdkEventButton* event)
801 {
802     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
803     WebKitWebViewBasePrivate* priv = webViewBase->priv;
804
805     if (priv->dialog)
806         return GDK_EVENT_STOP;
807
808     webkitWebViewBaseHandleMouseEvent(webViewBase, reinterpret_cast<GdkEvent*>(event));
809
810     return GDK_EVENT_STOP;
811 }
812
813 static gboolean webkitWebViewBaseButtonReleaseEvent(GtkWidget* widget, GdkEventButton* event)
814 {
815     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
816     WebKitWebViewBasePrivate* priv = webViewBase->priv;
817
818     if (priv->dialog)
819         return GDK_EVENT_STOP;
820
821     webkitWebViewBaseHandleMouseEvent(webViewBase, reinterpret_cast<GdkEvent*>(event));
822
823     return GDK_EVENT_STOP;
824 }
825
826 static void webkitWebViewBaseHandleWheelEvent(WebKitWebViewBase* webViewBase, GdkEvent* event, Optional<WebWheelEvent::Phase> phase = WTF::nullopt, Optional<WebWheelEvent::Phase> momentum = WTF::nullopt)
827 {
828     WebKitWebViewBasePrivate* priv = webViewBase->priv;
829     ASSERT(!priv->dialog);
830     if (phase)
831         priv->pageProxy->handleWheelEvent(NativeWebWheelEvent(event, phase.value(), momentum.valueOr(WebWheelEvent::Phase::PhaseNone)));
832     else
833         priv->pageProxy->handleWheelEvent(NativeWebWheelEvent(event));
834 }
835
836 static gboolean webkitWebViewBaseScrollEvent(GtkWidget* widget, GdkEventScroll* event)
837 {
838     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
839     WebKitWebViewBasePrivate* priv = webViewBase->priv;
840
841     if (std::exchange(priv->shouldForwardNextWheelEvent, false))
842         return GDK_EVENT_PROPAGATE;
843
844     if (priv->dialog)
845         return GDK_EVENT_PROPAGATE;
846
847     // Shift+Wheel scrolls in the perpendicular direction.
848     if (event->state & GDK_SHIFT_MASK) {
849         switch (event->direction) {
850         case GDK_SCROLL_UP:
851             event->direction = GDK_SCROLL_LEFT;
852             break;
853         case GDK_SCROLL_LEFT:
854             event->direction = GDK_SCROLL_UP;
855             break;
856         case GDK_SCROLL_DOWN:
857             event->direction = GDK_SCROLL_RIGHT;
858             break;
859         case GDK_SCROLL_RIGHT:
860             event->direction = GDK_SCROLL_DOWN;
861             break;
862         case GDK_SCROLL_SMOOTH:
863             std::swap(event->delta_x, event->delta_y);
864             break;
865         }
866     }
867
868     ViewGestureController& controller = webkitWebViewBaseViewGestureController(webViewBase);
869     if (controller.isSwipeGestureEnabled() && controller.handleScrollWheelEvent(event))
870         return GDK_EVENT_STOP;
871
872     webkitWebViewBaseHandleWheelEvent(webViewBase, reinterpret_cast<GdkEvent*>(event));
873
874     return GDK_EVENT_STOP;
875 }
876
877 static gboolean webkitWebViewBasePopupMenu(GtkWidget* widget)
878 {
879     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
880     WebKitWebViewBasePrivate* priv = webViewBase->priv;
881
882     GdkEvent* currentEvent = gtk_get_current_event();
883     if (!currentEvent)
884         currentEvent = gdk_event_new(GDK_NOTHING);
885     priv->contextMenuEvent.reset(currentEvent);
886     priv->pageProxy->handleContextMenuKeyEvent();
887
888     return TRUE;
889 }
890
891 static gboolean webkitWebViewBaseMotionNotifyEvent(GtkWidget* widget, GdkEventMotion* event)
892 {
893     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
894     WebKitWebViewBasePrivate* priv = webViewBase->priv;
895
896     if (priv->dialog) {
897         auto* widgetClass = GTK_WIDGET_CLASS(webkit_web_view_base_parent_class);
898         return widgetClass->motion_notify_event ? widgetClass->motion_notify_event(widget, event) : GDK_EVENT_PROPAGATE;
899     }
900
901     webkitWebViewBaseHandleMouseEvent(webViewBase, reinterpret_cast<GdkEvent*>(event));
902
903     return GDK_EVENT_PROPAGATE;
904 }
905
906 static gboolean webkitWebViewBaseCrossingNotifyEvent(GtkWidget* widget, GdkEventCrossing* crossingEvent)
907 {
908     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
909     WebKitWebViewBasePrivate* priv = webViewBase->priv;
910
911     if (priv->dialog)
912         return GDK_EVENT_PROPAGATE;
913
914 #if ENABLE(DEVELOPER_MODE)
915     // Do not send mouse move events to the WebProcess for crossing events during testing.
916     // WTR never generates crossing events and they can confuse tests.
917     // https://bugs.webkit.org/show_bug.cgi?id=185072.
918     if (UNLIKELY(priv->pageProxy->process().processPool().configuration().fullySynchronousModeIsAllowedForTesting()))
919         return GDK_EVENT_PROPAGATE;
920 #endif
921
922     // In the case of crossing events, it's very important the actual coordinates the WebProcess receives, because once the mouse leaves
923     // the web view, the WebProcess won't receive more events until the mouse enters again in the web view. So, if the coordinates of the leave
924     // event are not accurate, the WebProcess might not know the mouse left the view. This can happen because of double to integer conversion,
925     // if the coordinates of the leave event are for example (25.2, -0.9), the WebProcess will receive (25, 0) and any hit test will succeed
926     // because those coordinates are inside the web view.
927     GtkAllocation allocation;
928     gtk_widget_get_allocation(widget, &allocation);
929     double width = allocation.width;
930     double height = allocation.height;
931     double x = crossingEvent->x;
932     double y = crossingEvent->y;
933     if (x < 0 && x > -1)
934         x = -1;
935     else if (x >= width && x < width + 1)
936         x = width + 1;
937     if (y < 0 && y > -1)
938         y = -1;
939     else if (y >= height && y < height + 1)
940         y = height + 1;
941
942     GdkEvent* event = reinterpret_cast<GdkEvent*>(crossingEvent);
943     GUniquePtr<GdkEvent> copiedEvent;
944     if (x != crossingEvent->x || y != crossingEvent->y) {
945         copiedEvent.reset(gdk_event_copy(event));
946         copiedEvent->crossing.x = x;
947         copiedEvent->crossing.y = y;
948     }
949
950     webkitWebViewBaseHandleMouseEvent(webViewBase, copiedEvent ? copiedEvent.get() : event);
951
952     return GDK_EVENT_PROPAGATE;
953 }
954
955 #if ENABLE(TOUCH_EVENTS)
956 static void appendTouchEvent(Vector<WebPlatformTouchPoint>& touchPoints, const GdkEvent* event, WebPlatformTouchPoint::TouchPointState state)
957 {
958     gdouble x, y;
959     gdk_event_get_coords(event, &x, &y);
960
961     gdouble xRoot, yRoot;
962     gdk_event_get_root_coords(event, &xRoot, &yRoot);
963
964     uint32_t identifier = GPOINTER_TO_UINT(gdk_event_get_event_sequence(event));
965     touchPoints.uncheckedAppend(WebPlatformTouchPoint(identifier, state, IntPoint(xRoot, yRoot), IntPoint(x, y)));
966 }
967
968 static inline WebPlatformTouchPoint::TouchPointState touchPointStateForEvents(const GdkEvent* current, const GdkEvent* event)
969 {
970     if (gdk_event_get_event_sequence(current) != gdk_event_get_event_sequence(event))
971         return WebPlatformTouchPoint::TouchStationary;
972
973     switch (current->type) {
974     case GDK_TOUCH_UPDATE:
975         return WebPlatformTouchPoint::TouchMoved;
976     case GDK_TOUCH_BEGIN:
977         return WebPlatformTouchPoint::TouchPressed;
978     case GDK_TOUCH_END:
979         return WebPlatformTouchPoint::TouchReleased;
980     case GDK_TOUCH_CANCEL:
981         return WebPlatformTouchPoint::TouchCancelled;
982     default:
983         return WebPlatformTouchPoint::TouchStationary;
984     }
985 }
986
987 static void webkitWebViewBaseGetTouchPointsForEvent(WebKitWebViewBase* webViewBase, GdkEvent* event, Vector<WebPlatformTouchPoint>& touchPoints)
988 {
989     WebKitWebViewBasePrivate* priv = webViewBase->priv;
990     bool touchEnd = (event->type == GDK_TOUCH_END) || (event->type == GDK_TOUCH_CANCEL);
991     touchPoints.reserveInitialCapacity(touchEnd ? priv->touchEvents.size() + 1 : priv->touchEvents.size());
992
993     for (const auto& it : priv->touchEvents)
994         appendTouchEvent(touchPoints, it.value.get(), touchPointStateForEvents(it.value.get(), event));
995
996     // Touch was already removed from the TouchEventsMap, add it here.
997     if (touchEnd)
998         appendTouchEvent(touchPoints, event, WebPlatformTouchPoint::TouchReleased);
999 }
1000
1001 static gboolean webkitWebViewBaseTouchEvent(GtkWidget* widget, GdkEventTouch* event)
1002 {
1003     WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget);
1004     WebKitWebViewBasePrivate* priv = webViewBase->priv;
1005
1006     if (priv->dialog)
1007         return GDK_EVENT_STOP;
1008
1009     GdkEvent* touchEvent = reinterpret_cast<GdkEvent*>(event);
1010     uint32_t sequence = GPOINTER_TO_UINT(gdk_event_get_event_sequence(touchEvent));
1011
1012     switch (touchEvent->type) {
1013     case GDK_TOUCH_BEGIN: {
1014         ASSERT(!priv->touchEvents.contains(sequence));
1015         GUniquePtr<GdkEvent> event(gdk_event_copy(touchEvent));
1016         priv->touchEvents.add(sequence, WTFMove(event));
1017         break;
1018     }
1019     case GDK_TOUCH_UPDATE: {
1020         auto it = priv->touchEvents.find(sequence);
1021         ASSERT(it != priv->touchEvents.end());
1022         it->value.reset(gdk_event_copy(touchEvent));
1023         break;
1024     }
1025     case GDK_TOUCH_CANCEL:
1026         FALLTHROUGH;
1027     case GDK_TOUCH_END:
1028         ASSERT(priv->touchEvents.contains(sequence));
1029         priv->touchEvents.remove(sequence);
1030         break;
1031     default:
1032         break;
1033     }
1034
1035     Vector<WebPlatformTouchPoint> touchPoints;
1036     webkitWebViewBaseGetTouchPointsForEvent(webViewBase, touchEvent, touchPoints);
1037     priv->pageProxy->handleTouchEvent(NativeWebTouchEvent(reinterpret_cast<GdkEvent*>(event), WTFMove(touchPoints)));
1038
1039     return GDK_EVENT_STOP;
1040 }
1041 #endif // ENABLE(TOUCH_EVENTS)
1042
1043 #if HAVE(GTK_GESTURES)
1044 class TouchGestureController final : public GestureControllerClient {
1045     WTF_MAKE_FAST_ALLOCATED;
1046
1047 public:
1048     explicit TouchGestureController(WebKitWebViewBase* webViewBase)
1049         : m_webView(webViewBase)
1050     {
1051     }
1052
1053 private:
1054     static GUniquePtr<GdkEvent> createScrollEvent(GdkEventTouch* event, const FloatPoint& point, const FloatPoint& delta, bool isStop = false)
1055     {
1056         GUniquePtr<GdkEvent> scrollEvent(gdk_event_new(GDK_SCROLL));
1057         scrollEvent->scroll.time = event->time;
1058         scrollEvent->scroll.x = point.x();
1059         scrollEvent->scroll.y = point.y();
1060         scrollEvent->scroll.x_root = event->x_root;
1061         scrollEvent->scroll.y_root = event->y_root;
1062         scrollEvent->scroll.direction = GDK_SCROLL_SMOOTH;
1063         scrollEvent->scroll.delta_x = delta.x();
1064         scrollEvent->scroll.delta_y = delta.y();
1065         scrollEvent->scroll.state = event->state;
1066 #if GTK_CHECK_VERSION(3, 20, 0)
1067         scrollEvent->scroll.is_stop = isStop;
1068 #else
1069         UNUSED_PARAM(isStop);
1070 #endif
1071         scrollEvent->scroll.window = event->window ? GDK_WINDOW(g_object_ref(event->window)) : nullptr;
1072         auto* touchEvent = reinterpret_cast<GdkEvent*>(event);
1073         gdk_event_set_screen(scrollEvent.get(), gdk_event_get_screen(touchEvent));
1074         gdk_event_set_device(scrollEvent.get(), gdk_event_get_device(touchEvent));
1075         gdk_event_set_source_device(scrollEvent.get(), gdk_event_get_source_device(touchEvent));
1076         return scrollEvent;
1077     }
1078
1079     void simulateMouseClick(GdkEventTouch* event, unsigned button)
1080     {
1081         GUniquePtr<GdkEvent> pointerEvent(gdk_event_new(GDK_MOTION_NOTIFY));
1082         pointerEvent->motion.time = event->time;
1083         pointerEvent->motion.x = event->x;
1084         pointerEvent->motion.y = event->y;
1085         pointerEvent->motion.x_root = event->x_root;
1086         pointerEvent->motion.y_root = event->y_root;
1087         pointerEvent->motion.state = event->state;
1088         pointerEvent->motion.window = event->window ? GDK_WINDOW(g_object_ref(event->window)) : nullptr;
1089         auto* touchEvent = reinterpret_cast<GdkEvent*>(event);
1090         gdk_event_set_screen(pointerEvent.get(), gdk_event_get_screen(touchEvent));
1091         gdk_event_set_device(pointerEvent.get(), gdk_event_get_device(touchEvent));
1092         gdk_event_set_source_device(pointerEvent.get(), gdk_event_get_source_device(touchEvent));
1093         webkitWebViewBaseHandleMouseEvent(m_webView, pointerEvent.get());
1094
1095         pointerEvent.reset(gdk_event_new(GDK_BUTTON_PRESS));
1096         pointerEvent->button.button = button;
1097         pointerEvent->button.time = event->time;
1098         pointerEvent->button.x = event->x;
1099         pointerEvent->button.y = event->y;
1100         pointerEvent->button.x_root = event->x_root;
1101         pointerEvent->button.y_root = event->y_root;
1102         pointerEvent->button.window = event->window ? GDK_WINDOW(g_object_ref(event->window)) : nullptr;
1103         gdk_event_set_screen(pointerEvent.get(), gdk_event_get_screen(touchEvent));
1104         gdk_event_set_device(pointerEvent.get(), gdk_event_get_device(touchEvent));
1105         gdk_event_set_source_device(pointerEvent.get(), gdk_event_get_source_device(touchEvent));
1106         webkitWebViewBaseHandleMouseEvent(m_webView, pointerEvent.get());
1107
1108         pointerEvent->type = GDK_BUTTON_RELEASE;
1109         webkitWebViewBaseHandleMouseEvent(m_webView, pointerEvent.get());
1110     }
1111
1112     void tap(GdkEventTouch* event) final
1113     {
1114         simulateMouseClick(event, GDK_BUTTON_PRIMARY);
1115     }
1116
1117     void startDrag(GdkEventTouch* event, const FloatPoint& startPoint) final
1118     {
1119         GUniquePtr<GdkEvent> scrollEvent = createScrollEvent(event, startPoint, { });
1120         webkitWebViewBaseHandleWheelEvent(m_webView, scrollEvent.get(), WebWheelEvent::Phase::PhaseBegan);
1121     }
1122
1123     void drag(GdkEventTouch* event, const FloatPoint& point, const FloatPoint& delta) final
1124     {
1125         GUniquePtr<GdkEvent> scrollEvent = createScrollEvent(event, point, delta);
1126         webkitWebViewBaseHandleWheelEvent(m_webView, scrollEvent.get(), WebWheelEvent::Phase::PhaseChanged);
1127     }
1128
1129     void swipe(GdkEventTouch* event, const FloatPoint& velocity) final
1130     {
1131         GUniquePtr<GdkEvent> scrollEvent = createScrollEvent(event, FloatPoint::narrowPrecision(event->x, event->y), velocity, true);
1132         webkitWebViewBaseHandleWheelEvent(m_webView, scrollEvent.get(), WebWheelEvent::Phase::PhaseNone, WebWheelEvent::Phase::PhaseBegan);
1133     }
1134
1135     void startZoom(const IntPoint& center, double& initialScale, IntPoint& initialPoint) final
1136     {
1137         auto* page = m_webView->priv->pageProxy.get();
1138         ASSERT(page);
1139         initialScale = page->pageScaleFactor();
1140         page->getCenterForZoomGesture(center, initialPoint);
1141     }
1142
1143     void zoom(double scale, const IntPoint& origin) final
1144     {
1145         auto* page = m_webView->priv->pageProxy.get();
1146         ASSERT(page);
1147
1148         page->scalePage(scale, origin);
1149     }
1150
1151     void longPress(GdkEventTouch* event) final
1152     {
1153         simulateMouseClick(event, GDK_BUTTON_SECONDARY);
1154     }
1155
1156     WebKitWebViewBase* m_webView;
1157 };
1158
1159 GestureController& webkitWebViewBaseGestureController(WebKitWebViewBase* webViewBase)
1160 {
1161     WebKitWebViewBasePrivate* priv = webViewBase->priv;
1162     if (!priv->gestureController)
1163         priv->gestureController = std::make_unique<GestureController>(GTK_WIDGET(webViewBase), std::make_unique<TouchGestureController>(webViewBase));
1164     return *priv->gestureController;
1165 }
1166 #endif
1167
1168 ViewGestureController& webkitWebViewBaseViewGestureController(WebKitWebViewBase* webViewBase)
1169 {
1170     return *webViewBase->priv->viewGestureController;
1171 }
1172
1173 static gboolean webkitWebViewBaseQueryTooltip(GtkWidget* widget, gint /* x */, gint /* y */, gboolean keyboardMode, GtkTooltip* tooltip)
1174 {
1175     WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv;
1176
1177     if (keyboardMode) {
1178         // TODO: https://bugs.webkit.org/show_bug.cgi?id=61732.
1179         notImplemented();
1180         return FALSE;
1181     }
1182
1183     if (priv->tooltipText.length() <= 0)
1184         return FALSE;
1185
1186     if (!priv->tooltipArea.isEmpty()) {
1187         GdkRectangle area = priv->tooltipArea;
1188         gtk_tooltip_set_tip_area(tooltip, &area);
1189     } else
1190         gtk_tooltip_set_tip_area(tooltip, 0);
1191     gtk_tooltip_set_text(tooltip, priv->tooltipText.data());
1192
1193     return TRUE;
1194 }
1195
1196 #if ENABLE(DRAG_SUPPORT)
1197 static void webkitWebViewBaseDragDataGet(GtkWidget* widget, GdkDragContext* context, GtkSelectionData* selectionData, guint info, guint /* time */)
1198 {
1199     WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv;
1200     ASSERT(priv->dragAndDropHandler);
1201     priv->dragAndDropHandler->fillDragData(context, selectionData, info);
1202 }
1203
1204 static void webkitWebViewBaseDragEnd(GtkWidget* widget, GdkDragContext* context)
1205 {
1206     WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv;
1207     ASSERT(priv->dragAndDropHandler);
1208     priv->dragAndDropHandler->finishDrag(context);
1209 }
1210
1211 static void webkitWebViewBaseDragDataReceived(GtkWidget* widget, GdkDragContext* context, gint /* x */, gint /* y */, GtkSelectionData* selectionData, guint info, guint time)
1212 {
1213     webkitWebViewBaseDragAndDropHandler(WEBKIT_WEB_VIEW_BASE(widget)).dragEntered(context, selectionData, info, time);
1214 }
1215 #endif // ENABLE(DRAG_SUPPORT)
1216
1217 static gboolean webkitWebViewBaseEvent(GtkWidget* widget, GdkEvent* event)
1218 {
1219 #if HAVE(GTK_GESTURES)
1220     if (event->type == GDK_TOUCHPAD_PINCH)
1221         webkitWebViewBaseGestureController(WEBKIT_WEB_VIEW_BASE(widget)).handleEvent(event);
1222 #endif
1223
1224     return GDK_EVENT_PROPAGATE;
1225 }
1226
1227 static AtkObject* webkitWebViewBaseGetAccessible(GtkWidget* widget)
1228 {
1229     WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv;
1230     if (!priv->accessible) {
1231         // Create the accessible object and associate it to the widget.
1232         priv->accessible = adoptGRef(ATK_OBJECT(webkitWebViewBaseAccessibleNew(widget)));
1233
1234         // Set the parent to not break bottom-up navigation.
1235         if (auto* parentWidget = gtk_widget_get_parent(widget)) {
1236             if (auto* axParent = gtk_widget_get_accessible(parentWidget))
1237                 atk_object_set_parent(priv->accessible.get(), axParent);
1238         }
1239     }
1240
1241     return priv->accessible.get();
1242 }
1243
1244 #if ENABLE(DRAG_SUPPORT)
1245 static gboolean webkitWebViewBaseDragMotion(GtkWidget* widget, GdkDragContext* context, gint x, gint y, guint time)
1246 {
1247     webkitWebViewBaseDragAndDropHandler(WEBKIT_WEB_VIEW_BASE(widget)).dragMotion(context, IntPoint(x, y), time);
1248     return TRUE;
1249 }
1250
1251 static void webkitWebViewBaseDragLeave(GtkWidget* widget, GdkDragContext* context, guint /* time */)
1252 {
1253     WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv;
1254     ASSERT(priv->dragAndDropHandler);
1255     priv->dragAndDropHandler->dragLeave(context);
1256 }
1257
1258 static gboolean webkitWebViewBaseDragDrop(GtkWidget* widget, GdkDragContext* context, gint x, gint y, guint time)
1259 {
1260     WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv;
1261     ASSERT(priv->dragAndDropHandler);
1262     return priv->dragAndDropHandler->drop(context, IntPoint(x, y), time);
1263 }
1264 #endif // ENABLE(DRAG_SUPPORT)
1265
1266 static void webkitWebViewBaseHierarchyChanged(GtkWidget* widget, GtkWidget* oldToplevel)
1267 {
1268     WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv;
1269     if (widgetIsOnscreenToplevelWindow(oldToplevel) && GTK_WINDOW(oldToplevel) == priv->toplevelOnScreenWindow) {
1270         webkitWebViewBaseSetToplevelOnScreenWindow(WEBKIT_WEB_VIEW_BASE(widget), nullptr);
1271         return;
1272     }
1273
1274     if (!oldToplevel) {
1275         GtkWidget* toplevel = gtk_widget_get_toplevel(widget);
1276         if (widgetIsOnscreenToplevelWindow(toplevel))
1277             webkitWebViewBaseSetToplevelOnScreenWindow(WEBKIT_WEB_VIEW_BASE(widget), GTK_WINDOW(toplevel));
1278     }
1279 }
1280
1281 static gboolean webkitWebViewBaseFocus(GtkWidget* widget, GtkDirectionType direction)
1282 {
1283     // If a dialog is active, we need to forward focus events there. This
1284     // ensures that you can tab between elements in the box.
1285     WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv;
1286     if (priv->dialog) {
1287         gboolean returnValue;
1288         g_signal_emit_by_name(priv->dialog, "focus", direction, &returnValue);
1289         return returnValue;
1290     }
1291
1292     return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->focus(widget, direction);
1293 }
1294
1295 static void webkitWebViewBaseDestroy(GtkWidget* widget)
1296 {
1297     WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv;
1298     if (priv->dialog)
1299         gtk_widget_destroy(priv->dialog);
1300
1301     GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->destroy(widget);
1302 }
1303
1304 static void webkit_web_view_base_class_init(WebKitWebViewBaseClass* webkitWebViewBaseClass)
1305 {
1306     GtkWidgetClass* widgetClass = GTK_WIDGET_CLASS(webkitWebViewBaseClass);
1307     widgetClass->realize = webkitWebViewBaseRealize;
1308     widgetClass->unrealize = webkitWebViewBaseUnrealize;
1309     widgetClass->draw = webkitWebViewBaseDraw;
1310     widgetClass->size_allocate = webkitWebViewBaseSizeAllocate;
1311     widgetClass->get_preferred_width = webkitWebViewBaseGetPreferredWidth;
1312     widgetClass->get_preferred_height = webkitWebViewBaseGetPreferredHeight;
1313     widgetClass->map = webkitWebViewBaseMap;
1314     widgetClass->unmap = webkitWebViewBaseUnmap;
1315     widgetClass->focus = webkitWebViewBaseFocus;
1316     widgetClass->focus_in_event = webkitWebViewBaseFocusInEvent;
1317     widgetClass->focus_out_event = webkitWebViewBaseFocusOutEvent;
1318     widgetClass->key_press_event = webkitWebViewBaseKeyPressEvent;
1319     widgetClass->key_release_event = webkitWebViewBaseKeyReleaseEvent;
1320     widgetClass->button_press_event = webkitWebViewBaseButtonPressEvent;
1321     widgetClass->button_release_event = webkitWebViewBaseButtonReleaseEvent;
1322     widgetClass->scroll_event = webkitWebViewBaseScrollEvent;
1323     widgetClass->popup_menu = webkitWebViewBasePopupMenu;
1324     widgetClass->motion_notify_event = webkitWebViewBaseMotionNotifyEvent;
1325     widgetClass->enter_notify_event = webkitWebViewBaseCrossingNotifyEvent;
1326     widgetClass->leave_notify_event = webkitWebViewBaseCrossingNotifyEvent;
1327 #if ENABLE(TOUCH_EVENTS)
1328     widgetClass->touch_event = webkitWebViewBaseTouchEvent;
1329 #endif
1330     widgetClass->query_tooltip = webkitWebViewBaseQueryTooltip;
1331 #if ENABLE(DRAG_SUPPORT)
1332     widgetClass->drag_end = webkitWebViewBaseDragEnd;
1333     widgetClass->drag_data_get = webkitWebViewBaseDragDataGet;
1334     widgetClass->drag_motion = webkitWebViewBaseDragMotion;
1335     widgetClass->drag_leave = webkitWebViewBaseDragLeave;
1336     widgetClass->drag_drop = webkitWebViewBaseDragDrop;
1337     widgetClass->drag_data_received = webkitWebViewBaseDragDataReceived;
1338 #endif // ENABLE(DRAG_SUPPORT)
1339     widgetClass->event = webkitWebViewBaseEvent;
1340     widgetClass->get_accessible = webkitWebViewBaseGetAccessible;
1341     widgetClass->hierarchy_changed = webkitWebViewBaseHierarchyChanged;
1342     widgetClass->destroy = webkitWebViewBaseDestroy;
1343
1344     GObjectClass* gobjectClass = G_OBJECT_CLASS(webkitWebViewBaseClass);
1345     gobjectClass->constructed = webkitWebViewBaseConstructed;
1346     gobjectClass->dispose = webkitWebViewBaseDispose;
1347
1348     GtkContainerClass* containerClass = GTK_CONTAINER_CLASS(webkitWebViewBaseClass);
1349     containerClass->add = webkitWebViewBaseContainerAdd;
1350     containerClass->remove = webkitWebViewBaseContainerRemove;
1351     containerClass->forall = webkitWebViewBaseContainerForall;
1352
1353     // Before creating a WebKitWebViewBasePriv we need to be sure that WebKit is started.
1354     // Usually starting a context triggers InitializeWebKit2, but in case
1355     // we create a view without asking before for a default_context we get a crash.
1356     WebKit::InitializeWebKit2();
1357 }
1358
1359 WebKitWebViewBase* webkitWebViewBaseCreate(const API::PageConfiguration& configuration)
1360 {
1361     WebKitWebViewBase* webkitWebViewBase = WEBKIT_WEB_VIEW_BASE(g_object_new(WEBKIT_TYPE_WEB_VIEW_BASE, nullptr));
1362     webkitWebViewBaseCreateWebPage(webkitWebViewBase, configuration.copy());
1363     return webkitWebViewBase;
1364 }
1365
1366 GtkIMContext* webkitWebViewBaseGetIMContext(WebKitWebViewBase* webkitWebViewBase)
1367 {
1368     return webkitWebViewBase->priv->inputMethodFilter.context();
1369 }
1370
1371 WebPageProxy* webkitWebViewBaseGetPage(WebKitWebViewBase* webkitWebViewBase)
1372 {
1373     return webkitWebViewBase->priv->pageProxy.get();
1374 }
1375
1376 #if HAVE(GTK_SCALE_FACTOR)
1377 static void deviceScaleFactorChanged(WebKitWebViewBase* webkitWebViewBase)
1378 {
1379     webkitWebViewBase->priv->pageProxy->setIntrinsicDeviceScaleFactor(gtk_widget_get_scale_factor(GTK_WIDGET(webkitWebViewBase)));
1380 }
1381 #endif // HAVE(GTK_SCALE_FACTOR)
1382
1383 void webkitWebViewBaseCreateWebPage(WebKitWebViewBase* webkitWebViewBase, Ref<API::PageConfiguration>&& configuration)
1384 {
1385     WebKitWebViewBasePrivate* priv = webkitWebViewBase->priv;
1386     WebProcessPool* processPool = configuration->processPool();
1387     priv->pageProxy = processPool->createWebPage(*priv->pageClient, WTFMove(configuration));
1388     priv->pageProxy->initializeWebPage();
1389
1390     priv->acceleratedBackingStore = AcceleratedBackingStore::create(*priv->pageProxy);
1391
1392     priv->inputMethodFilter.setPage(priv->pageProxy.get());
1393
1394 #if HAVE(GTK_SCALE_FACTOR)
1395     // We attach this here, because changes in scale factor are passed directly to the page proxy.
1396     priv->pageProxy->setIntrinsicDeviceScaleFactor(gtk_widget_get_scale_factor(GTK_WIDGET(webkitWebViewBase)));
1397     g_signal_connect(webkitWebViewBase, "notify::scale-factor", G_CALLBACK(deviceScaleFactorChanged), nullptr);
1398 #endif
1399
1400     priv->viewGestureController = std::make_unique<WebKit::ViewGestureController>(*priv->pageProxy);
1401 }
1402
1403 void webkitWebViewBaseSetTooltipText(WebKitWebViewBase* webViewBase, const char* tooltip)
1404 {
1405     WebKitWebViewBasePrivate* priv = webViewBase->priv;
1406     if (tooltip && tooltip[0] != '\0') {
1407         priv->tooltipText = tooltip;
1408         gtk_widget_set_has_tooltip(GTK_WIDGET(webViewBase), TRUE);
1409     } else {
1410         priv->tooltipText = "";
1411         gtk_widget_set_has_tooltip(GTK_WIDGET(webViewBase), FALSE);
1412     }
1413
1414     gtk_widget_trigger_tooltip_query(GTK_WIDGET(webViewBase));
1415 }
1416
1417 void webkitWebViewBaseSetTooltipArea(WebKitWebViewBase* webViewBase, const IntRect& tooltipArea)
1418 {
1419     webViewBase->priv->tooltipArea = tooltipArea;
1420 }
1421
1422 #if ENABLE(DRAG_SUPPORT)
1423 DragAndDropHandler& webkitWebViewBaseDragAndDropHandler(WebKitWebViewBase* webViewBase)
1424 {
1425     WebKitWebViewBasePrivate* priv = webViewBase->priv;
1426     if (!priv->dragAndDropHandler)
1427         priv->dragAndDropHandler = std::make_unique<DragAndDropHandler>(*priv->pageProxy);
1428     return *priv->dragAndDropHandler;
1429 }
1430 #endif // ENABLE(DRAG_SUPPORT)
1431
1432 void webkitWebViewBaseForwardNextKeyEvent(WebKitWebViewBase* webkitWebViewBase)
1433 {
1434     webkitWebViewBase->priv->shouldForwardNextKeyEvent = TRUE;
1435 }
1436
1437 void webkitWebViewBaseForwardNextWheelEvent(WebKitWebViewBase* webkitWebViewBase)
1438 {
1439     webkitWebViewBase->priv->shouldForwardNextWheelEvent = true;
1440 }
1441
1442 void webkitWebViewBaseEnterFullScreen(WebKitWebViewBase* webkitWebViewBase)
1443 {
1444 #if ENABLE(FULLSCREEN_API)
1445     WebKitWebViewBasePrivate* priv = webkitWebViewBase->priv;
1446     ASSERT(!priv->fullScreenModeActive);
1447
1448     WebFullScreenManagerProxy* fullScreenManagerProxy = priv->pageProxy->fullScreenManager();
1449     fullScreenManagerProxy->willEnterFullScreen();
1450
1451     GtkWidget* topLevelWindow = gtk_widget_get_toplevel(GTK_WIDGET(webkitWebViewBase));
1452     if (gtk_widget_is_toplevel(topLevelWindow))
1453         gtk_window_fullscreen(GTK_WINDOW(topLevelWindow));
1454     fullScreenManagerProxy->didEnterFullScreen();
1455     priv->fullScreenModeActive = true;
1456     priv->sleepDisabler = PAL::SleepDisabler::create(_("Website running in fullscreen mode"), PAL::SleepDisabler::Type::Display);
1457 #endif
1458 }
1459
1460 void webkitWebViewBaseExitFullScreen(WebKitWebViewBase* webkitWebViewBase)
1461 {
1462 #if ENABLE(FULLSCREEN_API)
1463     WebKitWebViewBasePrivate* priv = webkitWebViewBase->priv;
1464     ASSERT(priv->fullScreenModeActive);
1465
1466     WebFullScreenManagerProxy* fullScreenManagerProxy = priv->pageProxy->fullScreenManager();
1467     fullScreenManagerProxy->willExitFullScreen();
1468
1469     GtkWidget* topLevelWindow = gtk_widget_get_toplevel(GTK_WIDGET(webkitWebViewBase));
1470     if (gtk_widget_is_toplevel(topLevelWindow))
1471         gtk_window_unfullscreen(GTK_WINDOW(topLevelWindow));
1472     fullScreenManagerProxy->didExitFullScreen();
1473     priv->fullScreenModeActive = false;
1474     priv->sleepDisabler = nullptr;
1475 #endif
1476 }
1477
1478 bool webkitWebViewBaseIsFullScreen(WebKitWebViewBase* webkitWebViewBase)
1479 {
1480 #if ENABLE(FULLSCREEN_API)
1481     return webkitWebViewBase->priv->fullScreenModeActive;
1482 #else
1483     return false;
1484 #endif
1485 }
1486
1487 void webkitWebViewBaseSetInspectorViewSize(WebKitWebViewBase* webkitWebViewBase, unsigned size)
1488 {
1489     if (webkitWebViewBase->priv->inspectorViewSize == size)
1490         return;
1491     webkitWebViewBase->priv->inspectorViewSize = size;
1492     if (webkitWebViewBase->priv->inspectorView)
1493         gtk_widget_queue_resize_no_redraw(GTK_WIDGET(webkitWebViewBase));
1494 }
1495
1496 static void activeContextMenuUnmapped(GtkMenu* menu, WebKitWebViewBase* webViewBase)
1497 {
1498     if (webViewBase->priv->activeContextMenuProxy && webViewBase->priv->activeContextMenuProxy->gtkMenu() == menu)
1499         webViewBase->priv->activeContextMenuProxy = nullptr;
1500 }
1501
1502 void webkitWebViewBaseSetActiveContextMenuProxy(WebKitWebViewBase* webkitWebViewBase, WebContextMenuProxyGtk* contextMenuProxy)
1503 {
1504     webkitWebViewBase->priv->activeContextMenuProxy = contextMenuProxy;
1505     g_signal_connect_object(contextMenuProxy->gtkMenu(), "unmap", G_CALLBACK(activeContextMenuUnmapped), webkitWebViewBase, static_cast<GConnectFlags>(0));
1506 }
1507
1508 WebContextMenuProxyGtk* webkitWebViewBaseGetActiveContextMenuProxy(WebKitWebViewBase* webkitWebViewBase)
1509 {
1510     return webkitWebViewBase->priv->activeContextMenuProxy;
1511 }
1512
1513 GdkEvent* webkitWebViewBaseTakeContextMenuEvent(WebKitWebViewBase* webkitWebViewBase)
1514 {
1515     return webkitWebViewBase->priv->contextMenuEvent.release();
1516 }
1517
1518 void webkitWebViewBaseSetFocus(WebKitWebViewBase* webViewBase, bool focused)
1519 {
1520     WebKitWebViewBasePrivate* priv = webViewBase->priv;
1521     if ((focused && priv->activityState & ActivityState::IsFocused) || (!focused && !(priv->activityState & ActivityState::IsFocused)))
1522         return;
1523
1524     OptionSet<ActivityState::Flag> flagsToUpdate { ActivityState::IsFocused };
1525     if (focused) {
1526         priv->activityState.add(ActivityState::IsFocused);
1527
1528         // If the view has received the focus and the window is not active
1529         // mark the current window as active now. This can happen if the
1530         // toplevel window is a GTK_WINDOW_POPUP and the focus has been
1531         // set programatically like WebKitTestRunner does, because POPUP
1532         // can't be focused.
1533         if (!(priv->activityState & ActivityState::WindowIsActive)) {
1534             priv->activityState.add(ActivityState::WindowIsActive);
1535             flagsToUpdate.add(ActivityState::WindowIsActive);
1536         }
1537     } else
1538         priv->activityState.remove(ActivityState::IsFocused);
1539
1540     webkitWebViewBaseScheduleUpdateActivityState(webViewBase, flagsToUpdate);
1541 }
1542
1543 bool webkitWebViewBaseIsInWindowActive(WebKitWebViewBase* webViewBase)
1544 {
1545     return webViewBase->priv->activityState.contains(ActivityState::WindowIsActive);
1546 }
1547
1548 bool webkitWebViewBaseIsFocused(WebKitWebViewBase* webViewBase)
1549 {
1550     return webViewBase->priv->activityState.contains(ActivityState::IsFocused);
1551 }
1552
1553 bool webkitWebViewBaseIsVisible(WebKitWebViewBase* webViewBase)
1554 {
1555     return webViewBase->priv->activityState.contains(ActivityState::IsVisible);
1556 }
1557
1558 bool webkitWebViewBaseIsInWindow(WebKitWebViewBase* webViewBase)
1559 {
1560     return webViewBase->priv->activityState.contains(ActivityState::IsInWindow);
1561 }
1562
1563 void webkitWebViewBaseSetInputMethodState(WebKitWebViewBase* webkitWebViewBase, bool enabled)
1564 {
1565     webkitWebViewBase->priv->inputMethodFilter.setEnabled(enabled);
1566 }
1567
1568 void webkitWebViewBaseUpdateTextInputState(WebKitWebViewBase* webkitWebViewBase)
1569 {
1570     const auto& editorState = webkitWebViewBase->priv->pageProxy->editorState();
1571     if (!editorState.isMissingPostLayoutData)
1572         webkitWebViewBase->priv->inputMethodFilter.setCursorRect(editorState.postLayoutData().caretRectAtStart);
1573 }
1574
1575 void webkitWebViewBaseSetContentsSize(WebKitWebViewBase* webkitWebViewBase, const IntSize& contentsSize)
1576 {
1577     WebKitWebViewBasePrivate* priv = webkitWebViewBase->priv;
1578     if (priv->contentsSize == contentsSize)
1579         return;
1580     priv->contentsSize = contentsSize;
1581 }
1582
1583 void webkitWebViewBaseResetClickCounter(WebKitWebViewBase* webkitWebViewBase)
1584 {
1585     webkitWebViewBase->priv->clickCounter.reset();
1586 }
1587
1588 void webkitWebViewBaseEnterAcceleratedCompositingMode(WebKitWebViewBase* webkitWebViewBase, const LayerTreeContext& layerTreeContext)
1589 {
1590     if (webkitWebViewBase->priv->acceleratedBackingStore)
1591         webkitWebViewBase->priv->acceleratedBackingStore->update(layerTreeContext);
1592 }
1593
1594 void webkitWebViewBaseUpdateAcceleratedCompositingMode(WebKitWebViewBase* webkitWebViewBase, const LayerTreeContext& layerTreeContext)
1595 {
1596     if (webkitWebViewBase->priv->acceleratedBackingStore)
1597         webkitWebViewBase->priv->acceleratedBackingStore->update(layerTreeContext);
1598 }
1599
1600 void webkitWebViewBaseExitAcceleratedCompositingMode(WebKitWebViewBase* webkitWebViewBase)
1601 {
1602     if (webkitWebViewBase->priv->acceleratedBackingStore)
1603         webkitWebViewBase->priv->acceleratedBackingStore->update(LayerTreeContext());
1604 }
1605
1606 bool webkitWebViewBaseMakeGLContextCurrent(WebKitWebViewBase* webkitWebViewBase)
1607 {
1608     if (webkitWebViewBase->priv->acceleratedBackingStore)
1609         return webkitWebViewBase->priv->acceleratedBackingStore->makeContextCurrent();
1610     return false;
1611 }
1612
1613 void webkitWebViewBaseDidRelaunchWebProcess(WebKitWebViewBase* webkitWebViewBase)
1614 {
1615     // Queue a resize to ensure the new DrawingAreaProxy is resized.
1616     gtk_widget_queue_resize_no_redraw(GTK_WIDGET(webkitWebViewBase));
1617
1618 #if PLATFORM(X11) && USE(TEXTURE_MAPPER_GL) && !USE(REDIRECTED_XCOMPOSITE_WINDOW)
1619     if (PlatformDisplay::sharedDisplay().type() != PlatformDisplay::Type::X11)
1620         return;
1621
1622     WebKitWebViewBasePrivate* priv = webkitWebViewBase->priv;
1623     auto* drawingArea = static_cast<DrawingAreaProxyCoordinatedGraphics*>(priv->pageProxy->drawingArea());
1624     ASSERT(drawingArea);
1625
1626     if (!gtk_widget_get_realized(GTK_WIDGET(webkitWebViewBase)))
1627         return;
1628
1629     uint64_t windowID = GDK_WINDOW_XID(gtk_widget_get_window(GTK_WIDGET(webkitWebViewBase)));
1630     drawingArea->setNativeSurfaceHandleForCompositing(windowID);
1631 #else
1632     UNUSED_PARAM(webkitWebViewBase);
1633 #endif
1634 }
1635
1636 void webkitWebViewBasePageClosed(WebKitWebViewBase* webkitWebViewBase)
1637 {
1638     if (webkitWebViewBase->priv->acceleratedBackingStore)
1639         webkitWebViewBase->priv->acceleratedBackingStore->update(LayerTreeContext());
1640 #if PLATFORM(X11) && USE(TEXTURE_MAPPER_GL) && !USE(REDIRECTED_XCOMPOSITE_WINDOW)
1641     if (PlatformDisplay::sharedDisplay().type() != PlatformDisplay::Type::X11)
1642         return;
1643
1644     if (!gtk_widget_get_realized(GTK_WIDGET(webkitWebViewBase)))
1645         return;
1646
1647     WebKitWebViewBasePrivate* priv = webkitWebViewBase->priv;
1648     auto* drawingArea = static_cast<DrawingAreaProxyCoordinatedGraphics*>(priv->pageProxy->drawingArea());
1649     ASSERT(drawingArea);
1650     drawingArea->destroyNativeSurfaceHandleForCompositing();
1651 #endif
1652 }
1653
1654 RefPtr<WebKit::ViewSnapshot> webkitWebViewBaseTakeViewSnapshot(WebKitWebViewBase* webkitWebViewBase)
1655 {
1656     WebPageProxy* page = webkitWebViewBase->priv->pageProxy.get();
1657
1658     IntSize size = page->viewSize();
1659
1660 #if HAVE_GTK_SCALE_FACTOR
1661     float deviceScale = page->deviceScaleFactor();
1662     size.scale(deviceScale);
1663 #endif
1664
1665     RefPtr<cairo_surface_t> surface = adoptRef(cairo_image_surface_create(CAIRO_FORMAT_RGB24, size.width(), size.height()));
1666
1667 #if HAVE_GTK_SCALE_FACTOR
1668     cairoSurfaceSetDeviceScale(surface.get(), deviceScale, deviceScale);
1669 #endif
1670
1671     RefPtr<cairo_t> cr = adoptRef(cairo_create(surface.get()));
1672     webkitWebViewBaseDraw(GTK_WIDGET(webkitWebViewBase), cr.get());
1673
1674     return ViewSnapshot::create(WTFMove(surface));
1675 }
1676
1677 void webkitWebViewBaseDidStartProvisionalLoadForMainFrame(WebKitWebViewBase* webkitWebViewBase)
1678 {
1679     if (webkitWebViewBase->priv->viewGestureController->isSwipeGestureEnabled())
1680         webkitWebViewBase->priv->viewGestureController->didStartProvisionalLoadForMainFrame();
1681 }
1682
1683 void webkitWebViewBaseDidFirstVisuallyNonEmptyLayoutForMainFrame(WebKitWebViewBase* webkitWebViewBase)
1684 {
1685     if (webkitWebViewBase->priv->viewGestureController->isSwipeGestureEnabled())
1686         webkitWebViewBase->priv->viewGestureController->didFirstVisuallyNonEmptyLayoutForMainFrame();
1687 }
1688
1689 void webkitWebViewBaseDidFinishLoadForMainFrame(WebKitWebViewBase* webkitWebViewBase)
1690 {
1691     if (webkitWebViewBase->priv->viewGestureController->isSwipeGestureEnabled())
1692         webkitWebViewBase->priv->viewGestureController->didFinishLoadForMainFrame();
1693 }
1694
1695 void webkitWebViewBaseDidFailLoadForMainFrame(WebKitWebViewBase* webkitWebViewBase)
1696 {
1697     if (webkitWebViewBase->priv->viewGestureController->isSwipeGestureEnabled())
1698         webkitWebViewBase->priv->viewGestureController->didFailLoadForMainFrame();
1699 }
1700
1701 void webkitWebViewBaseDidSameDocumentNavigationForMainFrame(WebKitWebViewBase* webkitWebViewBase, SameDocumentNavigationType type)
1702 {
1703     if (webkitWebViewBase->priv->viewGestureController->isSwipeGestureEnabled())
1704         webkitWebViewBase->priv->viewGestureController->didSameDocumentNavigationForMainFrame(type);
1705 }
1706
1707 void webkitWebViewBaseDidRestoreScrollPosition(WebKitWebViewBase* webkitWebViewBase)
1708 {
1709     if (webkitWebViewBase->priv->viewGestureController->isSwipeGestureEnabled())
1710         webkitWebViewBase->priv->viewGestureController->didRestoreScrollPosition();
1711 }