summaryrefslogtreecommitdiff
path: root/vcl/win/dtrans/DOTransferable.cxx
blob: 38329a209c1c44c8ffc5344e896760097962df6b (plain)
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * 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/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <sal/types.h>
#include <rtl/process.h>
#include <osl/diagnose.h>
#include <sal/log.hxx>

#include "DOTransferable.hxx"
#include "ImplHelper.hxx"
#include "WinClip.hxx"
#include "WinClipboard.hxx"
#include "DTransHelper.hxx"
#include "TxtCnvtHlp.hxx"
#include "MimeAttrib.hxx"
#include "FmtFilter.hxx"
#include "Fetc.hxx"
#include <com/sun/star/container/NoSuchElementException.hpp>
#include <com/sun/star/datatransfer/MimeContentTypeFactory.hpp>
#include <com/sun/star/datatransfer/UnsupportedFlavorException.hpp>
#include <com/sun/star/io/IOException.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>

using namespace osl;
using namespace cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::datatransfer;
using namespace com::sun::star::io;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;

namespace
{
    const Type CPPUTYPE_SEQINT8  = cppu::UnoType<Sequence< sal_Int8 >>::get();
    const Type CPPUTYPE_OUSTRING = cppu::UnoType<OUString>::get();

    bool isValidFlavor( const DataFlavor& aFlavor )
    {
        return ( aFlavor.MimeType.getLength( ) &&
                 ( ( aFlavor.DataType ==  CPPUTYPE_SEQINT8 ) ||
                 ( aFlavor.DataType == CPPUTYPE_OUSTRING ) ) );
    }

void clipDataToByteStream( CLIPFORMAT cf, STGMEDIUM stgmedium, CDOTransferable::ByteSequence_t& aByteSequence )
{
    CStgTransferHelper memTransferHelper;
    LPSTREAM pStream = nullptr;

    switch( stgmedium.tymed )
    {
    case TYMED_HGLOBAL:
        memTransferHelper.init( stgmedium.hGlobal );
        break;

    case TYMED_MFPICT:
        memTransferHelper.init( stgmedium.hMetaFilePict );
        break;

    case TYMED_ENHMF:
        memTransferHelper.init( stgmedium.hEnhMetaFile );
        break;

    case TYMED_ISTREAM:
        pStream = stgmedium.pstm;
        break;

    default:
        throw UnsupportedFlavorException( );
        break;
    }

    if (pStream)
    {
        // We have a stream, read from it.
        STATSTG aStat;
        HRESULT hr = pStream->Stat(&aStat, STATFLAG_NONAME);
        if (FAILED(hr))
        {
            SAL_WARN("vcl.win.dtrans", "clipDataToByteStream: Stat() failed");
            return;
        }

        size_t nMemSize = aStat.cbSize.QuadPart;
        aByteSequence.realloc(nMemSize);
        LARGE_INTEGER li;
        li.QuadPart = 0;
        hr = pStream->Seek(li, STREAM_SEEK_SET, nullptr);
        if (FAILED(hr))
        {
            SAL_WARN("vcl.win.dtrans", "clipDataToByteStream: Seek() failed");
        }

        ULONG nRead = 0;
        hr = pStream->Read(aByteSequence.getArray(), nMemSize, &nRead);
        if (FAILED(hr))
        {
            SAL_WARN("vcl.win.dtrans", "clipDataToByteStream: Read() failed");
        }
        if (nRead < nMemSize)
        {
            SAL_WARN("vcl.win.dtrans", "clipDataToByteStream: Read() was partial");
        }

        return;
    }

    int nMemSize = memTransferHelper.memSize( cf );
    aByteSequence.realloc( nMemSize );
    memTransferHelper.read( aByteSequence.getArray( ), nMemSize );
}

OUString byteStreamToOUString( CDOTransferable::ByteSequence_t& aByteStream )
{
    sal_Int32 nWChars;
    sal_Int32 nMemSize = aByteStream.getLength( );

    // if there is a trailing L"\0" subtract 1 from length
    // for unknown reason, the sequence may sometimes arrive empty
    if ( aByteStream.getLength( ) > 1 &&
         0 == aByteStream[ aByteStream.getLength( ) - 2 ] &&
         0 == aByteStream[ aByteStream.getLength( ) - 1 ] )
        nWChars = static_cast< sal_Int32 >( nMemSize / sizeof( sal_Unicode ) ) - 1;
    else
        nWChars = static_cast< sal_Int32 >( nMemSize / sizeof( sal_Unicode ) );

    return OUString( reinterpret_cast< sal_Unicode* >( aByteStream.getArray( ) ), nWChars );
}

Any byteStreamToAny( CDOTransferable::ByteSequence_t& aByteStream, const Type& aRequestedDataType )
{
    Any aAny;

    if ( aRequestedDataType == CPPUTYPE_OUSTRING )
    {
        OUString str = byteStreamToOUString( aByteStream );
        if (str.isEmpty())
            throw RuntimeException();
        aAny <<= str;
    }
    else
        aAny <<= aByteStream;

    return aAny;
}

bool cmpFullMediaType(
    const Reference< XMimeContentType >& xLhs, const Reference< XMimeContentType >& xRhs )
{
    return xLhs->getFullMediaType().equalsIgnoreAsciiCase( xRhs->getFullMediaType( ) );
}

bool cmpAllContentTypeParameter(
    const Reference< XMimeContentType >& xLhs, const Reference< XMimeContentType >& xRhs )
{
    Sequence< OUString > xLhsFlavors = xLhs->getParameters( );
    Sequence< OUString > xRhsFlavors = xRhs->getParameters( );
    bool bRet = true;

    try
    {
        if ( xLhsFlavors.getLength( ) == xRhsFlavors.getLength( ) )
        {
            OUString pLhs;
            OUString pRhs;

            for ( sal_Int32 i = 0; i < xLhsFlavors.getLength( ); i++ )
            {
                pLhs = xLhs->getParameterValue( xLhsFlavors[i] );
                pRhs = xRhs->getParameterValue( xLhsFlavors[i] );

                if ( !pLhs.equalsIgnoreAsciiCase( pRhs ) )
                {
                    bRet = false;
                    break;
                }
            }
        }
        else
            bRet = false;
    }
    catch( NoSuchElementException& )
    {
        bRet = false;
    }
    catch( IllegalArgumentException& )
    {
        bRet = false;
    }

    return bRet;
}

} // end namespace

