e9de041adeb7488b25fd61a0ed726bdafbe5ac3c
[WebKit-https.git] / Source / WebKit / UIProcess / API / gtk / WebKitWebViewGtk.cpp
1 /*
2  * Copyright (C) 2017 Igalia S.L.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public License
15  * along with this library; see the file COPYING.LIB.  If not, write to
16  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #include "config.h"
21 #include "WebKitWebView.h"
22
23 #include "WebKitAuthenticationDialog.h"
24 #include "WebKitScriptDialogImpl.h"
25 #include "WebKitWebViewBasePrivate.h"
26 #include "WebKitWebViewPrivate.h"
27 #include <WebCore/GtkUtilities.h>
28 #include <WebCore/PlatformDisplay.h>
29 #include <WebCore/PlatformScreen.h>
30 #include <glib/gi18n-lib.h>
31 #include <gtk/gtk.h>
32 #include <wtf/Environment.h>
33
34 gboolean webkitWebViewAuthenticate(WebKitWebView* webView, WebKitAuthenticationRequest* request)
35 {
36     CredentialStorageMode credentialStorageMode = webkit_authentication_request_can_save_credentials(request) ? AllowPersistentStorage : DisallowPersistentStorage;
37     webkitWebViewBaseAddDialog(WEBKIT_WEB_VIEW_BASE(webView), webkitAuthenticationDialogNew(request, credentialStorageMode));
38
39     return TRUE;
40 }
41
42 gboolean webkitWebViewScriptDialog(WebKitWebView* webView, WebKitScriptDialog* scriptDialog)
43 {
44     GUniquePtr<char> title(g_strdup_printf("JavaScript - %s", webkitWebViewGetPage(webView).pageLoadState().url().utf8().data()));
45     // Limit script dialog size to 80% of the web view size.
46     GtkRequisition maxSize = { static_cast<int>(gtk_widget_get_allocated_width(GTK_WIDGET(webView)) * 0.80), static_cast<int>(gtk_widget_get_allocated_height(GTK_WIDGET(webView)) * 0.80) };
47     webkitWebViewBaseAddDialog(WEBKIT_WEB_VIEW_BASE(webView), webkitScriptDialogImplNew(scriptDialog, title.get(), &maxSize));
48
49     return TRUE;
50 }
51
52 static void fileChooserDialogResponseCallback(GtkFileChooser* dialog, gint responseID, WebKitFileChooserRequest* request)
53 {
54     GRefPtr<WebKitFileChooserRequest> adoptedRequest = adoptGRef(request);
55     if (responseID == GTK_RESPONSE_ACCEPT) {
56         GUniquePtr<GSList> filesList(gtk_file_chooser_get_filenames(dialog));
57         GRefPtr<GPtrArray> filesArray = adoptGRef(g_ptr_array_new());
58         for (GSList* file = filesList.get(); file; file = g_slist_next(file))
59             g_ptr_array_add(filesArray.get(), file->data);
60         g_ptr_array_add(filesArray.get(), 0);
61         webkit_file_chooser_request_select_files(adoptedRequest.get(), reinterpret_cast<const gchar* const*>(filesArray->pdata));
62     } else
63         webkit_file_chooser_request_cancel(adoptedRequest.get());
64
65 #if GTK_CHECK_VERSION(3, 20, 0)
66     g_object_unref(dialog);
67 #else
68     gtk_widget_destroy(GTK_WIDGET(dialog));
69 #endif
70 }
71
72 gboolean webkitWebViewRunFileChooser(WebKitWebView* webView, WebKitFileChooserRequest* request)
73 {
74     GtkWidget* toplevel = gtk_widget_get_toplevel(GTK_WIDGET(webView));
75     if (!WebCore::widgetIsOnscreenToplevelWindow(toplevel))
76         toplevel = 0;
77
78     gboolean allowsMultipleSelection = webkit_file_chooser_request_get_select_multiple(request);
79
80 #if GTK_CHECK_VERSION(3, 20, 0)
81     GtkFileChooserNative* dialog = gtk_file_chooser_native_new(allowsMultipleSelection ? _("Select Files") : _("Select File"),
82         toplevel ? GTK_WINDOW(toplevel) : nullptr, GTK_FILE_CHOOSER_ACTION_OPEN, nullptr, nullptr);
83     if (toplevel)
84         gtk_native_dialog_set_modal(GTK_NATIVE_DIALOG(dialog), TRUE);
85 #else
86     GtkWidget* dialog = gtk_file_chooser_dialog_new(allowsMultipleSelection ? _("Select Files") : _("Select File"),
87         toplevel ? GTK_WINDOW(toplevel) : nullptr,
88         GTK_FILE_CHOOSER_ACTION_OPEN,
89         GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
90         GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
91         nullptr);
92     if (toplevel)
93         gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
94 #endif
95
96     if (GtkFileFilter* filter = webkit_file_chooser_request_get_mime_types_filter(request))
97         gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(dialog), filter);
98     gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), allowsMultipleSelection);
99
100     if (const gchar* const* selectedFiles = webkit_file_chooser_request_get_selected_files(request))
101         gtk_file_chooser_select_filename(GTK_FILE_CHOOSER(dialog), selectedFiles[0]);
102
103     g_signal_connect(dialog, "response", G_CALLBACK(fileChooserDialogResponseCallback), g_object_ref(request));
104
105 #if GTK_CHECK_VERSION(3, 20, 0)
106     gtk_native_dialog_show(GTK_NATIVE_DIALOG(dialog));
107 #else
108     gtk_widget_show(dialog);
109 #endif
110
111     return TRUE;
112 }
113
114 struct WindowStateEvent {
115     enum class Type { Maximize, Minimize, Restore };
116
117     WindowStateEvent(Type type, CompletionHandler<void()>&& completionHandler)
118         : type(type)
119         , completionHandler(WTFMove(completionHandler))
120         , completeTimer(RunLoop::main(), this, &WindowStateEvent::complete)
121     {
122         // Complete the event if not done after one second.
123         completeTimer.startOneShot(1_s);
124     }
125
126     ~WindowStateEvent()
127     {
128         complete();
129     }
130
131     void complete()
132     {
133         if (auto handler = std::exchange(completionHandler, nullptr))
134             handler();
135     }
136
137     Type type;
138     CompletionHandler<void()> completionHandler;
139     RunLoop::Timer<WindowStateEvent> completeTimer;
140 };
141
142 static const char* gWindowStateEventID = "wk-window-state-event";
143
144 static gboolean windowStateEventCallback(GtkWidget* window, GdkEventWindowState* event, WebKitWebView* view)
145 {
146     auto* state = static_cast<WindowStateEvent*>(g_object_get_data(G_OBJECT(view), gWindowStateEventID));
147     if (!state) {
148         g_signal_handlers_disconnect_by_func(window, reinterpret_cast<gpointer>(windowStateEventCallback), view);
149         return FALSE;
150     }
151
152     bool eventCompleted = false;
153     switch (state->type) {
154     case WindowStateEvent::Type::Maximize:
155         if (event->new_window_state & GDK_WINDOW_STATE_MAXIMIZED)
156             eventCompleted = true;
157         break;
158     case WindowStateEvent::Type::Minimize:
159         if ((event->new_window_state & GDK_WINDOW_STATE_ICONIFIED) || !gtk_widget_get_mapped(window))
160             eventCompleted = true;
161         break;
162     case WindowStateEvent::Type::Restore:
163         if (!(event->new_window_state & GDK_WINDOW_STATE_MAXIMIZED) && !(event->new_window_state & GDK_WINDOW_STATE_ICONIFIED))
164             eventCompleted = true;
165         break;
166     }
167
168     if (eventCompleted) {
169         g_signal_handlers_disconnect_by_func(window, reinterpret_cast<gpointer>(windowStateEventCallback), view);
170         g_object_set_data(G_OBJECT(view), gWindowStateEventID, nullptr);
171     }
172
173     return FALSE;
174 }
175
176 void webkitWebViewMaximizeWindow(WebKitWebView* view, CompletionHandler<void()>&& completionHandler)
177 {
178     auto* topLevel = gtk_widget_get_toplevel(GTK_WIDGET(view));
179     if (!gtk_widget_is_toplevel(topLevel)) {
180         completionHandler();
181         return;
182     }
183
184     auto* window = GTK_WINDOW(topLevel);
185     if (gtk_window_is_maximized(window)) {
186         completionHandler();
187         return;
188     }
189
190     g_object_set_data_full(G_OBJECT(view), gWindowStateEventID, new WindowStateEvent(WindowStateEvent::Type::Maximize, WTFMove(completionHandler)), [](gpointer userData) {
191         delete static_cast<WindowStateEvent*>(userData);
192     });
193     g_signal_connect_object(window, "window-state-event", G_CALLBACK(windowStateEventCallback), view, G_CONNECT_AFTER);
194     gtk_window_maximize(window);
195 #if ENABLE(DEVELOPER_MODE)
196     // Xvfb doesn't support maximize, so we resize the window to the screen size.
197     if (WebCore::PlatformDisplay::sharedDisplay().type() == WebCore::PlatformDisplay::Type::X11) {
198         if (Environment::hasValue("UNDER_XVFB", "yes")) {
199             auto screenRect = WebCore::screenAvailableRect(nullptr);
200             gtk_window_move(window, screenRect.x(), screenRect.y());
201             gtk_window_resize(window, screenRect.width(), screenRect.height());
202         }
203     }
204 #endif
205     gtk_widget_show(topLevel);
206 }
207
208 void webkitWebViewMinimizeWindow(WebKitWebView* view, CompletionHandler<void()>&& completionHandler)
209 {
210     auto* topLevel = gtk_widget_get_toplevel(GTK_WIDGET(view));
211     if (!gtk_widget_is_toplevel(topLevel)) {
212         completionHandler();
213         return;
214     }
215
216     auto* window = GTK_WINDOW(topLevel);
217     g_object_set_data_full(G_OBJECT(view), gWindowStateEventID, new WindowStateEvent(WindowStateEvent::Type::Minimize, WTFMove(completionHandler)), [](gpointer userData) {
218         delete static_cast<WindowStateEvent*>(userData);
219     });
220     g_signal_connect_object(window, "window-state-event", G_CALLBACK(windowStateEventCallback), view, G_CONNECT_AFTER);
221     gtk_window_iconify(window);
222     gtk_widget_hide(topLevel);
223 }
224
225 void webkitWebViewRestoreWindow(WebKitWebView* view, CompletionHandler<void()>&& completionHandler)
226 {
227     auto* topLevel = gtk_widget_get_toplevel(GTK_WIDGET(view));
228     if (!gtk_widget_is_toplevel(topLevel)) {
229         completionHandler();
230         return;
231     }
232
233     auto* window = GTK_WINDOW(topLevel);
234     if (gtk_widget_get_mapped(topLevel) && !gtk_window_is_maximized(window)) {
235         completionHandler();
236         return;
237     }
238
239     g_object_set_data_full(G_OBJECT(view), gWindowStateEventID, new WindowStateEvent(WindowStateEvent::Type::Restore, WTFMove(completionHandler)), [](gpointer userData) {
240         delete static_cast<WindowStateEvent*>(userData);
241     });
242     g_signal_connect_object(window, "window-state-event", G_CALLBACK(windowStateEventCallback), view, G_CONNECT_AFTER);
243     if (gtk_window_is_maximized(window))
244         gtk_window_unmaximize(window);
245     if (!gtk_widget_get_mapped(topLevel))
246         gtk_window_deiconify(window);
247 #if ENABLE(DEVELOPER_MODE)
248     // Xvfb doesn't support maximize, so we resize the window to the default size.
249     if (WebCore::PlatformDisplay::sharedDisplay().type() == WebCore::PlatformDisplay::Type::X11) {
250         if (Environment::hasValue("UNDER_XVFB", "yes")) {
251             int x, y;
252             gtk_window_get_default_size(window, &x, &y);
253             gtk_window_resize(window, x, y);
254         }
255     }
256 #endif
257     gtk_widget_show(topLevel);
258 }
259
260 /**
261  * webkit_web_view_new:
262  *
263  * Creates a new #WebKitWebView with the default #WebKitWebContext and
264  * no #WebKitUserContentManager associated with it.
265  * See also webkit_web_view_new_with_context(),
266  * webkit_web_view_new_with_user_content_manager(), and
267  * webkit_web_view_new_with_settings().
268  *
269  * Returns: The newly created #WebKitWebView widget
270  */
271 GtkWidget* webkit_web_view_new()
272 {
273     return webkit_web_view_new_with_context(webkit_web_context_get_default());
274 }
275
276 /**
277  * webkit_web_view_new_with_context:
278  * @context: the #WebKitWebContext to be used by the #WebKitWebView
279  *
280  * Creates a new #WebKitWebView with the given #WebKitWebContext and
281  * no #WebKitUserContentManager associated with it.
282  * See also webkit_web_view_new_with_user_content_manager() and
283  * webkit_web_view_new_with_settings().
284  *
285  * Returns: The newly created #WebKitWebView widget
286  */
287 GtkWidget* webkit_web_view_new_with_context(WebKitWebContext* context)
288 {
289     g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), 0);
290
291     return GTK_WIDGET(g_object_new(WEBKIT_TYPE_WEB_VIEW,
292         "is-ephemeral", webkit_web_context_is_ephemeral(context),
293         "web-context", context,
294         nullptr));
295 }
296
297 /**
298  * webkit_web_view_new_with_related_view: (constructor)
299  * @web_view: the related #WebKitWebView
300  *
301  * Creates a new #WebKitWebView sharing the same web process with @web_view.
302  * This method doesn't have any effect when %WEBKIT_PROCESS_MODEL_SHARED_SECONDARY_PROCESS
303  * process model is used, because a single web process is shared for all the web views in the
304  * same #WebKitWebContext. When using %WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES process model,
305  * this method should always be used when creating the #WebKitWebView in the #WebKitWebView::create signal.
306  * You can also use this method to implement other process models based on %WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES,
307  * like for example, sharing the same web process for all the views in the same security domain.
308  *
309  * The newly created #WebKitWebView will also have the same #WebKitUserContentManager
310  * and #WebKitSettings as @web_view.
311  *
312  * Returns: (transfer full): The newly created #WebKitWebView widget
313  *
314  * Since: 2.4
315  */
316 GtkWidget* webkit_web_view_new_with_related_view(WebKitWebView* webView)
317 {
318     g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);
319
320     return GTK_WIDGET(g_object_new(WEBKIT_TYPE_WEB_VIEW,
321         "user-content-manager", webkit_web_view_get_user_content_manager(webView),
322         "settings", webkit_web_view_get_settings(webView),
323         "related-view", webView,
324         nullptr));
325 }
326
327 /**
328  * webkit_web_view_new_with_settings:
329  * @settings: a #WebKitSettings
330  *
331  * Creates a new #WebKitWebView with the given #WebKitSettings.
332  * See also webkit_web_view_new_with_context(), and
333  * webkit_web_view_new_with_user_content_manager().
334  *
335  * Returns: The newly created #WebKitWebView widget
336  *
337  * Since: 2.6
338  */
339 GtkWidget* webkit_web_view_new_with_settings(WebKitSettings* settings)
340 {
341     g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), nullptr);
342     return GTK_WIDGET(g_object_new(WEBKIT_TYPE_WEB_VIEW, "settings", settings, nullptr));
343 }
344
345 /**
346  * webkit_web_view_new_with_user_content_manager:
347  * @user_content_manager: a #WebKitUserContentManager.
348  *
349  * Creates a new #WebKitWebView with the given #WebKitUserContentManager.
350  * The content loaded in the view may be affected by the content injected
351  * in the view by the user content manager.
352  *
353  * Returns: The newly created #WebKitWebView widget
354  *
355  * Since: 2.6
356  */
357 GtkWidget* webkit_web_view_new_with_user_content_manager(WebKitUserContentManager* userContentManager)
358 {
359     g_return_val_if_fail(WEBKIT_IS_USER_CONTENT_MANAGER(userContentManager), nullptr);
360
361     return GTK_WIDGET(g_object_new(WEBKIT_TYPE_WEB_VIEW, "user-content-manager", userContentManager, nullptr));
362 }