summaryrefslogtreecommitdiff
path: root/vcl/win/dtrans/MtaOleClipb.cxx
blob: 7b8b2b63738520fb95061ca378be86a55e62f3aa (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
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
/* -*- 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 .
 */

/*
    MtaOleClipb.cxx - documentation

    This class setup a single threaded apartment (sta) thread to deal with
    the ole clipboard, which runs only in an sta thread.
    The consequence is that callback from the ole clipboard are in the
    context of this sta thread. In the soffice applications this may lead
    to problems because they all use the one and only mutex called
    SolarMutex.
    In order to transfer clipboard requests to our sta thread we use a
    hidden window and forward these requests via window messages.
*/

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

#include "MtaOleClipb.hxx"

#include <svsys.h>
#include <win/saldata.hxx>

#include <osl/thread.h>

#include <wchar.h>
#include <process.h>

#include <systools/win32/comtools.hxx>

namespace
{
    const wchar_t g_szWndClsName[] = L"MtaOleReqWnd###";

    // messages constants

    const sal_uInt32 MSG_SETCLIPBOARD               = WM_USER + 0x0001;
    const sal_uInt32 MSG_GETCLIPBOARD               = WM_USER + 0x0002;
    const sal_uInt32 MSG_REGCLIPVIEWER              = WM_USER + 0x0003;
    const sal_uInt32 MSG_FLUSHCLIPBOARD             = WM_USER + 0x0004;
    const sal_uInt32 MSG_SHUTDOWN                   = WM_USER + 0x0005;

    const sal_uInt32 MAX_WAITTIME                   = 10000;  // msec
    const sal_uInt32 MAX_WAIT_SHUTDOWN              = 10000; // msec

    const bool MANUAL_RESET = true;
    const bool INIT_NONSIGNALED = false;

    /*  Cannot use osl conditions because they are blocking
        without waking up on messages sent by another thread
        this leads to deadlocks because we are blocking the
        communication between inter-thread marshalled COM
        pointers.
        COM Proxy-Stub communication uses SendMessages for
        synchronization purposes.
    */
    class Win32Condition
    {
    public:
        Win32Condition() = default;

        ~Win32Condition() { CloseHandle(m_hEvent); }

        // wait infinite for own event (or abort event) be signaled
        // leave messages sent through
        bool wait(HANDLE hEvtAbort)
        {
            const HANDLE hWaitArray[2] = { m_hEvent, hEvtAbort };
            while (true)
            {
                DWORD dwResult
                    = MsgWaitForMultipleObjects(2, hWaitArray, FALSE, INFINITE, QS_SENDMESSAGE);

                switch (dwResult)
                {
                    case WAIT_OBJECT_0: // wait successful
                        return true;

                    case WAIT_OBJECT_0 + 1: // wait aborted
                        return false;

                    case WAIT_OBJECT_0 + 2:
                    {
                        /* PeekMessage processes all messages in the SendMessage
                           queue that's what we want, messages from the PostMessage
                           queue stay untouched */
                        MSG msg;
                        PeekMessageW(&msg, nullptr, 0, 0, PM_NOREMOVE);

                        break;
                    }

                    default: // WAIT_FAILED?
                        return false;
                }
            }
        }

        // set the event
        void set() { SetEvent(m_hEvent); }

    private:
        HANDLE m_hEvent = CreateEventW(nullptr, MANUAL_RESET, INIT_NONSIGNALED, nullptr);

        // prevent copy/assignment
        Win32Condition(const Win32Condition&) = delete;
        Win32Condition& operator=(const Win32Condition&) = delete;
    };

    // we use one condition for every request

    struct MsgCtx
    {
        Win32Condition  aCondition;
        HRESULT         hr;
    };

} /* namespace private */

//  static member initialization

CMtaOleClipboard* CMtaOleClipboard::s_theMtaOleClipboardInst = nullptr;

// marshal an IDataObject

//inline
static HRESULT MarshalIDataObjectInStream( IDataObject* pIDataObject, LPSTREAM* ppStream )
{
    OSL_ASSERT( nullptr != pIDataObject );
    OSL_ASSERT( nullptr != ppStream );

    *ppStream = nullptr;
    return CoMarshalInterThreadInterfaceInStream(
        __uuidof(IDataObject),  //The IID of interface to be marshalled
        pIDataObject,           //The interface pointer
        ppStream                //IStream pointer
        );
}

// unmarshal an IDataObject

//inline
static HRESULT UnmarshalIDataObjectAndReleaseStream( LPSTREAM lpStream, IDataObject** ppIDataObject )
{
    OSL_ASSERT( nullptr != lpStream );
    OSL_ASSERT( nullptr != ppIDataObject );

    *ppIDataObject = nullptr;
    return CoGetInterfaceAndReleaseStream(
        lpStream,
        __uuidof(IDataObject),
        reinterpret_cast<LPVOID*>(ppIDataObject));
}

// helper class to ensure that the calling thread has com initialized

namespace {

class CAutoComInit
{
public:
   /*
       to be safe we call CoInitializeEx
       although it is not necessary if
       the calling thread was created
       using osl_CreateThread because
       this function calls CoInitializeEx
       for every thread it creates
    */
    CAutoComInit( ) : m_hResult( CoInitializeEx( nullptr, COINIT_APARTMENTTHREADED ) )
    {
        if ( S_OK == m_hResult )
            OSL_FAIL(
            "com was not yet initialized, the thread was not created using osl_createThread" );
        else if ( FAILED( m_hResult ) && !( RPC_E_CHANGED_MODE == m_hResult ) )
            OSL_FAIL(
            "com could not be initialized, maybe the thread was not created using osl_createThread" );
    }

    ~CAutoComInit( )
    {
        /*
            we only call CoUninitialize when
            CoInitializeEx returned S_FALSE, what
            means that com was already initialize
            for that thread so we keep the balance
            if CoInitializeEx returned S_OK what means
            com was not yet initialized we better
            let com initialized or we may run into
            the realm of undefined behaviour
        */
        if ( m_hResult == S_FALSE )
            CoUninitialize( );
    }

private:
    HRESULT m_hResult;
};

}

// ctor

CMtaOleClipboard::CMtaOleClipboard( ) :
    m_hOleThread( nullptr ),
    m_uOleThreadId( 0 ),
    // signals that the thread was successfully setup
    m_hEvtThrdReady(CreateEventW( nullptr, MANUAL_RESET, INIT_NONSIGNALED, nullptr )),
    m_hwndMtaOleReqWnd( nullptr ),
    // signals that the window is destroyed - to stop waiting any winproc result
    m_hEvtWndDisposed(CreateEventW(nullptr, MANUAL_RESET, INIT_NONSIGNALED, nullptr)),
    m_pfncClipViewerCallback(nullptr)
{
    OSL_ASSERT( nullptr != m_hEvtThrdReady );
    SAL_WARN_IF(!m_hEvtWndDisposed, "dtrans", "CreateEventW failed: m_hEvtWndDisposed is nullptr");

    s_theMtaOleClipboardInst = this;

    m_hOleThread = reinterpret_cast<HANDLE>(_beginthreadex(
        nullptr, 0, CMtaOleClipboard::oleThreadProc, this, 0, &m_uOleThreadId ));
    OSL_ASSERT( nullptr != m_hOleThread );
}

// dtor

CMtaOleClipboard::~CMtaOleClipboard( )
{
    // block calling threads out
    if ( nullptr != m_hEvtThrdReady )
        ResetEvent( m_hEvtThrdReady );

    // end the thread
    // because DestroyWindow can only be called
    // from within the thread that created the window
    sendMessage( MSG_SHUTDOWN );

    // wait for thread shutdown
    DWORD dwResult = WaitForSingleObject(m_hOleThread, MAX_WAIT_SHUTDOWN);
    OSL_ENSURE( dwResult == WAIT_OBJECT_0, "OleThread could not terminate" );

    if ( nullptr != m_hOleThread )
        CloseHandle( m_hOleThread );

    if ( nullptr != m_hEvtThrdReady )
        CloseHandle( m_hEvtThrdReady );

    if (m_hEvtWndDisposed)
        CloseHandle(m_hEvtWndDisposed);

    OSL_ENSURE( ( nullptr == m_pfncClipViewerCallback ),
                "Clipboard viewer not properly unregistered" );
}

HRESULT CMtaOleClipboard::flushClipboard( )
{
    if ( !WaitForThreadReady( ) )
    {
        OSL_FAIL( "clipboard sta thread not ready" );
        return E_FAIL;
    }

    OSL_ENSURE( GetCurrentThreadId( ) != m_uOleThreadId,
        "flushClipboard from within clipboard sta thread called" );

    MsgCtx  aMsgCtx;

    const bool bWaitSuccess = postMessage(MSG_FLUSHCLIPBOARD, 0, reinterpret_cast<LPARAM>(&aMsgCtx))
                              && aMsgCtx.aCondition.wait(m_hEvtWndDisposed);

    return bWaitSuccess ? aMsgCtx.hr : E_ABORT;
}

HRESULT CMtaOleClipboard::getClipboard( IDataObject** ppIDataObject )
{
    OSL_PRECOND( nullptr != ppIDataObject, "invalid parameter" );
    OSL_PRECOND( GetCurrentThreadId( ) != m_uOleThreadId, "getClipboard from within clipboard sta thread called" );

    if ( !WaitForThreadReady( ) )
    {
        OSL_FAIL( "clipboard sta thread not ready" );
        return E_FAIL;
    }

    CAutoComInit comAutoInit;
    LPSTREAM lpStream;

    *ppIDataObject = nullptr;

    MsgCtx    aMsgCtx;

    const bool bWaitSuccess = postMessage(MSG_GETCLIPBOARD, reinterpret_cast<WPARAM>(&lpStream),
                                          reinterpret_cast<LPARAM>(&aMsgCtx))
                              && aMsgCtx.aCondition.wait(m_hEvtWndDisposed);

    HRESULT hr = bWaitSuccess ? aMsgCtx.hr : E_ABORT;

    if ( SUCCEEDED( hr ) )
    {
        hr = UnmarshalIDataObjectAndReleaseStream( lpStream, ppIDataObject );
        OSL_ENSURE( SUCCEEDED( hr ), "unmarshalling clipboard data object failed" );
    }

    return hr;
}

// this is an asynchronous method that's why we don't wait until the
// request is completed

HRESULT CMtaOleClipboard::setClipboard( IDataObject* pIDataObject )
{
    if ( !WaitForThreadReady( ) )
    {
        OSL_FAIL( "clipboard sta thread not ready" );
        return E_FAIL;
    }

    CAutoComInit comAutoInit;

    OSL_ENSURE( GetCurrentThreadId( ) != m_uOleThreadId, "setClipboard from within the clipboard sta thread called" );

    // because we marshall this request
    // into the sta thread we better
    // acquire the interface here so
    // that the object will not be
    // destroyed before the ole clipboard
    // can acquire it
    // remember: pIDataObject may be NULL
    // which is a request to clear the
    // current clipboard content
    if ( pIDataObject )
        pIDataObject->AddRef( );

    postMessage(
        MSG_SETCLIPBOARD,
        reinterpret_cast< WPARAM >( pIDataObject ) );

    // because this is an asynchronous function
    // the return value is useless
    return S_OK;
}

// register a clipboard viewer

bool CMtaOleClipboard::registerClipViewer( LPFNC_CLIPVIEWER_CALLBACK_t pfncClipViewerCallback )
{
    if ( !WaitForThreadReady( ) )
    {
        OSL_FAIL( "clipboard sta thread not ready" );
        return false;
    }

    OSL_ENSURE( GetCurrentThreadId( ) != m_uOleThreadId, "registerClipViewer from within the OleThread called" );

    MsgCtx aMsgCtx;

    if (postMessage(MSG_REGCLIPVIEWER, reinterpret_cast<WPARAM>(pfncClipViewerCallback),
                    reinterpret_cast<LPARAM>(&aMsgCtx)))
        aMsgCtx.aCondition.wait(m_hEvtWndDisposed);

    return false;
}

// register a clipboard viewer

bool CMtaOleClipboard::onRegisterClipViewer( LPFNC_CLIPVIEWER_CALLBACK_t pfncClipViewerCallback )
{
    bool bRet = false;

    // register if not yet done
    if ( ( nullptr != pfncClipViewerCallback ) && ( nullptr == m_pfncClipViewerCallback ) )
    {
        // SetClipboardViewer sends a WM_DRAWCLIPBOARD message we ignore
        // this message if we register ourself as clip viewer
        m_bInRegisterClipViewer = true;
        bRet = AddClipboardFormatListener(m_hwndMtaOleReqWnd);
        m_bInRegisterClipViewer = false;

        // save the new callback function
        m_pfncClipViewerCallback = pfncClipViewerCallback;
    }
    else if ( ( nullptr == pfncClipViewerCallback ) && ( nullptr != m_pfncClipViewerCallback ) )
    {
        m_pfncClipViewerCallback = nullptr;

        // unregister if input parameter is NULL and we previously registered
        // as clipboard viewer
        bRet = RemoveClipboardFormatListener(m_hwndMtaOleReqWnd);
    }

    return bRet;
}

HRESULT CMtaOleClipboard::onSetClipboard( IDataObject* pIDataObject )
{
    return OleSetClipboard( pIDataObject );
}

HRESULT CMtaOleClipboard::onGetClipboard( LPSTREAM* ppStream )
{
    OSL_ASSERT(nullptr != ppStream);

    IDataObjectPtr pIDataObject;

    // forward the request to the OleClipboard
    HRESULT hr = OleGetClipboard( &pIDataObject );
    if ( SUCCEEDED( hr ) )
    {
        hr = MarshalIDataObjectInStream(pIDataObject.get(), ppStream);
        OSL_ENSURE(SUCCEEDED(hr), "marshalling cliboard data object failed");
    }
    return hr;
}

// flush the ole-clipboard

HRESULT CMtaOleClipboard::onFlushClipboard( )
{
    return OleFlushClipboard();
}

// handle clipboard update event

LRESULT CMtaOleClipboard::onClipboardUpdate()
{
    // we don't send a notification if we are
    // registering ourself as clipboard
    if (!m_bInRegisterClipViewer && m_pfncClipViewerCallback)
        m_pfncClipViewerCallback();
    return 0;
}

// SendMessage so we don't need to supply the HWND if we send
// something to our wrapped window

LRESULT CMtaOleClipboard::sendMessage( UINT msg, WPARAM wParam, LPARAM lParam )
{
    return ::SendMessageW( m_hwndMtaOleReqWnd, msg, wParam, lParam );
}

// PostMessage so we don't need to supply the HWND if we send
// something to our wrapped window

bool CMtaOleClipboard::postMessage( UINT msg, WPARAM wParam, LPARAM lParam )
{
    bool const ret = PostMessageW(m_hwndMtaOleReqWnd, msg, wParam, lParam);
    SAL_WARN_IF(!ret, "dtrans", "ERROR: PostMessage() failed!");
    return ret;
}

// the window proc

LRESULT CALLBACK CMtaOleClipboard::mtaOleReqWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
    LRESULT lResult = 0;

    // get a connection to the class-instance via the static member
    CMtaOleClipboard* pImpl = CMtaOleClipboard::s_theMtaOleClipboardInst;
    OSL_ASSERT( nullptr != pImpl );

    switch( uMsg )
    {
    case MSG_SETCLIPBOARD:
        {
            IDataObject* pIDataObject = reinterpret_cast< IDataObject* >( wParam );
            CMtaOleClipboard::onSetClipboard( pIDataObject );

            // in setClipboard we did acquire the
            // interface pointer in order to prevent
            // destruction of the object before the
            // ole clipboard can acquire the interface
            // now we release the interface so that
            // our lostOwnership mechanism works
            // remember: pIDataObject may be NULL
            if ( pIDataObject )
                pIDataObject->Release( );
        }
        break;

    case MSG_GETCLIPBOARD:
        {
            MsgCtx* aMsgCtx = reinterpret_cast< MsgCtx* >( lParam );
            OSL_ASSERT( aMsgCtx );

            aMsgCtx->hr = CMtaOleClipboard::onGetClipboard( reinterpret_cast< LPSTREAM* >(wParam) );
            aMsgCtx->aCondition.set( );
        }
        break;

    case MSG_FLUSHCLIPBOARD:
        {
            MsgCtx* aMsgCtx = reinterpret_cast< MsgCtx* >( lParam );
            OSL_ASSERT( aMsgCtx );

            aMsgCtx->hr = CMtaOleClipboard::onFlushClipboard( );
            aMsgCtx->aCondition.set( );
        }
        break;

    case MSG_REGCLIPVIEWER:
        {
            MsgCtx* pMsgCtx = reinterpret_cast<MsgCtx*>(lParam);
            SAL_WARN_IF(!pMsgCtx, "dtrans", "pMsgCtx is nullptr");

            pImpl->onRegisterClipViewer(
                reinterpret_cast<CMtaOleClipboard::LPFNC_CLIPVIEWER_CALLBACK_t>(wParam));
            pMsgCtx->aCondition.set();
        }
        break;

    case WM_CLIPBOARDUPDATE:
        lResult = pImpl->onClipboardUpdate();
        break;

    case MSG_SHUTDOWN:
        DestroyWindow( pImpl->m_hwndMtaOleReqWnd );
        break;

    // force the sta thread to end
    case WM_DESTROY:
        SetEvent(pImpl->m_hEvtWndDisposed); // stop waiting for conditions set by this wndproc
        PostQuitMessage( 0 );
        break;

    default:
        lResult = DefWindowProcW( hWnd, uMsg, wParam, lParam );
        break;
    }

    return lResult;
}

