File: drag_drop_operation.cc

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (498 lines) | stat: -rw-r--r-- 17,189 bytes parent folder | download
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
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/exo/drag_drop_operation.h"

#include "ash/drag_drop/drag_drop_controller.h"
#include "base/barrier_closure.h"
#include "base/check.h"
#include "base/memory/raw_ptr.h"
#include "base/pickle.h"
#include "base/strings/string_split.h"
#include "base/task/sequenced_task_runner.h"
#include "components/exo/data_exchange_delegate.h"
#include "components/exo/data_offer.h"
#include "components/exo/data_source.h"
#include "components/exo/extended_drag_source.h"
#include "components/exo/seat.h"
#include "components/exo/shell_surface_base.h"
#include "components/exo/shell_surface_util.h"
#include "components/exo/surface.h"
#include "components/exo/surface_tree_host.h"
#include "components/viz/common/frame_sinks/copy_output_request.h"
#include "components/viz/common/frame_sinks/copy_output_result.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/window_tracker.h"
#include "ui/base/clipboard/file_info.h"
#include "ui/base/data_transfer_policy/data_transfer_endpoint.h"
#include "ui/base/data_transfer_policy/data_transfer_endpoint_serializer.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/compositor/layer.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/transform_util.h"
#include "ui/gfx/geometry/vector2d.h"
#include "url/gurl.h"

