Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1819)

Side by Side Diff: ui/base/dragdrop/os_exchange_data_provider_win.cc

Issue 851853002: It is time. (Closed) Base URL: https://github.com/domokit/mojo.git@master
Patch Set: Trying to reup because the last upload failed. Created 5 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "ui/base/dragdrop/os_exchange_data_provider_win.h"
6
7 #include <algorithm>
8
9 #include "base/basictypes.h"
10 #include "base/files/file_path.h"
11 #include "base/i18n/file_util_icu.h"
12 #include "base/logging.h"
13 #include "base/pickle.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/win/scoped_hglobal.h"
16 #include "net/base/filename_util.h"
17 #include "ui/base/clipboard/clipboard.h"
18 #include "ui/base/clipboard/clipboard_util_win.h"
19 #include "ui/base/dragdrop/file_info.h"
20 #include "ui/base/l10n/l10n_util.h"
21 #include "ui/strings/grit/ui_strings.h"
22 #include "url/gurl.h"
23
24 namespace ui {
25
26 static const OSExchangeData::CustomFormat& GetRendererTaintCustomType() {
27 CR_DEFINE_STATIC_LOCAL(
28 ui::OSExchangeData::CustomFormat,
29 format,
30 (ui::Clipboard::GetFormatType("chromium/x-renderer-taint")));
31 return format;
32 }
33
34 // Creates a new STGMEDIUM object to hold the specified text. The caller
35 // owns the resulting object. The "Bytes" version does not NULL terminate, the
36 // string version does.
37 static STGMEDIUM* GetStorageForBytes(const void* data, size_t bytes);
38 template <typename T>
39 static STGMEDIUM* GetStorageForString(const std::basic_string<T>& data);
40 // Creates the contents of an Internet Shortcut file for the given URL.
41 static void GetInternetShortcutFileContents(const GURL& url, std::string* data);
42 // Creates a valid file name given a suggested title and URL.
43 static void CreateValidFileNameFromTitle(const GURL& url,
44 const base::string16& title,
45 base::string16* validated);
46 // Creates a new STGMEDIUM object to hold a file.
47 static STGMEDIUM* GetStorageForFileName(const base::FilePath& path);
48 static STGMEDIUM* GetIDListStorageForFileName(const base::FilePath& path);
49 // Creates a File Descriptor for the creation of a file to the given URL and
50 // returns a handle to it.
51 static STGMEDIUM* GetStorageForFileDescriptor(const base::FilePath& path);
52
53 ///////////////////////////////////////////////////////////////////////////////
54 // FormatEtcEnumerator
55
56 //
57 // This object implements an enumeration interface. The existence of an
58 // implementation of this interface is exposed to clients through
59 // OSExchangeData's EnumFormatEtc method. Our implementation is nobody's
60 // business but our own, so it lives in this file.
61 //
62 // This Windows API is truly a gem. It wants to be an enumerator but assumes
63 // some sort of sequential data (why not just use an array?). See comments
64 // throughout.
65 //
66 class FormatEtcEnumerator final : public IEnumFORMATETC {
67 public:
68 FormatEtcEnumerator(DataObjectImpl::StoredData::const_iterator begin,
69 DataObjectImpl::StoredData::const_iterator end);
70 ~FormatEtcEnumerator();
71
72 // IEnumFORMATETC implementation:
73 HRESULT __stdcall Next(
74 ULONG count, FORMATETC* elements_array, ULONG* elements_fetched);
75 HRESULT __stdcall Skip(ULONG skip_count);
76 HRESULT __stdcall Reset();
77 HRESULT __stdcall Clone(IEnumFORMATETC** clone);
78
79 // IUnknown implementation:
80 HRESULT __stdcall QueryInterface(const IID& iid, void** object);
81 ULONG __stdcall AddRef();
82 ULONG __stdcall Release();
83
84 private:
85 // This can only be called from |CloneFromOther|, since it initializes the
86 // contents_ from the other enumerator's contents.
87 FormatEtcEnumerator() : cursor_(0), ref_count_(0) {
88 }
89
90 // Clone a new FormatEtc from another instance of this enumeration.
91 static FormatEtcEnumerator* CloneFromOther(const FormatEtcEnumerator* other);
92
93 private:
94 // We are _forced_ to use a vector as our internal data model as Windows'
95 // retarded IEnumFORMATETC API assumes a deterministic ordering of elements
96 // through methods like Next and Skip. This exposes the underlying data
97 // structure to the user. Bah.
98 ScopedVector<FORMATETC> contents_;
99
100 // The cursor of the active enumeration - an index into |contents_|.
101 size_t cursor_;
102
103 LONG ref_count_;
104
105 DISALLOW_COPY_AND_ASSIGN(FormatEtcEnumerator);
106 };
107
108 // Safely makes a copy of all of the relevant bits of a FORMATETC object.
109 static void CloneFormatEtc(FORMATETC* source, FORMATETC* clone) {
110 *clone = *source;
111 if (source->ptd) {
112 source->ptd =
113 static_cast<DVTARGETDEVICE*>(CoTaskMemAlloc(sizeof(DVTARGETDEVICE)));
114 *(clone->ptd) = *(source->ptd);
115 }
116 }
117
118 FormatEtcEnumerator::FormatEtcEnumerator(
119 DataObjectImpl::StoredData::const_iterator start,
120 DataObjectImpl::StoredData::const_iterator end)
121 : ref_count_(0), cursor_(0) {
122 // Copy FORMATETC data from our source into ourselves.
123 while (start != end) {
124 FORMATETC* format_etc = new FORMATETC;
125 CloneFormatEtc(&(*start)->format_etc, format_etc);
126 contents_.push_back(format_etc);
127 ++start;
128 }
129 }
130
131 FormatEtcEnumerator::~FormatEtcEnumerator() {
132 }
133
134 STDMETHODIMP FormatEtcEnumerator::Next(
135 ULONG count, FORMATETC* elements_array, ULONG* elements_fetched) {
136 // MSDN says |elements_fetched| is allowed to be NULL if count is 1.
137 if (!elements_fetched)
138 DCHECK_EQ(count, 1ul);
139
140 // This method copies count elements into |elements_array|.
141 ULONG index = 0;
142 while (cursor_ < contents_.size() && index < count) {
143 CloneFormatEtc(contents_[cursor_], &elements_array[index]);
144 ++cursor_;
145 ++index;
146 }
147 // The out param is for how many we actually copied.
148 if (elements_fetched)
149 *elements_fetched = index;
150
151 // If the two don't agree, then we fail.
152 return index == count ? S_OK : S_FALSE;
153 }
154
155 STDMETHODIMP FormatEtcEnumerator::Skip(ULONG skip_count) {
156 cursor_ += skip_count;
157 // MSDN implies it's OK to leave the enumerator trashed.
158 // "Whatever you say, boss"
159 return cursor_ <= contents_.size() ? S_OK : S_FALSE;
160 }
161
162 STDMETHODIMP FormatEtcEnumerator::Reset() {
163 cursor_ = 0;
164 return S_OK;
165 }
166
167 STDMETHODIMP FormatEtcEnumerator::Clone(IEnumFORMATETC** clone) {
168 // Clone the current enumerator in its exact state, including cursor.
169 FormatEtcEnumerator* e = CloneFromOther(this);
170 e->AddRef();
171 *clone = e;
172 return S_OK;
173 }
174
175 STDMETHODIMP FormatEtcEnumerator::QueryInterface(const IID& iid,
176 void** object) {
177 *object = NULL;
178 if (IsEqualIID(iid, IID_IUnknown) || IsEqualIID(iid, IID_IEnumFORMATETC)) {
179 *object = this;
180 } else {
181 return E_NOINTERFACE;
182 }
183 AddRef();
184 return S_OK;
185 }
186
187 ULONG FormatEtcEnumerator::AddRef() {
188 return InterlockedIncrement(&ref_count_);
189 }
190
191 ULONG FormatEtcEnumerator::Release() {
192 if (InterlockedDecrement(&ref_count_) == 0) {
193 ULONG copied_refcnt = ref_count_;
194 delete this;
195 return copied_refcnt;
196 }
197 return ref_count_;
198 }
199
200 // static
201 FormatEtcEnumerator* FormatEtcEnumerator::CloneFromOther(
202 const FormatEtcEnumerator* other) {
203 FormatEtcEnumerator* e = new FormatEtcEnumerator;
204 // Copy FORMATETC data from our source into ourselves.
205 ScopedVector<FORMATETC>::const_iterator start = other->contents_.begin();
206 while (start != other->contents_.end()) {
207 FORMATETC* format_etc = new FORMATETC;
208 CloneFormatEtc(*start, format_etc);
209 e->contents_.push_back(format_etc);
210 ++start;
211 }
212 // Carry over
213 e->cursor_ = other->cursor_;
214 return e;
215 }
216
217 ///////////////////////////////////////////////////////////////////////////////
218 // OSExchangeDataProviderWin, public:
219
220 // static
221 bool OSExchangeDataProviderWin::HasPlainTextURL(IDataObject* source) {
222 base::string16 plain_text;
223 return (ClipboardUtil::GetPlainText(source, &plain_text) &&
224 !plain_text.empty() && GURL(plain_text).is_valid());
225 }
226
227 // static
228 bool OSExchangeDataProviderWin::GetPlainTextURL(IDataObject* source,
229 GURL* url) {
230 base::string16 plain_text;
231 if (ClipboardUtil::GetPlainText(source, &plain_text) &&
232 !plain_text.empty()) {
233 GURL gurl(plain_text);
234 if (gurl.is_valid()) {
235 *url = gurl;
236 return true;
237 }
238 }
239 return false;
240 }
241
242 // static
243 DataObjectImpl* OSExchangeDataProviderWin::GetDataObjectImpl(
244 const OSExchangeData& data) {
245 return static_cast<const OSExchangeDataProviderWin*>(&data.provider())->
246 data_.get();
247 }
248
249 // static
250 IDataObject* OSExchangeDataProviderWin::GetIDataObject(
251 const OSExchangeData& data) {
252 return static_cast<const OSExchangeDataProviderWin*>(&data.provider())->
253 data_object();
254 }
255
256 // static
257 IDataObjectAsyncCapability* OSExchangeDataProviderWin::GetIAsyncOperation(
258 const OSExchangeData& data) {
259 return static_cast<const OSExchangeDataProviderWin*>(&data.provider())->
260 async_operation();
261 }
262
263 OSExchangeDataProviderWin::OSExchangeDataProviderWin(IDataObject* source)
264 : data_(new DataObjectImpl()),
265 source_object_(source) {
266 }
267
268 OSExchangeDataProviderWin::OSExchangeDataProviderWin()
269 : data_(new DataObjectImpl()),
270 source_object_(data_.get()) {
271 }
272
273 OSExchangeDataProviderWin::~OSExchangeDataProviderWin() {
274 }
275
276 OSExchangeData::Provider* OSExchangeDataProviderWin::Clone() const {
277 return new OSExchangeDataProviderWin(data_object());
278 }
279
280 void OSExchangeDataProviderWin::MarkOriginatedFromRenderer() {
281 STGMEDIUM* storage = GetStorageForString(std::string());
282 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
283 GetRendererTaintCustomType().ToFormatEtc(), storage));
284 }
285
286 bool OSExchangeDataProviderWin::DidOriginateFromRenderer() const {
287 return HasCustomFormat(GetRendererTaintCustomType());
288 }
289
290 void OSExchangeDataProviderWin::SetString(const base::string16& data) {
291 STGMEDIUM* storage = GetStorageForString(data);
292 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
293 Clipboard::GetPlainTextWFormatType().ToFormatEtc(), storage));
294
295 // Also add the UTF8-encoded version.
296 storage = GetStorageForString(base::UTF16ToUTF8(data));
297 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
298 Clipboard::GetPlainTextFormatType().ToFormatEtc(), storage));
299 }
300
301 void OSExchangeDataProviderWin::SetURL(const GURL& url,
302 const base::string16& title) {
303 // NOTE WELL:
304 // Every time you change the order of the first two CLIPFORMATS that get
305 // added here, you need to update the EnumerationViaCOM test case in
306 // the _unittest.cc file to reflect the new arrangement otherwise that test
307 // will fail! It assumes an insertion order.
308
309 // Add text/x-moz-url for drags from Firefox
310 base::string16 x_moz_url_str = base::UTF8ToUTF16(url.spec());
311 x_moz_url_str += '\n';
312 x_moz_url_str += title;
313 STGMEDIUM* storage = GetStorageForString(x_moz_url_str);
314 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
315 Clipboard::GetMozUrlFormatType().ToFormatEtc(), storage));
316
317 // Add a .URL shortcut file for dragging to Explorer.
318 base::string16 valid_file_name;
319 CreateValidFileNameFromTitle(url, title, &valid_file_name);
320 std::string shortcut_url_file_contents;
321 GetInternetShortcutFileContents(url, &shortcut_url_file_contents);
322 SetFileContents(base::FilePath(valid_file_name), shortcut_url_file_contents);
323
324 // Add a UniformResourceLocator link for apps like IE and Word.
325 storage = GetStorageForString(base::UTF8ToUTF16(url.spec()));
326 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
327 Clipboard::GetUrlWFormatType().ToFormatEtc(), storage));
328 storage = GetStorageForString(url.spec());
329 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
330 Clipboard::GetUrlFormatType().ToFormatEtc(), storage));
331
332 // TODO(beng): add CF_HTML.
333 // http://code.google.com/p/chromium/issues/detail?id=6767
334
335 // Also add text representations (these should be last since they're the
336 // least preferable).
337 SetString(base::UTF8ToUTF16(url.spec()));
338 }
339
340 void OSExchangeDataProviderWin::SetFilename(const base::FilePath& path) {
341 STGMEDIUM* storage = GetStorageForFileName(path);
342 DataObjectImpl::StoredDataInfo* info = new DataObjectImpl::StoredDataInfo(
343 Clipboard::GetCFHDropFormatType().ToFormatEtc(), storage);
344 data_->contents_.push_back(info);
345
346 storage = GetIDListStorageForFileName(path);
347 if (!storage)
348 return;
349 info = new DataObjectImpl::StoredDataInfo(
350 Clipboard::GetIDListFormatType().ToFormatEtc(), storage);
351 data_->contents_.push_back(info);
352 }
353
354 void OSExchangeDataProviderWin::SetFilenames(
355 const std::vector<FileInfo>& filenames) {
356 for (size_t i = 0; i < filenames.size(); ++i) {
357 STGMEDIUM* storage = GetStorageForFileName(filenames[i].path);
358 DataObjectImpl::StoredDataInfo* info = new DataObjectImpl::StoredDataInfo(
359 Clipboard::GetCFHDropFormatType().ToFormatEtc(), storage);
360 data_->contents_.push_back(info);
361 }
362 }
363
364 void OSExchangeDataProviderWin::SetPickledData(
365 const OSExchangeData::CustomFormat& format,
366 const Pickle& data) {
367 STGMEDIUM* storage = GetStorageForBytes(data.data(), data.size());
368 data_->contents_.push_back(
369 new DataObjectImpl::StoredDataInfo(format.ToFormatEtc(), storage));
370 }
371
372 void OSExchangeDataProviderWin::SetFileContents(
373 const base::FilePath& filename,
374 const std::string& file_contents) {
375 // Add CFSTR_FILEDESCRIPTOR
376 STGMEDIUM* storage = GetStorageForFileDescriptor(filename);
377 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
378 Clipboard::GetFileDescriptorFormatType().ToFormatEtc(), storage));
379
380 // Add CFSTR_FILECONTENTS
381 storage = GetStorageForBytes(file_contents.data(), file_contents.length());
382 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
383 Clipboard::GetFileContentZeroFormatType().ToFormatEtc(), storage));
384 }
385
386 void OSExchangeDataProviderWin::SetHtml(const base::string16& html,
387 const GURL& base_url) {
388 // Add both MS CF_HTML and text/html format. CF_HTML should be in utf-8.
389 std::string utf8_html = base::UTF16ToUTF8(html);
390 std::string url = base_url.is_valid() ? base_url.spec() : std::string();
391
392 std::string cf_html = ClipboardUtil::HtmlToCFHtml(utf8_html, url);
393 STGMEDIUM* storage = GetStorageForBytes(cf_html.c_str(), cf_html.size());
394 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
395 Clipboard::GetHtmlFormatType().ToFormatEtc(), storage));
396
397 STGMEDIUM* storage_plain = GetStorageForBytes(utf8_html.c_str(),
398 utf8_html.size());
399 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
400 Clipboard::GetTextHtmlFormatType().ToFormatEtc(), storage_plain));
401 }
402
403 bool OSExchangeDataProviderWin::GetString(base::string16* data) const {
404 return ClipboardUtil::GetPlainText(source_object_.get(), data);
405 }
406
407 bool OSExchangeDataProviderWin::GetURLAndTitle(
408 OSExchangeData::FilenameToURLPolicy policy,
409 GURL* url,
410 base::string16* title) const {
411 base::string16 url_str;
412 bool success = ClipboardUtil::GetUrl(
413 source_object_.get(),
414 url,
415 title,
416 policy == OSExchangeData::CONVERT_FILENAMES ? true : false);
417 if (success) {
418 DCHECK(url->is_valid());
419 return true;
420 } else if (GetPlainTextURL(source_object_.get(), url)) {
421 if (url->is_valid())
422 *title = net::GetSuggestedFilename(*url, "", "", "", "", std::string());
423 else
424 title->clear();
425 return true;
426 }
427 return false;
428 }
429
430 bool OSExchangeDataProviderWin::GetFilename(base::FilePath* path) const {
431 std::vector<base::string16> filenames;
432 bool success = ClipboardUtil::GetFilenames(source_object_.get(), &filenames);
433 if (success)
434 *path = base::FilePath(filenames[0]);
435 return success;
436 }
437
438 bool OSExchangeDataProviderWin::GetFilenames(
439 std::vector<FileInfo>* filenames) const {
440 std::vector<base::string16> filenames_local;
441 bool success = ClipboardUtil::GetFilenames(source_object_.get(),
442 &filenames_local);
443 if (success) {
444 for (size_t i = 0; i < filenames_local.size(); ++i)
445 filenames->push_back(
446 FileInfo(base::FilePath(filenames_local[i]), base::FilePath()));
447 }
448 return success;
449 }
450
451 bool OSExchangeDataProviderWin::GetPickledData(
452 const OSExchangeData::CustomFormat& format,
453 Pickle* data) const {
454 DCHECK(data);
455 bool success = false;
456 STGMEDIUM medium;
457 FORMATETC format_etc = format.ToFormatEtc();
458 if (SUCCEEDED(source_object_->GetData(&format_etc, &medium))) {
459 if (medium.tymed & TYMED_HGLOBAL) {
460 base::win::ScopedHGlobal<char*> c_data(medium.hGlobal);
461 DCHECK_GT(c_data.Size(), 0u);
462 *data = Pickle(c_data.get(), static_cast<int>(c_data.Size()));
463 success = true;
464 }
465 ReleaseStgMedium(&medium);
466 }
467 return success;
468 }
469
470 bool OSExchangeDataProviderWin::GetFileContents(
471 base::FilePath* filename,
472 std::string* file_contents) const {
473 base::string16 filename_str;
474 if (!ClipboardUtil::GetFileContents(source_object_.get(), &filename_str,
475 file_contents)) {
476 return false;
477 }
478 *filename = base::FilePath(filename_str);
479 return true;
480 }
481
482 bool OSExchangeDataProviderWin::GetHtml(base::string16* html,
483 GURL* base_url) const {
484 std::string url;
485 bool success = ClipboardUtil::GetHtml(source_object_.get(), html, &url);
486 if (success)
487 *base_url = GURL(url);
488 return success;
489 }
490
491 bool OSExchangeDataProviderWin::HasString() const {
492 return ClipboardUtil::HasPlainText(source_object_.get());
493 }
494
495 bool OSExchangeDataProviderWin::HasURL(
496 OSExchangeData::FilenameToURLPolicy policy) const {
497 return (ClipboardUtil::HasUrl(
498 source_object_.get(),
499 policy == OSExchangeData::CONVERT_FILENAMES ? true : false) ||
500 HasPlainTextURL(source_object_.get()));
501 }
502
503 bool OSExchangeDataProviderWin::HasFile() const {
504 return ClipboardUtil::HasFilenames(source_object_.get());
505 }
506
507 bool OSExchangeDataProviderWin::HasFileContents() const {
508 return ClipboardUtil::HasFileContents(source_object_.get());
509 }
510
511 bool OSExchangeDataProviderWin::HasHtml() const {
512 return ClipboardUtil::HasHtml(source_object_.get());
513 }
514
515 bool OSExchangeDataProviderWin::HasCustomFormat(
516 const OSExchangeData::CustomFormat& format) const {
517 FORMATETC format_etc = format.ToFormatEtc();
518 return (source_object_->QueryGetData(&format_etc) == S_OK);
519 }
520
521 void OSExchangeDataProviderWin::SetDownloadFileInfo(
522 const OSExchangeData::DownloadFileInfo& download) {
523 // If the filename is not provided, set storage to NULL to indicate that
524 // the delay rendering will be used.
525 // TODO(dcheng): Is it actually possible for filename to be empty here? I
526 // think we always synthesize one in WebContentsDragWin.
527 STGMEDIUM* storage = NULL;
528 if (!download.filename.empty())
529 storage = GetStorageForFileName(download.filename);
530
531 // Add CF_HDROP.
532 DataObjectImpl::StoredDataInfo* info = new DataObjectImpl::StoredDataInfo(
533 Clipboard::GetCFHDropFormatType().ToFormatEtc(), storage);
534 info->downloader = download.downloader;
535 data_->contents_.push_back(info);
536 }
537
538 void OSExchangeDataProviderWin::SetDragImage(
539 const gfx::ImageSkia& image,
540 const gfx::Vector2d& cursor_offset) {
541 drag_image_ = image;
542 drag_image_offset_ = cursor_offset;
543 }
544
545 const gfx::ImageSkia& OSExchangeDataProviderWin::GetDragImage() const {
546 return drag_image_;
547 }
548
549 const gfx::Vector2d& OSExchangeDataProviderWin::GetDragImageOffset() const {
550 return drag_image_offset_;
551 }
552
553 ///////////////////////////////////////////////////////////////////////////////
554 // DataObjectImpl, IDataObject implementation:
555
556 // The following function, DuplicateMedium, is derived from WCDataObject.cpp
557 // in the WebKit source code. This is the license information for the file:
558 /*
559 * Copyright (C) 2007 Apple Inc. All rights reserved.
560 *
561 * Redistribution and use in source and binary forms, with or without
562 * modification, are permitted provided that the following conditions
563 * are met:
564 * 1. Redistributions of source code must retain the above copyright
565 * notice, this list of conditions and the following disclaimer.
566 * 2. Redistributions in binary form must reproduce the above copyright
567 * notice, this list of conditions and the following disclaimer in the
568 * documentation and/or other materials provided with the distribution.
569 *
570 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
571 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
572 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
573 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
574 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
575 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
576 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
577 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
578 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
579 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
580 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
581 */
582 static void DuplicateMedium(CLIPFORMAT source_clipformat,
583 STGMEDIUM* source,
584 STGMEDIUM* destination) {
585 switch (source->tymed) {
586 case TYMED_HGLOBAL:
587 destination->hGlobal =
588 static_cast<HGLOBAL>(OleDuplicateData(
589 source->hGlobal, source_clipformat, 0));
590 break;
591 case TYMED_MFPICT:
592 destination->hMetaFilePict =
593 static_cast<HMETAFILEPICT>(OleDuplicateData(
594 source->hMetaFilePict, source_clipformat, 0));
595 break;
596 case TYMED_GDI:
597 destination->hBitmap =
598 static_cast<HBITMAP>(OleDuplicateData(
599 source->hBitmap, source_clipformat, 0));
600 break;
601 case TYMED_ENHMF:
602 destination->hEnhMetaFile =
603 static_cast<HENHMETAFILE>(OleDuplicateData(
604 source->hEnhMetaFile, source_clipformat, 0));
605 break;
606 case TYMED_FILE:
607 destination->lpszFileName =
608 static_cast<LPOLESTR>(OleDuplicateData(
609 source->lpszFileName, source_clipformat, 0));
610 break;
611 case TYMED_ISTREAM:
612 destination->pstm = source->pstm;
613 destination->pstm->AddRef();
614 break;
615 case TYMED_ISTORAGE:
616 destination->pstg = source->pstg;
617 destination->pstg->AddRef();
618 break;
619 }
620
621 destination->tymed = source->tymed;
622 destination->pUnkForRelease = source->pUnkForRelease;
623 if (destination->pUnkForRelease)
624 destination->pUnkForRelease->AddRef();
625 }
626
627 DataObjectImpl::DataObjectImpl()
628 : is_aborting_(false),
629 in_drag_loop_(false),
630 in_async_mode_(false),
631 async_operation_started_(false),
632 observer_(NULL) {
633 }
634
635 DataObjectImpl::~DataObjectImpl() {
636 StopDownloads();
637 if (observer_)
638 observer_->OnDataObjectDisposed();
639 }
640
641 void DataObjectImpl::StopDownloads() {
642 for (StoredData::iterator iter = contents_.begin();
643 iter != contents_.end(); ++iter) {
644 if ((*iter)->downloader.get()) {
645 (*iter)->downloader->Stop();
646 (*iter)->downloader = 0;
647 }
648 }
649 }
650
651 void DataObjectImpl::RemoveData(const FORMATETC& format) {
652 if (format.ptd)
653 return; // Don't attempt to compare target devices.
654
655 for (StoredData::iterator i = contents_.begin(); i != contents_.end(); ++i) {
656 if (!(*i)->format_etc.ptd &&
657 format.cfFormat == (*i)->format_etc.cfFormat &&
658 format.dwAspect == (*i)->format_etc.dwAspect &&
659 format.lindex == (*i)->format_etc.lindex &&
660 format.tymed == (*i)->format_etc.tymed) {
661 contents_.erase(i);
662 return;
663 }
664 }
665 }
666
667 void DataObjectImpl::OnDownloadCompleted(const base::FilePath& file_path) {
668 DataObjectImpl::StoredData::iterator iter = contents_.begin();
669 for (; iter != contents_.end(); ++iter) {
670 if ((*iter)->format_etc.cfFormat == CF_HDROP) {
671 // Release the old storage.
672 if ((*iter)->owns_medium) {
673 ReleaseStgMedium((*iter)->medium);
674 delete (*iter)->medium;
675 }
676
677 // Update the storage.
678 (*iter)->owns_medium = true;
679 (*iter)->medium = GetStorageForFileName(file_path);
680
681 break;
682 }
683 }
684 DCHECK(iter != contents_.end());
685 }
686
687 void DataObjectImpl::OnDownloadAborted() {
688 }
689
690 HRESULT DataObjectImpl::GetData(FORMATETC* format_etc, STGMEDIUM* medium) {
691 if (is_aborting_)
692 return DV_E_FORMATETC;
693
694 StoredData::iterator iter = contents_.begin();
695 while (iter != contents_.end()) {
696 if ((*iter)->format_etc.cfFormat == format_etc->cfFormat &&
697 (*iter)->format_etc.lindex == format_etc->lindex &&
698 ((*iter)->format_etc.tymed & format_etc->tymed)) {
699 // If medium is NULL, delay-rendering will be used.
700 if ((*iter)->medium) {
701 DuplicateMedium((*iter)->format_etc.cfFormat, (*iter)->medium, medium);
702 } else {
703 // Fail all GetData() attempts for DownloadURL data if the drag and drop
704 // operation is still in progress.
705 if (in_drag_loop_)
706 return DV_E_FORMATETC;
707
708 bool wait_for_data = false;
709
710 // In async mode, we do not want to start waiting for the data before
711 // the async operation is started. This is because we want to postpone
712 // until Shell kicks off a background thread to do the work so that
713 // we do not block the UI thread.
714 if (!in_async_mode_ || async_operation_started_)
715 wait_for_data = true;
716
717 if (!wait_for_data)
718 return DV_E_FORMATETC;
719
720 // Notify the observer we start waiting for the data. This gives
721 // an observer a chance to end the drag and drop.
722 if (observer_)
723 observer_->OnWaitForData();
724
725 // Now we can start the download.
726 if ((*iter)->downloader.get()) {
727 (*iter)->downloader->Start(this);
728 if (!(*iter)->downloader->Wait()) {
729 is_aborting_ = true;
730 return DV_E_FORMATETC;
731 }
732 }
733
734 // The stored data should have been updated with the final version.
735 // So we just need to call this function again to retrieve it.
736 return GetData(format_etc, medium);
737 }
738 return S_OK;
739 }
740 ++iter;
741 }
742
743 return DV_E_FORMATETC;
744 }
745
746 HRESULT DataObjectImpl::GetDataHere(FORMATETC* format_etc,
747 STGMEDIUM* medium) {
748 return DATA_E_FORMATETC;
749 }
750
751 HRESULT DataObjectImpl::QueryGetData(FORMATETC* format_etc) {
752 StoredData::const_iterator iter = contents_.begin();
753 while (iter != contents_.end()) {
754 if ((*iter)->format_etc.cfFormat == format_etc->cfFormat)
755 return S_OK;
756 ++iter;
757 }
758 return DV_E_FORMATETC;
759 }
760
761 HRESULT DataObjectImpl::GetCanonicalFormatEtc(
762 FORMATETC* format_etc, FORMATETC* result) {
763 format_etc->ptd = NULL;
764 return E_NOTIMPL;
765 }
766
767 HRESULT DataObjectImpl::SetData(
768 FORMATETC* format_etc, STGMEDIUM* medium, BOOL should_release) {
769 RemoveData(*format_etc);
770
771 STGMEDIUM* local_medium = new STGMEDIUM;
772 if (should_release) {
773 *local_medium = *medium;
774 } else {
775 DuplicateMedium(format_etc->cfFormat, medium, local_medium);
776 }
777
778 DataObjectImpl::StoredDataInfo* info =
779 new DataObjectImpl::StoredDataInfo(*format_etc, local_medium);
780 info->medium->tymed = format_etc->tymed;
781 info->owns_medium = !!should_release;
782 // Make newly added data appear first.
783 // TODO(dcheng): Make various setters agree whether elements should be
784 // prioritized from front to back or back to front.
785 contents_.insert(contents_.begin(), info);
786
787 return S_OK;
788 }
789
790 HRESULT DataObjectImpl::EnumFormatEtc(
791 DWORD direction, IEnumFORMATETC** enumerator) {
792 if (direction == DATADIR_GET) {
793 FormatEtcEnumerator* e =
794 new FormatEtcEnumerator(contents_.begin(), contents_.end());
795 e->AddRef();
796 *enumerator = e;
797 return S_OK;
798 }
799 return E_NOTIMPL;
800 }
801
802 HRESULT DataObjectImpl::DAdvise(
803 FORMATETC* format_etc, DWORD advf, IAdviseSink* sink, DWORD* connection) {
804 return OLE_E_ADVISENOTSUPPORTED;
805 }
806
807 HRESULT DataObjectImpl::DUnadvise(DWORD connection) {
808 return OLE_E_ADVISENOTSUPPORTED;
809 }
810
811 HRESULT DataObjectImpl::EnumDAdvise(IEnumSTATDATA** enumerator) {
812 return OLE_E_ADVISENOTSUPPORTED;
813 }
814
815 ///////////////////////////////////////////////////////////////////////////////
816 // DataObjectImpl, IDataObjectAsyncCapability implementation:
817
818 HRESULT DataObjectImpl::EndOperation(
819 HRESULT result, IBindCtx* reserved, DWORD effects) {
820 async_operation_started_ = false;
821 return S_OK;
822 }
823
824 HRESULT DataObjectImpl::GetAsyncMode(BOOL* is_op_async) {
825 *is_op_async = in_async_mode_ ? TRUE : FALSE;
826 return S_OK;
827 }
828
829 HRESULT DataObjectImpl::InOperation(BOOL* in_async_op) {
830 *in_async_op = async_operation_started_ ? TRUE : FALSE;
831 return S_OK;
832 }
833
834 HRESULT DataObjectImpl::SetAsyncMode(BOOL do_op_async) {
835 in_async_mode_ = (do_op_async == TRUE);
836 return S_OK;
837 }
838
839 HRESULT DataObjectImpl::StartOperation(IBindCtx* reserved) {
840 async_operation_started_ = true;
841 return S_OK;
842 }
843
844 ///////////////////////////////////////////////////////////////////////////////
845 // DataObjectImpl, IUnknown implementation:
846
847 HRESULT DataObjectImpl::QueryInterface(const IID& iid, void** object) {
848 if (!object)
849 return E_POINTER;
850 if (IsEqualIID(iid, IID_IDataObject) || IsEqualIID(iid, IID_IUnknown)) {
851 *object = static_cast<IDataObject*>(this);
852 } else if (in_async_mode_ &&
853 IsEqualIID(iid, __uuidof(IDataObjectAsyncCapability))) {
854 *object = static_cast<IDataObjectAsyncCapability*>(this);
855 } else {
856 *object = NULL;
857 return E_NOINTERFACE;
858 }
859 AddRef();
860 return S_OK;
861 }
862
863 ULONG DataObjectImpl::AddRef() {
864 base::RefCountedThreadSafe<DownloadFileObserver>::AddRef();
865 return 0;
866 }
867
868 ULONG DataObjectImpl::Release() {
869 base::RefCountedThreadSafe<DownloadFileObserver>::Release();
870 return 0;
871 }
872
873 ///////////////////////////////////////////////////////////////////////////////
874 // DataObjectImpl, private:
875
876 static STGMEDIUM* GetStorageForBytes(const void* data, size_t bytes) {
877 HANDLE handle = GlobalAlloc(GPTR, static_cast<int>(bytes));
878 if (handle) {
879 base::win::ScopedHGlobal<uint8*> scoped(handle);
880 memcpy(scoped.get(), data, bytes);
881 }
882
883 STGMEDIUM* storage = new STGMEDIUM;
884 storage->hGlobal = handle;
885 storage->tymed = TYMED_HGLOBAL;
886 storage->pUnkForRelease = NULL;
887 return storage;
888 }
889
890 template <typename T>
891 static STGMEDIUM* GetStorageForString(const std::basic_string<T>& data) {
892 return GetStorageForBytes(
893 data.c_str(),
894 (data.size() + 1) * sizeof(typename std::basic_string<T>::value_type));
895 }
896
897 static void GetInternetShortcutFileContents(const GURL& url,
898 std::string* data) {
899 DCHECK(data);
900 static const std::string kInternetShortcutFileStart =
901 "[InternetShortcut]\r\nURL=";
902 static const std::string kInternetShortcutFileEnd =
903 "\r\n";
904 *data = kInternetShortcutFileStart + url.spec() + kInternetShortcutFileEnd;
905 }
906
907 static void CreateValidFileNameFromTitle(const GURL& url,
908 const base::string16& title,
909 base::string16* validated) {
910 if (title.empty()) {
911 if (url.is_valid()) {
912 *validated = net::GetSuggestedFilename(url, "", "", "", "",
913 std::string());
914 } else {
915 // Nothing else can be done, just use a default.
916 *validated =
917 l10n_util::GetStringUTF16(IDS_APP_UNTITLED_SHORTCUT_FILE_NAME);
918 }
919 } else {
920 *validated = title;
921 base::i18n::ReplaceIllegalCharactersInPath(validated, '-');
922 }
923 static const wchar_t extension[] = L".url";
924 static const size_t max_length = MAX_PATH - arraysize(extension);
925 if (validated->size() > max_length)
926 validated->erase(max_length);
927 *validated += extension;
928 }
929
930 static STGMEDIUM* GetStorageForFileName(const base::FilePath& path) {
931 const size_t kDropSize = sizeof(DROPFILES);
932 const size_t kTotalBytes =
933 kDropSize + (path.value().length() + 2) * sizeof(wchar_t);
934 HANDLE hdata = GlobalAlloc(GMEM_MOVEABLE, kTotalBytes);
935
936 base::win::ScopedHGlobal<DROPFILES*> locked_mem(hdata);
937 DROPFILES* drop_files = locked_mem.get();
938 drop_files->pFiles = sizeof(DROPFILES);
939 drop_files->fWide = TRUE;
940 wchar_t* data = reinterpret_cast<wchar_t*>(
941 reinterpret_cast<BYTE*>(drop_files) + kDropSize);
942 const size_t copy_size = (path.value().length() + 1) * sizeof(wchar_t);
943 memcpy(data, path.value().c_str(), copy_size);
944 data[path.value().length() + 1] = L'\0'; // Double NULL
945
946 STGMEDIUM* storage = new STGMEDIUM;
947 storage->tymed = TYMED_HGLOBAL;
948 storage->hGlobal = hdata;
949 storage->pUnkForRelease = NULL;
950 return storage;
951 }
952
953 static LPITEMIDLIST PIDLNext(LPITEMIDLIST pidl) {
954 return reinterpret_cast<LPITEMIDLIST>(
955 reinterpret_cast<BYTE*>(pidl) + pidl->mkid.cb);
956 }
957
958 static size_t PIDLSize(LPITEMIDLIST pidl) {
959 size_t s = 0;
960 while (pidl->mkid.cb > 0) {
961 s += pidl->mkid.cb;
962 pidl = PIDLNext(pidl);
963 }
964 // We add 2 because an LPITEMIDLIST is terminated by two NULL bytes.
965 return 2 + s;
966 }
967
968 static LPITEMIDLIST GetNthPIDL(CIDA* cida, int n) {
969 return reinterpret_cast<LPITEMIDLIST>(
970 reinterpret_cast<LPBYTE>(cida) + cida->aoffset[n]);
971 }
972
973 static LPITEMIDLIST GetPidlFromPath(const base::FilePath& path) {
974 LPITEMIDLIST pidl = NULL;
975 LPSHELLFOLDER desktop_folder = NULL;
976 LPWSTR path_str = const_cast<LPWSTR>(path.value().c_str());
977
978 if (FAILED(SHGetDesktopFolder(&desktop_folder)))
979 return NULL;
980
981 HRESULT hr = desktop_folder->ParseDisplayName(
982 NULL, NULL, path_str, NULL, &pidl, NULL);
983
984 return SUCCEEDED(hr) ? pidl : NULL;
985 }
986
987 static STGMEDIUM* GetIDListStorageForFileName(const base::FilePath& path) {
988 LPITEMIDLIST pidl = GetPidlFromPath(path);
989 if (!pidl)
990 return NULL;
991
992 // When using CFSTR_SHELLIDLIST the hGlobal field of the STGMEDIUM is a
993 // pointer to a CIDA*. A CIDA is a variable length struct that contains a PIDL
994 // count (a UINT), an array of offsets of the following PIDLs (a UINT[]) and
995 // then a series of PIDLs laid out contiguously in memory. A PIDL is
996 // represented by an ITEMIDLIST struct, which contains a single SHITEMID.
997 // Despite only containing a single SHITEMID, ITEMIDLISTs are so-named because
998 // SHITEMIDs contain their own size and so given one, the next can be found by
999 // looking at the section of memory after it. The end of a list is indicated
1000 // by two NULL bytes.
1001 // Here we require two PIDLs - the first PIDL is the parent folder and is
1002 // NULL here to indicate that the parent folder is the desktop, and the second
1003 // is the PIDL of |path|.
1004 const size_t kPIDLCountSize = sizeof(UINT);
1005 const size_t kPIDLOffsetsSize = 2 * sizeof(UINT);
1006 const size_t kFirstPIDLOffset = kPIDLCountSize + kPIDLOffsetsSize;
1007 const size_t kFirstPIDLSize = 2; // Empty PIDL - 2 NULL bytes.
1008 const size_t kSecondPIDLSize = PIDLSize(pidl);
1009 const size_t kCIDASize = kFirstPIDLOffset + kFirstPIDLSize + kSecondPIDLSize;
1010 HANDLE hdata = GlobalAlloc(GMEM_MOVEABLE, kCIDASize);
1011
1012 base::win::ScopedHGlobal<CIDA*> locked_mem(hdata);
1013 CIDA* cida = locked_mem.get();
1014 cida->cidl = 1; // We have one PIDL (not including the 0th root PIDL).
1015 cida->aoffset[0] = kFirstPIDLOffset;
1016 cida->aoffset[1] = kFirstPIDLOffset + kFirstPIDLSize;
1017 LPITEMIDLIST idl = GetNthPIDL(cida, 0);
1018 idl->mkid.cb = 0;
1019 idl->mkid.abID[0] = 0;
1020 idl = GetNthPIDL(cida, 1);
1021 memcpy(idl, pidl, kSecondPIDLSize);
1022
1023 STGMEDIUM* storage = new STGMEDIUM;
1024 storage->tymed = TYMED_HGLOBAL;
1025 storage->hGlobal = hdata;
1026 storage->pUnkForRelease = NULL;
1027 return storage;
1028 }
1029
1030 static STGMEDIUM* GetStorageForFileDescriptor(
1031 const base::FilePath& path) {
1032 base::string16 file_name = path.value();
1033 DCHECK(!file_name.empty());
1034 HANDLE hdata = GlobalAlloc(GPTR, sizeof(FILEGROUPDESCRIPTOR));
1035 base::win::ScopedHGlobal<FILEGROUPDESCRIPTOR*> locked_mem(hdata);
1036
1037 FILEGROUPDESCRIPTOR* descriptor = locked_mem.get();
1038 descriptor->cItems = 1;
1039 descriptor->fgd[0].dwFlags = FD_LINKUI;
1040 wcsncpy_s(descriptor->fgd[0].cFileName, MAX_PATH, file_name.c_str(),
1041 std::min(file_name.size(), static_cast<size_t>(MAX_PATH - 1u)));
1042
1043 STGMEDIUM* storage = new STGMEDIUM;
1044 storage->tymed = TYMED_HGLOBAL;
1045 storage->hGlobal = hdata;
1046 storage->pUnkForRelease = NULL;
1047 return storage;
1048 }
1049
1050 ///////////////////////////////////////////////////////////////////////////////
1051 // OSExchangeData, public:
1052
1053 // static
1054 OSExchangeData::Provider* OSExchangeData::CreateProvider() {
1055 return new OSExchangeDataProviderWin();
1056 }
1057
1058 } // namespace ui
OLDNEW
« no previous file with comments | « ui/base/dragdrop/os_exchange_data_provider_win.h ('k') | ui/base/dragdrop/os_exchange_data_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698