summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/modules/clipboard/clipboard_writer.cc
blob: 48469de5608aa09113f2d854357d18caf01cd0c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/modules/clipboard/clipboard_writer.h"

#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/mojom/clipboard/clipboard.mojom-blink.h"
#include "third_party/blink/public/mojom/clipboard/raw_clipboard.mojom-blink.h"
#include "third_party/blink/renderer/core/clipboard/clipboard_mime_types.h"
#include "third_party/blink/renderer/core/clipboard/raw_system_clipboard.h"
#include "third_party/blink/renderer/core/clipboard/system_clipboard.h"
#include "third_party/blink/renderer/core/dom/document_fragment.h"
#include "third_party/blink/renderer/core/editing/serializers/serialization.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/fileapi/file_reader_loader.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h"
#include "third_party/blink/renderer/platform/image-decoders/image_decoder.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/worker_pool.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"

namespace blink {

namespace {  // anonymous namespace for ClipboardWriter's derived classes.

// Writes a Blob with image/png content to the System Clipboard.
class ClipboardImageWriter final : public ClipboardWriter {
 public:
  ClipboardImageWriter(SystemClipboard* system_clipboard,
                       ClipboardPromise* promise)
      : ClipboardWriter(system_clipboard, promise) {}
  ~ClipboardImageWriter() override = default;

 private:
  void StartWrite(
      DOMArrayBuffer* raw_data,
      scoped_refptr<base::SingleThreadTaskRunner> task_runner) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    worker_pool::PostTask(
        FROM_HERE,
        CrossThreadBindOnce(&ClipboardImageWriter::DecodeOnBackgroundThread,
                            WrapCrossThreadPersistent(raw_data),
                            WrapCrossThreadPersistent(this), task_runner));
  }
  static void DecodeOnBackgroundThread(
      DOMArrayBuffer* png_data,
      ClipboardImageWriter* writer,
      scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
    DCHECK(!IsMainThread());
    std::unique_ptr<ImageDecoder> decoder = ImageDecoder::Create(
        SegmentReader::CreateFromSkData(
            SkData::MakeWithoutCopy(png_data->Data(), png_data->ByteLength())),
        true, ImageDecoder::kAlphaPremultiplied, ImageDecoder::kDefaultBitDepth,
        ColorBehavior::Tag());
    sk_sp<SkImage> image = nullptr;
    // `decoder` is nullptr if `png_data` doesn't begin with the PNG signature.
    if (decoder)
      image = ImageBitmap::GetSkImageFromDecoder(std::move(decoder));

    PostCrossThreadTask(*task_runner, FROM_HERE,
                        CrossThreadBindOnce(&ClipboardImageWriter::Write,
                                            WrapCrossThreadPersistent(writer),
                                            std::move(image)));
  }
  void Write(sk_sp<SkImage> image) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (!image) {
      promise_->RejectFromReadOrDecodeFailure();
      return;
    }
    if (!promise_->GetLocalFrame())
      return;
    SkBitmap bitmap;
    image->asLegacyBitmap(&bitmap);
    system_clipboard()->WriteImage(std::move(bitmap));
    promise_->CompleteWriteRepresentation();
  }
};

// Writes a Blob with text/plain content to the System Clipboard.
class ClipboardTextWriter final : public ClipboardWriter {
 public:
  ClipboardTextWriter(SystemClipboard* system_clipboard,
                      ClipboardPromise* promise)
      : ClipboardWriter(system_clipboard, promise) {}
  ~ClipboardTextWriter() override = default;

 private:
  void StartWrite(
      DOMArrayBuffer* raw_data,
      scoped_refptr<base::SingleThreadTaskRunner> task_runner) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    worker_pool::PostTask(
        FROM_HERE,
        CrossThreadBindOnce(&ClipboardTextWriter::DecodeOnBackgroundThread,
                            WrapCrossThreadPersistent(raw_data),
                            WrapCrossThreadPersistent(this), task_runner));
  }
  static void DecodeOnBackgroundThread(
      DOMArrayBuffer* raw_data,
      ClipboardTextWriter* writer,
      scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
    DCHECK(!IsMainThread());

    String wtf_string =
        String::FromUTF8(reinterpret_cast<const LChar*>(raw_data->Data()),
                         raw_data->ByteLength());
    DCHECK(wtf_string.IsSafeToSendToAnotherThread());
    PostCrossThreadTask(*task_runner, FROM_HERE,
                        CrossThreadBindOnce(&ClipboardTextWriter::Write,
                                            WrapCrossThreadPersistent(writer),
                                            std::move(wtf_string)));
  }
  void Write(const String& text) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (!promise_->GetLocalFrame())
      return;
    system_clipboard()->WritePlainText(text);

    promise_->CompleteWriteRepresentation();
  }
};

