File: system_clipboard.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (724 lines) | stat: -rw-r--r-- 22,972 bytes parent folder | download | duplicates (5)
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
// Copyright 2013 The Chromium Authors
// 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/core/clipboard/system_clipboard.h"

#include <variant>

#include "base/memory/scoped_refptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "build/build_config.h"
#include "mojo/public/cpp/base/big_buffer.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "skia/ext/skia_utils_base.h"
#include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h"
#include "third_party/blink/public/platform/browser_interface_broker_proxy.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_drag_data.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_local_frame_client.h"
#include "third_party/blink/renderer/core/clipboard/clipboard_utilities.h"
#include "third_party/blink/renderer/core/clipboard/data_object.h"
#include "third_party/blink/renderer/core/dom/document_fragment.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/platform/graphics/image.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/clipboard/clipboard_constants.h"
#include "ui/base/ui_base_features.h"

namespace blink {

namespace {

String NonNullString(const String& string) {
  return string.IsNull() ? g_empty_string16_bit : string;
}

// This function is needed to clone a PendingRemote because normally they are
// not clonable.  The input PendingRemote is "cloned" twice, so one of those
// copies is intended to replace the original PendingRemote passed in by the
// caller.
std::pair<mojo::PendingRemote<mojom::blink::FileSystemAccessDataTransferToken>,
          mojo::PendingRemote<mojom::blink::FileSystemAccessDataTransferToken>>
CloneFsaToken(
    mojo::PendingRemote<mojom::blink::FileSystemAccessDataTransferToken> in) {
  if (!in.is_valid()) {
    return {mojo::NullRemote(), mojo::NullRemote()};
  }
  mojo::Remote remote(std::move(in));
  mojo::PendingRemote<mojom::blink::FileSystemAccessDataTransferToken> copy;
  remote->Clone(copy.InitWithNewPipeAndPassReceiver());
  return {remote.Unbind(), std::move(copy)};
}

}  // namespace

SystemClipboard::SystemClipboard(LocalFrame* frame)
    : clipboard_(frame->DomWindow()),
      clipboard_listener_receiver_(this, frame->DomWindow()) {
  frame->GetBrowserInterfaceBroker().GetInterface(
      clipboard_.BindNewPipeAndPassReceiver(
          frame->GetTaskRunner(TaskType::kUserInteraction)));
#if BUILDFLAG(IS_OZONE)
  is_selection_buffer_available_ =
      frame->GetSettings()->GetSelectionClipboardBufferAvailable();
#endif  // BUILDFLAG(IS_OZONE)
}

bool SystemClipboard::IsSelectionMode() const {
  return buffer_ == mojom::blink::ClipboardBuffer::kSelection;
}

void SystemClipboard::SetSelectionMode(bool selection_mode) {
  buffer_ = selection_mode ? mojom::blink::ClipboardBuffer::kSelection
                           : mojom::blink::ClipboardBuffer::kStandard;
}

bool SystemClipboard::IsFormatAvailable(blink::mojom::ClipboardFormat format) {
  if (!IsValidBufferType(buffer_) || !clipboard_.is_bound())
    return false;
  bool result = false;
  clipboard_->IsFormatAvailable(format, buffer_, &result);
  return result;
}

ClipboardSequenceNumberToken SystemClipboard::SequenceNumber() {
  if (!IsValidBufferType(buffer_) || !clipboard_.is_bound())
    return ClipboardSequenceNumberToken();
  ClipboardSequenceNumberToken result;
  clipboard_->GetSequenceNumber(buffer_, &result);
  return result;
}

Vector<String> SystemClipboard::ReadAvailableTypes() {
  if (!IsValidBufferType(buffer_) || !clipboard_.is_bound())
    return {};
  Vector<String> types;
  clipboard_->ReadAvailableTypes(buffer_, &types);
  return types;
}

String SystemClipboard::ReadPlainText() {
  return ReadPlainText(buffer_);
}

String SystemClipboard::ReadPlainText(mojom::blink::ClipboardBuffer buffer) {
  if (!IsValidBufferType(buffer) || !clipboard_.is_bound())
    return String();

  if (snapshot_ && snapshot_->HasPlainText(buffer)) {
    return snapshot_->PlainText(buffer);
  }

  String text;
  clipboard_->ReadText(buffer, &text);
  if (snapshot_) {
    snapshot_->SetPlainText(buffer, text);
  }

  return text;
}

void SystemClipboard::ReadPlainText(
    mojom::blink::ClipboardBuffer buffer,
    mojom::blink::ClipboardHost::ReadTextCallback callback) {
  if (!IsValidBufferType(buffer) || !clipboard_.is_bound()) {
    std::move(callback).Run(String());
    return;
  }
  clipboard_->ReadText(buffer, std::move(callback));
}

void SystemClipboard::WritePlainText(const String& plain_text,
                                     SmartReplaceOption) {
  if (RuntimeEnabledFeatures::ClipboardSnapshotResetOnWriteEnabled()) {
    ResetSnapshot();
  } else {
    DCHECK(!snapshot_);
  }

  if (!clipboard_.is_bound())
    return;
  // TODO(https://crbug.com/106449): add support for smart replace, which is
  // currently under-specified.
  String text = plain_text;
#if BUILDFLAG(IS_WIN)
  ReplaceNewlinesWithWindowsStyleNewlines(text);
#endif
  clipboard_->WriteText(NonNullString(text));
}

String SystemClipboard::ReadHTML(KURL& url,
                                 unsigned& fragment_start,
                                 unsigned& fragment_end) {
  if (!IsValidBufferType(buffer_) || !clipboard_.is_bound()) {
    url = KURL();
    fragment_start = 0;
    fragment_end = 0;
    return String();
  }

  if (snapshot_ && snapshot_->HasHtml(buffer_)) {
    url = snapshot_->Url(buffer_);
    fragment_start = snapshot_->FragmentStart(buffer_);
    fragment_end = snapshot_->FragmentEnd(buffer_);
    return snapshot_->Html(buffer_);
  }

  // NOTE: `fragment_start` and `fragment_end` can be the same reference, so
  // use local variables here to make sure the snapshot is set correctly.
  String html;
  uint32_t local_fragment_start;
  uint32_t local_fragment_end;
  clipboard_->ReadHtml(buffer_, &html, &url, &local_fragment_start,
                       &local_fragment_end);
  if (html.empty()) {
    url = KURL();
    local_fragment_start = 0;
    local_fragment_end = 0;
  }

  if (snapshot_) {
    snapshot_->SetHtml(buffer_, html, url, local_fragment_start,
                       local_fragment_end);
  }

  fragment_start = local_fragment_start;
  fragment_end = local_fragment_end;
  return html;
}

void SystemClipboard::ReadHTML(
    mojom::blink::ClipboardHost::ReadHtmlCallback callback) {
  if (!IsValidBufferType(buffer_) || !clipboard_.is_bound()) {
    std::move(callback).Run(String(), KURL(), 0, 0);
    return;
  }
  clipboard_->ReadHtml(buffer_, std::move(callback));
}

void SystemClipboard::WriteHTML(const String& markup,
                                const KURL& document_url,
                                SmartReplaceOption smart_replace_option) {
  if (RuntimeEnabledFeatures::ClipboardSnapshotResetOnWriteEnabled()) {
    ResetSnapshot();
  } else {
    DCHECK(!snapshot_);
  }

  if (!clipboard_.is_bound())
    return;
  clipboard_->WriteHtml(NonNullString(markup), document_url);
  if (smart_replace_option == kCanSmartReplace)
    clipboard_->WriteSmartPasteMarker();
}

void SystemClipboard::ReadSvg(
    mojom::blink::ClipboardHost::ReadSvgCallback callback) {
  if (!IsValidBufferType(buffer_) || !clipboard_.is_bound()) {
    std::move(callback).Run(String());
    return;
  }
  clipboard_->ReadSvg(buffer_, std::move(callback));
}

void SystemClipboard::WriteSvg(const String& markup) {
  if (RuntimeEnabledFeatures::ClipboardSnapshotResetOnWriteEnabled()) {
    ResetSnapshot();
  } else {
    DCHECK(!snapshot_);
  }

  if (!clipboard_.is_bound())
    return;
  clipboard_->WriteSvg(NonNullString(markup));
}

String SystemClipboard::ReadRTF() {
  if (!IsValidBufferType(buffer_) || !clipboard_.is_bound())
    return String();

  if (snapshot_ && snapshot_->HasRtf(buffer_)) {
    return snapshot_->Rtf(buffer_);
  }

  String rtf;
  clipboard_->ReadRtf(buffer_, &rtf);
  if (snapshot_) {
    snapshot_->SetRtf(buffer_, rtf);
  }

  return rtf;
}

mojo_base::BigBuffer SystemClipboard::ReadPng(
    mojom::blink::ClipboardBuffer buffer) {
  if (!IsValidBufferType(buffer) || !clipboard_.is_bound())
    return mojo_base::BigBuffer();

  if (snapshot_ && snapshot_->HasPng(buffer)) {
    return snapshot_->Png(buffer);
  }

  mojo_base::BigBuffer png;
  clipboard_->ReadPng(buffer, &png);
  if (snapshot_) {
    snapshot_->SetPng(buffer, png);
  }

  return png;
}

String SystemClipboard::ReadImageAsImageMarkup(
    mojom::blink::ClipboardBuffer buffer) {
  mojo_base::BigBuffer png_data = ReadPng(buffer);
  return PNGToImageMarkup(png_data);
}

void SystemClipboard::WriteImageWithTag(Image* image,
                                        const KURL& url,
                                        const String& title) {
  if (RuntimeEnabledFeatures::ClipboardSnapshotResetOnWriteEnabled()) {
    ResetSnapshot();
  } else {
    DCHECK(!snapshot_);
  }

  DCHECK(image);

  if (!clipboard_.is_bound())
    return;

  PaintImage paint_image = image->PaintImageForCurrentFrame();
  // Orient the data.
  if (!image->HasDefaultOrientation()) {
    paint_image = Image::ResizeAndOrientImage(paint_image, image->Orientation(),
                                              gfx::Vector2dF(1, 1), 1,
                                              kInterpolationNone);
  }
  SkBitmap bitmap;
  if (sk_sp<SkImage> sk_image = paint_image.GetSwSkImage())
    sk_image->asLegacyBitmap(&bitmap);

  // The bitmap backing a canvas can be in non-native skia pixel order (aka
  // RGBA when kN32_SkColorType is BGRA-ordered, or higher bit-depth color-types
  // like F16. The IPC to the browser requires the bitmap to be in N32 format
  // so we convert it here if needed.
  SkBitmap n32_bitmap;
  if (skia::SkBitmapToN32OpaqueOrPremul(bitmap, &n32_bitmap) &&
      !n32_bitmap.isNull()) {
    clipboard_->WriteImage(n32_bitmap);
  }

  if (url.IsValid() && !url.IsEmpty()) {
#if !BUILDFLAG(IS_MAC)
    // See http://crbug.com/838808: Not writing text/plain on Mac for
    // consistency between platforms, and to help fix errors in applications
    // which prefer text/plain content over image content for compatibility with
    // Microsoft Word.
    clipboard_->WriteBookmark(url.GetString(), NonNullString(title));
#endif

    // When writing the image, we also write the image markup so that pasting
    // into rich text editors, such as Gmail, reveals the image. We also don't
    // want to call writeText(), since some applications (WordPad) don't pick
    // the image if there is also a text format on the clipboard.
    clipboard_->WriteHtml(URLToImageMarkup(url, title), KURL());
  }
}

void SystemClipboard::WriteImage(const SkBitmap& bitmap) {
  if (RuntimeEnabledFeatures::ClipboardSnapshotResetOnWriteEnabled()) {
    ResetSnapshot();
  } else {
    DCHECK(!snapshot_);
  }

  if (!clipboard_.is_bound())
    return;
  clipboard_->WriteImage(bitmap);
}

mojom::blink::ClipboardFilesPtr SystemClipboard::ReadFiles() {
  mojom::blink::ClipboardFilesPtr files;
  if (!IsValidBufferType(buffer_) || !clipboard_.is_bound())
    return files;

  if (snapshot_ && snapshot_->HasFiles(buffer_)) {
    return snapshot_->Files(buffer_);
  }

  clipboard_->ReadFiles(buffer_, &files);
  if (snapshot_) {
    snapshot_->SetFiles(buffer_, files);
  }

  return files;
}

String SystemClipboard::ReadDataTransferCustomData(const String& type) {
  if (!IsValidBufferType(buffer_) || !clipboard_.is_bound())
    return String();

  if (snapshot_ && snapshot_->HasCustomData(buffer_, type)) {
    return snapshot_->CustomData(buffer_, type);
  }

  String data;
  clipboard_->ReadDataTransferCustomData(buffer_, NonNullString(type), &data);
  if (snapshot_) {
    snapshot_->SetCustomData(buffer_, type, data);
  }

  return data;
}

void SystemClipboard::WriteDataObject(DataObject* data_object) {
  if (RuntimeEnabledFeatures::ClipboardSnapshotResetOnWriteEnabled()) {
    ResetSnapshot();
  } else {
    DCHECK(!snapshot_);
  }

  DCHECK(data_object);
  if (!clipboard_.is_bound())
    return;
  // This plagiarizes the logic in DropDataBuilder::Build, but only extracts the
  // data needed for the implementation of WriteDataObject.
  //
  // We avoid calling the WriteFoo functions if there is no data associated with
  // a type. This prevents stomping on clipboard contents that might have been
  // written by extension functions such as chrome.bookmarkManagerPrivate.copy.
  //
  // TODO(crbug.com/332555471): Use a mojo struct to send web_drag_data and
  // allow receiving side to extract the data required.
  // TODO(crbug.com/332571415): Properly support text/uri-list here.
  HashMap<String, String> custom_data;
  WebDragData data = data_object->ToWebDragData();
  for (const WebDragData::Item& item : data.Items()) {
    if (const auto* string_item = std::get_if<WebDragData::StringItem>(&item)) {
      if (string_item->type == ui::kMimeTypePlainText) {
        clipboard_->WriteText(NonNullString(string_item->data));
      } else if (string_item->type == ui::kMimeTypeHtml) {
        clipboard_->WriteHtml(NonNullString(string_item->data), KURL());
      } else if (string_item->type != ui::kMimeTypeDownloadUrl) {
        custom_data.insert(string_item->type, NonNullString(string_item->data));
      }
    }
  }
  if (!custom_data.empty()) {
    clipboard_->WriteDataTransferCustomData(std::move(custom_data));
  }
}

void SystemClipboard::CommitWrite() {
  if (RuntimeEnabledFeatures::ClipboardSnapshotResetOnWriteEnabled()) {
    ResetSnapshot();
  } else {
    DCHECK(!snapshot_);
  }

  if (!clipboard_.is_bound())
    return;
  clipboard_->CommitWrite();
}

void SystemClipboard::CopyToFindPboard(const String& text) {
#if BUILDFLAG(IS_MAC)
  if (!clipboard_.is_bound())
    return;
  clipboard_->WriteStringToFindPboard(text);
#endif
}

void SystemClipboard::ReadAvailableCustomAndStandardFormats(
    mojom::blink::ClipboardHost::ReadAvailableCustomAndStandardFormatsCallback
        callback) {
  if (!clipboard_.is_bound())
    return;
  clipboard_->ReadAvailableCustomAndStandardFormats(std::move(callback));
}

void SystemClipboard::ReadUnsanitizedCustomFormat(
    const String& type,
    mojom::blink::ClipboardHost::ReadUnsanitizedCustomFormatCallback callback) {
  // TODO(crbug.com/332555472): Add test coverage for all functions with this
  //  check in `SystemClipboard` and consider if it's appropriate to throw
  // exceptions or reject promises if the context is detached.
  if (!clipboard_.is_bound())
    return;
  // The format size restriction is added in `ClipboardItem::supports`.
  DCHECK_LT(type.length(), mojom::blink::ClipboardHost::kMaxFormatSize);
  clipboard_->ReadUnsanitizedCustomFormat(type, std::move(callback));
}

void SystemClipboard::WriteUnsanitizedCustomFormat(const String& type,
                                                   mojo_base::BigBuffer data) {
  if (RuntimeEnabledFeatures::ClipboardSnapshotResetOnWriteEnabled()) {
    ResetSnapshot();
  } else {
    DCHECK(!snapshot_);
  }

  if (!clipboard_.is_bound() ||
      data.size() >= mojom::blink::ClipboardHost::kMaxDataSize) {
    return;
  }
  // The format size restriction is added in `ClipboardItem::supports`.
  DCHECK_LT(type.length(), mojom::blink::ClipboardHost::kMaxFormatSize);
  clipboard_->WriteUnsanitizedCustomFormat(type, std::move(data));
}

void SystemClipboard::Trace(Visitor* visitor) const {
  PlatformEventDispatcher::Trace(visitor);
  visitor->Trace(clipboard_);
  visitor->Trace(clipboard_listener_receiver_);
}

bool SystemClipboard::IsValidBufferType(mojom::blink::ClipboardBuffer buffer) {
  switch (buffer) {
    case mojom::blink::ClipboardBuffer::kStandard:
      return true;
    case mojom::blink::ClipboardBuffer::kSelection:
      return is_selection_buffer_available_;
  }
  return true;
}

void SystemClipboard::TakeSnapshot() {
  ++snapshot_count_;
  if (snapshot_count_ == 1) {
    DCHECK(!snapshot_);
    snapshot_ = std::make_unique<Snapshot>();
  }
}

void SystemClipboard::DropSnapshot() {
  DCHECK_GT(snapshot_count_, 0u);
  --snapshot_count_;
  if (snapshot_count_ == 0) {
    snapshot_.reset();
  }
}

void SystemClipboard::ResetSnapshot() {
  if (snapshot_) {
    snapshot_ = std::make_unique<Snapshot>();
  }
}

SystemClipboard::Snapshot::Snapshot() = default;

SystemClipboard::Snapshot::~Snapshot() = default;

bool SystemClipboard::Snapshot::HasPlainText(
    mojom::blink::ClipboardBuffer buffer) const {
  return buffer_.has_value() && plain_text_.has_value();
}

const String& SystemClipboard::Snapshot::PlainText(
    mojom::blink::ClipboardBuffer buffer) const {
  DCHECK(HasPlainText(buffer));
  return plain_text_.value();
}

void SystemClipboard::Snapshot::SetPlainText(
    mojom::blink::ClipboardBuffer buffer,
    const String& text) {
  BindToBuffer(buffer);
  plain_text_ = text;
}

bool SystemClipboard::Snapshot::HasHtml(
    mojom::blink::ClipboardBuffer buffer) const {
  return buffer_.has_value() && html_.has_value();
}

const KURL& SystemClipboard::Snapshot::Url(
    mojom::blink::ClipboardBuffer buffer) const {
  DCHECK(HasHtml(buffer));
  return url_;
}

unsigned SystemClipboard::Snapshot::FragmentStart(
    mojom::blink::ClipboardBuffer buffer) const {
  DCHECK(HasHtml(buffer));
  return fragment_start_;
}

unsigned SystemClipboard::Snapshot::FragmentEnd(
    mojom::blink::ClipboardBuffer buffer) const {
  DCHECK(HasHtml(buffer));
  return fragment_end_;
}

const String& SystemClipboard::Snapshot::Html(
    mojom::blink::ClipboardBuffer buffer) const {
  DCHECK(HasHtml(buffer));
  return html_.value();
}

void SystemClipboard::Snapshot::SetHtml(mojom::blink::ClipboardBuffer buffer,
                                        const String& html,
                                        const KURL& url,
                                        unsigned fragment_start,
                                        unsigned fragment_end) {
  BindToBuffer(buffer);
  html_ = html;
  url_ = url;
  fragment_start_ = fragment_start;
  fragment_end_ = fragment_end;
}

bool SystemClipboard::Snapshot::HasRtf(
    mojom::blink::ClipboardBuffer buffer) const {
  return buffer_.has_value() && rtf_.has_value();
}

const String& SystemClipboard::Snapshot::Rtf(
    mojom::blink::ClipboardBuffer buffer) const {
  DCHECK(HasRtf(buffer));
  return rtf_.value();
}

void SystemClipboard::Snapshot::SetRtf(mojom::blink::ClipboardBuffer buffer,
                                       const String& rtf) {
  BindToBuffer(buffer);
  rtf_ = rtf;
}

bool SystemClipboard::Snapshot::HasPng(
    mojom::blink::ClipboardBuffer buffer) const {
  return buffer_.has_value() && png_.has_value();
}

mojo_base::BigBuffer SystemClipboard::Snapshot::Png(
    mojom::blink::ClipboardBuffer buffer) const {
  DCHECK(HasPng(buffer));
  // Make an owning copy of the png to return to user.
  base::span<const uint8_t> span = base::span(png_.value());
  return mojo_base::BigBuffer(span);
}

// TODO(https://crbug.com/1412180): Reduce data copies.
void SystemClipboard::Snapshot::SetPng(mojom::blink::ClipboardBuffer buffer,
                                       const mojo_base::BigBuffer& png) {
  BindToBuffer(buffer);
  // Make an owning copy of the png to save locally.
  base::span<const uint8_t> span = base::span(png);
  png_ = mojo_base::BigBuffer(span);
}

bool SystemClipboard::Snapshot::HasFiles(
    mojom::blink::ClipboardBuffer buffer) const {
  return buffer_.has_value() && files_.has_value();
}

mojom::blink::ClipboardFilesPtr SystemClipboard::Snapshot::Files(
    mojom::blink::ClipboardBuffer buffer) const {
  DCHECK(HasFiles(buffer));
  return CloneFiles(files_.value());
}

void SystemClipboard::Snapshot::SetFiles(
    mojom::blink::ClipboardBuffer buffer,
    mojom::blink::ClipboardFilesPtr& files) {
  BindToBuffer(buffer);
  files_ = CloneFiles(files);
}

bool SystemClipboard::Snapshot::HasCustomData(
    mojom::blink::ClipboardBuffer buffer,
    const String& type) const {
  return buffer_.has_value() && custom_data_.Contains(type);
}

String SystemClipboard::Snapshot::CustomData(
    mojom::blink::ClipboardBuffer buffer,
    const String& type) const {
  DCHECK(HasCustomData(buffer, type));
  return custom_data_.at(type);
}

void SystemClipboard::Snapshot::SetCustomData(
    mojom::blink::ClipboardBuffer buffer,
    const String& type,
    const String& data) {
  BindToBuffer(buffer);
  custom_data_.Set(type, data);
}

void SystemClipboard::OnClipboardDataChanged() {
  // If we're not listening (receiver not bound), don't notify controllers
  if (!clipboard_listener_receiver_.is_bound()) {
    return;
  }
  NotifyControllers();
}

void SystemClipboard::StartListening(LocalDOMWindow* window) {
  if (!base::FeatureList::IsEnabled(features::kClipboardChangeEvent)) {
    return;
  }

  // If we're already listening (receiver is bound), no need to register again
  if (!clipboard_listener_receiver_.is_bound() && clipboard_.is_bound()) {
    clipboard_->RegisterClipboardListener(
        clipboard_listener_receiver_.BindNewPipeAndPassRemote(
            window->GetTaskRunner(TaskType::kUserInteraction)));
  }
}

void SystemClipboard::StopListening() {
  clipboard_listener_receiver_.reset();
}

// static
mojom::blink::ClipboardFilesPtr SystemClipboard::Snapshot::CloneFiles(
    mojom::blink::ClipboardFilesPtr& files) {
  if (!files) {
    return {};
  }

  WTF::Vector<mojom::blink::DataTransferFilePtr> vec;
  for (auto& dtf : files->files) {
    auto clones = CloneFsaToken(std::move(dtf->file_system_access_token));
    dtf->file_system_access_token = std::move(clones.first);
    vec.emplace_back(mojom::blink::DataTransferFile::New(
        dtf->path, dtf->display_name, std::move(clones.second)));
  }

  return mojom::blink::ClipboardFiles::New(std::move(vec),
                                           files->file_system_id);
}

void SystemClipboard::Snapshot::BindToBuffer(
    mojom::blink::ClipboardBuffer buffer) {
  if (!buffer_) {
    buffer_ = buffer;
  } else {
    DCHECK_EQ(*buffer_, buffer);
  }
}

ScopedSystemClipboardSnapshot::ScopedSystemClipboardSnapshot(
    SystemClipboard& clipboard)
    : clipboard_(clipboard) {
  clipboard.TakeSnapshot();
}

ScopedSystemClipboardSnapshot::~ScopedSystemClipboardSnapshot() {
  clipboard_.DropSnapshot();
}

}  // namespace blink