CDOTransferable::CDOTransferable(
    const Reference< XComponentContext >& rxContext, IDataObjectPtr rDataObject ) :
    m_rDataObject( rDataObject ),
    m_xContext( rxContext ),
    m_DataFormatTranslator( rxContext ),
    m_bUnicodeRegistered( false ),
    m_TxtFormatOnClipboard( CF_INVALID )
{
    initFlavorList();
}

CDOTransferable::CDOTransferable(
    const Reference<XComponentContext>& rxContext,
    const css::uno::Reference<css::datatransfer::clipboard::XClipboard>& xClipboard,
    const std::vector<sal_uInt32>& rFormats)
    : m_xClipboard(xClipboard)
    , m_xContext(rxContext)
    , m_DataFormatTranslator(rxContext)
    , m_bUnicodeRegistered(false)
    , m_TxtFormatOnClipboard(CF_INVALID)
{
    initFlavorListFromFormatList(rFormats);
}

Any SAL_CALL CDOTransferable::getTransferData( const DataFlavor& aFlavor )
{
    OSL_ASSERT( isValidFlavor( aFlavor ) );

    std::unique_lock aGuard( m_aMutex );

    // convert dataflavor to formatetc

    CFormatEtc fetc = m_DataFormatTranslator.getFormatEtcFromDataFlavor( aFlavor );
    OSL_ASSERT( CF_INVALID != fetc.getClipformat() );

    //  get the data from clipboard in a byte stream

    ByteSequence_t clipDataStream;

    try
    {
        clipDataStream = getClipboardData( fetc );
    }
    catch( UnsupportedFlavorException& )
    {
        if ( CDataFormatTranslator::isUnicodeTextFormat( fetc.getClipformat( ) ) &&
             m_bUnicodeRegistered )
        {
             OUString aUnicodeText = synthesizeUnicodeText( );
             Any aAny( aUnicodeText );
             return aAny;
        }
        // #i124085# CF_DIBV5 should not be possible, but keep for reading from the
        // clipboard for being on the safe side
        else if(CF_DIBV5 == fetc.getClipformat())
        {
            // #i123407# CF_DIBV5 has priority; if the try to fetch this failed,
            // check CF_DIB availability as an alternative
            fetc.setClipformat(CF_DIB);

            clipDataStream = getClipboardData( fetc );
                // pass UnsupportedFlavorException out, tried all possibilities
        }
        else
            throw; // pass through exception
    }

    // return the data as any

    return byteStreamToAny( clipDataStream, aFlavor.DataType );
}