// Writes a blob with text/html content to the System Clipboard.
class ClipboardHtmlWriter final : public ClipboardWriter {
 public:
  ClipboardHtmlWriter(SystemClipboard* system_clipboard,
                      ClipboardPromise* promise)
      : ClipboardWriter(system_clipboard, promise) {}
  ~ClipboardHtmlWriter() override = default;

 private:
  void StartWrite(
      DOMArrayBuffer* html_data,
      scoped_refptr<base::SingleThreadTaskRunner> task_runner) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    auto* execution_context = promise_->GetExecutionContext();
    if (!execution_context)
      return;
    execution_context->CountUse(WebFeature::kHtmlClipboardApiWrite);

    String html_string =
        String::FromUTF8(reinterpret_cast<const LChar*>(html_data->Data()),
                         html_data->ByteLength());

    // Sanitizing on the main thread because HTML DOM nodes can only be used
    // on the main thread.
    KURL url;
    unsigned fragment_start = 0;
    unsigned fragment_end = html_string.length();

    LocalFrame* local_frame = promise_->GetLocalFrame();
    if (!local_frame)
      return;
    Document* document = local_frame->GetDocument();
    DocumentFragment* fragment = CreateSanitizedFragmentFromMarkupWithContext(
        *document, html_string, fragment_start, fragment_end, url);
    String sanitized_html =
        CreateMarkup(fragment, kIncludeNode, kResolveAllURLs);
    Write(sanitized_html, url);
  }

  void Write(const String& sanitized_html, KURL url) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    system_clipboard()->WriteHTML(sanitized_html, url);
    promise_->CompleteWriteRepresentation();
  }
};

// Writes a blob with image/svg+xml content to the System Clipboard.
class ClipboardSvgWriter final : public ClipboardWriter {
 public:
  ClipboardSvgWriter(SystemClipboard* system_clipboard,
                     ClipboardPromise* promise)
      : ClipboardWriter(system_clipboard, promise) {}
  ~ClipboardSvgWriter() override = default;

 private:
  void StartWrite(
      DOMArrayBuffer* svg_data,
      scoped_refptr<base::SingleThreadTaskRunner> task_runner) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    String svg_string =
        String::FromUTF8(reinterpret_cast<const LChar*>(svg_data->Data()),
                         svg_data->ByteLength());

    // Sanitizing on the main thread because SVG/XML DOM nodes can only be used
    // on the main thread.
    KURL url;
    unsigned fragment_start = 0;
    unsigned fragment_end = svg_string.length();

    LocalFrame* local_frame = promise_->GetLocalFrame();
    if (!local_frame)
      return;
    Document* document = local_frame->GetDocument();
    DocumentFragment* fragment = CreateSanitizedFragmentFromMarkupWithContext(
        *document, svg_string, fragment_start, fragment_end, url);
    String sanitized_svg =
        CreateMarkup(fragment, kIncludeNode, kResolveAllURLs);
    Write(sanitized_svg);
  }

  void Write(const String& svg_html) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    system_clipboard()->WriteSvg(svg_html);
    promise_->CompleteWriteRepresentation();
  }
};

// Writes a Blob with arbitrary, unsanitized content to the System Clipboard.
class ClipboardRawDataWriter final : public ClipboardWriter {
 public:
  ClipboardRawDataWriter(RawSystemClipboard* raw_system_clipboard,
                         ClipboardPromise* promise,
                         String mime_type)
      : ClipboardWriter(raw_system_clipboard, promise), mime_type_(mime_type) {}
  ~ClipboardRawDataWriter() override = default;

 private:
  void StartWrite(
      DOMArrayBuffer* raw_data,
      scoped_refptr<base::SingleThreadTaskRunner> task_runner) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    // Raw Data is written directly, and doesn't require decoding.
    Write(raw_data);
  }

  void Write(DOMArrayBuffer* raw_data) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    if (raw_data->ByteLength() >=
        mojom::blink::RawClipboardHost::kMaxDataSize) {
      promise_->RejectFromReadOrDecodeFailure();
      return;
    }

    uint8_t* raw_data_pointer = static_cast<uint8_t*>(raw_data->Data());
    mojo_base::BigBuffer buffer(std::vector<uint8_t>(
        raw_data_pointer, raw_data_pointer + raw_data->ByteLength()));

    if (!promise_->GetLocalFrame())
      return;
    raw_system_clipboard()->Write(mime_type_, std::move(buffer));

    promise_->CompleteWriteRepresentation();
  }

  String mime_type_;
};

}  // anonymous namespace

