Skip to content

Truly independent web browser

LibWeb+UI: Add Paste and Match Style

Andreas Kling7f0f4225decc
diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cpp
index d6012a0cb03..9e7d411d3c8 100644
--- a/Libraries/LibWeb/Page/EventHandler.cpp
+++ b/Libraries/LibWeb/Page/EventHandler.cpp
@@ -2135,13 +2135,23 @@ EventResult EventHandler::handle_keydown(UIEvents::KeyCode key, u32 modifiers, u
if (key == UIEvents::KeyCode::Key_X)
return perform_cut_action();
if (key == UIEvents::KeyCode::Key_V)
- return perform_paste_action();
+ return perform_paste_action(Clipboard::PasteMode::AllMimeTypes);
if (key == UIEvents::KeyCode::Key_Z)
return Editing::perform_history_action(*document, Editing::HistoryAction::Undo);
#if !defined(AK_OS_MACOS)
// INTEROP: Chromium redoes on Ctrl+Y on Windows and Linux; on macOS Cmd+Y is not a redo shortcut.
if (key == UIEvents::KeyCode::Key_Y)
return Editing::perform_history_action(*document, Editing::HistoryAction::Redo);
+#endif
+ }
+ if ((modifiers & UIEvents::Mod_PlatformCtrl) != 0 && (modifiers & UIEvents::Mod_Shift) != 0 && key == UIEvents::KeyCode::Key_V) {
+#if defined(AK_OS_MACOS)
+ // INTEROP: On macOS the system-wide Paste and Match Style shortcut also holds Option. Gecko accepts it with and
+ // without Option, and Blink accepts it with Option.
+ return perform_paste_action(Clipboard::PasteMode::PlainTextOnly);
+#else
+ if ((modifiers & UIEvents::Mod_Alt) == 0)
+ return perform_paste_action(Clipboard::PasteMode::PlainTextOnly);
#endif
}
if ((modifiers & UIEvents::Mod_PlatformCtrl) != 0 && (modifiers & UIEvents::Mod_Shift) != 0 && (modifiers & UIEvents::Mod_Alt) == 0
@@ -2836,7 +2846,7 @@ bool EventHandler::perform_cut_action(ClipboardActionTrigger trigger)
}
// https://w3c.github.io/clipboard-apis/#paste-action
-EventResult EventHandler::perform_paste_action()
+EventResult EventHandler::perform_paste_action(Clipboard::PasteMode paste_mode)
{
auto document = m_navigable->active_document();
if (!document || !document->is_fully_active())
@@ -2844,7 +2854,10 @@ EventResult EventHandler::perform_paste_action()
// NB: The system clipboard lives in the UI process. So, retrieve its contents first — and run the rest of the paste
// action once the contents arrive.
- document->page().request_clipboard_entries_for_paste(GC::create_function(document->heap(), GC::captures(GC::Ref { *document }), [](auto& document, Vector<Clipboard::SystemClipboardItem> system_clipboard_data) {
+ document->page().request_clipboard_entries_for_paste(GC::create_function(document->heap(), GC::captures(GC::Ref { *document }, paste_mode), [](auto& document, auto paste_mode, Vector<Clipboard::SystemClipboardItem> system_clipboard_data) {
+ for (auto& item : system_clipboard_data)
+ Clipboard::apply_paste_mode(item, paste_mode);
+
if (auto navigable = document->navigable())
navigable->event_handler().perform_paste_action(system_clipboard_data);
}));
diff --git a/Libraries/LibWeb/Page/EventHandler.h b/Libraries/LibWeb/Page/EventHandler.h
index 912a7a171df..160d4b2d094 100644
--- a/Libraries/LibWeb/Page/EventHandler.h
+++ b/Libraries/LibWeb/Page/EventHandler.h
@@ -28,6 +28,7 @@
#include <LibWeb/Forward.h>
#include <LibWeb/Layout/LayoutRustFFI.h>
#include <LibWeb/Painting/Forward.h>
+#include <LibWebCommon/Clipboard/SystemClipboard.h>
#include <LibWebCommon/Gamepad/GamepadSnapshot.h>
#include <LibWebCommon/Page/EventResult.h>
#include <LibWebCommon/Page/InputEvent.h>
@@ -123,7 +124,7 @@ public:
EventResult handle_drag_and_drop_event(DragEvent::Type, CSSPixelPoint, CSSPixelPoint screen_position, unsigned button, unsigned buttons, unsigned modifiers, Vector<HTML::SelectedFile> files);
EventResult handle_pinch_event(CSSPixelPoint, PinchEvent const&, Optional<RemoteInputEventTarget>* remote_target);
- [[nodiscard]] EventResult perform_paste_action();
+ [[nodiscard]] EventResult perform_paste_action(Clipboard::PasteMode);
EventResult perform_paste_action(Vector<Clipboard::SystemClipboardItem> const& system_clipboard_data);
// A null system_clipboard_data stands for content the UI process pastes in its place, like the primary selection.
EventResult perform_paste_action(NonnullRefPtr<HTML::DragDataStore> const&, Vector<Clipboard::SystemClipboardItem> const* system_clipboard_data);
diff --git a/Libraries/LibWebCommon/Clipboard/SystemClipboard.cpp b/Libraries/LibWebCommon/Clipboard/SystemClipboard.cpp
index 8ee79408578..721dc49d24b 100644
--- a/Libraries/LibWebCommon/Clipboard/SystemClipboard.cpp
+++ b/Libraries/LibWebCommon/Clipboard/SystemClipboard.cpp
@@ -7,6 +7,25 @@
#include <LibIPC/Decoder.h>
#include <LibIPC/Encoder.h>
#include <LibWebCommon/Clipboard/SystemClipboard.h>
+#include <LibWebCommon/MimeSniff/MimeType.h>
+
+namespace Web::Clipboard {
+
+void apply_paste_mode(SystemClipboardItem& item, PasteMode paste_mode)
+{
+ if (paste_mode == PasteMode::AllMimeTypes)
+ return;
+
+ // INTEROP: A paste without formatting only exposes the plain text to the page, like the other engines, and so a
+ // paste event handler can't reinsert the formatted content. A copied file whose type is text/plain is
+ // still a file, so it is left out too.
+ item.system_clipboard_representations.remove_all_matching([](SystemClipboardRepresentation const& representation) {
+ auto mime_type = MimeSniff::MimeType::parse(representation.name);
+ return !mime_type.has_value() || mime_type->essence() != "text/plain"sv || !representation.data.has<ByteString>();
+ });
+}
+
+}
template<>
ErrorOr<void> IPC::encode(Encoder& encoder, Web::Clipboard::SystemClipboardRepresentation const& output)
diff --git a/Libraries/LibWebCommon/Clipboard/SystemClipboard.h b/Libraries/LibWebCommon/Clipboard/SystemClipboard.h
index c5e3e16cce5..3b259465b99 100644
--- a/Libraries/LibWebCommon/Clipboard/SystemClipboard.h
+++ b/Libraries/LibWebCommon/Clipboard/SystemClipboard.h
@@ -35,6 +35,13 @@ struct SystemClipboardItem {
Vector<SystemClipboardRepresentation> system_clipboard_representations;
};
+enum class PasteMode : u8 {
+ AllMimeTypes,
+ PlainTextOnly,
+};
+
+WEBCOMMON_API void apply_paste_mode(SystemClipboardItem&, PasteMode);
+
}
namespace IPC {
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index 12023804627..3734731d5bf 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -898,9 +898,15 @@ static bool is_activation_triggering_input_event(Web::InputEvent const& event)
static bool is_paste_shortcut(Web::InputEvent const& event)
{
auto const* key_event = event.get_pointer<Web::KeyEvent>();
- return key_event && key_event->type == Web::KeyEvent::Type::KeyDown && key_event->key == Web::UIEvents::KeyCode::Key_V
- && (key_event->modifiers & Web::UIEvents::Mod_PlatformCtrl) != 0
- && (key_event->modifiers & (Web::UIEvents::Mod_Shift | Web::UIEvents::Mod_Alt)) == 0;
+ if (!key_event || key_event->type != Web::KeyEvent::Type::KeyDown || key_event->key != Web::UIEvents::KeyCode::Key_V
+ || (key_event->modifiers & Web::UIEvents::Mod_PlatformCtrl) == 0)
+ return false;
+
+#if defined(AK_OS_MACOS)
+ return (key_event->modifiers & Web::UIEvents::Mod_Alt) == 0 || (key_event->modifiers & Web::UIEvents::Mod_Shift) != 0;
+#else
+ return (key_event->modifiers & Web::UIEvents::Mod_Alt) == 0;
+#endif
}
// A page busy for a while handles input late, and its activation counts from then. A page that never finishes handling
@@ -2809,12 +2815,13 @@ WebContentPage& ViewImplementation::focused_navigable_host() const
return host ? *host : page();
}
-void ViewImplementation::paste_from_clipboard()
+void ViewImplementation::paste_from_clipboard(Web::Clipboard::PasteMode paste_mode)
{
// The user asked the browser to paste, which hands the page the system clipboard data.
- read_clipboard_item([host = NonnullRefPtr { focused_navigable_host() }](Web::Clipboard::SystemClipboardItem item) {
+ read_clipboard_item([host = NonnullRefPtr { focused_navigable_host() }, paste_mode](Web::Clipboard::SystemClipboardItem item) {
if (!host->is_open())
return;
+ Web::Clipboard::apply_paste_mode(item, paste_mode);
Vector<Web::Clipboard::SystemClipboardItem> system_clipboard_data;
if (!item.system_clipboard_representations.is_empty())
system_clipboard_data.append(move(item));
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index 57509aa6e74..a28ca0f2442 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -488,7 +488,7 @@ public:
void file_picker_closed(Vector<Web::HTML::SelectedFile> selected_files);
void select_dropdown_closed(Optional<u32> const& selected_item_id);
- void paste_from_clipboard();
+ void paste_from_clipboard(Web::Clipboard::PasteMode);
// Used by platform input methods to drive marked/preedit-text composition, and to query the on-screen caret
// position for placing IME overlays.
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index 9173ab0e7d4..d4a7e492c3d 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -2490,7 +2490,7 @@ void WebContentPage::did_request_paste_from_clipboard_for_testing()
client().did_misbehave("did_request_paste_from_clipboard_for_testing"sv, "not driven by WebDriver or a test"sv);
return;
}
- view().paste_from_clipboard();
+ view().paste_from_clipboard(Web::Clipboard::PasteMode::AllMimeTypes);
}
void WebContentPage::did_request_spell_check(u64 request_id, Utf16String text)
diff --git a/Services/Hub/ConnectionFromUI.cpp b/Services/Hub/ConnectionFromUI.cpp
index ef370400d90..604404f53a1 100644
--- a/Services/Hub/ConnectionFromUI.cpp
+++ b/Services/Hub/ConnectionFromUI.cpp
@@ -979,10 +979,10 @@ void ConnectionFromUI::view_cut_selection(u64 view_id)
}
}
-void ConnectionFromUI::view_paste(u64 view_id)
+void ConnectionFromUI::view_paste(u64 view_id, Web::Clipboard::PasteMode paste_mode)
{
if (auto* view = find_view(view_id))
- view->paste_from_clipboard();
+ view->paste_from_clipboard(paste_mode);
}
void ConnectionFromUI::view_select_all(u64 view_id)
diff --git a/Services/Hub/ConnectionFromUI.h b/Services/Hub/ConnectionFromUI.h
index 220a1ecdc41..01454ecf3c8 100644
--- a/Services/Hub/ConnectionFromUI.h
+++ b/Services/Hub/ConnectionFromUI.h
@@ -168,7 +168,7 @@ private:
virtual void view_undo(u64 view_id) override;
virtual void view_redo(u64 view_id) override;
virtual void view_cut_selection(u64 view_id) override;
- virtual void view_paste(u64 view_id) override;
+ virtual void view_paste(u64 view_id, Web::Clipboard::PasteMode) override;
virtual void view_select_all(u64 view_id) override;
virtual void view_get_source(u64 view_id) override;
virtual void view_traverse_the_history_by_delta(u64 view_id, i32 delta) override;
diff --git a/Services/Hub/HubServer.ipc b/Services/Hub/HubServer.ipc
index aaedea7ac79..ee26d549867 100644
--- a/Services/Hub/HubServer.ipc
+++ b/Services/Hub/HubServer.ipc
@@ -245,7 +245,7 @@ endpoint HubServer
view_undo(u64 view_id) =|
view_redo(u64 view_id) =|
view_cut_selection(u64 view_id) =|
- view_paste(u64 view_id) =|
+ view_paste(u64 view_id, Web::Clipboard::PasteMode paste_mode) =|
view_select_all(u64 view_id) =|
view_get_source(u64 view_id) =|
view_debug_request(u64 view_id, ByteString request, ByteString argument) =|
diff --git a/Tests/LibWeb/Text/expected/Editing/clipboard-paste-as-plain-text.txt b/Tests/LibWeb/Text/expected/Editing/clipboard-paste-as-plain-text.txt
new file mode 100644
index 00000000000..86c288faf04
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/clipboard-paste-as-plain-text.txt
@@ -0,0 +1,2 @@
+paste event: types=["text/plain"] html=""
+editor: <b id="destination">seedplain flavor</b>
diff --git a/Tests/LibWeb/Text/input/Editing/clipboard-paste-as-plain-text.html b/Tests/LibWeb/Text/input/Editing/clipboard-paste-as-plain-text.html
new file mode 100644
index 00000000000..4dec3015266
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/clipboard-paste-as-plain-text.html
@@ -0,0 +1,35 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<div id="editor" contenteditable="true"><b id="destination">seed</b></div>
+<script>
+ asyncTest(async done => {
+ const modCtrl = (1 << 1) | (1 << 3); // Ctrl and Super, to cover the platform clipboard modifier everywhere.
+ const modShift = 1 << 2;
+ const editor = document.getElementById("editor");
+ const destination = document.getElementById("destination");
+
+ // Seed the system clipboard with both a text/plain and a text/html representation, by canceling a copy event.
+ editor.focus();
+ getSelection().selectAllChildren(destination);
+ editor.addEventListener("copy", e => {
+ e.preventDefault();
+ e.clipboardData.setData("text/plain", "plain flavor");
+ e.clipboardData.setData("text/html", "<i>html flavor</i>");
+ }, { once: true });
+ internals.sendKey(editor, "C", modCtrl);
+
+ // The paste event only sees the plain text, and the text takes on the style of where it lands.
+ getSelection().collapse(destination.firstChild, 4);
+ const pasteEvent = new Promise(resolve => {
+ editor.addEventListener("paste", e => {
+ resolve(`types=${JSON.stringify(e.clipboardData.types)} html=${JSON.stringify(e.clipboardData.getData("text/html"))}`);
+ }, { once: true });
+ });
+ internals.sendKey(editor, "V", modCtrl | modShift);
+ println(`paste event: ${await pasteEvent}`);
+
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ println(`editor: ${editor.innerHTML}`);
+ done();
+ });
+</script>
diff --git a/UI/Qt/Actions.h b/UI/Qt/Actions.h
index 07b5c4e5e37..f3ae04c7406 100644
--- a/UI/Qt/Actions.h
+++ b/UI/Qt/Actions.h
@@ -40,6 +40,7 @@ enum class ActionID {
CopySelection,
CutSelection,
Paste,
+ PasteAndMatchStyle,
SelectAll,
LookUpSelectedText,
diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cpp
index 19d0108c4a0..eaf37536969 100644
--- a/UI/Qt/Application.cpp
+++ b/UI/Qt/Application.cpp
@@ -2656,6 +2656,7 @@ QMenuBar* Application::create_application_menu_bar(ForBrowserWindow for_browser_
edit_menu->addAction(create_application_action(*menu_bar, application.cut_selection_action(), IncludeActionIcon::No));
edit_menu->addAction(create_application_action(*menu_bar, application.copy_selection_action(), IncludeActionIcon::No));
edit_menu->addAction(create_application_action(*menu_bar, application.paste_action(), IncludeActionIcon::No));
+ edit_menu->addAction(create_application_action(*menu_bar, application.paste_and_match_style_action(), IncludeActionIcon::No));
edit_menu->addAction(create_application_action(*menu_bar, application.select_all_action(), IncludeActionIcon::No));
edit_menu->addSeparator();
if (for_browser_window == ForBrowserWindow::Yes) {
diff --git a/UI/Qt/ApplicationActions.cpp b/UI/Qt/ApplicationActions.cpp
index 0d10fad53b0..015734e3728 100644
--- a/UI/Qt/ApplicationActions.cpp
+++ b/UI/Qt/ApplicationActions.cpp
@@ -15,6 +15,7 @@
#include <UI/Qt/Tab.h>
#include <QApplication>
+#include <QClipboard>
#include <QLineEdit>
#include <QPlainTextEdit>
@@ -73,6 +74,20 @@ static constexpr auto undo_text_field = [](auto& text_field) { text_field.undo()
static constexpr auto redo_text_field = [](auto& text_field) { text_field.redo(); };
static constexpr auto copy_text_field = [](auto& text_field) { text_field.copy(); };
static constexpr auto cut_text_field = [](auto& text_field) { text_field.cut(); };
+static constexpr auto paste_text_field = [](auto& text_field) {
+ // NB: With no text on the clipboard, QLineEdit::paste() would delete the selected text.
+ if (!QApplication::clipboard()->text().isEmpty())
+ text_field.paste();
+};
+static constexpr auto paste_and_match_style_text_field = [](auto& text_field) {
+ // NB: QPlainTextEdit::paste() formats Markdown from the clipboard, so insert its plain text directly instead.
+ if constexpr (IsSame<decltype(text_field), QPlainTextEdit&>) {
+ if (auto text = QApplication::clipboard()->text(); !text.isEmpty())
+ text_field.insertPlainText(text);
+ } else {
+ paste_text_field(text_field);
+ }
+};
static constexpr auto select_all_text_field = [](auto& text_field) { text_field.selectAll(); };
static Function<void()> debug_request(StringView request)
@@ -110,8 +125,11 @@ ApplicationActions::ApplicationActions(PageOptions const& options)
m_cut_selection_action = Action::create("Cut"sv, ActionID::CutSelection, on_focused_text_field_or_active_view(cut_text_field, [](RemoteView& view) {
HubConnection::the().async_view_cut_selection(view.view_id());
}));
- m_paste_action = Action::create("Paste"sv, ActionID::Paste, on_active_view([](RemoteView& view) {
- HubConnection::the().async_view_paste(view.view_id());
+ m_paste_action = Action::create("Paste"sv, ActionID::Paste, on_focused_text_field_or_active_view(paste_text_field, [](RemoteView& view) {
+ HubConnection::the().async_view_paste(view.view_id(), Web::Clipboard::PasteMode::AllMimeTypes);
+ }));
+ m_paste_and_match_style_action = Action::create("Paste and Match Style"sv, ActionID::PasteAndMatchStyle, on_focused_text_field_or_active_view(paste_and_match_style_text_field, [](RemoteView& view) {
+ HubConnection::the().async_view_paste(view.view_id(), Web::Clipboard::PasteMode::PlainTextOnly);
}));
m_select_all_action = Action::create("Select All"sv, ActionID::SelectAll, on_focused_text_field_or_active_view(select_all_text_field, [](RemoteView& view) {
HubConnection::the().async_view_select_all(view.view_id());
diff --git a/UI/Qt/ApplicationActions.h b/UI/Qt/ApplicationActions.h
index 8479b7c25ef..dd1afedef97 100644
--- a/UI/Qt/ApplicationActions.h
+++ b/UI/Qt/ApplicationActions.h
@@ -47,6 +47,7 @@ public:
Action& redo_action() { return *m_redo_action; }
Action& cut_selection_action() { return *m_cut_selection_action; }
Action& paste_action() { return *m_paste_action; }
+ Action& paste_and_match_style_action() { return *m_paste_and_match_style_action; }
Action& select_all_action() { return *m_select_all_action; }
Action& open_about_page_action() { return *m_open_about_page_action; }
Action& open_downloads_page_action() { return *m_open_downloads_page_action; }
@@ -88,6 +89,7 @@ private:
RefPtr<Action> m_redo_action;
RefPtr<Action> m_cut_selection_action;
RefPtr<Action> m_paste_action;
+ RefPtr<Action> m_paste_and_match_style_action;
RefPtr<Action> m_select_all_action;
RefPtr<Action> m_open_about_page_action;
RefPtr<Action> m_open_downloads_page_action;
diff --git a/UI/Qt/ContextMenus.cpp b/UI/Qt/ContextMenus.cpp
index cc9574acc7d..a372c688016 100644
--- a/UI/Qt/ContextMenus.cpp
+++ b/UI/Qt/ContextMenus.cpp
@@ -123,7 +123,10 @@ static void add_text_edit_actions(Menu& menu, u64 view_id, bool is_editable, boo
}
if (is_editable) {
menu.add_action(Action::create("Paste"sv, ActionID::Paste, on_view(view_id, [](RemoteView& view) {
- HubConnection::the().async_view_paste(view.view_id());
+ HubConnection::the().async_view_paste(view.view_id(), Web::Clipboard::PasteMode::AllMimeTypes);
+ })));
+ menu.add_action(Action::create("Paste and Match Style"sv, ActionID::PasteAndMatchStyle, on_view(view_id, [](RemoteView& view) {
+ HubConnection::the().async_view_paste(view.view_id(), Web::Clipboard::PasteMode::PlainTextOnly);
})));
menu.add_action(Action::create("Select All"sv, ActionID::SelectAll, on_view(view_id, [](RemoteView& view) {
HubConnection::the().async_view_select_all(view.view_id());
diff --git a/UI/Qt/Menu.cpp b/UI/Qt/Menu.cpp
index 6d8a174bf50..aa3bbb794b7 100644
--- a/UI/Qt/Menu.cpp
+++ b/UI/Qt/Menu.cpp
@@ -234,6 +234,13 @@ static Action::Observer& initialize_native_control(Action& action, QAction& qact
case ActionID::Paste:
qaction.setShortcut(QKeySequence::StandardKey::Paste);
break;
+ case ActionID::PasteAndMatchStyle:
+#if defined(AK_OS_MACOS)
+ qaction.setShortcuts({ QKeySequence(Qt::CTRL | Qt::ALT | Qt::SHIFT | Qt::Key_V), QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_V) });
+#else
+ qaction.setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_V));
+#endif
+ break;
case ActionID::SelectAll:
qaction.setShortcut(QKeySequence::StandardKey::SelectAll);
break;