namespace exo {
namespace {

using ::ui::mojom::DragOperation;

uint32_t DndActionsToDragOperations(const base::flat_set<DndAction>& actions) {
  uint32_t dnd_operations = 0;
  for (const DndAction action : actions) {
    switch (action) {
      case DndAction::kNone:
        [[fallthrough]];
        // We don't support the ask action
      case DndAction::kAsk:
        break;
      case DndAction::kCopy:
        dnd_operations |= ui::DragDropTypes::DragOperation::DRAG_COPY;
        break;
      case DndAction::kMove:
        dnd_operations |= ui::DragDropTypes::DragOperation::DRAG_MOVE;
        break;
    }
  }
  return dnd_operations;
}

DndAction DragOperationsToPreferredDndAction(int op) {
  if (op & ui::DragDropTypes::DragOperation::DRAG_COPY)
    return DndAction::kCopy;

  if (op & ui::DragDropTypes::DragOperation::DRAG_MOVE)
    return DndAction::kMove;

  return DndAction::kNone;
}

DndAction DragOperationToDndAction(DragOperation op) {
  switch (op) {
    case DragOperation::kNone:
      return DndAction::kNone;
    case DragOperation::kMove:
      return DndAction::kMove;
    case DragOperation::kCopy:
      return DndAction::kCopy;
    case DragOperation::kLink:
      return DndAction::kAsk;
    default:
      NOTREACHED() << op;
      return DndAction::kNone;
  }
  NOTREACHED();
}

}  // namespace

// Internal representation of a drag icon surface. Used when a non-null surface
// is passed in wl_data_device::start_drag requests.
// TODO(crbug.com/1119385): Rework icon implementation to avoid frame copies.
class DragDropOperation::IconSurface final : public SurfaceTreeHost,
                                             public ScopedSurface {
 public:
  IconSurface(Surface* icon, DragDropOperation* operation)
      : SurfaceTreeHost("ExoDragIcon"),
        ScopedSurface(icon, operation),
        operation_(operation) {
    DCHECK(operation_);
    DCHECK(!icon->HasSurfaceDelegate());

    Surface* origin_surface = operation_->origin_->get();
    origin_surface->window()->AddChild(host_window());
    SetRootSurface(icon);
  }

  IconSurface(const IconSurface&) = delete;
  IconSurface& operator=(const IconSurface&) = delete;
  ~IconSurface() override = default;

 private:
  // SurfaceTreeHost:
  void OnSurfaceCommit() override {
    SurfaceTreeHost::OnSurfaceCommit();
    RequestCaptureIcon();
  }

  void RequestCaptureIcon() {
    SubmitCompositorFrame();

    std::unique_ptr<viz::CopyOutputRequest> request =
        std::make_unique<viz::CopyOutputRequest>(
            viz::CopyOutputRequest::ResultFormat::RGBA,
            viz::CopyOutputRequest::ResultDestination::kSystemMemory,
            base::BindOnce(&IconSurface::OnCaptured,
                           weak_ptr_factory_.GetWeakPtr()));
    request->set_result_task_runner(
        base::SequencedTaskRunner::GetCurrentDefault());

    host_window()->layer()->RequestCopyOfOutput(std::move(request));
  }

  void OnCaptured(std::unique_ptr<viz::CopyOutputResult> icon_result) {
    // An empty response means the request was deleted before it was completed.
    // If this happens, and no operation has yet finished, restart the capture.
    if (icon_result->IsEmpty()) {
      RequestCaptureIcon();
      return;
    }

    auto scoped_bitmap = icon_result->ScopedAccessSkBitmap();
    operation_->OnDragIconCaptured(scoped_bitmap.GetOutScopedBitmap());
  }

  const raw_ptr<DragDropOperation, ExperimentalAsh> operation_;
  base::WeakPtrFactory<IconSurface> weak_ptr_factory_{this};
};

base::WeakPtr<DragDropOperation> DragDropOperation::Create(
    DataExchangeDelegate* data_exchange_delegate,
    DataSource* source,
    Surface* origin,
    Surface* icon,
    const gfx::PointF& drag_start_point,
    ui::mojom::DragEventSource event_source) {
  auto* dnd_op = new DragDropOperation(data_exchange_delegate, source, origin,
                                       icon, drag_start_point, event_source);
  return dnd_op->weak_ptr_factory_.GetWeakPtr();
}

DragDropOperation::DragDropOperation(
    DataExchangeDelegate* data_exchange_delegate,
    DataSource* source,
    Surface* origin,
    Surface* icon,
    const gfx::PointF& drag_start_point,
    ui::mojom::DragEventSource event_source)
    : source_(std::make_unique<ScopedDataSource>(source, this)),
      origin_(std::make_unique<ScopedSurface>(origin, this)),
      drag_start_point_(drag_start_point),
      os_exchange_data_(std::make_unique<ui::OSExchangeData>()),
      event_source_(event_source) {
  aura::Window* root_window = origin_->get()->window()->GetRootWindow();
  DCHECK(root_window);
  drag_drop_controller_ = static_cast<ash::DragDropController*>(
      aura::client::GetDragDropClient(root_window));
  DCHECK(drag_drop_controller_);

  if (drag_drop_controller_->IsDragDropInProgress())
    drag_drop_controller_->DragCancel();

  drag_drop_controller_->AddObserver(this);

  ui::EndpointType endpoint_type =
      data_exchange_delegate->GetDataTransferEndpointType(
          origin_->get()->window());
  os_exchange_data_->SetSource(
      std::make_unique<ui::DataTransferEndpoint>(endpoint_type));

  extended_drag_source_ = ExtendedDragSource::Get();
  if (extended_drag_source_) {
    drag_drop_controller_->set_toplevel_window_drag_delegate(
        extended_drag_source_);
    extended_drag_source_->AddObserver(this);
  }

  int num_additional_callbacks = 0;

  // TODO(crbug.com/1371493): Remove this once the issue is fixed.
  std::string callbacks;

  // TODO(crbug.com/1298033): Move DTE retrieval into
  // DataSource::GetDataForPreferredMimeTypes()
  // Lacros sends additional metadata, in a custom MIME type, to sync drag
  // source metadata. Hence, the number of callbacks is incremented by one.
  if (endpoint_type == ui::EndpointType::kLacros) {
    callbacks += "lacros,";
    ++num_additional_callbacks;
  }

  // When the icon is present, we increment the number of callbacks so we can
  // wait for the icon to be captured as well.
  if (icon) {
    icon_ = std::make_unique<IconSurface>(icon, this);
    ++num_additional_callbacks;
    callbacks += "icon,";
  }

  auto start_op_callback =
      base::BindOnce(&DragDropOperation::ScheduleStartDragDropOperation,
                     weak_ptr_factory_.GetWeakPtr());

  // TODO(crbug.com/1371493): Remove these when the issue is fixed.
  start_drag_drop_timer_.Start(FROM_HERE, base::Seconds(2), this,
                               &DragDropOperation::DragDataReadTimeout);
  LOG(ERROR) << "Starting data read for drag operation: additonal callbacks:"
             << callbacks;

  counter_ =
      base::BarrierClosure(DataSource::kMaxDataTypes + num_additional_callbacks,
                           std::move(start_op_callback));

  // TODO(crbug.com/1298033): Move DTE retrieval into
  // DataSource::GetDataForPreferredMimeTypes()
  if (endpoint_type == ui::EndpointType::kLacros) {
    source->ReadDataTransferEndpoint(
        base::BindOnce(&DragDropOperation::OnDataTransferEndpointRead,
                       weak_ptr_factory_.GetWeakPtr()),
        counter_);
  }

  source->GetDataForPreferredMimeTypes(
      base::BindOnce(&DragDropOperation::OnTextRead,
                     weak_ptr_factory_.GetWeakPtr()),
      DataSource::ReadDataCallback(),
      base::BindOnce(&DragDropOperation::OnHTMLRead,
                     weak_ptr_factory_.GetWeakPtr()),
      DataSource::ReadDataCallback(),
      base::BindOnce(&DragDropOperation::OnFilenamesRead,
                     weak_ptr_factory_.GetWeakPtr(), data_exchange_delegate,
                     origin->window()),
      base::BindOnce(&DragDropOperation::OnFileContentsRead,
                     weak_ptr_factory_.GetWeakPtr()),
      base::BindOnce(&DragDropOperation::OnWebCustomDataRead,
                     weak_ptr_factory_.GetWeakPtr()),
      counter_);
}

DragDropOperation::~DragDropOperation() {
  drag_drop_controller_->RemoveObserver(this);

  if (source_)
    source_->get()->Cancelled();

  if (drag_drop_controller_->IsDragDropInProgress() && started_) {
    drag_drop_controller_->DragCancel();
  }

  if (extended_drag_source_)
    ResetExtendedDragSource();
}

void DragDropOperation::AbortIfPending() {
  if (!started_) {
    delete this;
  }
}

void DragDropOperation::OnDataTransferEndpointRead(const std::string& mime_type,
                                                   std::u16string data) {
  DCHECK(os_exchange_data_);

  std::string utf8_json = base::UTF16ToUTF8(data);
  auto drag_source_dte = ui::ConvertJsonToDataTransferEndpoint(utf8_json);

  os_exchange_data_->SetSource(std::move(drag_source_dte));

  counter_.Run();
}

void DragDropOperation::OnTextRead(const std::string& mime_type,
                                   std::u16string data) {
  DCHECK(os_exchange_data_);
  os_exchange_data_->SetString(std::move(data));

  // Prefer to use the HTML MIME type if possible
  if (mime_type_.empty())
    mime_type_ = mime_type;
  counter_.Run();
}

void DragDropOperation::OnHTMLRead(const std::string& mime_type,
                                   std::u16string data) {
  DCHECK(os_exchange_data_);
  os_exchange_data_->SetHtml(std::move(data), GURL());
  mime_type_ = mime_type;
  counter_.Run();
}

void DragDropOperation::OnFilenamesRead(
    DataExchangeDelegate* data_exchange_delegate,
    aura::Window* source,
    const std::string& mime_type,
    const std::vector<uint8_t>& data) {
  DCHECK(os_exchange_data_);
  os_exchange_data_->SetFilenames(data_exchange_delegate->GetFilenames(
      data_exchange_delegate->GetDataTransferEndpointType(source), data));
  mime_type_ = mime_type;
  counter_.Run();
}

void DragDropOperation::OnFileContentsRead(const std::string& mime_type,
                                           const base::FilePath& filename,
                                           const std::vector<uint8_t>& data) {
  DCHECK(os_exchange_data_);
  os_exchange_data_->SetFileContents(filename,
                                     std::string(data.begin(), data.end()));
  mime_type_ = mime_type;
  counter_.Run();
}

void DragDropOperation::OnWebCustomDataRead(const std::string& mime_type,
                                            const std::vector<uint8_t>& data) {
  DCHECK(os_exchange_data_);
  base::Pickle pickle(reinterpret_cast<const char*>(data.data()), data.size());
  os_exchange_data_->SetPickledData(
      ui::ClipboardFormatType::WebCustomDataType(), pickle);
  mime_type_ = mime_type;
  counter_.Run();
}

void DragDropOperation::OnDragIconCaptured(const SkBitmap& icon_bitmap) {
  DCHECK(icon_);

  float scale_factor = origin_->get()->window()->layer()->device_scale_factor();
  gfx::ImageSkia icon_skia =
      gfx::ImageSkia::CreateFromBitmap(icon_bitmap, scale_factor);
  gfx::Vector2d icon_offset = -icon_->get()->GetBufferOffset();

  if (os_exchange_data_) {
    os_exchange_data_->provider().SetDragImage(icon_skia, icon_offset);
  } else {
    drag_drop_controller_->SetDragImage(icon_skia, icon_offset);
  }

  if (!captured_icon_) {
    captured_icon_ = true;
    counter_.Run();
  }
}

void DragDropOperation::ScheduleStartDragDropOperation() {
  start_drag_drop_timer_.Stop();

  // StartDragAndDrop uses a nested run loop. When restarting, we a) don't want
  // to interrupt the callers task for an arbitrary period of time and b) want
  // to let any nested run loops that are currently running to have a chance to
  // exit to avoid arbitrarily deep nesting. We can accomplish both of those
  // things by posting a new task to actually start the drag and drop operation.
  if (extended_drag_source_) {
    ShellSurfaceBase* shell_surface = GetShellSurfaceBaseForWindow(
        origin_->get()->window()->GetToplevelWindow());
    if (shell_surface)
      shell_surface->set_in_extended_drag(true);
  }

  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, base::BindOnce(&DragDropOperation::StartDragDropOperation,
                                weak_ptr_factory_.GetWeakPtr()));
}