// getTransferDataFlavors

Sequence< DataFlavor > SAL_CALL CDOTransferable::getTransferDataFlavors(  )
{
    return m_FlavorList;
}

// isDataFlavorSupported
// returns true if we find a DataFlavor with the same MimeType and
// DataType

sal_Bool SAL_CALL CDOTransferable::isDataFlavorSupported( const DataFlavor& aFlavor )
{
    OSL_ASSERT( isValidFlavor( aFlavor ) );

    for (DataFlavor const& df : m_FlavorList)
        if ( compareDataFlavors( aFlavor, df ) )
            return true;

    return false;
}

// the list of dataflavors currently on the clipboard will be initialized
// only once; if the client of this Transferable will hold a reference
// to it and the underlying clipboard content changes, the client does
// possible operate on an invalid list
// if there is only text on the clipboard we will also offer unicode text
// an synthesize this format on the fly if requested, to accomplish this
// we save the first offered text format which we will later use for the
// conversion

void CDOTransferable::initFlavorList( )
{
    std::vector<sal_uInt32> aFormats;
    sal::systools::COMReference<IEnumFORMATETC> pEnumFormatEtc;
    HRESULT hr = m_rDataObject->EnumFormatEtc( DATADIR_GET, &pEnumFormatEtc );
    if ( SUCCEEDED( hr ) )
    {
        pEnumFormatEtc->Reset( );

        FORMATETC fetc;
        while ( S_OK == pEnumFormatEtc->Next( 1, &fetc, nullptr ) )
        {
            aFormats.push_back(fetc.cfFormat);
            // see MSDN IEnumFORMATETC
            CoTaskMemFree( fetc.ptd );
        }
        initFlavorListFromFormatList(aFormats);
    }
}

void CDOTransferable::initFlavorListFromFormatList(const std::vector<sal_uInt32>& rFormats)
{
    for (sal_uInt32 cfFormat : rFormats)
    {
        // we use locales only to determine the
        // charset if there is text on the clipboard
        // we don't offer this format
        if (CF_LOCALE == cfFormat)
            continue;

        // if text or oemtext is offered we pretend to have unicode text
        if (CDataFormatTranslator::isTextFormat(cfFormat))
        {
            if (!m_bUnicodeRegistered)
            {
                m_TxtFormatOnClipboard = cfFormat;
                m_bUnicodeRegistered   = true;

                // register unicode text as format
                addSupportedFlavor(formatEtcToDataFlavor(CF_UNICODETEXT));
            }
        }
        else
            addSupportedFlavor(formatEtcToDataFlavor(cfFormat));
    }
}