// ClipboardWriter functions.

// static
ClipboardWriter* ClipboardWriter::Create(SystemClipboard* system_clipboard,
                                         const String& mime_type,
                                         ClipboardPromise* promise) {
  DCHECK(ClipboardWriter::IsValidType(mime_type, /*is_raw=*/false));
  if (mime_type == kMimeTypeImagePng) {
    return MakeGarbageCollected<ClipboardImageWriter>(system_clipboard,
                                                      promise);
  }
  if (mime_type == kMimeTypeTextPlain)
    return MakeGarbageCollected<ClipboardTextWriter>(system_clipboard, promise);

  if (mime_type == kMimeTypeTextHTML)
    return MakeGarbageCollected<ClipboardHtmlWriter>(system_clipboard, promise);

  if (mime_type == kMimeTypeImageSvg &&
      RuntimeEnabledFeatures::ClipboardSvgEnabled())
    return MakeGarbageCollected<ClipboardSvgWriter>(system_clipboard, promise);

  NOTREACHED()
      << "IsValidType() and Create() have inconsistent implementations.";
  return nullptr;
}

// static
ClipboardWriter* ClipboardWriter::Create(
    RawSystemClipboard* raw_system_clipboard,
    const String& mime_type,
    ClipboardPromise* promise) {
  DCHECK(base::FeatureList::IsEnabled(features::kRawClipboard));
  DCHECK(ClipboardWriter::IsValidType(mime_type, /*is_raw=*/true));
  return MakeGarbageCollected<ClipboardRawDataWriter>(raw_system_clipboard,
                                                      promise, mime_type);
}

ClipboardWriter::ClipboardWriter(SystemClipboard* system_clipboard,
                                 ClipboardPromise* promise)
    : ClipboardWriter(system_clipboard, nullptr, promise) {}

ClipboardWriter::ClipboardWriter(RawSystemClipboard* raw_system_clipboard,
                                 ClipboardPromise* promise)
    : ClipboardWriter(nullptr, raw_system_clipboard, promise) {}

ClipboardWriter::ClipboardWriter(SystemClipboard* system_clipboard,
                                 RawSystemClipboard* raw_system_clipboard,
                                 ClipboardPromise* promise)
    : promise_(promise),
      clipboard_task_runner_(promise->GetExecutionContext()->GetTaskRunner(
          TaskType::kUserInteraction)),
      file_reading_task_runner_(promise->GetExecutionContext()->GetTaskRunner(
          TaskType::kFileReading)),
      system_clipboard_(system_clipboard),
      raw_system_clipboard_(raw_system_clipboard),
      self_keep_alive_(PERSISTENT_FROM_HERE, this) {}

ClipboardWriter::~ClipboardWriter() {
  DCHECK(!file_reader_);
}

// static
bool ClipboardWriter::IsValidType(const String& type, bool is_raw) {
  if (is_raw)
    return type.length() < mojom::blink::RawClipboardHost::kMaxFormatSize;

  if (type == kMimeTypeImageSvg)
    return RuntimeEnabledFeatures::ClipboardSvgEnabled();

  // TODO(https://crbug.com/1029857): Add support for other types.
  return type == kMimeTypeImagePng || type == kMimeTypeTextPlain ||
         type == kMimeTypeTextHTML;
}

void ClipboardWriter::WriteToSystem(Blob* blob) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!file_reader_);
  file_reader_ = std::make_unique<FileReaderLoader>(
      FileReaderLoader::kReadAsArrayBuffer, this,
      std::move(file_reading_task_runner_));
  file_reader_->Start(blob->GetBlobDataHandle());
}

// FileReaderLoaderClient implementation.

void ClipboardWriter::DidStartLoading() {}
void ClipboardWriter::DidReceiveData() {}

void ClipboardWriter::DidFinishLoading() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DOMArrayBuffer* array_buffer = file_reader_->ArrayBufferResult();
  DCHECK(array_buffer);

  file_reader_.reset();
  self_keep_alive_.Clear();

  StartWrite(array_buffer, clipboard_task_runner_);
}

void ClipboardWriter::DidFail(FileErrorCode error_code) {
  file_reader_.reset();
  self_keep_alive_.Clear();
  promise_->RejectFromReadOrDecodeFailure();
}

void ClipboardWriter::Trace(Visitor* visitor) const {
  visitor->Trace(promise_);
  visitor->Trace(system_clipboard_);
  visitor->Trace(raw_system_clipboard_);
}

}  // namespace blink