void DragDropOperation::StartDragDropOperation() {
  uint32_t dnd_operations =
      DndActionsToDragOperations(source_->get()->GetActions());

  base::WeakPtr<DragDropOperation> weak_ptr = weak_ptr_factory_.GetWeakPtr();

  started_ = true;
  gfx::Point drag_start_point = gfx::ToFlooredPoint(drag_start_point_);

  // This triggers a nested run loop that terminates when the drag and drop
  // operation is completed.
  DragOperation op = drag_drop_controller_->StartDragAndDrop(
      std::move(os_exchange_data_), origin_->get()->window()->GetRootWindow(),
      origin_->get()->window(), drag_start_point, dnd_operations,
      event_source_);

  // The instance deleted during StartDragAndDrop's nested RunLoop.
  if (!weak_ptr)
    return;

  // Always reset the in_extended_drag becacuse ExtendedDragSource may be
  // destroyed during nested loop.
  if (origin_->get()) {
    ShellSurfaceBase* shell_surface = GetShellSurfaceBaseForWindow(
        origin_->get()->window()->GetToplevelWindow());
    if (shell_surface)
      shell_surface->set_in_extended_drag(false);
  }

  // In tests, drag_drop_controller_ does not create a nested message loop and
  // so StartDragAndDrop exits before the drag&drop session finishes. In that
  // case the cleanup process shouldn't be made.
  if (drag_drop_controller_->IsDragDropInProgress())
    return;

  if (op != DragOperation::kNone) {
    // Success

    // TODO(crbug.com/994065) This is currently not the actual mime type
    // used by the recipient, just an arbitrary one we pick out of the
    // offered types so we can report back whether or not the drop can
    // succeed. This may need to change in the future.
    source_->get()->Target(mime_type_);

    source_->get()->Action(DragOperationToDndAction(op));
    source_->get()->DndDropPerformed();
    source_->get()->DndFinished();

    // Reset |source_| so it the destructor doesn't try to cancel it.
    source_.reset();
  }

  // On failure the destructor will handle canceling the data source.
  delete this;
}