inline
void CDOTransferable::addSupportedFlavor( const DataFlavor& aFlavor )
{
    // we ignore all formats that couldn't be translated
    if ( aFlavor.MimeType.getLength( ) )
    {
        OSL_ASSERT( isValidFlavor( aFlavor ) );

        m_FlavorList.realloc( m_FlavorList.getLength( ) + 1 );
        m_FlavorList.getArray()[m_FlavorList.getLength( ) - 1] = aFlavor;
    }
}

DataFlavor CDOTransferable::formatEtcToDataFlavor(sal_uInt32 cfFormat)
{
    return m_DataFormatTranslator.getDataFlavorFromFormatEtc(cfFormat);
}

// returns the current locale on clipboard; if there is no locale on
// clipboard the function returns the current thread locale

LCID CDOTransferable::getLocaleFromClipboard( )
{
    LCID lcid = GetThreadLocale( );

    try
    {
        CFormatEtc fetc = CDataFormatTranslator::getFormatEtcForClipformat( CF_LOCALE );
        ByteSequence_t aLCIDSeq = getClipboardData( fetc );
        lcid = *reinterpret_cast<LCID*>( aLCIDSeq.getArray( ) );

        // because of a Win95/98 Bug; there the high word
        // of a locale has the same value as the
        // low word e.g. 0x07040704 that's not right
        // correct is 0x00000704
        lcid &= 0x0000FFFF;
    }
    catch(...)
    {
        // we take the default locale
    }

    return lcid;
}

void CDOTransferable::tryToGetIDataObjectIfAbsent()
{
    if (!m_rDataObject.is())
    {
        auto xClipboard = m_xClipboard.get(); // holding the reference while we get the object
        if (CWinClipboard* pWinClipboard = dynamic_cast<CWinClipboard*>(xClipboard.get()))
        {
            m_rDataObject = pWinClipboard->getIDataObject();
        }
    }
}

// I think it's not necessary to call ReleaseStgMedium
// in case of failures because nothing should have been
// allocated etc.

CDOTransferable::ByteSequence_t CDOTransferable::getClipboardData( CFormatEtc& aFormatEtc )
{
    STGMEDIUM stgmedium;
    tryToGetIDataObjectIfAbsent();
    if (!m_rDataObject.is()) // Maybe we are shutting down, and clipboard is already destroyed?
        throw RuntimeException();
    HRESULT hr = m_rDataObject->GetData( aFormatEtc, &stgmedium );

    // in case of failure to get a WMF metafile handle, try to get a memory block
    if( FAILED( hr ) &&
        ( CF_METAFILEPICT == aFormatEtc.getClipformat() ) &&
        ( TYMED_MFPICT == aFormatEtc.getTymed() ) )
    {
        CFormatEtc aTempFormat( aFormatEtc );
        aTempFormat.setTymed( TYMED_HGLOBAL );
        hr = m_rDataObject->GetData( aTempFormat, &stgmedium );
    }

    if (FAILED(hr) && aFormatEtc.getTymed() == TYMED_HGLOBAL)
    {
        // Handle type is not memory, try stream.
        CFormatEtc aTempFormat(aFormatEtc);
        aTempFormat.setTymed(TYMED_ISTREAM);
        hr = m_rDataObject->GetData(aTempFormat, &stgmedium);
    }

    if ( FAILED( hr ) )
    {
        OSL_ASSERT( (hr != E_INVALIDARG) &&
                    (hr != DV_E_DVASPECT) &&
                    (hr != DV_E_LINDEX) &&
                    (hr != DV_E_TYMED) );

        if ( DV_E_FORMATETC == hr )
            throw UnsupportedFlavorException( );
        else if ( STG_E_MEDIUMFULL == hr )
            throw IOException( );
        else
            throw RuntimeException( );
    }

    ByteSequence_t byteStream;

    try
    {
        if ( CF_ENHMETAFILE == aFormatEtc.getClipformat() )
            byteStream = WinENHMFPictToOOMFPict( stgmedium.hEnhMetaFile );
        else if (CF_HDROP == aFormatEtc.getClipformat())
            byteStream = CF_HDROPToFileList(stgmedium.hGlobal);
        else if ( CF_BITMAP == aFormatEtc.getClipformat() )
        {
            byteStream = WinBITMAPToOOBMP(stgmedium.hBitmap);
            if( aFormatEtc.getTymed() == TYMED_GDI &&
                ! stgmedium.pUnkForRelease )
            {
                DeleteObject(stgmedium.hBitmap);
            }
        }
        else
        {
            clipDataToByteStream( aFormatEtc.getClipformat( ), stgmedium, byteStream );

            // format conversion if necessary
            // #i124085# DIBV5 should not happen currently, but keep as a hint here
            if(CF_DIBV5 == aFormatEtc.getClipformat() || CF_DIB == aFormatEtc.getClipformat())
            {
                byteStream = WinDIBToOOBMP(byteStream);
            }
            else if(CF_METAFILEPICT == aFormatEtc.getClipformat())
            {
                byteStream = WinMFPictToOOMFPict(byteStream);
            }
        }

        ReleaseStgMedium( &stgmedium );
    }
    catch( CStgTransferHelper::CStgTransferException& )
    {
        ReleaseStgMedium( &stgmedium );
        throw IOException( );
    }

    return byteStream;
}

