1 // Copyright (c) 2010 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 "app/os_exchange_data_provider_win.h"
7 #include "app/clipboard/clipboard_util_win.h"
8 #include "app/l10n_util.h"
9 #include "base/file_path.h"
10 #include "base/i18n/file_util_icu.h"
11 #include "base/logging.h"
12 #include "base/pickle.h"
13 #include "base/scoped_handle.h"
14 #include "base/stl_util-inl.h"
15 #include "base/utf_string_conversions.h"
16 #include "googleurl/src/gurl.h"
17 #include "grit/app_strings.h"
18 #include "net/base/net_util.h"
20 // Creates a new STGMEDIUM object to hold the specified text. The caller
21 // owns the resulting object. The "Bytes" version does not NULL terminate, the
22 // string version does.
23 static STGMEDIUM
* GetStorageForBytes(const char* data
, size_t bytes
);
24 static STGMEDIUM
* GetStorageForWString(const std::wstring
& data
);
25 static STGMEDIUM
* GetStorageForString(const std::string
& data
);
26 // Creates the contents of an Internet Shortcut file for the given URL.
27 static void GetInternetShortcutFileContents(const GURL
& url
, std::string
* data
);
28 // Creates a valid file name given a suggested title and URL.
29 static void CreateValidFileNameFromTitle(const GURL
& url
,
30 const std::wstring
& title
,
31 std::wstring
* validated
);
32 // Creates a new STGMEDIUM object to hold a file.
33 static STGMEDIUM
* GetStorageForFileName(const std::wstring
& full_path
);
34 // Creates a File Descriptor for the creation of a file to the given URL and
35 // returns a handle to it.
36 static STGMEDIUM
* GetStorageForFileDescriptor(
37 const std::wstring
& valid_file_name
);
39 ///////////////////////////////////////////////////////////////////////////////
40 // FormatEtcEnumerator
43 // This object implements an enumeration interface. The existence of an
44 // implementation of this interface is exposed to clients through
45 // OSExchangeData's EnumFormatEtc method. Our implementation is nobody's
46 // business but our own, so it lives in this file.
48 // This Windows API is truly a gem. It wants to be an enumerator but assumes
49 // some sort of sequential data (why not just use an array?). See comments
52 class FormatEtcEnumerator
: public IEnumFORMATETC
{
54 FormatEtcEnumerator(DataObjectImpl::StoredData::const_iterator begin
,
55 DataObjectImpl::StoredData::const_iterator end
);
56 ~FormatEtcEnumerator();
58 // IEnumFORMATETC implementation:
59 HRESULT __stdcall
Next(
60 ULONG count
, FORMATETC
* elements_array
, ULONG
* elements_fetched
);
61 HRESULT __stdcall
Skip(ULONG skip_count
);
62 HRESULT __stdcall
Reset();
63 HRESULT __stdcall
Clone(IEnumFORMATETC
** clone
);
65 // IUnknown implementation:
66 HRESULT __stdcall
QueryInterface(const IID
& iid
, void** object
);
67 ULONG __stdcall
AddRef();
68 ULONG __stdcall
Release();
71 // This can only be called from |CloneFromOther|, since it initializes the
72 // contents_ from the other enumerator's contents.
73 FormatEtcEnumerator() : ref_count_(0) {
76 // Clone a new FormatEtc from another instance of this enumeration.
77 static FormatEtcEnumerator
* CloneFromOther(const FormatEtcEnumerator
* other
);
80 // We are _forced_ to use a vector as our internal data model as Windows'
81 // retarded IEnumFORMATETC API assumes a deterministic ordering of elements
82 // through methods like Next and Skip. This exposes the underlying data
83 // structure to the user. Bah.
84 std::vector
<FORMATETC
*> contents_
;
86 // The cursor of the active enumeration - an index into |contents_|.
91 DISALLOW_COPY_AND_ASSIGN(FormatEtcEnumerator
);
94 // Safely makes a copy of all of the relevant bits of a FORMATETC object.
95 static void CloneFormatEtc(FORMATETC
* source
, FORMATETC
* clone
) {
99 static_cast<DVTARGETDEVICE
*>(CoTaskMemAlloc(sizeof(DVTARGETDEVICE
)));
100 *(clone
->ptd
) = *(source
->ptd
);
104 FormatEtcEnumerator::FormatEtcEnumerator(
105 DataObjectImpl::StoredData::const_iterator start
,
106 DataObjectImpl::StoredData::const_iterator end
)
107 : ref_count_(0), cursor_(0) {
108 // Copy FORMATETC data from our source into ourselves.
109 while (start
!= end
) {
110 FORMATETC
* format_etc
= new FORMATETC
;
111 CloneFormatEtc(&(*start
)->format_etc
, format_etc
);
112 contents_
.push_back(format_etc
);
117 FormatEtcEnumerator::~FormatEtcEnumerator() {
118 STLDeleteContainerPointers(contents_
.begin(), contents_
.end());
121 STDMETHODIMP
FormatEtcEnumerator::Next(
122 ULONG count
, FORMATETC
* elements_array
, ULONG
* elements_fetched
) {
123 // MSDN says |elements_fetched| is allowed to be NULL if count is 1.
124 if (!elements_fetched
)
127 // This method copies count elements into |elements_array|.
129 while (cursor_
< contents_
.size() && index
< count
) {
130 CloneFormatEtc(contents_
[cursor_
], &elements_array
[index
]);
134 // The out param is for how many we actually copied.
135 if (elements_fetched
)
136 *elements_fetched
= index
;
138 // If the two don't agree, then we fail.
139 return index
== count
? S_OK
: S_FALSE
;
142 STDMETHODIMP
FormatEtcEnumerator::Skip(ULONG skip_count
) {
143 cursor_
+= skip_count
;
144 // MSDN implies it's OK to leave the enumerator trashed.
145 // "Whatever you say, boss"
146 return cursor_
<= contents_
.size() ? S_OK
: S_FALSE
;
149 STDMETHODIMP
FormatEtcEnumerator::Reset() {
154 STDMETHODIMP
FormatEtcEnumerator::Clone(IEnumFORMATETC
** clone
) {
155 // Clone the current enumerator in its exact state, including cursor.
156 FormatEtcEnumerator
* e
= CloneFromOther(this);
162 STDMETHODIMP
FormatEtcEnumerator::QueryInterface(const IID
& iid
,
165 if (IsEqualIID(iid
, IID_IUnknown
) || IsEqualIID(iid
, IID_IEnumFORMATETC
)) {
168 return E_NOINTERFACE
;
174 ULONG
FormatEtcEnumerator::AddRef() {
175 return InterlockedIncrement(&ref_count_
);
178 ULONG
FormatEtcEnumerator::Release() {
179 if (InterlockedDecrement(&ref_count_
) == 0) {
180 ULONG copied_refcnt
= ref_count_
;
182 return copied_refcnt
;
188 FormatEtcEnumerator
* FormatEtcEnumerator::CloneFromOther(
189 const FormatEtcEnumerator
* other
) {
190 FormatEtcEnumerator
* e
= new FormatEtcEnumerator
;
191 // Copy FORMATETC data from our source into ourselves.
192 std::vector
<FORMATETC
*>::const_iterator start
= other
->contents_
.begin();
193 while (start
!= other
->contents_
.end()) {
194 FORMATETC
* format_etc
= new FORMATETC
;
195 CloneFormatEtc(*start
, format_etc
);
196 e
->contents_
.push_back(format_etc
);
200 e
->cursor_
= other
->cursor_
;
204 ///////////////////////////////////////////////////////////////////////////////
205 // OSExchangeDataProviderWin, public:
208 bool OSExchangeDataProviderWin::HasPlainTextURL(IDataObject
* source
) {
209 std::wstring plain_text
;
210 return (ClipboardUtil::GetPlainText(source
, &plain_text
) &&
211 !plain_text
.empty() && GURL(plain_text
).is_valid());
215 bool OSExchangeDataProviderWin::GetPlainTextURL(IDataObject
* source
,
217 std::wstring plain_text
;
218 if (ClipboardUtil::GetPlainText(source
, &plain_text
) &&
219 !plain_text
.empty()) {
220 GURL
gurl(plain_text
);
221 if (gurl
.is_valid()) {
230 DataObjectImpl
* OSExchangeDataProviderWin::GetDataObjectImpl(
231 const OSExchangeData
& data
) {
232 return static_cast<const OSExchangeDataProviderWin
*>(&data
.provider())->
237 IDataObject
* OSExchangeDataProviderWin::GetIDataObject(
238 const OSExchangeData
& data
) {
239 return static_cast<const OSExchangeDataProviderWin
*>(&data
.provider())->
244 IAsyncOperation
* OSExchangeDataProviderWin::GetIAsyncOperation(
245 const OSExchangeData
& data
) {
246 return static_cast<const OSExchangeDataProviderWin
*>(&data
.provider())->
250 OSExchangeDataProviderWin::OSExchangeDataProviderWin(IDataObject
* source
)
251 : data_(new DataObjectImpl()),
252 source_object_(source
) {
255 OSExchangeDataProviderWin::OSExchangeDataProviderWin()
256 : data_(new DataObjectImpl()),
257 source_object_(data_
.get()) {
260 OSExchangeDataProviderWin::~OSExchangeDataProviderWin() {
263 void OSExchangeDataProviderWin::SetString(const std::wstring
& data
) {
264 STGMEDIUM
* storage
= GetStorageForWString(data
);
265 data_
->contents_
.push_back(
266 new DataObjectImpl::StoredDataInfo(CF_UNICODETEXT
, storage
));
268 // Also add plain text.
269 storage
= GetStorageForString(WideToUTF8(data
));
270 data_
->contents_
.push_back(
271 new DataObjectImpl::StoredDataInfo(CF_TEXT
, storage
));
274 void OSExchangeDataProviderWin::SetURL(const GURL
& url
,
275 const std::wstring
& title
) {
277 // Every time you change the order of the first two CLIPFORMATS that get
278 // added here, you need to update the EnumerationViaCOM test case in
279 // the _unittest.cc file to reflect the new arrangement otherwise that test
280 // will fail! It assumes an insertion order.
282 // Add text/x-moz-url for drags from Firefox
283 std::wstring x_moz_url_str
= UTF8ToWide(url
.spec());
284 x_moz_url_str
+= '\n';
285 x_moz_url_str
+= title
;
286 STGMEDIUM
* storage
= GetStorageForWString(x_moz_url_str
);
287 data_
->contents_
.push_back(new DataObjectImpl::StoredDataInfo(
288 ClipboardUtil::GetMozUrlFormat()->cfFormat
, storage
));
290 // Add a .URL shortcut file for dragging to Explorer.
291 std::wstring valid_file_name
;
292 CreateValidFileNameFromTitle(url
, title
, &valid_file_name
);
293 std::string shortcut_url_file_contents
;
294 GetInternetShortcutFileContents(url
, &shortcut_url_file_contents
);
295 SetFileContents(valid_file_name
, shortcut_url_file_contents
);
297 // Add a UniformResourceLocator link for apps like IE and Word.
298 storage
= GetStorageForWString(UTF8ToWide(url
.spec()));
299 data_
->contents_
.push_back(new DataObjectImpl::StoredDataInfo(
300 ClipboardUtil::GetUrlWFormat()->cfFormat
, storage
));
301 storage
= GetStorageForString(url
.spec());
302 data_
->contents_
.push_back(new DataObjectImpl::StoredDataInfo(
303 ClipboardUtil::GetUrlFormat()->cfFormat
, storage
));
305 // TODO(beng): add CF_HTML.
306 // http://code.google.com/p/chromium/issues/detail?id=6767
308 // Also add text representations (these should be last since they're the
309 // least preferable).
310 storage
= GetStorageForWString(UTF8ToWide(url
.spec()));
311 data_
->contents_
.push_back(
312 new DataObjectImpl::StoredDataInfo(CF_UNICODETEXT
, storage
));
313 storage
= GetStorageForString(url
.spec());
314 data_
->contents_
.push_back(
315 new DataObjectImpl::StoredDataInfo(CF_TEXT
, storage
));
318 void OSExchangeDataProviderWin::SetFilename(const std::wstring
& full_path
) {
319 STGMEDIUM
* storage
= GetStorageForFileName(full_path
);
320 DataObjectImpl::StoredDataInfo
* info
=
321 new DataObjectImpl::StoredDataInfo(CF_HDROP
, storage
);
322 data_
->contents_
.push_back(info
);
325 void OSExchangeDataProviderWin::SetPickledData(CLIPFORMAT format
,
326 const Pickle
& data
) {
327 STGMEDIUM
* storage
= GetStorageForString(
328 std::string(static_cast<const char *>(data
.data()),
329 static_cast<size_t>(data
.size())));
330 data_
->contents_
.push_back(
331 new DataObjectImpl::StoredDataInfo(format
, storage
));
334 void OSExchangeDataProviderWin::SetFileContents(
335 const std::wstring
& filename
,
336 const std::string
& file_contents
) {
337 // Add CFSTR_FILEDESCRIPTOR
338 STGMEDIUM
* storage
= GetStorageForFileDescriptor(filename
);
339 data_
->contents_
.push_back(new DataObjectImpl::StoredDataInfo(
340 ClipboardUtil::GetFileDescriptorFormat()->cfFormat
, storage
));
342 // Add CFSTR_FILECONTENTS
343 storage
= GetStorageForBytes(file_contents
.data(), file_contents
.length());
344 data_
->contents_
.push_back(new DataObjectImpl::StoredDataInfo(
345 ClipboardUtil::GetFileContentFormatZero(), storage
));
348 void OSExchangeDataProviderWin::SetHtml(const std::wstring
& html
,
349 const GURL
& base_url
) {
350 // Add both MS CF_HTML and text/html format. CF_HTML should be in utf-8.
351 std::string utf8_html
= WideToUTF8(html
);
352 std::string url
= base_url
.is_valid() ? base_url
.spec() : std::string();
354 std::string cf_html
= ClipboardUtil::HtmlToCFHtml(utf8_html
, url
);
355 STGMEDIUM
* storage
= GetStorageForBytes(cf_html
.c_str(), cf_html
.size());
356 data_
->contents_
.push_back(new DataObjectImpl::StoredDataInfo(
357 ClipboardUtil::GetHtmlFormat()->cfFormat
, storage
));
359 STGMEDIUM
* storage_plain
= GetStorageForBytes(utf8_html
.c_str(),
361 data_
->contents_
.push_back(new DataObjectImpl::StoredDataInfo(
362 ClipboardUtil::GetTextHtmlFormat()->cfFormat
, storage_plain
));
365 bool OSExchangeDataProviderWin::GetString(std::wstring
* data
) const {
366 return ClipboardUtil::GetPlainText(source_object_
, data
);
369 bool OSExchangeDataProviderWin::GetURLAndTitle(GURL
* url
,
370 std::wstring
* title
) const {
371 std::wstring url_str
;
372 bool success
= ClipboardUtil::GetUrl(source_object_
, &url_str
, title
, true);
374 GURL
test_url(url_str
);
375 if (test_url
.is_valid()) {
379 } else if (GetPlainTextURL(source_object_
, url
)) {
386 bool OSExchangeDataProviderWin::GetFilename(std::wstring
* full_path
) const {
387 std::vector
<std::wstring
> filenames
;
388 bool success
= ClipboardUtil::GetFilenames(source_object_
, &filenames
);
390 full_path
->assign(filenames
[0]);
394 bool OSExchangeDataProviderWin::GetPickledData(CLIPFORMAT format
,
395 Pickle
* data
) const {
397 FORMATETC format_etc
=
398 { format
, NULL
, DVASPECT_CONTENT
, -1, TYMED_HGLOBAL
};
399 bool success
= false;
401 if (SUCCEEDED(source_object_
->GetData(&format_etc
, &medium
))) {
402 if (medium
.tymed
& TYMED_HGLOBAL
) {
403 ScopedHGlobal
<char> c_data(medium
.hGlobal
);
404 DCHECK(c_data
.Size() > 0);
405 // Need to subtract 1 as SetPickledData adds an extra byte to the end.
406 *data
= Pickle(c_data
.get(), static_cast<int>(c_data
.Size() - 1));
409 ReleaseStgMedium(&medium
);
414 bool OSExchangeDataProviderWin::GetFileContents(
415 std::wstring
* filename
,
416 std::string
* file_contents
) const {
417 return ClipboardUtil::GetFileContents(source_object_
, filename
,
421 bool OSExchangeDataProviderWin::GetHtml(std::wstring
* html
,
422 GURL
* base_url
) const {
424 bool success
= ClipboardUtil::GetHtml(source_object_
, html
, &url
);
426 *base_url
= GURL(url
);
430 bool OSExchangeDataProviderWin::HasString() const {
431 return ClipboardUtil::HasPlainText(source_object_
);
434 bool OSExchangeDataProviderWin::HasURL() const {
435 return (ClipboardUtil::HasUrl(source_object_
) ||
436 HasPlainTextURL(source_object_
));
439 bool OSExchangeDataProviderWin::HasFile() const {
440 return ClipboardUtil::HasFilenames(source_object_
);
443 bool OSExchangeDataProviderWin::HasFileContents() const {
444 return ClipboardUtil::HasFileContents(source_object_
);
447 bool OSExchangeDataProviderWin::HasHtml() const {
448 return ClipboardUtil::HasHtml(source_object_
);
451 bool OSExchangeDataProviderWin::HasCustomFormat(CLIPFORMAT format
) const {
452 FORMATETC format_etc
=
453 { format
, NULL
, DVASPECT_CONTENT
, -1, TYMED_HGLOBAL
};
454 return (source_object_
->QueryGetData(&format_etc
) == S_OK
);
457 void OSExchangeDataProviderWin::SetDownloadFileInfo(
458 const OSExchangeData::DownloadFileInfo
& download
) {
459 // If the filename is not provided, set stoarge to NULL to indicate that
460 // the delay rendering will be used.
461 STGMEDIUM
* storage
= NULL
;
462 if (!download
.filename
.empty())
463 storage
= GetStorageForFileName(download
.filename
.value());
466 DataObjectImpl::StoredDataInfo
* info
= new DataObjectImpl::StoredDataInfo(
467 ClipboardUtil::GetCFHDropFormat()->cfFormat
, storage
);
468 info
->downloader
= download
.downloader
;
469 data_
->contents_
.push_back(info
);
472 ///////////////////////////////////////////////////////////////////////////////
473 // DataObjectImpl, IDataObject implementation:
475 // The following function, DuplicateMedium, is derived from WCDataObject.cpp
476 // in the WebKit source code. This is the license information for the file:
478 * Copyright (C) 2007 Apple Inc. All rights reserved.
480 * Redistribution and use in source and binary forms, with or without
481 * modification, are permitted provided that the following conditions
483 * 1. Redistributions of source code must retain the above copyright
484 * notice, this list of conditions and the following disclaimer.
485 * 2. Redistributions in binary form must reproduce the above copyright
486 * notice, this list of conditions and the following disclaimer in the
487 * documentation and/or other materials provided with the distribution.
489 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
490 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
491 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
492 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
493 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
494 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
495 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
496 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
497 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
498 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
499 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
501 static void DuplicateMedium(CLIPFORMAT source_clipformat
,
503 STGMEDIUM
* destination
) {
504 switch (source
->tymed
) {
506 destination
->hGlobal
=
507 static_cast<HGLOBAL
>(OleDuplicateData(
508 source
->hGlobal
, source_clipformat
, 0));
511 destination
->hMetaFilePict
=
512 static_cast<HMETAFILEPICT
>(OleDuplicateData(
513 source
->hMetaFilePict
, source_clipformat
, 0));
516 destination
->hBitmap
=
517 static_cast<HBITMAP
>(OleDuplicateData(
518 source
->hBitmap
, source_clipformat
, 0));
521 destination
->hEnhMetaFile
=
522 static_cast<HENHMETAFILE
>(OleDuplicateData(
523 source
->hEnhMetaFile
, source_clipformat
, 0));
526 destination
->lpszFileName
=
527 static_cast<LPOLESTR
>(OleDuplicateData(
528 source
->lpszFileName
, source_clipformat
, 0));
531 destination
->pstm
= source
->pstm
;
532 destination
->pstm
->AddRef();
535 destination
->pstg
= source
->pstg
;
536 destination
->pstg
->AddRef();
540 destination
->tymed
= source
->tymed
;
541 destination
->pUnkForRelease
= source
->pUnkForRelease
;
542 if (destination
->pUnkForRelease
)
543 destination
->pUnkForRelease
->AddRef();
546 DataObjectImpl::DataObjectImpl()
547 : is_aborting_(false),
548 in_async_mode_(false),
549 async_operation_started_(false),
553 DataObjectImpl::~DataObjectImpl() {
555 STLDeleteContainerPointers(contents_
.begin(), contents_
.end());
557 observer_
->OnDataObjectDisposed();
560 void DataObjectImpl::StopDownloads() {
561 for (StoredData::iterator iter
= contents_
.begin();
562 iter
!= contents_
.end(); ++iter
) {
563 if ((*iter
)->downloader
.get()) {
564 (*iter
)->downloader
->Stop();
565 (*iter
)->downloader
= 0;
570 void DataObjectImpl::OnDownloadCompleted(const FilePath
& file_path
) {
571 CLIPFORMAT hdrop_format
= ClipboardUtil::GetCFHDropFormat()->cfFormat
;
572 DataObjectImpl::StoredData::iterator iter
= contents_
.begin();
573 for (; iter
!= contents_
.end(); ++iter
) {
574 if ((*iter
)->format_etc
.cfFormat
== hdrop_format
) {
575 // Release the old storage.
576 if ((*iter
)->owns_medium
) {
577 ReleaseStgMedium((*iter
)->medium
);
578 delete (*iter
)->medium
;
581 // Update the storage.
582 (*iter
)->owns_medium
= true;
583 (*iter
)->medium
= GetStorageForFileName(file_path
.value());
588 DCHECK(iter
!= contents_
.end());
591 void DataObjectImpl::OnDownloadAborted() {
594 HRESULT
DataObjectImpl::GetData(FORMATETC
* format_etc
, STGMEDIUM
* medium
) {
596 return DV_E_FORMATETC
;
598 StoredData::iterator iter
= contents_
.begin();
599 while (iter
!= contents_
.end()) {
600 if ((*iter
)->format_etc
.cfFormat
== format_etc
->cfFormat
&&
601 (*iter
)->format_etc
.lindex
== format_etc
->lindex
&&
602 ((*iter
)->format_etc
.tymed
& format_etc
->tymed
)) {
603 // If medium is NULL, delay-rendering will be used.
604 if ((*iter
)->medium
) {
605 DuplicateMedium((*iter
)->format_etc
.cfFormat
, (*iter
)->medium
, medium
);
607 // Check if the left button is down.
608 bool is_left_button_down
= (GetKeyState(VK_LBUTTON
) & 0x8000) != 0;
610 bool wait_for_data
= false;
611 if ((*iter
)->in_delay_rendering
) {
612 // Make sure the left button is up. Sometimes the drop target, like
613 // Shell, might be too aggresive in calling GetData when the left
614 // button is not released.
615 if (is_left_button_down
)
616 return DV_E_FORMATETC
;
618 // In async mode, we do not want to start waiting for the data before
619 // the async operation is started. This is because we want to postpone
620 // until Shell kicks off a background thread to do the work so that
621 // we do not block the UI thread.
622 if (!in_async_mode_
|| async_operation_started_
)
623 wait_for_data
= true;
625 // If the left button is up and the target has not requested the data
626 // yet, it probably means that the target does not support delay-
627 // rendering. So instead, we wait for the data.
628 if (is_left_button_down
) {
629 (*iter
)->in_delay_rendering
= true;
630 memset(medium
, 0, sizeof(STGMEDIUM
));
632 wait_for_data
= true;
637 return DV_E_FORMATETC
;
639 // Notify the observer we start waiting for the data. This gives
640 // an observer a chance to end the drag and drop.
642 observer_
->OnWaitForData();
644 // Now we can start the download.
645 if ((*iter
)->downloader
.get()) {
646 if (!(*iter
)->downloader
->Start(this)) {
648 return DV_E_FORMATETC
;
652 // The stored data should have been updated with the final version.
653 // So we just need to call this function again to retrieve it.
654 return GetData(format_etc
, medium
);
661 return DV_E_FORMATETC
;
664 HRESULT
DataObjectImpl::GetDataHere(FORMATETC
* format_etc
,
666 return DATA_E_FORMATETC
;
669 HRESULT
DataObjectImpl::QueryGetData(FORMATETC
* format_etc
) {
670 StoredData::const_iterator iter
= contents_
.begin();
671 while (iter
!= contents_
.end()) {
672 if ((*iter
)->format_etc
.cfFormat
== format_etc
->cfFormat
)
676 return DV_E_FORMATETC
;
679 HRESULT
DataObjectImpl::GetCanonicalFormatEtc(
680 FORMATETC
* format_etc
, FORMATETC
* result
) {
681 format_etc
->ptd
= NULL
;
685 HRESULT
DataObjectImpl::SetData(
686 FORMATETC
* format_etc
, STGMEDIUM
* medium
, BOOL should_release
) {
687 STGMEDIUM
* local_medium
= new STGMEDIUM
;
688 if (should_release
) {
689 *local_medium
= *medium
;
691 DuplicateMedium(format_etc
->cfFormat
, medium
, local_medium
);
694 DataObjectImpl::StoredDataInfo
* info
=
695 new DataObjectImpl::StoredDataInfo(format_etc
->cfFormat
, local_medium
);
696 info
->medium
->tymed
= format_etc
->tymed
;
697 info
->owns_medium
= !!should_release
;
698 contents_
.push_back(info
);
703 HRESULT
DataObjectImpl::EnumFormatEtc(
704 DWORD direction
, IEnumFORMATETC
** enumerator
) {
705 if (direction
== DATADIR_GET
) {
706 FormatEtcEnumerator
* e
=
707 new FormatEtcEnumerator(contents_
.begin(), contents_
.end());
715 HRESULT
DataObjectImpl::DAdvise(
716 FORMATETC
* format_etc
, DWORD advf
, IAdviseSink
* sink
, DWORD
* connection
) {
717 return OLE_E_ADVISENOTSUPPORTED
;
720 HRESULT
DataObjectImpl::DUnadvise(DWORD connection
) {
721 return OLE_E_ADVISENOTSUPPORTED
;
724 HRESULT
DataObjectImpl::EnumDAdvise(IEnumSTATDATA
** enumerator
) {
725 return OLE_E_ADVISENOTSUPPORTED
;
728 ///////////////////////////////////////////////////////////////////////////////
729 // DataObjectImpl, IAsyncOperation implementation:
731 HRESULT
DataObjectImpl::EndOperation(
732 HRESULT result
, IBindCtx
* reserved
, DWORD effects
) {
733 async_operation_started_
= false;
737 HRESULT
DataObjectImpl::GetAsyncMode(BOOL
* is_op_async
) {
738 *is_op_async
= in_async_mode_
? TRUE
: FALSE
;
742 HRESULT
DataObjectImpl::InOperation(BOOL
* in_async_op
) {
743 *in_async_op
= async_operation_started_
? TRUE
: FALSE
;
747 HRESULT
DataObjectImpl::SetAsyncMode(BOOL do_op_async
) {
748 in_async_mode_
= (do_op_async
== TRUE
);
752 HRESULT
DataObjectImpl::StartOperation(IBindCtx
* reserved
) {
753 async_operation_started_
= true;
757 ///////////////////////////////////////////////////////////////////////////////
758 // DataObjectImpl, IUnknown implementation:
760 HRESULT
DataObjectImpl::QueryInterface(const IID
& iid
, void** object
) {
763 if (IsEqualIID(iid
, IID_IDataObject
) || IsEqualIID(iid
, IID_IUnknown
)) {
764 *object
= static_cast<IDataObject
*>(this);
765 } else if (in_async_mode_
&& IsEqualIID(iid
, IID_IAsyncOperation
)) {
766 *object
= static_cast<IAsyncOperation
*>(this);
769 return E_NOINTERFACE
;
775 ULONG
DataObjectImpl::AddRef() {
776 base::RefCountedThreadSafe
<DownloadFileObserver
>::AddRef();
780 ULONG
DataObjectImpl::Release() {
781 base::RefCountedThreadSafe
<DownloadFileObserver
>::Release();
785 ///////////////////////////////////////////////////////////////////////////////
786 // DataObjectImpl, private:
788 static STGMEDIUM
* GetStorageForBytes(const char* data
, size_t bytes
) {
789 HANDLE handle
= GlobalAlloc(GPTR
, static_cast<int>(bytes
));
790 ScopedHGlobal
<char> scoped(handle
);
791 size_t allocated
= static_cast<size_t>(GlobalSize(handle
));
792 memcpy(scoped
.get(), data
, allocated
);
794 STGMEDIUM
* storage
= new STGMEDIUM
;
795 storage
->hGlobal
= handle
;
796 storage
->tymed
= TYMED_HGLOBAL
;
797 storage
->pUnkForRelease
= NULL
;
802 static HGLOBAL
CopyStringToGlobalHandle(const T
& payload
) {
803 int bytes
= static_cast<int>(payload
.size() + 1) * sizeof(T::value_type
);
804 HANDLE handle
= GlobalAlloc(GPTR
, bytes
);
805 void* data
= GlobalLock(handle
);
806 size_t allocated
= static_cast<size_t>(GlobalSize(handle
));
807 memcpy(data
, payload
.c_str(), allocated
);
808 static_cast<T::value_type
*>(data
)[payload
.size()] = '\0';
809 GlobalUnlock(handle
);
813 static STGMEDIUM
* GetStorageForWString(const std::wstring
& data
) {
814 STGMEDIUM
* storage
= new STGMEDIUM
;
815 storage
->hGlobal
= CopyStringToGlobalHandle
<std::wstring
>(data
);
816 storage
->tymed
= TYMED_HGLOBAL
;
817 storage
->pUnkForRelease
= NULL
;
821 static STGMEDIUM
* GetStorageForString(const std::string
& data
) {
822 STGMEDIUM
* storage
= new STGMEDIUM
;
823 storage
->hGlobal
= CopyStringToGlobalHandle
<std::string
>(data
);
824 storage
->tymed
= TYMED_HGLOBAL
;
825 storage
->pUnkForRelease
= NULL
;
829 static void GetInternetShortcutFileContents(const GURL
& url
,
832 static const std::string kInternetShortcutFileStart
=
833 "[InternetShortcut]\r\nURL=";
834 static const std::string kInternetShortcutFileEnd
=
836 *data
= kInternetShortcutFileStart
+ url
.spec() + kInternetShortcutFileEnd
;
839 static void CreateValidFileNameFromTitle(const GURL
& url
,
840 const std::wstring
& title
,
841 std::wstring
* validated
) {
843 if (url
.is_valid()) {
844 *validated
= net::GetSuggestedFilename(
845 url
, std::string(), std::string(), FilePath()).ToWStringHack();
847 // Nothing else can be done, just use a default.
848 *validated
= l10n_util::GetString(IDS_APP_UNTITLED_SHORTCUT_FILE_NAME
);
852 file_util::ReplaceIllegalCharactersInPath(validated
, '-');
854 static const wchar_t extension
[] = L
".url";
855 static const size_t max_length
= MAX_PATH
- arraysize(extension
);
856 if (validated
->size() > max_length
)
857 validated
->erase(max_length
);
858 *validated
+= extension
;
861 static STGMEDIUM
* GetStorageForFileName(const std::wstring
& full_path
) {
862 const size_t kDropSize
= sizeof(DROPFILES
);
863 const size_t kTotalBytes
=
864 kDropSize
+ (full_path
.length() + 2) * sizeof(wchar_t);
865 HANDLE hdata
= GlobalAlloc(GMEM_MOVEABLE
, kTotalBytes
);
867 ScopedHGlobal
<DROPFILES
> locked_mem(hdata
);
868 DROPFILES
* drop_files
= locked_mem
.get();
869 drop_files
->pFiles
= sizeof(DROPFILES
);
870 drop_files
->fWide
= TRUE
;
871 wchar_t* data
= reinterpret_cast<wchar_t*>(
872 reinterpret_cast<BYTE
*>(drop_files
) + kDropSize
);
873 const size_t copy_size
= (full_path
.length() + 1) * sizeof(wchar_t);
874 memcpy(data
, full_path
.c_str(), copy_size
);
875 data
[full_path
.length() + 1] = L
'\0'; // Double NULL
877 STGMEDIUM
* storage
= new STGMEDIUM
;
878 storage
->tymed
= TYMED_HGLOBAL
;
879 storage
->hGlobal
= drop_files
;
880 storage
->pUnkForRelease
= NULL
;
884 static STGMEDIUM
* GetStorageForFileDescriptor(
885 const std::wstring
& valid_file_name
) {
886 DCHECK(!valid_file_name
.empty() && valid_file_name
.size() + 1 <= MAX_PATH
);
887 HANDLE handle
= GlobalAlloc(GPTR
, sizeof(FILEGROUPDESCRIPTOR
));
888 FILEGROUPDESCRIPTOR
* descriptor
=
889 reinterpret_cast<FILEGROUPDESCRIPTOR
*>(GlobalLock(handle
));
891 descriptor
->cItems
= 1;
892 wcscpy_s(descriptor
->fgd
[0].cFileName
,
893 valid_file_name
.size() + 1,
894 valid_file_name
.c_str());
895 descriptor
->fgd
[0].dwFlags
= FD_LINKUI
;
897 GlobalUnlock(handle
);
899 STGMEDIUM
* storage
= new STGMEDIUM
;
900 storage
->hGlobal
= handle
;
901 storage
->tymed
= TYMED_HGLOBAL
;
902 storage
->pUnkForRelease
= NULL
;
907 ///////////////////////////////////////////////////////////////////////////////
908 // OSExchangeData, public:
911 OSExchangeData::Provider
* OSExchangeData::CreateProvider() {
912 return new OSExchangeDataProviderWin();
916 OSExchangeData::CustomFormat
OSExchangeData::RegisterCustomFormat(
917 const std::string
& type
) {
918 return RegisterClipboardFormat(ASCIIToWide(type
).c_str());