File: DropTargetGtk3.cpp

package info (click to toggle)
webkit2gtk 2.42.2-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 362,452 kB
  • sloc: cpp: 2,881,971; javascript: 282,447; ansic: 134,088; python: 43,789; ruby: 18,308; perl: 15,872; asm: 14,389; xml: 4,395; yacc: 2,350; sh: 2,074; java: 1,734; lex: 1,323; makefile: 288; pascal: 60
file content (287 lines) | stat: -rw-r--r-- 11,144 bytes parent folder | download | duplicates (3)
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
/*
 * Copyright (C) 2020 Igalia S.L.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "DropTarget.h"

#if ENABLE(DRAG_SUPPORT) && !USE(GTK4)

#include "SandboxExtension.h"
#include "WebKitWebViewBasePrivate.h"
#include <WebCore/DragData.h>
#include <WebCore/GRefPtrGtk.h>
#include <WebCore/GtkUtilities.h>
#include <WebCore/PasteboardCustomData.h>
#include <gtk/gtk.h>
#include <wtf/glib/GUniquePtr.h>

namespace WebKit {
using namespace WebCore;

enum DropTargetType { Markup, Text, URIList, NetscapeURL, SmartPaste, Custom };

DropTarget::DropTarget(GtkWidget* webView)
    : m_webView(webView)
    , m_leaveTimer(RunLoop::main(), this, &DropTarget::leaveTimerFired)
{
    GRefPtr<GtkTargetList> list = adoptGRef(gtk_target_list_new(nullptr, 0));
    gtk_target_list_add_text_targets(list.get(), DropTargetType::Text);
    gtk_target_list_add(list.get(), gdk_atom_intern_static_string("text/html"), 0, DropTargetType::Markup);
    gtk_target_list_add_uri_targets(list.get(), DropTargetType::URIList);
    gtk_target_list_add(list.get(), gdk_atom_intern_static_string("_NETSCAPE_URL"), 0, DropTargetType::NetscapeURL);
    gtk_target_list_add(list.get(), gdk_atom_intern_static_string("application/vnd.webkitgtk.smartpaste"), 0, DropTargetType::SmartPaste);
    gtk_target_list_add(list.get(), gdk_atom_intern_static_string(PasteboardCustomData::gtkType().characters()), 0, DropTargetType::Custom);
    gtk_drag_dest_set(m_webView, static_cast<GtkDestDefaults>(0), nullptr, 0,
        static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_LINK));
    gtk_drag_dest_set_target_list(m_webView, list.get());

    g_signal_connect_after(m_webView, "drag-motion", G_CALLBACK(+[](GtkWidget*, GdkDragContext* context, gint x, gint y, guint time, gpointer userData) -> gboolean {
        auto& drop = *static_cast<DropTarget*>(userData);
        if (drop.m_drop != context) {
            drop.accept(context, IntPoint(x, y), time);
        } else if (drop.m_drop == context)
            drop.update({ x, y }, time);
        return TRUE;
    }), this);

    g_signal_connect_after(m_webView, "drag-leave", G_CALLBACK(+[](GtkWidget*, GdkDragContext* context, guint time, gpointer userData) {
        auto& drop = *static_cast<DropTarget*>(userData);
        if (drop.m_drop != context)
            return;
        drop.leave();
    }), this);

    g_signal_connect_after(m_webView, "drag-drop", G_CALLBACK(+[](GtkWidget*, GdkDragContext* context, gint x, gint y, guint time, gpointer userData) -> gboolean {
        auto& drop = *static_cast<DropTarget*>(userData);
        if (drop.m_drop != context) {
            gtk_drag_finish(context, FALSE, FALSE, time);
            return TRUE;
        }
        drop.drop({ x, y }, time);
        return TRUE;
    }), this);

    g_signal_connect_after(m_webView, "drag-data-received", G_CALLBACK(+[](GtkWidget*, GdkDragContext* context, gint x, gint y, GtkSelectionData* data, guint info, guint time, gpointer userData) {
        auto& drop = *static_cast<DropTarget*>(userData);
        if (drop.m_drop != context)
            return;
        drop.dataReceived({ x, y }, data, info, time);
    }), this);
}

DropTarget::~DropTarget()
{
    g_signal_handlers_disconnect_by_data(m_webView, this);
}

void DropTarget::accept(GdkDragContext* drop, std::optional<WebCore::IntPoint> position, unsigned time)
{
    if (m_leaveTimer.isActive()) {
        m_leaveTimer.stop();
        leaveTimerFired();
    }

    m_drop = drop;
    m_position = position;
    m_dataRequestCount = 0;
    m_selectionData = std::nullopt;

    // WebCore needs the selection data to decide, so we need to preload the
    // data of targets we support. Once all data requests are done we start
    // notifying the web process about the DND events.
    auto* list = gdk_drag_context_list_targets(m_drop.get());
    static const char* const supportedTargets[] = {
        "text/plain;charset=utf-8",
        "text/html",
        "_NETSCAPE_URL",
        "text/uri-list",
        "application/vnd.webkitgtk.smartpaste",
        "org.webkitgtk.WebKit.custom-pasteboard-data"
    };
    Vector<GdkAtom, 4> targets;
    for (unsigned i = 0; i < G_N_ELEMENTS(supportedTargets); ++i) {
        GdkAtom atom = gdk_atom_intern_static_string(supportedTargets[i]);
        if (g_list_find(list, atom))
            targets.append(atom);
        else if (!i) {
            atom = gdk_atom_intern_static_string("text/plain");
            if (g_list_find(list, atom))
                targets.append(atom);
        }
    }

    if (targets.isEmpty())
        return;

    m_dataRequestCount = targets.size();
    m_selectionData = SelectionData();
    for (auto* atom : targets)
        gtk_drag_get_data(m_webView, m_drop.get(), atom, time);
}

void DropTarget::enter(IntPoint&& position, unsigned time)
{
    m_position = WTFMove(position);

    auto* page = webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(m_webView));
    ASSERT(page);
    page->resetCurrentDragInformation();

    DragData dragData(&m_selectionData.value(), *m_position, convertWidgetPointToScreenPoint(m_webView, *m_position), gdkDragActionToDragOperation(gdk_drag_context_get_actions(m_drop.get())));
    page->dragEntered(dragData);
}

void DropTarget::update(IntPoint&& position, unsigned time)
{
    if (m_dataRequestCount || !m_selectionData)
        return;

    m_position = WTFMove(position);

    auto* page = webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(m_webView));
    ASSERT(page);

    DragData dragData(&m_selectionData.value(), *m_position, convertWidgetPointToScreenPoint(m_webView, *m_position), gdkDragActionToDragOperation(gdk_drag_context_get_actions(m_drop.get())));
    page->dragUpdated(dragData);
}

void DropTarget::dataReceived(IntPoint&& position, GtkSelectionData* data, unsigned info, unsigned time)
{
    switch (info) {
    case DropTargetType::Text: {
        GUniquePtr<char> text(reinterpret_cast<char*>(gtk_selection_data_get_text(data)));
        m_selectionData->setText(String::fromUTF8(text.get()));
        break;
    }
    case DropTargetType::Markup: {
        gint length;
        const auto* markupData = gtk_selection_data_get_data_with_length(data, &length);
        if (length > 0) {
            // If data starts with UTF-16 BOM assume it's UTF-16, otherwise assume UTF-8.
            if (length >= 2 && reinterpret_cast<const UChar*>(markupData)[0] == 0xFEFF)
                m_selectionData->setMarkup(String(reinterpret_cast<const UChar*>(markupData) + 1, (length / 2) - 1));
            else
                m_selectionData->setMarkup(String::fromUTF8(markupData, length));
        }
        break;
    }
    case DropTargetType::URIList: {
        gint length;
        const auto* uriListData = gtk_selection_data_get_data_with_length(data, &length);
        if (length > 0)
            m_selectionData->setURIList(String::fromUTF8(uriListData, length));
        break;
    }
    case DropTargetType::NetscapeURL: {
        gint length;
        const auto* urlData = gtk_selection_data_get_data_with_length(data, &length);
        if (length > 0) {
            Vector<String> tokens = String::fromUTF8(urlData, length).split('\n');
            URL url({ }, tokens[0]);
            if (url.isValid())
                m_selectionData->setURL(url, tokens.size() > 1 ? tokens[1] : String());
        }
        break;
    }
    case DropTargetType::SmartPaste:
        m_selectionData->setCanSmartReplace(true);
        break;
    case DropTargetType::Custom: {
        int length;
        const auto* customData = gtk_selection_data_get_data_with_length(data, &length);
        if (length > 0)
            m_selectionData->setCustomData(SharedBuffer::create(customData, static_cast<size_t>(length)));
        break;
    }
    }

    if (--m_dataRequestCount)
        return;

    enter(WTFMove(position), time);
}

void DropTarget::didPerformAction()
{
    if (!m_drop)
        return;

    auto* page = webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(m_webView));
    ASSERT(page);

    m_operation = page->currentDragOperation();

    gdk_drag_status(m_drop.get(), dragOperationToSingleGdkDragAction(m_operation), GDK_CURRENT_TIME);
}

void DropTarget::leaveTimerFired()
{
    auto* page = webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(m_webView));
    ASSERT(page);

    SelectionData emptyData;
    DragData dragData(m_selectionData ? &m_selectionData.value() : &emptyData, *m_position, convertWidgetPointToScreenPoint(m_webView, *m_position), { });
    page->dragExited(dragData);
    page->resetCurrentDragInformation();

    m_drop = nullptr;
    m_position = std::nullopt;
    m_selectionData = std::nullopt;
}

void DropTarget::leave()
{
    // GTK emits drag-leave before drag-drop, but we need to know whether a drop
    // happened to notify the web process about the drag exit.
    m_leaveTimer.startOneShot(0_s);
}

void DropTarget::drop(IntPoint&& position, unsigned time)
{
    // If we don't have data at this point, allow the leave timer to fire, ending the drop operation.
    if (!m_selectionData)
        return;

    if (m_leaveTimer.isActive())
        m_leaveTimer.stop();

    auto* page = webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(m_webView));
    ASSERT(page);

    OptionSet<DragApplicationFlags> flags;
    if (gdk_drag_context_get_selected_action(m_drop.get()) == GDK_ACTION_COPY)
        flags.add(DragApplicationFlags::IsCopyKeyDown);
    DragData dragData(&m_selectionData.value(), position, convertWidgetPointToScreenPoint(m_webView, position), gdkDragActionToDragOperation(gdk_drag_context_get_actions(m_drop.get())), flags);
    page->performDragOperation(dragData, { }, { }, { });
    gtk_drag_finish(m_drop.get(), TRUE, FALSE, time);

    m_drop = nullptr;
    m_position = std::nullopt;
    m_selectionData = std::nullopt;
}

} // namespace WebKit

#endif // ENABLE(DRAG_SUPPORT) && !USE(GTK4)