OUString CDOTransferable::synthesizeUnicodeText( )
{
    ByteSequence_t aTextSequence;
    CFormatEtc     fetc;
    LCID           lcid = getLocaleFromClipboard( );
    sal_uInt32     cpForTxtCnvt = 0;

    if ( CF_TEXT == m_TxtFormatOnClipboard )
    {
        fetc = CDataFormatTranslator::getFormatEtcForClipformat( CF_TEXT );
        aTextSequence = getClipboardData( fetc );

        // determine the codepage used for text conversion
        cpForTxtCnvt = getWinCPFromLocaleId( lcid, LOCALE_IDEFAULTANSICODEPAGE ).toInt32( );
    }
    else if ( CF_OEMTEXT == m_TxtFormatOnClipboard )
    {
        fetc = CDataFormatTranslator::getFormatEtcForClipformat( CF_OEMTEXT );
        aTextSequence = getClipboardData( fetc );

        // determine the codepage used for text conversion
        cpForTxtCnvt = getWinCPFromLocaleId( lcid, LOCALE_IDEFAULTCODEPAGE ).toInt32( );
    }
    else
        OSL_ASSERT( false );

    CStgTransferHelper stgTransferHelper;

    // convert the text
    MultiByteToWideCharEx( cpForTxtCnvt,
                           reinterpret_cast<char*>( aTextSequence.getArray( ) ),
                           -1,
                           stgTransferHelper,
                           false);

    CRawHGlobalPtr  ptrHGlob(stgTransferHelper);
    sal_Unicode*    pWChar = static_cast<sal_Unicode*>(ptrHGlob.GetMemPtr());

    return OUString(pWChar);
}

bool CDOTransferable::compareDataFlavors(
    const DataFlavor& lhs, const DataFlavor& rhs )
{
    if ( !m_rXMimeCntFactory.is( ) )
    {
        m_rXMimeCntFactory = MimeContentTypeFactory::create( m_xContext );
    }

    bool bRet = false;

    try
    {
        Reference< XMimeContentType > xLhs( m_rXMimeCntFactory->createMimeContentType( lhs.MimeType ) );
        Reference< XMimeContentType > xRhs( m_rXMimeCntFactory->createMimeContentType( rhs.MimeType ) );

        if ( cmpFullMediaType( xLhs, xRhs ) )
        {
            bRet = cmpAllContentTypeParameter( xLhs, xRhs );
        }
    }
    catch( IllegalArgumentException& )
    {
        OSL_FAIL( "Invalid content type detected" );
        bRet = false;
    }

    return bRet;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */