File: wayland_exchange_data_provider.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 (319 lines) | stat: -rw-r--r-- 10,519 bytes parent folder | download | duplicates (4)
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
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/ozone/platform/wayland/host/wayland_exchange_data_provider.h"

#include <cstdint>
#include <memory>
#include <string>
#include <vector>

#include "base/check.h"
#include "base/logging.h"
#include "base/pickle.h"
#include "base/strings/strcat.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "net/base/mime_util.h"
#include "ui/base/clipboard/clipboard_constants.h"
#include "ui/base/clipboard/clipboard_format_type.h"
#include "ui/base/clipboard/file_info.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/base/dragdrop/os_exchange_data_provider.h"
#include "ui/base/dragdrop/os_exchange_data_provider_non_backed.h"
#include "ui/ozone/public/platform_clipboard.h"
#include "url/gurl.h"
#include "url/url_canon.h"
#include "url/url_util.h"

namespace ui {

namespace {

constexpr FilenameToURLPolicy kFilenameToURLPolicy =
    FilenameToURLPolicy::CONVERT_FILENAMES;

// Returns name parameter in application/octet-stream;name=<...>, or empty
// string if parsing fails.
std::string GetApplicationOctetStreamName(const std::string& mime_type) {
  base::StringPairs params;
  if (net::MatchesMimeType(std::string(ui::kMimeTypeOctetStream), mime_type) &&
      net::ParseMimeType(mime_type, nullptr, &params)) {
    for (const auto& kv : params) {
      if (kv.first == "name") {
        return kv.second;
      }
    }
  }
  return std::string();
}

// Converts mime type string to OSExchangeData::Format, if supported, otherwise
// 0 is returned.
int MimeTypeToFormat(const std::string& mime_type) {
  if (mime_type == ui::kMimeTypePlainText ||
      mime_type == ui::kMimeTypeUtf8PlainText) {
    return OSExchangeData::STRING;
  }
  if (mime_type == ui::kMimeTypeUriList) {
    return OSExchangeData::FILE_NAME;
  }
  if (mime_type == ui::kMimeTypeMozillaUrl) {
    return OSExchangeData::URL;
  }
  if (mime_type == ui::kMimeTypeHtml || mime_type == ui::kMimeTypeUtf8Html) {
    return OSExchangeData::HTML;
  }
  if (!GetApplicationOctetStreamName(mime_type).empty()) {
    return OSExchangeData::FILE_CONTENTS;
  }
  if (mime_type == ui::kMimeTypeDataTransferCustomData) {
    return OSExchangeData::PICKLED_DATA;
  }
  return 0;
}

// Converts raw data to either narrow or wide string.
template <typename StringType>
StringType BytesTo(PlatformClipboard::Data bytes) {
  using ValueType = typename StringType::value_type;
  const size_t bytes_size = bytes->size();
  const size_t rounded_bytes_size =
      bytes_size - (bytes_size % sizeof(ValueType));
  if (bytes_size != rounded_bytes_size) {
    // This is suspicious.
    LOG(WARNING)
        << "Data is possibly truncated, or a wrong conversion is requested.";
  }

  StringType result;
  result.resize(rounded_bytes_size / sizeof(ValueType));
  base::as_writable_byte_span(result).copy_from(
      base::span(*bytes).first(rounded_bytes_size));
  return result;
}

void AddString(PlatformClipboard::Data data, OSExchangeDataProvider* provider) {
  DCHECK(provider);

  if (data->as_vector().empty()) {
    return;
  }

  provider->SetString(base::UTF8ToUTF16(BytesTo<std::string>(data)));
}

void AddHtml(PlatformClipboard::Data data, OSExchangeDataProvider* provider) {
  DCHECK(provider);

  if (data->as_vector().empty()) {
    return;
  }

  provider->SetHtml(base::UTF8ToUTF16(BytesTo<std::string>(data)), GURL());
}

// Parses |data| as if it had text/uri-list format.  Its brief spec is:
// 1.  Any lines beginning with the '#' character are comment lines.
// 2.  Non-comment lines shall be URIs (URNs or URLs).
// 3.  Lines are terminated with a CRLF pair.
// 4.  URL encoding is used.
void AddFiles(PlatformClipboard::Data data, OSExchangeDataProvider* provider) {
  DCHECK(provider);

  std::string data_as_string = BytesTo<std::string>(data);

  const auto lines = base::SplitString(
      data_as_string, "\r\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
  std::vector<FileInfo> filenames;
  for (const auto& line : lines) {
    if (line.empty() || line[0] == '#')
      continue;
    GURL url(line);
    if (!url.is_valid() || !url.SchemeIsFile()) {
      LOG(WARNING) << "Invalid URI found: " << line;
      continue;
    }

    url::RawCanonOutputT<char16_t> unescaped;
    url::DecodeURLEscapeSequences(
        url.path_piece(), url::DecodeURLMode::kUTF8OrIsomorphic, &unescaped);

    const base::FilePath path(base::UTF16ToUTF8(unescaped.view()));
    filenames.emplace_back(path, path.BaseName());
  }
  if (filenames.empty())
    return;

  provider->SetFilenames(filenames);
}

void AddFileContents(const std::string& filename,
                     PlatformClipboard::Data data,
                     OSExchangeDataProvider* provider) {
  DCHECK(provider);

  if (filename.empty()) {
    return;
  }

  provider->SetFileContents(base::FilePath(filename),
                            BytesTo<std::string>(data));
}

// Parses |data| as if it had text/x-moz-url format, which is basically
// two lines separated with newline, where the first line is the URL and
// the second one is page title.  The unpleasant feature of text/x-moz-url is
// that the URL has UTF-16 encoding.
void AddUrl(PlatformClipboard::Data data, OSExchangeDataProvider* provider) {
  DCHECK(provider);

  if (data->as_vector().empty()) {
    return;
  }

  std::u16string data_as_string16 = BytesTo<std::u16string>(data);

  const auto lines =
      base::SplitString(data_as_string16, u"\r\n", base::TRIM_WHITESPACE,
                        base::SPLIT_WANT_NONEMPTY);
  if (lines.size() != 2U) {
    LOG(WARNING) << "Invalid data passed as text/x-moz-url; it must contain "
                 << "exactly 2 lines but has " << lines.size() << " instead.";
    return;
  }
  GURL url(lines[0]);
  if (!url.is_valid()) {
    LOG(WARNING) << "Invalid data passed as text/x-moz-url; the first line "
                 << "must contain a valid URL but it doesn't.";
    return;
  }

  provider->SetURL(url, lines[1]);
}

}  // namespace

WaylandExchangeDataProvider::WaylandExchangeDataProvider() = default;

WaylandExchangeDataProvider::~WaylandExchangeDataProvider() = default;

std::unique_ptr<OSExchangeDataProvider> WaylandExchangeDataProvider::Clone()
    const {
  auto clone = std::make_unique<WaylandExchangeDataProvider>();
  CopyData(clone.get());
  return clone;
}

std::vector<std::string> WaylandExchangeDataProvider::BuildMimeTypesList()
    const {
  // Drag'n'drop manuals usually suggest putting data in order so the more
  // specific a MIME type is, the earlier it occurs in the list.  Wayland
  // specs don't say anything like that, but here we follow that common
  // practice: begin with URIs and end with plain text.  Just in case.
  std::vector<std::string> mime_types;
  if (HasFile())
    mime_types.push_back(ui::kMimeTypeUriList);

  if (HasURL(kFilenameToURLPolicy))
    mime_types.push_back(ui::kMimeTypeMozillaUrl);

  if (HasHtml()) {
    mime_types.push_back(ui::kMimeTypeHtml);
  }

  if (HasString()) {
    mime_types.push_back(ui::kMimeTypeUtf8PlainText);
    mime_types.push_back(ui::kMimeTypePlainText);
  }

  if (HasFileContents()) {
    std::optional<FileContentsInfo> file_contents = GetFileContents();

    std::string filename = file_contents->filename.value();
    base::ReplaceChars(filename, "\\", "\\\\", &filename);
    base::ReplaceChars(filename, "\"", "\\\"", &filename);
    const std::string mime_type =
        base::StrCat({ui::kMimeTypeOctetStream, ";name=\"", filename, "\""});
    mime_types.push_back(mime_type);
  }

  for (auto item : pickle_data())
    mime_types.push_back(item.first.GetName());

  return mime_types;
}

// TODO(crbug.com/40192823): Support custom formats/pickled data.
void WaylandExchangeDataProvider::AddData(PlatformClipboard::Data data,
                                          const std::string& mime_type) {
  DCHECK(data);
  DCHECK(IsMimeTypeSupported(mime_type));
  int format = MimeTypeToFormat(mime_type);
  switch (format) {
    case OSExchangeData::STRING:
      AddString(data, this);
      break;
    case OSExchangeData::HTML:
      AddHtml(data, this);
      break;
    case OSExchangeData::URL:
      AddUrl(data, this);
      break;
    case OSExchangeData::FILE_NAME:
      AddFiles(data, this);
      break;
    case OSExchangeData::FILE_CONTENTS:
      AddFileContents(GetApplicationOctetStreamName(mime_type), data, this);
      break;
  }
}

// TODO(crbug.com/40192823): Support custom formats/pickled data.
bool WaylandExchangeDataProvider::ExtractData(const std::string& mime_type,
                                              std::string* out_content) const {
  DCHECK(out_content);
  DCHECK(IsMimeTypeSupported(mime_type));
  if (std::optional<ui::OSExchangeData::UrlInfo> url_info;
      mime_type == ui::kMimeTypeMozillaUrl &&
      (url_info = GetURLAndTitle(kFilenameToURLPolicy)).has_value()) {
    out_content->append(url_info->url.spec());
    return true;
  }
  if ((mime_type == ui::kMimeTypeHtml || mime_type == ui::kMimeTypeUtf8Html) &&
      HasHtml()) {
    const std::optional<ui::OSExchangeData::HtmlInfo>& html_content = GetHtml();
    out_content->append(base::UTF16ToUTF8(html_content->html));
    return true;
  }
  if (mime_type.starts_with(ui::kMimeTypeOctetStream) && HasFileContents()) {
    std::optional<FileContentsInfo> file_contents = GetFileContents();
    out_content->append(file_contents->file_contents);
    return true;
  }
  if (mime_type == ui::kMimeTypeDataTransferCustomData &&
      HasCustomFormat(ui::ClipboardFormatType::DataTransferCustomType())) {
    std::optional<base::Pickle> pickle =
        GetPickledData(ui::ClipboardFormatType::DataTransferCustomType());
    *out_content = std::string(reinterpret_cast<const char*>(pickle->data()),
                               pickle->size());
    return true;
  }
  // Lastly, attempt to extract string data. Note: Keep this as the last
  // condition otherwise, for data maps that contain both string and custom
  // data, for example, it may result in subtle issues, such as,
  // https://crbug.com/1271311.
  if (std::optional<std::u16string> data = GetString(); data.has_value()) {
    out_content->append(base::UTF16ToUTF8(*data));
    return true;
  }
  return false;
}

bool IsMimeTypeSupported(const std::string& mime_type) {
  return MimeTypeToFormat(mime_type) != 0;
}

}  // namespace ui