forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnsDataObj.cpp
2165 lines (1814 loc) · 66.4 KB
/
nsDataObj.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/ArrayUtils.h"
#include <ole2.h>
#include <shlobj.h>
#include "nsDataObj.h"
#include "nsClipboard.h"
#include "nsReadableUtils.h"
#include "nsITransferable.h"
#include "nsISupportsPrimitives.h"
#include "IEnumFE.h"
#include "nsPrimitiveHelpers.h"
#include "nsXPIDLString.h"
#include "nsImageClipboard.h"
#include "nsCRT.h"
#include "nsPrintfCString.h"
#include "nsIStringBundle.h"
#include "nsEscape.h"
#include "nsIURL.h"
#include "nsNetUtil.h"
#include "mozilla/Services.h"
#include "nsIOutputStream.h"
#include "nsXPCOMStrings.h"
#include "nscore.h"
#include "nsDirectoryServiceDefs.h"
#include "nsITimer.h"
#include "nsThreadUtils.h"
#include "mozilla/Preferences.h"
#include "nsIContentPolicy.h"
#include "nsContentUtils.h"
#include "nsINode.h"
#include "WinUtils.h"
#include "mozilla/LazyIdleThread.h"
#include "mozilla/WindowsVersion.h"
#include <algorithm>
using namespace mozilla;
using namespace mozilla::widget;
#define DEFAULT_THREAD_TIMEOUT_MS 30000
NS_IMPL_ISUPPORTS(nsDataObj::CStream, nsIStreamListener)
//-----------------------------------------------------------------------------
// CStream implementation
nsDataObj::CStream::CStream() :
mChannelRead(false),
mStreamRead(0)
{
}
//-----------------------------------------------------------------------------
nsDataObj::CStream::~CStream()
{
}
//-----------------------------------------------------------------------------
// helper - initializes the stream
nsresult nsDataObj::CStream::Init(nsIURI *pSourceURI,
uint32_t aContentPolicyType,
nsINode* aRequestingNode)
{
// we can not create a channel without a requestingNode
if (!aRequestingNode) {
return NS_ERROR_FAILURE;
}
nsresult rv;
rv = NS_NewChannel(getter_AddRefs(mChannel),
pSourceURI,
aRequestingNode,
nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS,
aContentPolicyType,
nullptr, // loadGroup
nullptr, // aCallbacks
nsIRequest::LOAD_FROM_CACHE);
NS_ENSURE_SUCCESS(rv, rv);
rv = mChannel->AsyncOpen2(this);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
//-----------------------------------------------------------------------------
// IUnknown's QueryInterface, nsISupport's AddRef and Release are shared by
// IUnknown and nsIStreamListener.
STDMETHODIMP nsDataObj::CStream::QueryInterface(REFIID refiid, void** ppvResult)
{
*ppvResult = nullptr;
if (IID_IUnknown == refiid ||
refiid == IID_IStream)
{
*ppvResult = this;
}
if (nullptr != *ppvResult)
{
((LPUNKNOWN)*ppvResult)->AddRef();
return S_OK;
}
return E_NOINTERFACE;
}
// nsIStreamListener implementation
NS_IMETHODIMP
nsDataObj::CStream::OnDataAvailable(nsIRequest *aRequest,
nsISupports *aContext,
nsIInputStream *aInputStream,
uint64_t aOffset, // offset within the stream
uint32_t aCount) // bytes available on this call
{
// Extend the write buffer for the incoming data.
uint8_t* buffer = mChannelData.AppendElements(aCount);
if (buffer == nullptr)
return NS_ERROR_OUT_OF_MEMORY;
NS_ASSERTION((mChannelData.Length() == (aOffset + aCount)),
"stream length mismatch w/write buffer");
// Read() may not return aCount on a single call, so loop until we've
// accumulated all the data OnDataAvailable has promised.
nsresult rv;
uint32_t odaBytesReadTotal = 0;
do {
uint32_t bytesReadByCall = 0;
rv = aInputStream->Read((char*)(buffer + odaBytesReadTotal),
aCount, &bytesReadByCall);
odaBytesReadTotal += bytesReadByCall;
} while (aCount < odaBytesReadTotal && NS_SUCCEEDED(rv));
return rv;
}
NS_IMETHODIMP nsDataObj::CStream::OnStartRequest(nsIRequest *aRequest,
nsISupports *aContext)
{
mChannelResult = NS_OK;
return NS_OK;
}
NS_IMETHODIMP nsDataObj::CStream::OnStopRequest(nsIRequest *aRequest,
nsISupports *aContext,
nsresult aStatusCode)
{
mChannelRead = true;
mChannelResult = aStatusCode;
return NS_OK;
}
// Pumps thread messages while waiting for the async listener operation to
// complete. Failing this call will fail the stream incall from Windows
// and cancel the operation.
nsresult nsDataObj::CStream::WaitForCompletion()
{
// We are guaranteed OnStopRequest will get called, so this should be ok.
while (!mChannelRead) {
// Pump messages
NS_ProcessNextEvent(nullptr, true);
}
if (!mChannelData.Length())
mChannelResult = NS_ERROR_FAILURE;
return mChannelResult;
}
//-----------------------------------------------------------------------------
// IStream
STDMETHODIMP nsDataObj::CStream::Clone(IStream** ppStream)
{
return E_NOTIMPL;
}
//-----------------------------------------------------------------------------
STDMETHODIMP nsDataObj::CStream::Commit(DWORD dwFrags)
{
return E_NOTIMPL;
}
//-----------------------------------------------------------------------------
STDMETHODIMP nsDataObj::CStream::CopyTo(IStream* pDestStream,
ULARGE_INTEGER nBytesToCopy,
ULARGE_INTEGER* nBytesRead,
ULARGE_INTEGER* nBytesWritten)
{
return E_NOTIMPL;
}
//-----------------------------------------------------------------------------
STDMETHODIMP nsDataObj::CStream::LockRegion(ULARGE_INTEGER nStart,
ULARGE_INTEGER nBytes,
DWORD dwFlags)
{
return E_NOTIMPL;
}
//-----------------------------------------------------------------------------
STDMETHODIMP nsDataObj::CStream::Read(void* pvBuffer,
ULONG nBytesToRead,
ULONG* nBytesRead)
{
// Wait for the write into our buffer to complete via the stream listener.
// We can't respond to this by saying "call us back later".
if (NS_FAILED(WaitForCompletion()))
return E_FAIL;
// Bytes left for Windows to read out of our buffer
ULONG bytesLeft = mChannelData.Length() - mStreamRead;
// Let Windows know what we will hand back, usually this is the entire buffer
*nBytesRead = std::min(bytesLeft, nBytesToRead);
// Copy the buffer data over
memcpy(pvBuffer, ((char*)mChannelData.Elements() + mStreamRead), *nBytesRead);
// Update our bytes read tracking
mStreamRead += *nBytesRead;
return S_OK;
}
//-----------------------------------------------------------------------------
STDMETHODIMP nsDataObj::CStream::Revert(void)
{
return E_NOTIMPL;
}
//-----------------------------------------------------------------------------
STDMETHODIMP nsDataObj::CStream::Seek(LARGE_INTEGER nMove,
DWORD dwOrigin,
ULARGE_INTEGER* nNewPos)
{
if (nNewPos == nullptr)
return STG_E_INVALIDPOINTER;
if (nMove.LowPart == 0 && nMove.HighPart == 0 &&
(dwOrigin == STREAM_SEEK_SET || dwOrigin == STREAM_SEEK_CUR)) {
nNewPos->LowPart = 0;
nNewPos->HighPart = 0;
return S_OK;
}
return E_NOTIMPL;
}
//-----------------------------------------------------------------------------
STDMETHODIMP nsDataObj::CStream::SetSize(ULARGE_INTEGER nNewSize)
{
return E_NOTIMPL;
}
//-----------------------------------------------------------------------------
STDMETHODIMP nsDataObj::CStream::Stat(STATSTG* statstg, DWORD dwFlags)
{
if (statstg == nullptr)
return STG_E_INVALIDPOINTER;
if (!mChannel || NS_FAILED(WaitForCompletion()))
return E_FAIL;
memset((void*)statstg, 0, sizeof(STATSTG));
if (dwFlags != STATFLAG_NONAME)
{
nsCOMPtr<nsIURI> sourceURI;
if (NS_FAILED(mChannel->GetURI(getter_AddRefs(sourceURI)))) {
return E_FAIL;
}
nsAutoCString strFileName;
nsCOMPtr<nsIURL> sourceURL = do_QueryInterface(sourceURI);
sourceURL->GetFileName(strFileName);
if (strFileName.IsEmpty())
return E_FAIL;
NS_UnescapeURL(strFileName);
NS_ConvertUTF8toUTF16 wideFileName(strFileName);
uint32_t nMaxNameLength = (wideFileName.Length()*2) + 2;
void * retBuf = CoTaskMemAlloc(nMaxNameLength); // freed by caller
if (!retBuf)
return STG_E_INSUFFICIENTMEMORY;
ZeroMemory(retBuf, nMaxNameLength);
memcpy(retBuf, wideFileName.get(), wideFileName.Length()*2);
statstg->pwcsName = (LPOLESTR)retBuf;
}
SYSTEMTIME st;
statstg->type = STGTY_STREAM;
GetSystemTime(&st);
SystemTimeToFileTime((const SYSTEMTIME*)&st, (LPFILETIME)&statstg->mtime);
statstg->ctime = statstg->atime = statstg->mtime;
statstg->cbSize.LowPart = (DWORD)mChannelData.Length();
statstg->grfMode = STGM_READ;
statstg->grfLocksSupported = LOCK_ONLYONCE;
statstg->clsid = CLSID_NULL;
return S_OK;
}
//-----------------------------------------------------------------------------
STDMETHODIMP nsDataObj::CStream::UnlockRegion(ULARGE_INTEGER nStart,
ULARGE_INTEGER nBytes,
DWORD dwFlags)
{
return E_NOTIMPL;
}
//-----------------------------------------------------------------------------
STDMETHODIMP nsDataObj::CStream::Write(const void* pvBuffer,
ULONG nBytesToRead,
ULONG* nBytesRead)
{
return E_NOTIMPL;
}
//-----------------------------------------------------------------------------
HRESULT nsDataObj::CreateStream(IStream **outStream)
{
NS_ENSURE_TRUE(outStream, E_INVALIDARG);
nsresult rv = NS_ERROR_FAILURE;
nsAutoString wideFileName;
nsCOMPtr<nsIURI> sourceURI;
HRESULT res;
res = GetDownloadDetails(getter_AddRefs(sourceURI),
wideFileName);
if(FAILED(res))
return res;
nsDataObj::CStream *pStream = new nsDataObj::CStream();
NS_ENSURE_TRUE(pStream, E_OUTOFMEMORY);
pStream->AddRef();
// query the requestingNode from the transferable and add it to the new channel
nsCOMPtr<nsIDOMNode> requestingDomNode;
mTransferable->GetRequestingNode(getter_AddRefs(requestingDomNode));
nsCOMPtr<nsINode> requestingNode = do_QueryInterface(requestingDomNode);
MOZ_ASSERT(requestingNode, "can not create channel without a node");
// default transferable content policy is nsIContentPolicy::TYPE_OTHER
uint32_t contentPolicyType = nsIContentPolicy::TYPE_OTHER;
mTransferable->GetContentPolicyType(&contentPolicyType);
rv = pStream->Init(sourceURI, contentPolicyType, requestingNode);
if (NS_FAILED(rv))
{
pStream->Release();
return E_FAIL;
}
*outStream = pStream;
return S_OK;
}
static GUID CLSID_nsDataObj =
{ 0x1bba7640, 0xdf52, 0x11cf, { 0x82, 0x7b, 0, 0xa0, 0x24, 0x3a, 0xe5, 0x05 } };
/*
* deliberately not using MAX_PATH. This is because on platforms < XP
* a file created with a long filename may be mishandled by the shell
* resulting in it not being able to be deleted or moved.
* See bug 250392 for more details.
*/
#define NS_MAX_FILEDESCRIPTOR 128 + 1
/*
* Class nsDataObj
*/
//-----------------------------------------------------
// construction
//-----------------------------------------------------
nsDataObj::nsDataObj(nsIURI * uri)
: m_cRef(0), mTransferable(nullptr),
mIsAsyncMode(FALSE), mIsInOperation(FALSE)
{
mIOThread = new LazyIdleThread(DEFAULT_THREAD_TIMEOUT_MS,
NS_LITERAL_CSTRING("nsDataObj"),
LazyIdleThread::ManualShutdown);
m_enumFE = new CEnumFormatEtc();
m_enumFE->AddRef();
if (uri) {
// A URI was obtained, so pass this through to the DataObject
// so it can create a SourceURL for CF_HTML flavour
uri->GetSpec(mSourceURL);
}
}
//-----------------------------------------------------
// destruction
//-----------------------------------------------------
nsDataObj::~nsDataObj()
{
NS_IF_RELEASE(mTransferable);
mDataFlavors.Clear();
m_enumFE->Release();
// Free arbitrary system formats
for (uint32_t idx = 0; idx < mDataEntryList.Length(); idx++) {
CoTaskMemFree(mDataEntryList[idx]->fe.ptd);
ReleaseStgMedium(&mDataEntryList[idx]->stgm);
CoTaskMemFree(mDataEntryList[idx]);
}
}
//-----------------------------------------------------
// IUnknown interface methods - see inknown.h for documentation
//-----------------------------------------------------
STDMETHODIMP nsDataObj::QueryInterface(REFIID riid, void** ppv)
{
*ppv=nullptr;
if ( (IID_IUnknown == riid) || (IID_IDataObject == riid) ) {
*ppv = this;
AddRef();
return S_OK;
} else if (IID_IAsyncOperation == riid) {
*ppv = static_cast<IAsyncOperation*>(this);
AddRef();
return S_OK;
}
return E_NOINTERFACE;
}
//-----------------------------------------------------
STDMETHODIMP_(ULONG) nsDataObj::AddRef()
{
++m_cRef;
NS_LOG_ADDREF(this, m_cRef, "nsDataObj", sizeof(*this));
return m_cRef;
}
//-----------------------------------------------------
STDMETHODIMP_(ULONG) nsDataObj::Release()
{
--m_cRef;
NS_LOG_RELEASE(this, m_cRef, "nsDataObj");
if (0 != m_cRef)
return m_cRef;
// We have released our last ref on this object and need to delete the
// temp file. External app acting as drop target may still need to open the
// temp file. Addref a timer so it can delay deleting file and destroying
// this object. Delete file anyway and destroy this obj if there's a problem.
if (mCachedTempFile) {
nsresult rv;
mTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
mTimer->InitWithFuncCallback(nsDataObj::RemoveTempFile, this,
500, nsITimer::TYPE_ONE_SHOT);
return AddRef();
}
mCachedTempFile->Remove(false);
mCachedTempFile = nullptr;
}
delete this;
return 0;
}
//-----------------------------------------------------
BOOL nsDataObj::FormatsMatch(const FORMATETC& source, const FORMATETC& target) const
{
if ((source.cfFormat == target.cfFormat) &&
(source.dwAspect & target.dwAspect) &&
(source.tymed & target.tymed)) {
return TRUE;
} else {
return FALSE;
}
}
//-----------------------------------------------------
// IDataObject methods
//-----------------------------------------------------
STDMETHODIMP nsDataObj::GetData(LPFORMATETC aFormat, LPSTGMEDIUM pSTM)
{
if (!mTransferable)
return DV_E_FORMATETC;
uint32_t dfInx = 0;
static CLIPFORMAT fileDescriptorFlavorA = ::RegisterClipboardFormat( CFSTR_FILEDESCRIPTORA );
static CLIPFORMAT fileDescriptorFlavorW = ::RegisterClipboardFormat( CFSTR_FILEDESCRIPTORW );
static CLIPFORMAT uniformResourceLocatorA = ::RegisterClipboardFormat( CFSTR_INETURLA );
static CLIPFORMAT uniformResourceLocatorW = ::RegisterClipboardFormat( CFSTR_INETURLW );
static CLIPFORMAT fileFlavor = ::RegisterClipboardFormat( CFSTR_FILECONTENTS );
static CLIPFORMAT PreferredDropEffect = ::RegisterClipboardFormat( CFSTR_PREFERREDDROPEFFECT );
// Arbitrary system formats are used for image feedback during drag
// and drop. We are responsible for storing these internally during
// drag operations.
LPDATAENTRY pde;
if (LookupArbitraryFormat(aFormat, &pde, FALSE)) {
return CopyMediumData(pSTM, &pde->stgm, aFormat, FALSE)
? S_OK : E_UNEXPECTED;
}
// Firefox internal formats
ULONG count;
FORMATETC fe;
m_enumFE->Reset();
while (NOERROR == m_enumFE->Next(1, &fe, &count)
&& dfInx < mDataFlavors.Length()) {
nsCString& df = mDataFlavors.ElementAt(dfInx);
if (FormatsMatch(fe, *aFormat)) {
pSTM->pUnkForRelease = nullptr; // caller is responsible for deleting this data
CLIPFORMAT format = aFormat->cfFormat;
switch(format) {
// Someone is asking for plain or unicode text
case CF_TEXT:
case CF_UNICODETEXT:
return GetText(df, *aFormat, *pSTM);
// Some 3rd party apps that receive drag and drop files from the browser
// window require support for this.
case CF_HDROP:
return GetFile(*aFormat, *pSTM);
// Someone is asking for an image
case CF_DIBV5:
case CF_DIB:
return GetDib(df, *aFormat, *pSTM);
default:
if ( format == fileDescriptorFlavorA )
return GetFileDescriptor ( *aFormat, *pSTM, false );
if ( format == fileDescriptorFlavorW )
return GetFileDescriptor ( *aFormat, *pSTM, true);
if ( format == uniformResourceLocatorA )
return GetUniformResourceLocator( *aFormat, *pSTM, false);
if ( format == uniformResourceLocatorW )
return GetUniformResourceLocator( *aFormat, *pSTM, true);
if ( format == fileFlavor )
return GetFileContents ( *aFormat, *pSTM );
if ( format == PreferredDropEffect )
return GetPreferredDropEffect( *aFormat, *pSTM );
//MOZ_LOG(gWindowsLog, LogLevel::Info,
// ("***** nsDataObj::GetData - Unknown format %u\n", format));
return GetText(df, *aFormat, *pSTM);
} //switch
} // if
dfInx++;
} // while
return DATA_E_FORMATETC;
}
//-----------------------------------------------------
STDMETHODIMP nsDataObj::GetDataHere(LPFORMATETC pFE, LPSTGMEDIUM pSTM)
{
return E_FAIL;
}
//-----------------------------------------------------
// Other objects querying to see if we support a
// particular format
//-----------------------------------------------------
STDMETHODIMP nsDataObj::QueryGetData(LPFORMATETC pFE)
{
// Arbitrary system formats are used for image feedback during drag
// and drop. We are responsible for storing these internally during
// drag operations.
LPDATAENTRY pde;
if (LookupArbitraryFormat(pFE, &pde, FALSE))
return S_OK;
// Firefox internal formats
ULONG count;
FORMATETC fe;
m_enumFE->Reset();
while (NOERROR == m_enumFE->Next(1, &fe, &count)) {
if (fe.cfFormat == pFE->cfFormat) {
return S_OK;
}
}
return E_FAIL;
}
//-----------------------------------------------------
STDMETHODIMP nsDataObj::GetCanonicalFormatEtc
(LPFORMATETC pFEIn, LPFORMATETC pFEOut)
{
return E_NOTIMPL;
}
//-----------------------------------------------------
STDMETHODIMP nsDataObj::SetData(LPFORMATETC aFormat, LPSTGMEDIUM aMedium, BOOL shouldRel)
{
// Arbitrary system formats are used for image feedback during drag
// and drop. We are responsible for storing these internally during
// drag operations.
LPDATAENTRY pde;
if (LookupArbitraryFormat(aFormat, &pde, TRUE)) {
// Release the old data the lookup handed us for this format. This
// may have been set in CopyMediumData when we originally stored the
// data.
if (pde->stgm.tymed) {
ReleaseStgMedium(&pde->stgm);
memset(&pde->stgm, 0, sizeof(STGMEDIUM));
}
bool result = true;
if (shouldRel) {
// If shouldRel is TRUE, the data object called owns the storage medium
// after the call returns. Store the incoming data in our data array for
// release when we are destroyed. This is the common case with arbitrary
// data from explorer.
pde->stgm = *aMedium;
} else {
// Copy the incoming data into our data array. (AFAICT, this never gets
// called with arbitrary formats for drag images.)
result = CopyMediumData(&pde->stgm, aMedium, aFormat, TRUE);
}
pde->fe.tymed = pde->stgm.tymed;
return result ? S_OK : DV_E_TYMED;
}
if (shouldRel)
ReleaseStgMedium(aMedium);
return S_OK;
}
bool
nsDataObj::LookupArbitraryFormat(FORMATETC *aFormat, LPDATAENTRY *aDataEntry, BOOL aAddorUpdate)
{
*aDataEntry = nullptr;
if (aFormat->ptd != nullptr)
return false;
// See if it's already in our list. If so return the data entry.
for (uint32_t idx = 0; idx < mDataEntryList.Length(); idx++) {
if (mDataEntryList[idx]->fe.cfFormat == aFormat->cfFormat &&
mDataEntryList[idx]->fe.dwAspect == aFormat->dwAspect &&
mDataEntryList[idx]->fe.lindex == aFormat->lindex) {
if (aAddorUpdate || (mDataEntryList[idx]->fe.tymed & aFormat->tymed)) {
// If the caller requests we update, or if the
// medium type matches, return the entry.
*aDataEntry = mDataEntryList[idx];
return true;
} else {
// Medium does not match, not found.
return false;
}
}
}
if (!aAddorUpdate)
return false;
// Add another entry to mDataEntryList
LPDATAENTRY dataEntry = (LPDATAENTRY)CoTaskMemAlloc(sizeof(DATAENTRY));
if (!dataEntry)
return false;
dataEntry->fe = *aFormat;
*aDataEntry = dataEntry;
memset(&dataEntry->stgm, 0, sizeof(STGMEDIUM));
// Add this to our IEnumFORMATETC impl. so we can return it when
// it's requested.
m_enumFE->AddFormatEtc(aFormat);
// Store a copy internally in the arbitrary formats array.
mDataEntryList.AppendElement(dataEntry);
return true;
}
bool
nsDataObj::CopyMediumData(STGMEDIUM *aMediumDst, STGMEDIUM *aMediumSrc, LPFORMATETC aFormat, BOOL aSetData)
{
STGMEDIUM stgmOut = *aMediumSrc;
switch (stgmOut.tymed) {
case TYMED_ISTREAM:
stgmOut.pstm->AddRef();
break;
case TYMED_ISTORAGE:
stgmOut.pstg->AddRef();
break;
case TYMED_HGLOBAL:
if (!aMediumSrc->pUnkForRelease) {
if (aSetData) {
if (aMediumSrc->tymed != TYMED_HGLOBAL)
return false;
stgmOut.hGlobal = OleDuplicateData(aMediumSrc->hGlobal, aFormat->cfFormat, 0);
if (!stgmOut.hGlobal)
return false;
} else {
// We are returning this data from LookupArbitraryFormat, indicate to the
// shell we hold it and will free it.
stgmOut.pUnkForRelease = static_cast<IDataObject*>(this);
}
}
break;
default:
return false;
}
if (stgmOut.pUnkForRelease)
stgmOut.pUnkForRelease->AddRef();
*aMediumDst = stgmOut;
return true;
}
//-----------------------------------------------------
STDMETHODIMP nsDataObj::EnumFormatEtc(DWORD dwDir, LPENUMFORMATETC *ppEnum)
{
switch (dwDir) {
case DATADIR_GET:
m_enumFE->Clone(ppEnum);
break;
case DATADIR_SET:
// fall through
default:
*ppEnum = nullptr;
} // switch
if (nullptr == *ppEnum)
return E_FAIL;
(*ppEnum)->Reset();
// Clone already AddRefed the result so don't addref it again.
return NOERROR;
}
//-----------------------------------------------------
STDMETHODIMP nsDataObj::DAdvise(LPFORMATETC pFE, DWORD dwFlags,
LPADVISESINK pIAdviseSink, DWORD* pdwConn)
{
return OLE_E_ADVISENOTSUPPORTED;
}
//-----------------------------------------------------
STDMETHODIMP nsDataObj::DUnadvise(DWORD dwConn)
{
return OLE_E_ADVISENOTSUPPORTED;
}
//-----------------------------------------------------
STDMETHODIMP nsDataObj::EnumDAdvise(LPENUMSTATDATA *ppEnum)
{
return OLE_E_ADVISENOTSUPPORTED;
}
// IAsyncOperation methods
STDMETHODIMP nsDataObj::EndOperation(HRESULT hResult,
IBindCtx *pbcReserved,
DWORD dwEffects)
{
mIsInOperation = FALSE;
return S_OK;
}
STDMETHODIMP nsDataObj::GetAsyncMode(BOOL *pfIsOpAsync)
{
*pfIsOpAsync = mIsAsyncMode;
return S_OK;
}
STDMETHODIMP nsDataObj::InOperation(BOOL *pfInAsyncOp)
{
*pfInAsyncOp = mIsInOperation;
return S_OK;
}
STDMETHODIMP nsDataObj::SetAsyncMode(BOOL fDoOpAsync)
{
mIsAsyncMode = fDoOpAsync;
return S_OK;
}
STDMETHODIMP nsDataObj::StartOperation(IBindCtx *pbcReserved)
{
mIsInOperation = TRUE;
return S_OK;
}
//-----------------------------------------------------
// GetData and SetData helper functions
//-----------------------------------------------------
HRESULT nsDataObj::AddSetFormat(FORMATETC& aFE)
{
return S_OK;
}
//-----------------------------------------------------
HRESULT nsDataObj::AddGetFormat(FORMATETC& aFE)
{
return S_OK;
}
//
// GetDIB
//
// Someone is asking for a bitmap. The data in the transferable will be a straight
// imgIContainer, so just QI it.
//
HRESULT
nsDataObj::GetDib(const nsACString& inFlavor,
FORMATETC &aFormat,
STGMEDIUM & aSTG)
{
ULONG result = E_FAIL;
uint32_t len = 0;
nsCOMPtr<nsISupports> genericDataWrapper;
mTransferable->GetTransferData(PromiseFlatCString(inFlavor).get(), getter_AddRefs(genericDataWrapper), &len);
nsCOMPtr<imgIContainer> image ( do_QueryInterface(genericDataWrapper) );
if ( !image ) {
// Check if the image was put in an nsISupportsInterfacePointer wrapper.
// This might not be necessary any more, but could be useful for backwards
// compatibility.
nsCOMPtr<nsISupportsInterfacePointer> ptr(do_QueryInterface(genericDataWrapper));
if ( ptr ) {
nsCOMPtr<nsISupports> supports;
ptr->GetData(getter_AddRefs(supports));
image = do_QueryInterface(supports);
}
}
if ( image ) {
// use the |nsImageToClipboard| helper class to build up a bitmap. We now own
// the bits, and pass them back to the OS in |aSTG|.
nsImageToClipboard converter(image, aFormat.cfFormat == CF_DIBV5);
HANDLE bits = nullptr;
nsresult rv = converter.GetPicture ( &bits );
if ( NS_SUCCEEDED(rv) && bits ) {
aSTG.hGlobal = bits;
aSTG.tymed = TYMED_HGLOBAL;
result = S_OK;
}
} // if we have an image
else
NS_WARNING ( "Definitely not an image on clipboard" );
return result;
}
//
// GetFileDescriptor
//
HRESULT
nsDataObj :: GetFileDescriptor ( FORMATETC& aFE, STGMEDIUM& aSTG, bool aIsUnicode )
{
HRESULT res = S_OK;
// How we handle this depends on if we're dealing with an internet
// shortcut, since those are done under the covers.
if (IsFlavourPresent(kFilePromiseMime) ||
IsFlavourPresent(kFileMime))
{
if (aIsUnicode)
return GetFileDescriptor_IStreamW(aFE, aSTG);
else
return GetFileDescriptor_IStreamA(aFE, aSTG);
}
else if (IsFlavourPresent(kURLMime))
{
if ( aIsUnicode )
res = GetFileDescriptorInternetShortcutW ( aFE, aSTG );
else
res = GetFileDescriptorInternetShortcutA ( aFE, aSTG );
}
else
NS_WARNING ( "Not yet implemented\n" );
return res;
} // GetFileDescriptor
//
HRESULT
nsDataObj :: GetFileContents ( FORMATETC& aFE, STGMEDIUM& aSTG )
{
HRESULT res = S_OK;
// How we handle this depends on if we're dealing with an internet
// shortcut, since those are done under the covers.
if (IsFlavourPresent(kFilePromiseMime) ||
IsFlavourPresent(kFileMime))
return GetFileContents_IStream(aFE, aSTG);
else if (IsFlavourPresent(kURLMime))
return GetFileContentsInternetShortcut ( aFE, aSTG );
else
NS_WARNING ( "Not yet implemented\n" );
return res;
} // GetFileContents
//
// Given a unicode string, we ensure that it contains only characters which are valid within
// the file system. Remove all forbidden characters from the name, and completely disallow
// any title that starts with a forbidden name and extension (e.g. "nul" is invalid, but
// "nul." and "nul.txt" are also invalid and will cause problems).
//
// It would seem that this is more functionality suited to being in nsIFile.
//
static void
MangleTextToValidFilename(nsString & aText)
{
static const char* forbiddenNames[] = {
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
"CON", "PRN", "AUX", "NUL", "CLOCK$"
};
aText.StripChars(FILE_PATH_SEPARATOR FILE_ILLEGAL_CHARACTERS);
aText.CompressWhitespace(true, true);
uint32_t nameLen;
for (size_t n = 0; n < ArrayLength(forbiddenNames); ++n) {
nameLen = (uint32_t) strlen(forbiddenNames[n]);
if (aText.EqualsIgnoreCase(forbiddenNames[n], nameLen)) {
// invalid name is either the entire string, or a prefix with a period
if (aText.Length() == nameLen || aText.CharAt(nameLen) == char16_t('.')) {
aText.Truncate();
break;
}
}
}
}
//
// Given a unicode string, convert it down to a valid local charset filename
// with the supplied extension. This ensures that we do not cut MBCS characters
// in the middle.
//
// It would seem that this is more functionality suited to being in nsIFile.
//
static bool
CreateFilenameFromTextA(nsString & aText, const char * aExtension,
char * aFilename, uint32_t aFilenameLen)
{
// ensure that the supplied name doesn't have invalid characters. If
// a valid mangled filename couldn't be created then it will leave the
// text empty.
MangleTextToValidFilename(aText);
if (aText.IsEmpty())
return false;
// repeatably call WideCharToMultiByte as long as the title doesn't fit in the buffer
// available to us. Continually reduce the length of the source title until the MBCS
// version will fit in the buffer with room for the supplied extension. Doing it this
// way ensures that even in MBCS environments there will be a valid MBCS filename of
// the correct length.
int maxUsableFilenameLen = aFilenameLen - strlen(aExtension) - 1; // space for ext + null byte
int currLen, textLen = (int) std::min(aText.Length(), aFilenameLen);
char defaultChar = '_';
do {
currLen = WideCharToMultiByte(CP_ACP,
WC_COMPOSITECHECK|WC_DEFAULTCHAR,
aText.get(), textLen--, aFilename, maxUsableFilenameLen, &defaultChar, nullptr);
}
while (currLen == 0 && textLen > 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER);
if (currLen > 0 && textLen > 0) {
strcpy(&aFilename[currLen], aExtension);
return true;
}
else {
// empty names aren't permitted
return false;
}
}
static bool
CreateFilenameFromTextW(nsString & aText, const wchar_t * aExtension,
wchar_t * aFilename, uint32_t aFilenameLen)
{
// ensure that the supplied name doesn't have invalid characters. If
// a valid mangled filename couldn't be created then it will leave the
// text empty.
MangleTextToValidFilename(aText);