void DragDropOperation::OnDragStarted() {
  if (!started_) {
    delete this;
  }
}

void DragDropOperation::OnDragActionsChanged(int actions) {
  if (!started_) {
    return;
  }

  DndAction dnd_action = DragOperationsToPreferredDndAction(actions);
  // We send a mime type along with the action to indicate to the application
  // that dropping is/is not currently possible. We do not currently know of
  // any applications that care about the specific mime type until the drop is
  // actually performed.
  if (dnd_action != DndAction::kNone)
    source_->get()->Target(mime_type_);
  else
    source_->get()->Target(absl::nullopt);

  source_->get()->Action(dnd_action);
}

void DragDropOperation::OnExtendedDragSourceDestroying(
    ExtendedDragSource* source) {
  ResetExtendedDragSource();
}

void DragDropOperation::ResetExtendedDragSource() {
  DCHECK(extended_drag_source_);
  extended_drag_source_->RemoveObserver(this);
  drag_drop_controller_->set_toplevel_window_drag_delegate(nullptr);
  extended_drag_source_ = nullptr;
}

void DragDropOperation::OnSurfaceDestroying(Surface* surface) {
  DCHECK(surface == origin_->get() || (icon_ && surface == icon_->get()));
  delete this;
}

void DragDropOperation::OnDataSourceDestroying(DataSource* source) {
  DCHECK_EQ(source, source_->get());
  source_.reset();
  LOG(ERROR) << "DataSource was destroyed by client";
  delete this;
}

void DragDropOperation::DragDataReadTimeout() {
  LOG(ERROR) << "DragDataReadTimeout";
}

}  // namespace exo