Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / ui / base / dragdrop / os_exchange_data_provider_win.cc
blob0389429b0ae5cdd45eadd90728196422e8384499
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.
5 #include "ui/base/dragdrop/os_exchange_data_provider_win.h"
7 #include <algorithm>
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"
24 namespace ui {
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;
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);
53 ///////////////////////////////////////////////////////////////////////////////
54 // FormatEtcEnumerator
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.
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.
66 class FormatEtcEnumerator final : public IEnumFORMATETC {
67 public:
68 FormatEtcEnumerator(DataObjectImpl::StoredData::const_iterator begin,
69 DataObjectImpl::StoredData::const_iterator end);
70 ~FormatEtcEnumerator();
72 // IEnumFORMATETC implementation:
73 HRESULT __stdcall Next(ULONG count,
74 FORMATETC* elements_array,
75 ULONG* elements_fetched) override;
76 HRESULT __stdcall Skip(ULONG skip_count) override;
77 HRESULT __stdcall Reset() override;
78 HRESULT __stdcall Clone(IEnumFORMATETC** clone) override;
80 // IUnknown implementation:
81 HRESULT __stdcall QueryInterface(const IID& iid, void** object) override;
82 ULONG __stdcall AddRef() override;
83 ULONG __stdcall Release() override;
85 private:
86 // This can only be called from |CloneFromOther|, since it initializes the
87 // contents_ from the other enumerator's contents.
88 FormatEtcEnumerator() : cursor_(0), ref_count_(0) {
91 // Clone a new FormatEtc from another instance of this enumeration.
92 static FormatEtcEnumerator* CloneFromOther(const FormatEtcEnumerator* other);
94 private:
95 // We are _forced_ to use a vector as our internal data model as Windows'
96 // retarded IEnumFORMATETC API assumes a deterministic ordering of elements
97 // through methods like Next and Skip. This exposes the underlying data
98 // structure to the user. Bah.
99 ScopedVector<FORMATETC> contents_;
101 // The cursor of the active enumeration - an index into |contents_|.
102 size_t cursor_;
104 LONG ref_count_;
106 DISALLOW_COPY_AND_ASSIGN(FormatEtcEnumerator);
109 // Safely makes a copy of all of the relevant bits of a FORMATETC object.
110 static void CloneFormatEtc(FORMATETC* source, FORMATETC* clone) {
111 *clone = *source;
112 if (source->ptd) {
113 source->ptd =
114 static_cast<DVTARGETDEVICE*>(CoTaskMemAlloc(sizeof(DVTARGETDEVICE)));
115 *(clone->ptd) = *(source->ptd);
119 FormatEtcEnumerator::FormatEtcEnumerator(
120 DataObjectImpl::StoredData::const_iterator start,
121 DataObjectImpl::StoredData::const_iterator end)
122 : cursor_(0), ref_count_(0) {
123 // Copy FORMATETC data from our source into ourselves.
124 while (start != end) {
125 FORMATETC* format_etc = new FORMATETC;
126 CloneFormatEtc(&(*start)->format_etc, format_etc);
127 contents_.push_back(format_etc);
128 ++start;
132 FormatEtcEnumerator::~FormatEtcEnumerator() {
135 STDMETHODIMP FormatEtcEnumerator::Next(
136 ULONG count, FORMATETC* elements_array, ULONG* elements_fetched) {
137 // MSDN says |elements_fetched| is allowed to be NULL if count is 1.
138 if (!elements_fetched)
139 DCHECK_EQ(count, 1ul);
141 // This method copies count elements into |elements_array|.
142 ULONG index = 0;
143 while (cursor_ < contents_.size() && index < count) {
144 CloneFormatEtc(contents_[cursor_], &elements_array[index]);
145 ++cursor_;
146 ++index;
148 // The out param is for how many we actually copied.
149 if (elements_fetched)
150 *elements_fetched = index;
152 // If the two don't agree, then we fail.
153 return index == count ? S_OK : S_FALSE;
156 STDMETHODIMP FormatEtcEnumerator::Skip(ULONG skip_count) {
157 cursor_ += skip_count;
158 // MSDN implies it's OK to leave the enumerator trashed.
159 // "Whatever you say, boss"
160 return cursor_ <= contents_.size() ? S_OK : S_FALSE;
163 STDMETHODIMP FormatEtcEnumerator::Reset() {
164 cursor_ = 0;
165 return S_OK;
168 STDMETHODIMP FormatEtcEnumerator::Clone(IEnumFORMATETC** clone) {
169 // Clone the current enumerator in its exact state, including cursor.
170 FormatEtcEnumerator* e = CloneFromOther(this);
171 e->AddRef();
172 *clone = e;
173 return S_OK;
176 STDMETHODIMP FormatEtcEnumerator::QueryInterface(const IID& iid,
177 void** object) {
178 *object = NULL;
179 if (IsEqualIID(iid, IID_IUnknown) || IsEqualIID(iid, IID_IEnumFORMATETC)) {
180 *object = this;
181 } else {
182 return E_NOINTERFACE;
184 AddRef();
185 return S_OK;
188 ULONG FormatEtcEnumerator::AddRef() {
189 return InterlockedIncrement(&ref_count_);
192 ULONG FormatEtcEnumerator::Release() {
193 if (InterlockedDecrement(&ref_count_) == 0) {
194 ULONG copied_refcnt = ref_count_;
195 delete this;
196 return copied_refcnt;
198 return ref_count_;
201 // static
202 FormatEtcEnumerator* FormatEtcEnumerator::CloneFromOther(
203 const FormatEtcEnumerator* other) {
204 FormatEtcEnumerator* e = new FormatEtcEnumerator;
205 // Copy FORMATETC data from our source into ourselves.
206 ScopedVector<FORMATETC>::const_iterator start = other->contents_.begin();
207 while (start != other->contents_.end()) {
208 FORMATETC* format_etc = new FORMATETC;
209 CloneFormatEtc(*start, format_etc);
210 e->contents_.push_back(format_etc);
211 ++start;
213 // Carry over
214 e->cursor_ = other->cursor_;
215 return e;
218 ///////////////////////////////////////////////////////////////////////////////
219 // OSExchangeDataProviderWin, public:
221 // static
222 bool OSExchangeDataProviderWin::HasPlainTextURL(IDataObject* source) {
223 base::string16 plain_text;
224 return (ClipboardUtil::GetPlainText(source, &plain_text) &&
225 !plain_text.empty() && GURL(plain_text).is_valid());
228 // static
229 bool OSExchangeDataProviderWin::GetPlainTextURL(IDataObject* source,
230 GURL* url) {
231 base::string16 plain_text;
232 if (ClipboardUtil::GetPlainText(source, &plain_text) &&
233 !plain_text.empty()) {
234 GURL gurl(plain_text);
235 if (gurl.is_valid()) {
236 *url = gurl;
237 return true;
240 return false;
243 // static
244 DataObjectImpl* OSExchangeDataProviderWin::GetDataObjectImpl(
245 const OSExchangeData& data) {
246 return static_cast<const OSExchangeDataProviderWin*>(&data.provider())->
247 data_.get();
250 // static
251 IDataObject* OSExchangeDataProviderWin::GetIDataObject(
252 const OSExchangeData& data) {
253 return static_cast<const OSExchangeDataProviderWin*>(&data.provider())->
254 data_object();
257 // static
258 IDataObjectAsyncCapability* OSExchangeDataProviderWin::GetIAsyncOperation(
259 const OSExchangeData& data) {
260 return static_cast<const OSExchangeDataProviderWin*>(&data.provider())->
261 async_operation();
264 OSExchangeDataProviderWin::OSExchangeDataProviderWin(IDataObject* source)
265 : data_(new DataObjectImpl()),
266 source_object_(source) {
269 OSExchangeDataProviderWin::OSExchangeDataProviderWin()
270 : data_(new DataObjectImpl()),
271 source_object_(data_.get()) {
274 OSExchangeDataProviderWin::~OSExchangeDataProviderWin() {
277 OSExchangeData::Provider* OSExchangeDataProviderWin::Clone() const {
278 return new OSExchangeDataProviderWin(data_object());
281 void OSExchangeDataProviderWin::MarkOriginatedFromRenderer() {
282 STGMEDIUM* storage = GetStorageForString(std::string());
283 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
284 GetRendererTaintCustomType().ToFormatEtc(), storage));
287 bool OSExchangeDataProviderWin::DidOriginateFromRenderer() const {
288 return HasCustomFormat(GetRendererTaintCustomType());
291 void OSExchangeDataProviderWin::SetString(const base::string16& data) {
292 STGMEDIUM* storage = GetStorageForString(data);
293 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
294 Clipboard::GetPlainTextWFormatType().ToFormatEtc(), storage));
296 // Also add the UTF8-encoded version.
297 storage = GetStorageForString(base::UTF16ToUTF8(data));
298 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
299 Clipboard::GetPlainTextFormatType().ToFormatEtc(), storage));
302 void OSExchangeDataProviderWin::SetURL(const GURL& url,
303 const base::string16& title) {
304 // NOTE WELL:
305 // Every time you change the order of the first two CLIPFORMATS that get
306 // added here, you need to update the EnumerationViaCOM test case in
307 // the _unittest.cc file to reflect the new arrangement otherwise that test
308 // will fail! It assumes an insertion order.
310 // Add text/x-moz-url for drags from Firefox
311 base::string16 x_moz_url_str = base::UTF8ToUTF16(url.spec());
312 x_moz_url_str += '\n';
313 x_moz_url_str += title;
314 STGMEDIUM* storage = GetStorageForString(x_moz_url_str);
315 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
316 Clipboard::GetMozUrlFormatType().ToFormatEtc(), storage));
318 // Add a .URL shortcut file for dragging to Explorer.
319 base::string16 valid_file_name;
320 CreateValidFileNameFromTitle(url, title, &valid_file_name);
321 std::string shortcut_url_file_contents;
322 GetInternetShortcutFileContents(url, &shortcut_url_file_contents);
323 SetFileContents(base::FilePath(valid_file_name), shortcut_url_file_contents);
325 // Add a UniformResourceLocator link for apps like IE and Word.
326 storage = GetStorageForString(base::UTF8ToUTF16(url.spec()));
327 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
328 Clipboard::GetUrlWFormatType().ToFormatEtc(), storage));
329 storage = GetStorageForString(url.spec());
330 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
331 Clipboard::GetUrlFormatType().ToFormatEtc(), storage));
333 // TODO(beng): add CF_HTML.
334 // http://code.google.com/p/chromium/issues/detail?id=6767
336 // Also add text representations (these should be last since they're the
337 // least preferable).
338 SetString(base::UTF8ToUTF16(url.spec()));
341 void OSExchangeDataProviderWin::SetFilename(const base::FilePath& path) {
342 STGMEDIUM* storage = GetStorageForFileName(path);
343 DataObjectImpl::StoredDataInfo* info = new DataObjectImpl::StoredDataInfo(
344 Clipboard::GetCFHDropFormatType().ToFormatEtc(), storage);
345 data_->contents_.push_back(info);
347 storage = GetIDListStorageForFileName(path);
348 if (!storage)
349 return;
350 info = new DataObjectImpl::StoredDataInfo(
351 Clipboard::GetIDListFormatType().ToFormatEtc(), storage);
352 data_->contents_.push_back(info);
355 void OSExchangeDataProviderWin::SetFilenames(
356 const std::vector<FileInfo>& filenames) {
357 for (size_t i = 0; i < filenames.size(); ++i) {
358 STGMEDIUM* storage = GetStorageForFileName(filenames[i].path);
359 DataObjectImpl::StoredDataInfo* info = new DataObjectImpl::StoredDataInfo(
360 Clipboard::GetCFHDropFormatType().ToFormatEtc(), storage);
361 data_->contents_.push_back(info);
365 void OSExchangeDataProviderWin::SetPickledData(
366 const OSExchangeData::CustomFormat& format,
367 const base::Pickle& data) {
368 STGMEDIUM* storage = GetStorageForBytes(data.data(), data.size());
369 data_->contents_.push_back(
370 new DataObjectImpl::StoredDataInfo(format.ToFormatEtc(), storage));
373 void OSExchangeDataProviderWin::SetFileContents(
374 const base::FilePath& filename,
375 const std::string& file_contents) {
376 // Add CFSTR_FILEDESCRIPTOR
377 STGMEDIUM* storage = GetStorageForFileDescriptor(filename);
378 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
379 Clipboard::GetFileDescriptorFormatType().ToFormatEtc(), storage));
381 // Add CFSTR_FILECONTENTS
382 storage = GetStorageForBytes(file_contents.data(), file_contents.length());
383 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
384 Clipboard::GetFileContentZeroFormatType().ToFormatEtc(), storage));
387 void OSExchangeDataProviderWin::SetHtml(const base::string16& html,
388 const GURL& base_url) {
389 // Add both MS CF_HTML and text/html format. CF_HTML should be in utf-8.
390 std::string utf8_html = base::UTF16ToUTF8(html);
391 std::string url = base_url.is_valid() ? base_url.spec() : std::string();
393 std::string cf_html = ClipboardUtil::HtmlToCFHtml(utf8_html, url);
394 STGMEDIUM* storage = GetStorageForBytes(cf_html.c_str(), cf_html.size());
395 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
396 Clipboard::GetHtmlFormatType().ToFormatEtc(), storage));
398 STGMEDIUM* storage_plain = GetStorageForBytes(utf8_html.c_str(),
399 utf8_html.size());
400 data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
401 Clipboard::GetTextHtmlFormatType().ToFormatEtc(), storage_plain));
404 bool OSExchangeDataProviderWin::GetString(base::string16* data) const {
405 return ClipboardUtil::GetPlainText(source_object_.get(), data);
408 bool OSExchangeDataProviderWin::GetURLAndTitle(
409 OSExchangeData::FilenameToURLPolicy policy,
410 GURL* url,
411 base::string16* title) const {
412 base::string16 url_str;
413 bool success = ClipboardUtil::GetUrl(
414 source_object_.get(), url, title,
415 policy == OSExchangeData::CONVERT_FILENAMES ? true : false);
416 if (success) {
417 DCHECK(url->is_valid());
418 return true;
419 } else if (GetPlainTextURL(source_object_.get(), url)) {
420 if (url->is_valid())
421 *title = net::GetSuggestedFilename(*url, "", "", "", "", std::string());
422 else
423 title->clear();
424 return true;
426 return false;
429 bool OSExchangeDataProviderWin::GetFilename(base::FilePath* path) const {
430 std::vector<base::string16> filenames;
431 bool success = ClipboardUtil::GetFilenames(source_object_.get(), &filenames);
432 if (success)
433 *path = base::FilePath(filenames[0]);
434 return success;
437 bool OSExchangeDataProviderWin::GetFilenames(
438 std::vector<FileInfo>* filenames) const {
439 std::vector<base::string16> filenames_local;
440 bool success =
441 ClipboardUtil::GetFilenames(source_object_.get(), &filenames_local);
442 if (success) {
443 for (size_t i = 0; i < filenames_local.size(); ++i)
444 filenames->push_back(
445 FileInfo(base::FilePath(filenames_local[i]), base::FilePath()));
447 return success;
450 bool OSExchangeDataProviderWin::GetPickledData(
451 const OSExchangeData::CustomFormat& format,
452 base::Pickle* data) const {
453 DCHECK(data);
454 bool success = false;
455 STGMEDIUM medium;
456 FORMATETC format_etc = format.ToFormatEtc();
457 if (SUCCEEDED(source_object_->GetData(&format_etc, &medium))) {
458 if (medium.tymed & TYMED_HGLOBAL) {
459 base::win::ScopedHGlobal<char*> c_data(medium.hGlobal);
460 DCHECK_GT(c_data.Size(), 0u);
461 *data = base::Pickle(c_data.get(), static_cast<int>(c_data.Size()));
462 success = true;
464 ReleaseStgMedium(&medium);
466 return success;
469 bool OSExchangeDataProviderWin::GetFileContents(
470 base::FilePath* filename,
471 std::string* file_contents) const {
472 base::string16 filename_str;
473 if (!ClipboardUtil::GetFileContents(source_object_.get(), &filename_str,
474 file_contents)) {
475 return false;
477 *filename = base::FilePath(filename_str);
478 return true;
481 bool OSExchangeDataProviderWin::GetHtml(base::string16* html,
482 GURL* base_url) const {
483 std::string url;
484 bool success = ClipboardUtil::GetHtml(source_object_.get(), html, &url);
485 if (success)
486 *base_url = GURL(url);
487 return success;
490 bool OSExchangeDataProviderWin::HasString() const {
491 return ClipboardUtil::HasPlainText(source_object_.get());
494 bool OSExchangeDataProviderWin::HasURL(
495 OSExchangeData::FilenameToURLPolicy policy) const {
496 return (ClipboardUtil::HasUrl(
497 source_object_.get(),
498 policy == OSExchangeData::CONVERT_FILENAMES ? true : false) ||
499 HasPlainTextURL(source_object_.get()));
502 bool OSExchangeDataProviderWin::HasFile() const {
503 return ClipboardUtil::HasFilenames(source_object_.get());
506 bool OSExchangeDataProviderWin::HasFileContents() const {
507 return ClipboardUtil::HasFileContents(source_object_.get());
510 bool OSExchangeDataProviderWin::HasHtml() const {
511 return ClipboardUtil::HasHtml(source_object_.get());
514 bool OSExchangeDataProviderWin::HasCustomFormat(
515 const OSExchangeData::CustomFormat& format) const {
516 FORMATETC format_etc = format.ToFormatEtc();
517 return (source_object_->QueryGetData(&format_etc) == S_OK);
520 void OSExchangeDataProviderWin::SetDownloadFileInfo(
521 const OSExchangeData::DownloadFileInfo& download) {
522 // If the filename is not provided, set storage to NULL to indicate that
523 // the delay rendering will be used.
524 // TODO(dcheng): Is it actually possible for filename to be empty here? I
525 // think we always synthesize one in WebContentsDragWin.
526 STGMEDIUM* storage = NULL;
527 if (!download.filename.empty())
528 storage = GetStorageForFileName(download.filename);
530 // Add CF_HDROP.
531 DataObjectImpl::StoredDataInfo* info = new DataObjectImpl::StoredDataInfo(
532 Clipboard::GetCFHDropFormatType().ToFormatEtc(), storage);
533 info->downloader = download.downloader;
534 data_->contents_.push_back(info);
536 // Adding a download file always enables async mode.
537 data_->SetAsyncMode(VARIANT_TRUE);
540 void OSExchangeDataProviderWin::SetDragImage(
541 const gfx::ImageSkia& image,
542 const gfx::Vector2d& cursor_offset) {
543 drag_image_ = image;
544 drag_image_offset_ = cursor_offset;
547 const gfx::ImageSkia& OSExchangeDataProviderWin::GetDragImage() const {
548 return drag_image_;
551 const gfx::Vector2d& OSExchangeDataProviderWin::GetDragImageOffset() const {
552 return drag_image_offset_;
555 ///////////////////////////////////////////////////////////////////////////////
556 // DataObjectImpl, IDataObject implementation:
558 // The following function, DuplicateMedium, is derived from WCDataObject.cpp
559 // in the WebKit source code. This is the license information for the file:
561 * Copyright (C) 2007 Apple Inc. All rights reserved.
563 * Redistribution and use in source and binary forms, with or without
564 * modification, are permitted provided that the following conditions
565 * are met:
566 * 1. Redistributions of source code must retain the above copyright
567 * notice, this list of conditions and the following disclaimer.
568 * 2. Redistributions in binary form must reproduce the above copyright
569 * notice, this list of conditions and the following disclaimer in the
570 * documentation and/or other materials provided with the distribution.
572 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
573 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
574 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
575 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
576 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
577 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
578 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
579 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
580 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
581 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
582 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
584 static void DuplicateMedium(CLIPFORMAT source_clipformat,
585 STGMEDIUM* source,
586 STGMEDIUM* destination) {
587 switch (source->tymed) {
588 case TYMED_HGLOBAL:
589 destination->hGlobal =
590 static_cast<HGLOBAL>(OleDuplicateData(
591 source->hGlobal, source_clipformat, 0));
592 break;
593 case TYMED_MFPICT:
594 destination->hMetaFilePict =
595 static_cast<HMETAFILEPICT>(OleDuplicateData(
596 source->hMetaFilePict, source_clipformat, 0));
597 break;
598 case TYMED_GDI:
599 destination->hBitmap =
600 static_cast<HBITMAP>(OleDuplicateData(
601 source->hBitmap, source_clipformat, 0));
602 break;
603 case TYMED_ENHMF:
604 destination->hEnhMetaFile =
605 static_cast<HENHMETAFILE>(OleDuplicateData(
606 source->hEnhMetaFile, source_clipformat, 0));
607 break;
608 case TYMED_FILE:
609 destination->lpszFileName =
610 static_cast<LPOLESTR>(OleDuplicateData(
611 source->lpszFileName, source_clipformat, 0));
612 break;
613 case TYMED_ISTREAM:
614 destination->pstm = source->pstm;
615 destination->pstm->AddRef();
616 break;
617 case TYMED_ISTORAGE:
618 destination->pstg = source->pstg;
619 destination->pstg->AddRef();
620 break;
623 destination->tymed = source->tymed;
624 destination->pUnkForRelease = source->pUnkForRelease;
625 if (destination->pUnkForRelease)
626 destination->pUnkForRelease->AddRef();
629 DataObjectImpl::StoredDataInfo::StoredDataInfo(const FORMATETC& format_etc,
630 STGMEDIUM* medium)
631 : format_etc(format_etc), medium(medium), owns_medium(true) {
634 DataObjectImpl::StoredDataInfo::~StoredDataInfo() {
635 if (owns_medium) {
636 ReleaseStgMedium(medium);
637 delete medium;
639 if (downloader.get())
640 downloader->Stop();
643 DataObjectImpl::DataObjectImpl()
644 : is_aborting_(false),
645 in_drag_loop_(false),
646 in_async_mode_(false),
647 async_operation_started_(false),
648 observer_(NULL) {
651 DataObjectImpl::~DataObjectImpl() {
652 StopDownloads();
653 if (observer_)
654 observer_->OnDataObjectDisposed();
657 void DataObjectImpl::StopDownloads() {
658 for (StoredData::iterator iter = contents_.begin();
659 iter != contents_.end(); ++iter) {
660 if ((*iter)->downloader.get()) {
661 (*iter)->downloader->Stop();
662 (*iter)->downloader = 0;
667 void DataObjectImpl::RemoveData(const FORMATETC& format) {
668 if (format.ptd)
669 return; // Don't attempt to compare target devices.
671 for (StoredData::iterator i = contents_.begin(); i != contents_.end(); ++i) {
672 if (!(*i)->format_etc.ptd &&
673 format.cfFormat == (*i)->format_etc.cfFormat &&
674 format.dwAspect == (*i)->format_etc.dwAspect &&
675 format.lindex == (*i)->format_etc.lindex &&
676 format.tymed == (*i)->format_etc.tymed) {
677 contents_.erase(i);
678 return;
683 void DataObjectImpl::OnDownloadCompleted(const base::FilePath& file_path) {
684 DataObjectImpl::StoredData::iterator iter = contents_.begin();
685 for (; iter != contents_.end(); ++iter) {
686 if ((*iter)->format_etc.cfFormat == CF_HDROP) {
687 // Release the old storage.
688 if ((*iter)->owns_medium) {
689 ReleaseStgMedium((*iter)->medium);
690 delete (*iter)->medium;
693 // Update the storage.
694 (*iter)->owns_medium = true;
695 (*iter)->medium = GetStorageForFileName(file_path);
697 break;
700 DCHECK(iter != contents_.end());
703 void DataObjectImpl::OnDownloadAborted() {
706 HRESULT DataObjectImpl::GetData(FORMATETC* format_etc, STGMEDIUM* medium) {
707 if (is_aborting_)
708 return DV_E_FORMATETC;
710 StoredData::iterator iter = contents_.begin();
711 while (iter != contents_.end()) {
712 if ((*iter)->format_etc.cfFormat == format_etc->cfFormat &&
713 (*iter)->format_etc.lindex == format_etc->lindex &&
714 ((*iter)->format_etc.tymed & format_etc->tymed)) {
715 // If medium is NULL, delay-rendering will be used.
716 if ((*iter)->medium) {
717 DuplicateMedium((*iter)->format_etc.cfFormat, (*iter)->medium, medium);
718 } else {
719 // Fail all GetData() attempts for DownloadURL data if the drag and drop
720 // operation is still in progress.
721 if (in_drag_loop_)
722 return DV_E_FORMATETC;
724 bool wait_for_data = false;
726 // In async mode, we do not want to start waiting for the data before
727 // the async operation is started. This is because we want to postpone
728 // until Shell kicks off a background thread to do the work so that
729 // we do not block the UI thread.
730 if (!in_async_mode_ || async_operation_started_)
731 wait_for_data = true;
733 if (!wait_for_data)
734 return DV_E_FORMATETC;
736 // Notify the observer we start waiting for the data. This gives
737 // an observer a chance to end the drag and drop.
738 if (observer_)
739 observer_->OnWaitForData();
741 // Now we can start the download.
742 if ((*iter)->downloader.get()) {
743 (*iter)->downloader->Start(this);
744 if (!(*iter)->downloader->Wait()) {
745 is_aborting_ = true;
746 return DV_E_FORMATETC;
750 // The stored data should have been updated with the final version.
751 // So we just need to call this function again to retrieve it.
752 return GetData(format_etc, medium);
754 return S_OK;
756 ++iter;
759 return DV_E_FORMATETC;
762 HRESULT DataObjectImpl::GetDataHere(FORMATETC* format_etc,
763 STGMEDIUM* medium) {
764 return DATA_E_FORMATETC;
767 HRESULT DataObjectImpl::QueryGetData(FORMATETC* format_etc) {
768 StoredData::const_iterator iter = contents_.begin();
769 while (iter != contents_.end()) {
770 if ((*iter)->format_etc.cfFormat == format_etc->cfFormat)
771 return S_OK;
772 ++iter;
774 return DV_E_FORMATETC;
777 HRESULT DataObjectImpl::GetCanonicalFormatEtc(
778 FORMATETC* format_etc, FORMATETC* result) {
779 format_etc->ptd = NULL;
780 return E_NOTIMPL;
783 HRESULT DataObjectImpl::SetData(
784 FORMATETC* format_etc, STGMEDIUM* medium, BOOL should_release) {
785 RemoveData(*format_etc);
787 STGMEDIUM* local_medium = new STGMEDIUM;
788 if (should_release) {
789 *local_medium = *medium;
790 } else {
791 DuplicateMedium(format_etc->cfFormat, medium, local_medium);
794 DataObjectImpl::StoredDataInfo* info =
795 new DataObjectImpl::StoredDataInfo(*format_etc, local_medium);
796 info->medium->tymed = format_etc->tymed;
797 info->owns_medium = !!should_release;
798 // Make newly added data appear first.
799 // TODO(dcheng): Make various setters agree whether elements should be
800 // prioritized from front to back or back to front.
801 contents_.insert(contents_.begin(), info);
803 return S_OK;
806 HRESULT DataObjectImpl::EnumFormatEtc(
807 DWORD direction, IEnumFORMATETC** enumerator) {
808 if (direction == DATADIR_GET) {
809 FormatEtcEnumerator* e =
810 new FormatEtcEnumerator(contents_.begin(), contents_.end());
811 e->AddRef();
812 *enumerator = e;
813 return S_OK;
815 return E_NOTIMPL;
818 HRESULT DataObjectImpl::DAdvise(
819 FORMATETC* format_etc, DWORD advf, IAdviseSink* sink, DWORD* connection) {
820 return OLE_E_ADVISENOTSUPPORTED;
823 HRESULT DataObjectImpl::DUnadvise(DWORD connection) {
824 return OLE_E_ADVISENOTSUPPORTED;
827 HRESULT DataObjectImpl::EnumDAdvise(IEnumSTATDATA** enumerator) {
828 return OLE_E_ADVISENOTSUPPORTED;
831 ///////////////////////////////////////////////////////////////////////////////
832 // DataObjectImpl, IDataObjectAsyncCapability implementation:
834 HRESULT DataObjectImpl::EndOperation(
835 HRESULT result, IBindCtx* reserved, DWORD effects) {
836 async_operation_started_ = false;
837 return S_OK;
840 HRESULT DataObjectImpl::GetAsyncMode(BOOL* is_op_async) {
841 *is_op_async = in_async_mode_ ? VARIANT_TRUE : VARIANT_FALSE;
842 return S_OK;
845 HRESULT DataObjectImpl::InOperation(BOOL* in_async_op) {
846 *in_async_op = async_operation_started_ ? VARIANT_TRUE : VARIANT_FALSE;
847 return S_OK;
850 HRESULT DataObjectImpl::SetAsyncMode(BOOL do_op_async) {
851 in_async_mode_ = !!do_op_async;
852 return S_OK;
855 HRESULT DataObjectImpl::StartOperation(IBindCtx* reserved) {
856 async_operation_started_ = true;
857 return S_OK;
860 ///////////////////////////////////////////////////////////////////////////////
861 // DataObjectImpl, IUnknown implementation:
863 HRESULT DataObjectImpl::QueryInterface(const IID& iid, void** object) {
864 if (!object)
865 return E_POINTER;
866 if (IsEqualIID(iid, IID_IDataObject) || IsEqualIID(iid, IID_IUnknown)) {
867 *object = static_cast<IDataObject*>(this);
868 } else if (in_async_mode_ &&
869 IsEqualIID(iid, __uuidof(IDataObjectAsyncCapability))) {
870 *object = static_cast<IDataObjectAsyncCapability*>(this);
871 } else {
872 *object = NULL;
873 return E_NOINTERFACE;
875 AddRef();
876 return S_OK;
879 ULONG DataObjectImpl::AddRef() {
880 base::RefCountedThreadSafe<DownloadFileObserver>::AddRef();
881 return 0;
884 ULONG DataObjectImpl::Release() {
885 base::RefCountedThreadSafe<DownloadFileObserver>::Release();
886 return 0;
889 ///////////////////////////////////////////////////////////////////////////////
890 // DataObjectImpl, private:
892 static STGMEDIUM* GetStorageForBytes(const void* data, size_t bytes) {
893 HANDLE handle = GlobalAlloc(GPTR, static_cast<int>(bytes));
894 if (handle) {
895 base::win::ScopedHGlobal<uint8*> scoped(handle);
896 memcpy(scoped.get(), data, bytes);
899 STGMEDIUM* storage = new STGMEDIUM;
900 storage->hGlobal = handle;
901 storage->tymed = TYMED_HGLOBAL;
902 storage->pUnkForRelease = NULL;
903 return storage;
906 template <typename T>
907 static STGMEDIUM* GetStorageForString(const std::basic_string<T>& data) {
908 return GetStorageForBytes(
909 data.c_str(),
910 (data.size() + 1) * sizeof(typename std::basic_string<T>::value_type));
913 static void GetInternetShortcutFileContents(const GURL& url,
914 std::string* data) {
915 DCHECK(data);
916 static const std::string kInternetShortcutFileStart =
917 "[InternetShortcut]\r\nURL=";
918 static const std::string kInternetShortcutFileEnd =
919 "\r\n";
920 *data = kInternetShortcutFileStart + url.spec() + kInternetShortcutFileEnd;
923 static void CreateValidFileNameFromTitle(const GURL& url,
924 const base::string16& title,
925 base::string16* validated) {
926 if (title.empty()) {
927 if (url.is_valid()) {
928 *validated = net::GetSuggestedFilename(url, "", "", "", "",
929 std::string());
930 } else {
931 // Nothing else can be done, just use a default.
932 *validated =
933 l10n_util::GetStringUTF16(IDS_APP_UNTITLED_SHORTCUT_FILE_NAME);
935 } else {
936 *validated = title;
937 base::i18n::ReplaceIllegalCharactersInPath(validated, '-');
939 static const wchar_t extension[] = L".url";
940 static const size_t max_length = MAX_PATH - arraysize(extension);
941 if (validated->size() > max_length)
942 validated->erase(max_length);
943 *validated += extension;
946 static STGMEDIUM* GetStorageForFileName(const base::FilePath& path) {
947 const size_t kDropSize = sizeof(DROPFILES);
948 const size_t kTotalBytes =
949 kDropSize + (path.value().length() + 2) * sizeof(wchar_t);
950 HANDLE hdata = GlobalAlloc(GMEM_MOVEABLE, kTotalBytes);
952 base::win::ScopedHGlobal<DROPFILES*> locked_mem(hdata);
953 DROPFILES* drop_files = locked_mem.get();
954 drop_files->pFiles = sizeof(DROPFILES);
955 drop_files->fWide = TRUE;
956 wchar_t* data = reinterpret_cast<wchar_t*>(
957 reinterpret_cast<BYTE*>(drop_files) + kDropSize);
958 const size_t copy_size = (path.value().length() + 1) * sizeof(wchar_t);
959 memcpy(data, path.value().c_str(), copy_size);
960 data[path.value().length() + 1] = L'\0'; // Double NULL
962 STGMEDIUM* storage = new STGMEDIUM;
963 storage->tymed = TYMED_HGLOBAL;
964 storage->hGlobal = hdata;
965 storage->pUnkForRelease = NULL;
966 return storage;
969 static LPITEMIDLIST PIDLNext(LPITEMIDLIST pidl) {
970 return reinterpret_cast<LPITEMIDLIST>(
971 reinterpret_cast<BYTE*>(pidl) + pidl->mkid.cb);
974 static size_t PIDLSize(LPITEMIDLIST pidl) {
975 size_t s = 0;
976 while (pidl->mkid.cb > 0) {
977 s += pidl->mkid.cb;
978 pidl = PIDLNext(pidl);
980 // We add 2 because an LPITEMIDLIST is terminated by two NULL bytes.
981 return 2 + s;
984 static LPITEMIDLIST GetNthPIDL(CIDA* cida, int n) {
985 return reinterpret_cast<LPITEMIDLIST>(
986 reinterpret_cast<LPBYTE>(cida) + cida->aoffset[n]);
989 static LPITEMIDLIST GetPidlFromPath(const base::FilePath& path) {
990 LPITEMIDLIST pidl = NULL;
991 LPSHELLFOLDER desktop_folder = NULL;
992 LPWSTR path_str = const_cast<LPWSTR>(path.value().c_str());
994 if (FAILED(SHGetDesktopFolder(&desktop_folder)))
995 return NULL;
997 HRESULT hr = desktop_folder->ParseDisplayName(
998 NULL, NULL, path_str, NULL, &pidl, NULL);
1000 return SUCCEEDED(hr) ? pidl : NULL;
1003 static STGMEDIUM* GetIDListStorageForFileName(const base::FilePath& path) {
1004 LPITEMIDLIST pidl = GetPidlFromPath(path);
1005 if (!pidl)
1006 return NULL;
1008 // When using CFSTR_SHELLIDLIST the hGlobal field of the STGMEDIUM is a
1009 // pointer to a CIDA*. A CIDA is a variable length struct that contains a PIDL
1010 // count (a UINT), an array of offsets of the following PIDLs (a UINT[]) and
1011 // then a series of PIDLs laid out contiguously in memory. A PIDL is
1012 // represented by an ITEMIDLIST struct, which contains a single SHITEMID.
1013 // Despite only containing a single SHITEMID, ITEMIDLISTs are so-named because
1014 // SHITEMIDs contain their own size and so given one, the next can be found by
1015 // looking at the section of memory after it. The end of a list is indicated
1016 // by two NULL bytes.
1017 // Here we require two PIDLs - the first PIDL is the parent folder and is
1018 // NULL here to indicate that the parent folder is the desktop, and the second
1019 // is the PIDL of |path|.
1020 const size_t kPIDLCountSize = sizeof(UINT);
1021 const size_t kPIDLOffsetsSize = 2 * sizeof(UINT);
1022 const size_t kFirstPIDLOffset = kPIDLCountSize + kPIDLOffsetsSize;
1023 const size_t kFirstPIDLSize = 2; // Empty PIDL - 2 NULL bytes.
1024 const size_t kSecondPIDLSize = PIDLSize(pidl);
1025 const size_t kCIDASize = kFirstPIDLOffset + kFirstPIDLSize + kSecondPIDLSize;
1026 HANDLE hdata = GlobalAlloc(GMEM_MOVEABLE, kCIDASize);
1028 base::win::ScopedHGlobal<CIDA*> locked_mem(hdata);
1029 CIDA* cida = locked_mem.get();
1030 cida->cidl = 1; // We have one PIDL (not including the 0th root PIDL).
1031 cida->aoffset[0] = kFirstPIDLOffset;
1032 cida->aoffset[1] = kFirstPIDLOffset + kFirstPIDLSize;
1033 LPITEMIDLIST idl = GetNthPIDL(cida, 0);
1034 idl->mkid.cb = 0;
1035 idl->mkid.abID[0] = 0;
1036 idl = GetNthPIDL(cida, 1);
1037 memcpy(idl, pidl, kSecondPIDLSize);
1039 STGMEDIUM* storage = new STGMEDIUM;
1040 storage->tymed = TYMED_HGLOBAL;
1041 storage->hGlobal = hdata;
1042 storage->pUnkForRelease = NULL;
1043 return storage;
1046 static STGMEDIUM* GetStorageForFileDescriptor(
1047 const base::FilePath& path) {
1048 base::string16 file_name = path.value();
1049 DCHECK(!file_name.empty());
1050 HANDLE hdata = GlobalAlloc(GPTR, sizeof(FILEGROUPDESCRIPTOR));
1051 base::win::ScopedHGlobal<FILEGROUPDESCRIPTOR*> locked_mem(hdata);
1053 FILEGROUPDESCRIPTOR* descriptor = locked_mem.get();
1054 descriptor->cItems = 1;
1055 descriptor->fgd[0].dwFlags = FD_LINKUI;
1056 wcsncpy_s(descriptor->fgd[0].cFileName, MAX_PATH, file_name.c_str(),
1057 std::min(file_name.size(), static_cast<size_t>(MAX_PATH - 1u)));
1059 STGMEDIUM* storage = new STGMEDIUM;
1060 storage->tymed = TYMED_HGLOBAL;
1061 storage->hGlobal = hdata;
1062 storage->pUnkForRelease = NULL;
1063 return storage;
1066 ///////////////////////////////////////////////////////////////////////////////
1067 // OSExchangeData, public:
1069 // static
1070 OSExchangeData::Provider* OSExchangeData::CreateProvider() {
1071 return new OSExchangeDataProviderWin();
1074 } // namespace ui