unsigned int CMtaOleClipboard::run()
{
    HRESULT hr = OleInitialize(nullptr);
    OSL_ASSERT(SUCCEEDED(hr));

    WNDCLASSEXW  wcex;

    SalData* pSalData = GetSalData();
    OSL_ASSERT(nullptr != pSalData->mhInst);

    ZeroMemory( &wcex, sizeof(wcex) );

    wcex.cbSize         = sizeof(wcex);
    wcex.style          = 0;
    wcex.lpfnWndProc    = CMtaOleClipboard::mtaOleReqWndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = pSalData->mhInst;
    wcex.hIcon          = nullptr;
    wcex.hCursor        = nullptr;
    wcex.hbrBackground  = nullptr;
    wcex.lpszMenuName   = nullptr;
    wcex.lpszClassName  = g_szWndClsName;
    wcex.hIconSm        = nullptr;

    ATOM aMtaOleReqWndClassAtom = RegisterClassExW(&wcex);

    if (0 != aMtaOleReqWndClassAtom)
        m_hwndMtaOleReqWnd = CreateWindowW(
            g_szWndClsName, nullptr, 0, 0, 0, 0, 0, nullptr, nullptr, pSalData->mhInst, nullptr );

    unsigned int nRet;

    if ( IsWindow( m_hwndMtaOleReqWnd ) )
    {
        if ( nullptr != m_hEvtThrdReady )
            SetEvent( m_hEvtThrdReady );

        // pumping messages
        MSG msg;
        while( GetMessageW( &msg, nullptr, 0, 0 ) )
            DispatchMessageW( &msg );

        nRet = 0;
    }
    else
        nRet = ~0U;

    if (aMtaOleReqWndClassAtom)
        UnregisterClassW(g_szWndClsName, nullptr);

    OleUninitialize( );

    return nRet;
}

unsigned int WINAPI CMtaOleClipboard::oleThreadProc( LPVOID pParam )
{
    osl_setThreadName("CMtaOleClipboard::run()");

    CMtaOleClipboard* pInst =
        static_cast<CMtaOleClipboard*>( pParam );
    OSL_ASSERT( nullptr != pInst );

    return pInst->run( );
}

bool CMtaOleClipboard::WaitForThreadReady( ) const
{
    bool bRet = false;

    if ( nullptr != m_hEvtThrdReady )
    {
        DWORD dwResult = WaitForSingleObject(
            m_hEvtThrdReady, MAX_WAITTIME );
        bRet = ( dwResult == WAIT_OBJECT_0 );
    }

    return bRet;
}

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