Home | History | Annotate | Download | only in dragdrop
      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 
     24 namespace 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.
     29 static STGMEDIUM* GetStorageForBytes(const void* data, size_t bytes);
     30 template <typename T>
     31 static STGMEDIUM* GetStorageForString(const std::basic_string<T>& data);
     32 // Creates the contents of an Internet Shortcut file for the given URL.
     33 static void GetInternetShortcutFileContents(const GURL& url, std::string* data);
     34 // Creates a valid file name given a suggested title and URL.
     35 static void CreateValidFileNameFromTitle(const GURL& url,
     36                                          const base::string16& title,
     37                                          base::string16* validated);
     38 // Creates a new STGMEDIUM object to hold a file.
     39 static STGMEDIUM* GetStorageForFileName(const base::FilePath& path);
     40 static 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.
     43 static 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 //
     58 class 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.
    101 static 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 
    110 FormatEtcEnumerator::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 
    123 FormatEtcEnumerator::~FormatEtcEnumerator() {
    124 }
    125 
    126 STDMETHODIMP 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 
    147 STDMETHODIMP 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 
    154 STDMETHODIMP FormatEtcEnumerator::Reset() {
    155   cursor_ = 0;
    156   return S_OK;
    157 }
    158 
    159 STDMETHODIMP 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 
    167 STDMETHODIMP 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 
    179 ULONG FormatEtcEnumerator::AddRef() {
    180   return InterlockedIncrement(&ref_count_);
    181 }
    182 
    183 ULONG 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
    193 FormatEtcEnumerator* 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
    213 bool 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
    220 bool 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
    235 DataObjectImpl* OSExchangeDataProviderWin::GetDataObjectImpl(
    236     const OSExchangeData& data) {
    237   return static_cast<const OSExchangeDataProviderWin*>(&data.provider())->
    238       data_.get();
    239 }
    240 
    241 // static
    242 IDataObject* OSExchangeDataProviderWin::GetIDataObject(
    243     const OSExchangeData& data) {
    244   return static_cast<const OSExchangeDataProviderWin*>(&data.provider())->
    245       data_object();
    246 }
    247 
    248 // static
    249 IDataObjectAsyncCapability* OSExchangeDataProviderWin::GetIAsyncOperation(
    250     const OSExchangeData& data) {
    251   return static_cast<const OSExchangeDataProviderWin*>(&data.provider())->
    252       async_operation();
    253 }
    254 
    255 OSExchangeDataProviderWin::OSExchangeDataProviderWin(IDataObject* source)
    256     : data_(new DataObjectImpl()),
    257       source_object_(source) {
    258 }
    259 
    260 OSExchangeDataProviderWin::OSExchangeDataProviderWin()
    261     : data_(new DataObjectImpl()),
    262       source_object_(data_.get()) {
    263 }
    264 
    265 OSExchangeDataProviderWin::~OSExchangeDataProviderWin() {
    266 }
    267 
    268 OSExchangeData::Provider* OSExchangeDataProviderWin::Clone() const {
    269   return new OSExchangeDataProviderWin(data_object());
    270 }
    271 
    272 void 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(UTF16ToUTF8(data));
    279   data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
    280       Clipboard::GetPlainTextFormatType().ToFormatEtc(), storage));
    281 }
    282 
    283 void 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 = 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(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(UTF8ToUTF16(url.spec()));
    320 }
    321 
    322 void 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 
    336 void 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 
    346 void 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 
    354 void 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 
    368 void 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 = 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 
    385 bool OSExchangeDataProviderWin::GetString(base::string16* data) const {
    386   return ClipboardUtil::GetPlainText(source_object_, data);
    387 }
    388 
    389 bool OSExchangeDataProviderWin::GetURLAndTitle(GURL* url,
    390                                                base::string16* title) const {
    391   base::string16 url_str;
    392   bool success = ClipboardUtil::GetUrl(source_object_, &url_str, title, true);
    393   if (success) {
    394     GURL test_url(url_str);
    395     if (test_url.is_valid()) {
    396       *url = test_url;
    397       return true;
    398     }
    399   } else if (GetPlainTextURL(source_object_, url)) {
    400     if (url->is_valid())
    401       *title = net::GetSuggestedFilename(*url, "", "", "", "", std::string());
    402     else
    403       title->clear();
    404     return true;
    405   }
    406   return false;
    407 }
    408 
    409 bool OSExchangeDataProviderWin::GetFilename(base::FilePath* path) const {
    410   std::vector<base::string16> filenames;
    411   bool success = ClipboardUtil::GetFilenames(source_object_, &filenames);
    412   if (success)
    413     *path = base::FilePath(filenames[0]);
    414   return success;
    415 }
    416 
    417 bool OSExchangeDataProviderWin::GetFilenames(
    418     std::vector<OSExchangeData::FileInfo>* filenames) const {
    419   std::vector<base::string16> filenames_local;
    420   bool success = ClipboardUtil::GetFilenames(source_object_, &filenames_local);
    421   if (success) {
    422     for (size_t i = 0; i < filenames_local.size(); ++i)
    423       filenames->push_back(
    424           OSExchangeData::FileInfo(base::FilePath(filenames_local[i]),
    425                                    base::FilePath()));
    426   }
    427   return success;
    428 }
    429 
    430 bool OSExchangeDataProviderWin::GetPickledData(
    431     const OSExchangeData::CustomFormat& format,
    432     Pickle* data) const {
    433   DCHECK(data);
    434   bool success = false;
    435   STGMEDIUM medium;
    436   FORMATETC format_etc = format.ToFormatEtc();
    437   if (SUCCEEDED(source_object_->GetData(&format_etc, &medium))) {
    438     if (medium.tymed & TYMED_HGLOBAL) {
    439       base::win::ScopedHGlobal<char> c_data(medium.hGlobal);
    440       DCHECK_GT(c_data.Size(), 0u);
    441       *data = Pickle(c_data.get(), static_cast<int>(c_data.Size()));
    442       success = true;
    443     }
    444     ReleaseStgMedium(&medium);
    445   }
    446   return success;
    447 }
    448 
    449 bool OSExchangeDataProviderWin::GetFileContents(
    450     base::FilePath* filename,
    451     std::string* file_contents) const {
    452   base::string16 filename_str;
    453   if (!ClipboardUtil::GetFileContents(source_object_, &filename_str,
    454                                       file_contents)) {
    455     return false;
    456   }
    457   *filename = base::FilePath(filename_str);
    458   return true;
    459 }
    460 
    461 bool OSExchangeDataProviderWin::GetHtml(base::string16* html,
    462                                         GURL* base_url) const {
    463   std::string url;
    464   bool success = ClipboardUtil::GetHtml(source_object_, html, &url);
    465   if (success)
    466     *base_url = GURL(url);
    467   return success;
    468 }
    469 
    470 bool OSExchangeDataProviderWin::HasString() const {
    471   return ClipboardUtil::HasPlainText(source_object_);
    472 }
    473 
    474 bool OSExchangeDataProviderWin::HasURL() const {
    475   return (ClipboardUtil::HasUrl(source_object_) ||
    476           HasPlainTextURL(source_object_));
    477 }
    478 
    479 bool OSExchangeDataProviderWin::HasFile() const {
    480   return ClipboardUtil::HasFilenames(source_object_);
    481 }
    482 
    483 bool OSExchangeDataProviderWin::HasFileContents() const {
    484   return ClipboardUtil::HasFileContents(source_object_);
    485 }
    486 
    487 bool OSExchangeDataProviderWin::HasHtml() const {
    488   return ClipboardUtil::HasHtml(source_object_);
    489 }
    490 
    491 bool OSExchangeDataProviderWin::HasCustomFormat(
    492     const OSExchangeData::CustomFormat& format) const {
    493   FORMATETC format_etc = format.ToFormatEtc();
    494   return (source_object_->QueryGetData(&format_etc) == S_OK);
    495 }
    496 
    497 void OSExchangeDataProviderWin::SetDownloadFileInfo(
    498     const OSExchangeData::DownloadFileInfo& download) {
    499   // If the filename is not provided, set storage to NULL to indicate that
    500   // the delay rendering will be used.
    501   // TODO(dcheng): Is it actually possible for filename to be empty here? I
    502   // think we always synthesize one in WebContentsDragWin.
    503   STGMEDIUM* storage = NULL;
    504   if (!download.filename.empty())
    505     storage = GetStorageForFileName(download.filename);
    506 
    507   // Add CF_HDROP.
    508   DataObjectImpl::StoredDataInfo* info = new DataObjectImpl::StoredDataInfo(
    509       Clipboard::GetCFHDropFormatType().ToFormatEtc(), storage);
    510   info->downloader = download.downloader;
    511   data_->contents_.push_back(info);
    512 }
    513 
    514 void OSExchangeDataProviderWin::SetInDragLoop(bool in_drag_loop) {
    515   data_->set_in_drag_loop(in_drag_loop);
    516 }
    517 
    518 #if defined(USE_AURA)
    519 
    520 void OSExchangeDataProviderWin::SetDragImage(
    521     const gfx::ImageSkia& image,
    522     const gfx::Vector2d& cursor_offset) {
    523   drag_image_ = image;
    524   drag_image_offset_ = cursor_offset;
    525 }
    526 
    527 const gfx::ImageSkia& OSExchangeDataProviderWin::GetDragImage() const {
    528   return drag_image_;
    529 }
    530 
    531 const gfx::Vector2d& OSExchangeDataProviderWin::GetDragImageOffset() const {
    532   return drag_image_offset_;
    533 }
    534 
    535 #endif
    536 
    537 ///////////////////////////////////////////////////////////////////////////////
    538 // DataObjectImpl, IDataObject implementation:
    539 
    540 // The following function, DuplicateMedium, is derived from WCDataObject.cpp
    541 // in the WebKit source code. This is the license information for the file:
    542 /*
    543  * Copyright (C) 2007 Apple Inc.  All rights reserved.
    544  *
    545  * Redistribution and use in source and binary forms, with or without
    546  * modification, are permitted provided that the following conditions
    547  * are met:
    548  * 1. Redistributions of source code must retain the above copyright
    549  *    notice, this list of conditions and the following disclaimer.
    550  * 2. Redistributions in binary form must reproduce the above copyright
    551  *    notice, this list of conditions and the following disclaimer in the
    552  *    documentation and/or other materials provided with the distribution.
    553  *
    554  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
    555  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    556  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    557  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
    558  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    559  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    560  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    561  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
    562  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    563  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    564  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    565  */
    566 static void DuplicateMedium(CLIPFORMAT source_clipformat,
    567                             STGMEDIUM* source,
    568                             STGMEDIUM* destination) {
    569   switch (source->tymed) {
    570     case TYMED_HGLOBAL:
    571       destination->hGlobal =
    572           static_cast<HGLOBAL>(OleDuplicateData(
    573               source->hGlobal, source_clipformat, 0));
    574       break;
    575     case TYMED_MFPICT:
    576       destination->hMetaFilePict =
    577           static_cast<HMETAFILEPICT>(OleDuplicateData(
    578               source->hMetaFilePict, source_clipformat, 0));
    579       break;
    580     case TYMED_GDI:
    581       destination->hBitmap =
    582           static_cast<HBITMAP>(OleDuplicateData(
    583               source->hBitmap, source_clipformat, 0));
    584       break;
    585     case TYMED_ENHMF:
    586       destination->hEnhMetaFile =
    587           static_cast<HENHMETAFILE>(OleDuplicateData(
    588               source->hEnhMetaFile, source_clipformat, 0));
    589       break;
    590     case TYMED_FILE:
    591       destination->lpszFileName =
    592           static_cast<LPOLESTR>(OleDuplicateData(
    593               source->lpszFileName, source_clipformat, 0));
    594       break;
    595     case TYMED_ISTREAM:
    596       destination->pstm = source->pstm;
    597       destination->pstm->AddRef();
    598       break;
    599     case TYMED_ISTORAGE:
    600       destination->pstg = source->pstg;
    601       destination->pstg->AddRef();
    602       break;
    603   }
    604 
    605   destination->tymed = source->tymed;
    606   destination->pUnkForRelease = source->pUnkForRelease;
    607   if (destination->pUnkForRelease)
    608     destination->pUnkForRelease->AddRef();
    609 }
    610 
    611 DataObjectImpl::DataObjectImpl()
    612     : is_aborting_(false),
    613       in_drag_loop_(false),
    614       in_async_mode_(false),
    615       async_operation_started_(false),
    616       observer_(NULL) {
    617 }
    618 
    619 DataObjectImpl::~DataObjectImpl() {
    620   StopDownloads();
    621   if (observer_)
    622     observer_->OnDataObjectDisposed();
    623 }
    624 
    625 void DataObjectImpl::StopDownloads() {
    626   for (StoredData::iterator iter = contents_.begin();
    627        iter != contents_.end(); ++iter) {
    628     if ((*iter)->downloader.get()) {
    629       (*iter)->downloader->Stop();
    630       (*iter)->downloader = 0;
    631     }
    632   }
    633 }
    634 
    635 void DataObjectImpl::RemoveData(const FORMATETC& format) {
    636   if (format.ptd)
    637     return;  // Don't attempt to compare target devices.
    638 
    639   for (StoredData::iterator i = contents_.begin(); i != contents_.end(); ++i) {
    640     if (!(*i)->format_etc.ptd &&
    641         format.cfFormat == (*i)->format_etc.cfFormat &&
    642         format.dwAspect == (*i)->format_etc.dwAspect &&
    643         format.lindex == (*i)->format_etc.lindex &&
    644         format.tymed == (*i)->format_etc.tymed) {
    645       contents_.erase(i);
    646       return;
    647     }
    648   }
    649 }
    650 
    651 void DataObjectImpl::OnDownloadCompleted(const base::FilePath& file_path) {
    652   DataObjectImpl::StoredData::iterator iter = contents_.begin();
    653   for (; iter != contents_.end(); ++iter) {
    654     if ((*iter)->format_etc.cfFormat == CF_HDROP) {
    655       // Release the old storage.
    656       if ((*iter)->owns_medium) {
    657         ReleaseStgMedium((*iter)->medium);
    658         delete (*iter)->medium;
    659       }
    660 
    661       // Update the storage.
    662       (*iter)->owns_medium = true;
    663       (*iter)->medium = GetStorageForFileName(file_path);
    664 
    665       break;
    666     }
    667   }
    668   DCHECK(iter != contents_.end());
    669 }
    670 
    671 void DataObjectImpl::OnDownloadAborted() {
    672 }
    673 
    674 HRESULT DataObjectImpl::GetData(FORMATETC* format_etc, STGMEDIUM* medium) {
    675   if (is_aborting_)
    676     return DV_E_FORMATETC;
    677 
    678   StoredData::iterator iter = contents_.begin();
    679   while (iter != contents_.end()) {
    680     if ((*iter)->format_etc.cfFormat == format_etc->cfFormat &&
    681         (*iter)->format_etc.lindex == format_etc->lindex &&
    682         ((*iter)->format_etc.tymed & format_etc->tymed)) {
    683       // If medium is NULL, delay-rendering will be used.
    684       if ((*iter)->medium) {
    685         DuplicateMedium((*iter)->format_etc.cfFormat, (*iter)->medium, medium);
    686       } else {
    687         // Fail all GetData() attempts for DownloadURL data if the drag and drop
    688         // operation is still in progress.
    689         if (in_drag_loop_)
    690           return DV_E_FORMATETC;
    691 
    692         bool wait_for_data = false;
    693 
    694         // In async mode, we do not want to start waiting for the data before
    695         // the async operation is started. This is because we want to postpone
    696         // until Shell kicks off a background thread to do the work so that
    697         // we do not block the UI thread.
    698         if (!in_async_mode_ || async_operation_started_)
    699           wait_for_data = true;
    700 
    701         if (!wait_for_data)
    702           return DV_E_FORMATETC;
    703 
    704         // Notify the observer we start waiting for the data. This gives
    705         // an observer a chance to end the drag and drop.
    706         if (observer_)
    707           observer_->OnWaitForData();
    708 
    709         // Now we can start the download.
    710         if ((*iter)->downloader.get()) {
    711           (*iter)->downloader->Start(this);
    712           if (!(*iter)->downloader->Wait()) {
    713             is_aborting_ = true;
    714             return DV_E_FORMATETC;
    715           }
    716         }
    717 
    718         // The stored data should have been updated with the final version.
    719         // So we just need to call this function again to retrieve it.
    720         return GetData(format_etc, medium);
    721       }
    722       return S_OK;
    723     }
    724     ++iter;
    725   }
    726 
    727   return DV_E_FORMATETC;
    728 }
    729 
    730 HRESULT DataObjectImpl::GetDataHere(FORMATETC* format_etc,
    731                                     STGMEDIUM* medium) {
    732   return DATA_E_FORMATETC;
    733 }
    734 
    735 HRESULT DataObjectImpl::QueryGetData(FORMATETC* format_etc) {
    736   StoredData::const_iterator iter = contents_.begin();
    737   while (iter != contents_.end()) {
    738     if ((*iter)->format_etc.cfFormat == format_etc->cfFormat)
    739       return S_OK;
    740     ++iter;
    741   }
    742   return DV_E_FORMATETC;
    743 }
    744 
    745 HRESULT DataObjectImpl::GetCanonicalFormatEtc(
    746     FORMATETC* format_etc, FORMATETC* result) {
    747   format_etc->ptd = NULL;
    748   return E_NOTIMPL;
    749 }
    750 
    751 HRESULT DataObjectImpl::SetData(
    752     FORMATETC* format_etc, STGMEDIUM* medium, BOOL should_release) {
    753   RemoveData(*format_etc);
    754 
    755   STGMEDIUM* local_medium = new STGMEDIUM;
    756   if (should_release) {
    757     *local_medium = *medium;
    758   } else {
    759     DuplicateMedium(format_etc->cfFormat, medium, local_medium);
    760   }
    761 
    762   DataObjectImpl::StoredDataInfo* info =
    763       new DataObjectImpl::StoredDataInfo(*format_etc, local_medium);
    764   info->medium->tymed = format_etc->tymed;
    765   info->owns_medium = !!should_release;
    766   // Make newly added data appear first.
    767   // TODO(dcheng): Make various setters agree whether elements should be
    768   // prioritized from front to back or back to front.
    769   contents_.insert(contents_.begin(), info);
    770 
    771   return S_OK;
    772 }
    773 
    774 HRESULT DataObjectImpl::EnumFormatEtc(
    775     DWORD direction, IEnumFORMATETC** enumerator) {
    776   if (direction == DATADIR_GET) {
    777     FormatEtcEnumerator* e =
    778         new FormatEtcEnumerator(contents_.begin(), contents_.end());
    779     e->AddRef();
    780     *enumerator = e;
    781     return S_OK;
    782   }
    783   return E_NOTIMPL;
    784 }
    785 
    786 HRESULT DataObjectImpl::DAdvise(
    787     FORMATETC* format_etc, DWORD advf, IAdviseSink* sink, DWORD* connection) {
    788   return OLE_E_ADVISENOTSUPPORTED;
    789 }
    790 
    791 HRESULT DataObjectImpl::DUnadvise(DWORD connection) {
    792   return OLE_E_ADVISENOTSUPPORTED;
    793 }
    794 
    795 HRESULT DataObjectImpl::EnumDAdvise(IEnumSTATDATA** enumerator) {
    796   return OLE_E_ADVISENOTSUPPORTED;
    797 }
    798 
    799 ///////////////////////////////////////////////////////////////////////////////
    800 // DataObjectImpl, IDataObjectAsyncCapability implementation:
    801 
    802 HRESULT DataObjectImpl::EndOperation(
    803     HRESULT result, IBindCtx* reserved, DWORD effects) {
    804   async_operation_started_ = false;
    805   return S_OK;
    806 }
    807 
    808 HRESULT DataObjectImpl::GetAsyncMode(BOOL* is_op_async) {
    809   *is_op_async = in_async_mode_ ? TRUE : FALSE;
    810   return S_OK;
    811 }
    812 
    813 HRESULT DataObjectImpl::InOperation(BOOL* in_async_op) {
    814   *in_async_op = async_operation_started_ ? TRUE : FALSE;
    815   return S_OK;
    816 }
    817 
    818 HRESULT DataObjectImpl::SetAsyncMode(BOOL do_op_async) {
    819   in_async_mode_ = (do_op_async == TRUE);
    820   return S_OK;
    821 }
    822 
    823 HRESULT DataObjectImpl::StartOperation(IBindCtx* reserved) {
    824   async_operation_started_ = true;
    825   return S_OK;
    826 }
    827 
    828 ///////////////////////////////////////////////////////////////////////////////
    829 // DataObjectImpl, IUnknown implementation:
    830 
    831 HRESULT DataObjectImpl::QueryInterface(const IID& iid, void** object) {
    832   if (!object)
    833     return E_POINTER;
    834   if (IsEqualIID(iid, IID_IDataObject) || IsEqualIID(iid, IID_IUnknown)) {
    835     *object = static_cast<IDataObject*>(this);
    836   } else if (in_async_mode_ &&
    837              IsEqualIID(iid, __uuidof(IDataObjectAsyncCapability))) {
    838     *object = static_cast<IDataObjectAsyncCapability*>(this);
    839   } else {
    840     *object = NULL;
    841     return E_NOINTERFACE;
    842   }
    843   AddRef();
    844   return S_OK;
    845 }
    846 
    847 ULONG DataObjectImpl::AddRef() {
    848   base::RefCountedThreadSafe<DownloadFileObserver>::AddRef();
    849   return 0;
    850 }
    851 
    852 ULONG DataObjectImpl::Release() {
    853   base::RefCountedThreadSafe<DownloadFileObserver>::Release();
    854   return 0;
    855 }
    856 
    857 ///////////////////////////////////////////////////////////////////////////////
    858 // DataObjectImpl, private:
    859 
    860 static STGMEDIUM* GetStorageForBytes(const void* data, size_t bytes) {
    861   HANDLE handle = GlobalAlloc(GPTR, static_cast<int>(bytes));
    862   if (handle) {
    863     base::win::ScopedHGlobal<uint8> scoped(handle);
    864     memcpy(scoped.get(), data, bytes);
    865   }
    866 
    867   STGMEDIUM* storage = new STGMEDIUM;
    868   storage->hGlobal = handle;
    869   storage->tymed = TYMED_HGLOBAL;
    870   storage->pUnkForRelease = NULL;
    871   return storage;
    872 }
    873 
    874 template <typename T>
    875 static STGMEDIUM* GetStorageForString(const std::basic_string<T>& data) {
    876   return GetStorageForBytes(
    877       data.c_str(),
    878       (data.size() + 1) * sizeof(std::basic_string<T>::value_type));
    879 }
    880 
    881 static void GetInternetShortcutFileContents(const GURL& url,
    882                                             std::string* data) {
    883   DCHECK(data);
    884   static const std::string kInternetShortcutFileStart =
    885       "[InternetShortcut]\r\nURL=";
    886   static const std::string kInternetShortcutFileEnd =
    887       "\r\n";
    888   *data = kInternetShortcutFileStart + url.spec() + kInternetShortcutFileEnd;
    889 }
    890 
    891 static void CreateValidFileNameFromTitle(const GURL& url,
    892                                          const base::string16& title,
    893                                          base::string16* validated) {
    894   if (title.empty()) {
    895     if (url.is_valid()) {
    896       *validated = net::GetSuggestedFilename(url, "", "", "", "",
    897                                              std::string());
    898     } else {
    899       // Nothing else can be done, just use a default.
    900       *validated =
    901           l10n_util::GetStringUTF16(IDS_APP_UNTITLED_SHORTCUT_FILE_NAME);
    902     }
    903   } else {
    904     *validated = title;
    905     file_util::ReplaceIllegalCharactersInPath(validated, '-');
    906   }
    907   static const wchar_t extension[] = L".url";
    908   static const size_t max_length = MAX_PATH - arraysize(extension);
    909   if (validated->size() > max_length)
    910     validated->erase(max_length);
    911   *validated += extension;
    912 }
    913 
    914 static STGMEDIUM* GetStorageForFileName(const base::FilePath& path) {
    915   const size_t kDropSize = sizeof(DROPFILES);
    916   const size_t kTotalBytes =
    917       kDropSize + (path.value().length() + 2) * sizeof(wchar_t);
    918   HANDLE hdata = GlobalAlloc(GMEM_MOVEABLE, kTotalBytes);
    919 
    920   base::win::ScopedHGlobal<DROPFILES> locked_mem(hdata);
    921   DROPFILES* drop_files = locked_mem.get();
    922   drop_files->pFiles = sizeof(DROPFILES);
    923   drop_files->fWide = TRUE;
    924   wchar_t* data = reinterpret_cast<wchar_t*>(
    925       reinterpret_cast<BYTE*>(drop_files) + kDropSize);
    926   const size_t copy_size = (path.value().length() + 1) * sizeof(wchar_t);
    927   memcpy(data, path.value().c_str(), copy_size);
    928   data[path.value().length() + 1] = L'\0';  // Double NULL
    929 
    930   STGMEDIUM* storage = new STGMEDIUM;
    931   storage->tymed = TYMED_HGLOBAL;
    932   storage->hGlobal = hdata;
    933   storage->pUnkForRelease = NULL;
    934   return storage;
    935 }
    936 
    937 static LPITEMIDLIST PIDLNext(LPITEMIDLIST pidl) {
    938   return reinterpret_cast<LPITEMIDLIST>(
    939       reinterpret_cast<BYTE*>(pidl) + pidl->mkid.cb);
    940 }
    941 
    942 static size_t PIDLSize(LPITEMIDLIST pidl) {
    943   size_t s = 0;
    944   while (pidl->mkid.cb > 0) {
    945     s += pidl->mkid.cb;
    946     pidl = PIDLNext(pidl);
    947   }
    948   // We add 2 because an LPITEMIDLIST is terminated by two NULL bytes.
    949   return 2 + s;
    950 }
    951 
    952 static LPITEMIDLIST GetNthPIDL(CIDA* cida, int n) {
    953   return reinterpret_cast<LPITEMIDLIST>(
    954       reinterpret_cast<LPBYTE>(cida) + cida->aoffset[n]);
    955 }
    956 
    957 static LPITEMIDLIST GetPidlFromPath(const base::FilePath& path) {
    958   LPITEMIDLIST pidl = NULL;
    959   LPSHELLFOLDER desktop_folder = NULL;
    960   LPWSTR path_str = const_cast<LPWSTR>(path.value().c_str());
    961 
    962   if (FAILED(SHGetDesktopFolder(&desktop_folder)))
    963     return NULL;
    964 
    965   HRESULT hr = desktop_folder->ParseDisplayName(
    966       NULL, NULL, path_str, NULL, &pidl, NULL);
    967 
    968   return SUCCEEDED(hr) ? pidl : NULL;
    969 }
    970 
    971 static STGMEDIUM* GetIDListStorageForFileName(const base::FilePath& path) {
    972   LPITEMIDLIST pidl = GetPidlFromPath(path);
    973   if (!pidl)
    974     return NULL;
    975 
    976   // When using CFSTR_SHELLIDLIST the hGlobal field of the STGMEDIUM is a
    977   // pointer to a CIDA*. A CIDA is a variable length struct that contains a PIDL
    978   // count (a UINT), an array of offsets of the following PIDLs (a UINT[]) and
    979   // then a series of PIDLs laid out contiguously in memory. A PIDL is
    980   // represented by an ITEMIDLIST struct, which contains a single SHITEMID.
    981   // Despite only containing a single SHITEMID, ITEMIDLISTs are so-named because
    982   // SHITEMIDs contain their own size and so given one, the next can be found by
    983   // looking at the section of memory after it. The end of a list is indicated
    984   // by two NULL bytes.
    985   // Here we require two PIDLs - the first PIDL is the parent folder and is
    986   // NULL here to indicate that the parent folder is the desktop, and the second
    987   // is the PIDL of |path|.
    988   const size_t kPIDLCountSize = sizeof(UINT);
    989   const size_t kPIDLOffsetsSize = 2 * sizeof(UINT);
    990   const size_t kFirstPIDLOffset = kPIDLCountSize + kPIDLOffsetsSize;
    991   const size_t kFirstPIDLSize = 2;  // Empty PIDL - 2 NULL bytes.
    992   const size_t kSecondPIDLSize = PIDLSize(pidl);
    993   const size_t kCIDASize = kFirstPIDLOffset + kFirstPIDLSize + kSecondPIDLSize;
    994   HANDLE hdata = GlobalAlloc(GMEM_MOVEABLE, kCIDASize);
    995 
    996   base::win::ScopedHGlobal<CIDA> locked_mem(hdata);
    997   CIDA* cida = locked_mem.get();
    998   cida->cidl = 1;     // We have one PIDL (not including the 0th root PIDL).
    999   cida->aoffset[0] = kFirstPIDLOffset;
   1000   cida->aoffset[1] = kFirstPIDLOffset + kFirstPIDLSize;
   1001   LPITEMIDLIST idl = GetNthPIDL(cida, 0);
   1002   idl->mkid.cb = 0;
   1003   idl->mkid.abID[0] = 0;
   1004   idl = GetNthPIDL(cida, 1);
   1005   memcpy(idl, pidl, kSecondPIDLSize);
   1006 
   1007   STGMEDIUM* storage = new STGMEDIUM;
   1008   storage->tymed = TYMED_HGLOBAL;
   1009   storage->hGlobal = hdata;
   1010   storage->pUnkForRelease = NULL;
   1011   return storage;
   1012 }
   1013 
   1014 static STGMEDIUM* GetStorageForFileDescriptor(
   1015     const base::FilePath& path) {
   1016   base::string16 file_name = path.value();
   1017   DCHECK(!file_name.empty());
   1018   HANDLE hdata = GlobalAlloc(GPTR, sizeof(FILEGROUPDESCRIPTOR));
   1019   base::win::ScopedHGlobal<FILEGROUPDESCRIPTOR> locked_mem(hdata);
   1020 
   1021   FILEGROUPDESCRIPTOR* descriptor = locked_mem.get();
   1022   descriptor->cItems = 1;
   1023   descriptor->fgd[0].dwFlags = FD_LINKUI;
   1024   wcsncpy_s(descriptor->fgd[0].cFileName, MAX_PATH, file_name.c_str(),
   1025             std::min(file_name.size(), static_cast<size_t>(MAX_PATH - 1u)));
   1026 
   1027   STGMEDIUM* storage = new STGMEDIUM;
   1028   storage->tymed = TYMED_HGLOBAL;
   1029   storage->hGlobal = hdata;
   1030   storage->pUnkForRelease = NULL;
   1031   return storage;
   1032 }
   1033 
   1034 ///////////////////////////////////////////////////////////////////////////////
   1035 // OSExchangeData, public:
   1036 
   1037 // static
   1038 OSExchangeData::Provider* OSExchangeData::CreateProvider() {
   1039   return new OSExchangeDataProviderWin();
   1040 }
   1041 
   1042 }  // namespace ui
   1043