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