summaryrefslogtreecommitdiff
path: root/extensions/source/scanner/scanwin.cxx
blob: fb4fc159257920b9c95ba9a01a4da36d0523fa8f (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
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
/* -*- 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 <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/util/XCloseable.hpp>
#include <com/sun/star/util/XCloseBroadcaster.hpp>
#include <com/sun/star/util/XCloseListener.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <cppuhelper/implbase.hxx>
#include <comphelper/processfactory.hxx>

#include <prewin.h>
#include <postwin.h>
#include <math.h>
#include <tools/stream.hxx>
#include <tools/helpers.hxx>
#include <osl/mutex.hxx>
#include <osl/module.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/sysdata.hxx>
#include "scanner.hxx"

#if defined _MSC_VER
#pragma warning (push,1)
#pragma warning (disable:4668)
#endif
#include "twain/twain.h"
#if defined _MSC_VER
#pragma warning (pop)
#endif

using namespace ::com::sun::star;

#define TWAIN_EVENT_NONE        0x00000000UL
#define TWAIN_EVENT_QUIT        0x00000001UL
#define TWAIN_EVENT_SCANNING    0x00000002UL
#define TWAIN_EVENT_XFER        0x00000004UL

#define PFUNC                   (*pDSM)
#define PTWAINMSG               MSG*
#define FIXTODOUBLE( nFix )     ((double)nFix.Whole+(double)nFix.Frac/65536.)
#define FIXTOLONG( nFix )       ((long)floor(FIXTODOUBLE(nFix)+0.5))

#if defined(_WIN32)
#define TWAIN_LIBNAME           "TWAIN_32.DLL"
#define TWAIN_FUNCNAME          "DSM_Entry"
#endif

enum TwainState
{
    TWAIN_STATE_NONE = 0,
    TWAIN_STATE_SCANNING = 1,
    TWAIN_STATE_DONE = 2,
    TWAIN_STATE_CANCELED = 3
};

class ImpTwain : public ::cppu::WeakImplHelper< util::XCloseListener >
{
    friend LRESULT CALLBACK TwainMsgProc( int nCode, WPARAM wParam, LPARAM lParam );

    uno::Reference< uno::XInterface >           mxSelfRef;
    uno::Reference< scanner::XScannerManager >  mxMgr;
    ScannerManager&                             mrMgr;
    TW_IDENTITY                                 aAppIdent;
    TW_IDENTITY                                 aSrcIdent;
    Link<unsigned long,void>                    aNotifyLink;
    DSMENTRYPROC                                pDSM;
    osl::Module*                                pMod;
    ULONG_PTR                                   nCurState;
    HWND                                        hTwainWnd;
    HHOOK                                       hTwainHook;
    bool                                        mbCloseFrameOnExit;

    bool                                        ImplHandleMsg( void* pMsg );
    void                                        ImplCreate();
    void                                        ImplOpenSourceManager();
    void                                        ImplOpenSource();
    bool                                        ImplEnableSource();
    void                                        ImplXfer();
    void                                        ImplFallback( ULONG_PTR nEvent );
    void                                        ImplSendCloseEvent();
    void                                        ImplDeregisterCloseListener();
    void                                        ImplRegisterCloseListener();
    uno::Reference< frame::XFrame >             ImplGetActiveFrame();
    uno::Reference< util::XCloseBroadcaster >   ImplGetActiveFrameCloseBroadcaster();

                                                DECL_LINK_TYPED( ImplFallbackHdl, void*, void );
                                                DECL_LINK_TYPED( ImplDestroyHdl, void*, void );

    // from util::XCloseListener
    virtual void SAL_CALL queryClosing( const lang::EventObject& Source, sal_Bool GetsOwnership ) throw (util::CloseVetoException, uno::RuntimeException);
    virtual void SAL_CALL notifyClosing( const lang::EventObject& Source ) throw (uno::RuntimeException);

    // from lang::XEventListener
    virtual void SAL_CALL disposing( const lang::EventObject& Source ) throw (uno::RuntimeException);

public:

                                                ImpTwain( ScannerManager& rMgr, const Link<unsigned long,void>& rNotifyLink );
                                                ~ImpTwain();

    void                                        Destroy();

    bool                                        SelectSource();
    bool                                        InitXfer();
};

static ImpTwain* pImpTwainInstance = NULL;

LRESULT CALLBACK TwainWndProc( HWND hWnd,UINT nMsg, WPARAM nPar1, LPARAM nPar2 )
{
    return DefWindowProc( hWnd, nMsg, nPar1, nPar2 );
}

LRESULT CALLBACK TwainMsgProc( int nCode, WPARAM wParam, LPARAM lParam )
{
    MSG* pMsg = (MSG*) lParam;

    if( ( nCode < 0 ) || ( pImpTwainInstance->hTwainWnd != pMsg->hwnd ) || !pImpTwainInstance->ImplHandleMsg( (void*) lParam ) )
    {
        return CallNextHookEx( pImpTwainInstance->hTwainHook, nCode, wParam, lParam );
    }
    else
    {
        pMsg->message = WM_USER;
        pMsg->lParam = 0;

        return 0;
    }
}

// #107835# hold reference to ScannerManager, to prevent premature death
ImpTwain::ImpTwain( ScannerManager& rMgr, const Link<unsigned long,void>& rNotifyLink ) :
            mxMgr( uno::Reference< scanner::XScannerManager >( static_cast< OWeakObject* >( &rMgr ), uno::UNO_QUERY) ),
            mrMgr( rMgr ),
            aNotifyLink( rNotifyLink ),
            pDSM( NULL ),
            pMod( NULL ),
            nCurState( 1 ),
            hTwainWnd( 0 ),
            hTwainHook( 0 ),
            mbCloseFrameOnExit( false )
{
    // setup TWAIN window
    pImpTwainInstance = this;

    aAppIdent.Id = 0;
    aAppIdent.Version.MajorNum = 1;
    aAppIdent.Version.MinorNum = 0;
    aAppIdent.Version.Language = TWLG_USA;
    aAppIdent.Version.Country = TWCY_USA;
    aAppIdent.ProtocolMajor = TWON_PROTOCOLMAJOR;
    aAppIdent.ProtocolMinor = TWON_PROTOCOLMINOR;
    aAppIdent.SupportedGroups = DG_IMAGE | DG_CONTROL;
    strncpy( aAppIdent.Version.Info, "8.0", 32 );
    aAppIdent.Version.Info[32] = aAppIdent.Version.Info[33] = 0;
    strncpy( aAppIdent.Manufacturer, "Sun Microsystems", 32 );
    aAppIdent.Manufacturer[32] = aAppIdent.Manufacturer[33] = 0;
    strncpy( aAppIdent.ProductFamily,"Office", 32 );
    aAppIdent.ProductFamily[32] = aAppIdent.ProductFamily[33] = 0;
    strncpy( aAppIdent.ProductName, "Office", 32 );
    aAppIdent.ProductName[32] = aAppIdent.ProductName[33] = 0;

    WNDCLASS aWc = { 0, &TwainWndProc, 0, sizeof( WNDCLASS ), GetModuleHandle( NULL ), NULL, NULL, NULL, NULL, "TwainClass" };
    RegisterClass( &aWc );

    hTwainWnd = CreateWindowEx( WS_EX_TOPMOST, aWc.lpszClassName, "TWAIN", 0, 0, 0, 0, 0, HWND_DESKTOP, NULL, aWc.hInstance, 0 );
    hTwainHook = SetWindowsHookEx( WH_GETMESSAGE, &TwainMsgProc, NULL, GetCurrentThreadId() );

    // block destruction until ImplDestroyHdl is called
    mxSelfRef = static_cast< ::cppu::OWeakObject* >( this );
}

ImpTwain::~ImpTwain()
{
    // are we responsible for application shutdown?
    if( mbCloseFrameOnExit )
        ImplSendCloseEvent();
}

void ImpTwain::Destroy()
{
    ImplFallback( TWAIN_EVENT_NONE );
    Application::PostUserEvent( LINK( this, ImpTwain, ImplDestroyHdl ), NULL );
}

bool ImpTwain::SelectSource()
{
    TW_UINT16 nRet = TWRC_FAILURE;

    ImplOpenSourceManager();

    if( 3 == nCurState )
    {
        TW_IDENTITY aIdent;

        aIdent.Id = 0, aIdent.ProductName[ 0 ] = '\0';
        aNotifyLink.Call( TWAIN_EVENT_SCANNING );
        nRet = PFUNC( &aAppIdent, NULL, DG_CONTROL, DAT_IDENTITY, MSG_USERSELECT, &aIdent );
    }

    ImplFallback( TWAIN_EVENT_QUIT );

    return( TWRC_SUCCESS == nRet );
}

bool ImpTwain::InitXfer()
{
    bool bRet = false;

    ImplOpenSourceManager();

    if( 3 == nCurState )
    {
        ImplOpenSource();

        if( 4 == nCurState )
            bRet = ImplEnableSource();
    }

    if( !bRet )
        ImplFallback( TWAIN_EVENT_QUIT );

    return bRet;
}

void ImpTwain::ImplOpenSourceManager()
{
    if( 1 == nCurState )
    {
        pMod = new ::osl::Module( OUString() );

        if( pMod->load( OUString( TWAIN_LIBNAME  ) ) )
        {
            nCurState = 2;

            pDSM = (DSMENTRYPROC) pMod->getSymbol(OUString(TWAIN_FUNCNAME));
            if (pDSM &&
                ( PFUNC( &aAppIdent, NULL, DG_CONTROL, DAT_PARENT, MSG_OPENDSM, &hTwainWnd ) == TWRC_SUCCESS ) )
            {
                nCurState = 3;
            }
        }
        else
        {
            delete pMod;
            pMod = NULL;
        }
    }
}

void ImpTwain::ImplOpenSource()
{
    if( 3 == nCurState )
    {
        if( ( PFUNC( &aAppIdent, NULL, DG_CONTROL, DAT_IDENTITY, MSG_GETDEFAULT, &aSrcIdent ) == TWRC_SUCCESS ) &&
            ( PFUNC( &aAppIdent, NULL, DG_CONTROL, DAT_IDENTITY, MSG_OPENDS, &aSrcIdent ) == TWRC_SUCCESS ) )
        {
            TW_CAPABILITY   aCap = { CAP_XFERCOUNT, TWON_ONEVALUE, GlobalAlloc( GHND, sizeof( TW_ONEVALUE ) ) };
            TW_ONEVALUE*    pVal = (TW_ONEVALUE*) GlobalLock( aCap.hContainer );

            pVal->ItemType = TWTY_INT16, pVal->Item = 1;
            GlobalUnlock( aCap.hContainer );
            PFUNC( &aAppIdent, &aSrcIdent, DG_CONTROL, DAT_CAPABILITY, MSG_SET, &aCap );
            GlobalFree( aCap.hContainer );
            nCurState = 4;
        }
    }
}

bool ImpTwain::ImplEnableSource()
{
    bool bRet = false;

    if( 4 == nCurState )
    {
        TW_USERINTERFACE aUI = { true, true, hTwainWnd };

        aNotifyLink.Call( TWAIN_EVENT_SCANNING );
        nCurState = 5;

        // register as vetoable close listener, to prevent application to die under us
        ImplRegisterCloseListener();

        if( PFUNC( &aAppIdent, &aSrcIdent, DG_CONTROL, DAT_USERINTERFACE, MSG_ENABLEDS, &aUI ) == TWRC_SUCCESS )
        {
            bRet = true;
        }
        else
        {
            nCurState = 4;

            // deregister as vetoable close listener, dialog failed
            ImplDeregisterCloseListener();
        }
    }

    return bRet;
}

bool ImpTwain::ImplHandleMsg( void* pMsg )
{
    TW_UINT16   nRet;
    PTWAINMSG   pMess = (PTWAINMSG) pMsg;
    TW_EVENT    aEvt = { pMess, MSG_NULL };

    if (pDSM)
        nRet = PFUNC( &aAppIdent, &aSrcIdent, DG_CONTROL, DAT_EVENT, MSG_PROCESSEVENT, &aEvt );
    else
        nRet = TWRC_NOTDSEVENT;

    if( aEvt.TWMessage != MSG_NULL )
    {
        switch( aEvt.TWMessage )
        {
            case MSG_XFERREADY:
            {
                ULONG_PTR nEvent = TWAIN_EVENT_QUIT;

                if( 5 == nCurState )
                {
                    nCurState = 6;
                    ImplXfer();

                    if( mrMgr.GetData() )
                        nEvent = TWAIN_EVENT_XFER;
                }

                ImplFallback( nEvent );
            }
            break;

            case MSG_CLOSEDSREQ:
                ImplFallback( TWAIN_EVENT_QUIT );
            break;

            default:
            break;
        }
    }
    else
        nRet = TWRC_NOTDSEVENT;

    return( TWRC_DSEVENT == nRet );
}

void ImpTwain::ImplXfer()
{
    if( nCurState == 6 )
    {
        TW_IMAGEINFO    aInfo;
        TW_UINT32       hDIB = 0;
        long            nWidth, nHeight, nXRes, nYRes;

        if( PFUNC( &aAppIdent, &aSrcIdent, DG_IMAGE, DAT_IMAGEINFO, MSG_GET, &aInfo ) == TWRC_SUCCESS )
        {
            nWidth = aInfo.ImageWidth;
            nHeight = aInfo.ImageLength;
            nXRes = FIXTOLONG( aInfo.XResolution );
            nYRes = FIXTOLONG( aInfo.YResolution );
        }
        else
            nWidth = nHeight = nXRes = nYRes = -1L;

        switch( PFUNC( &aAppIdent, &aSrcIdent, DG_IMAGE, DAT_IMAGENATIVEXFER, MSG_GET, &hDIB ) )
        {
            case TWRC_CANCEL:
                nCurState = 7;
            break;

            case TWRC_XFERDONE:
            {
                if( hDIB )
                {
                    if( ( nXRes != -1 ) && ( nYRes != - 1 ) && ( nWidth != - 1 ) && ( nHeight != - 1 ) )
                    {
                        // set resolution of bitmap
                        BITMAPINFOHEADER*   pBIH = (BITMAPINFOHEADER*) GlobalLock( (HGLOBAL) (sal_IntPtr) hDIB );
                        static const double fFactor = 100.0 / 2.54;

                        pBIH->biXPelsPerMeter = FRound( fFactor * nXRes );
                        pBIH->biYPelsPerMeter = FRound( fFactor * nYRes );

                        GlobalUnlock( (HGLOBAL) (sal_IntPtr) hDIB );
                    }

                    mrMgr.SetData( (void*) (sal_IntPtr) hDIB );
                }
                else
                    GlobalFree( (HGLOBAL) (sal_IntPtr) hDIB );

                nCurState = 7;
            }
            break;

            default:
            break;
        }
    }
}

void ImpTwain::ImplFallback( ULONG_PTR nEvent )
{
    Application::PostUserEvent( LINK( this, ImpTwain, ImplFallbackHdl ), (void*) nEvent );
}

IMPL_LINK_TYPED( ImpTwain, ImplFallbackHdl, void*, pData, void )
{
    const sal_uIntPtr nEvent = (sal_uIntPtr) pData;
    bool        bFallback = true;

    switch( nCurState )
    {
        case 7:
        case 6:
        {
            TW_PENDINGXFERS aXfers;

            if( PFUNC( &aAppIdent, &aSrcIdent, DG_CONTROL, DAT_PENDINGXFERS, MSG_ENDXFER, &aXfers ) == TWRC_SUCCESS )
            {
                if( aXfers.Count != 0 )
                    PFUNC( &aAppIdent, &aSrcIdent, DG_CONTROL, DAT_PENDINGXFERS, MSG_RESET, &aXfers );
            }

            nCurState = 5;
        }
        break;

        case 5:
        {
            TW_USERINTERFACE aUI = { true, true, hTwainWnd };

            PFUNC( &aAppIdent, &aSrcIdent, DG_CONTROL, DAT_USERINTERFACE, MSG_DISABLEDS, &aUI );
            nCurState = 4;

            // deregister as vetoable close listener
            ImplDeregisterCloseListener();
        }
        break;

        case 4:
        {
            PFUNC( &aAppIdent, NULL, DG_CONTROL, DAT_IDENTITY, MSG_CLOSEDS, &aSrcIdent );
            nCurState = 3;
        }
        break;

        case 3:
        {
            PFUNC( &aAppIdent, NULL, DG_CONTROL, DAT_PARENT, MSG_CLOSEDSM, &hTwainWnd );
            nCurState = 2;
        }
        break;

        case 2:
        {
            delete pMod;
            pMod = NULL;
            nCurState = 1;
        }
        break;

        default:
        {
            if( nEvent != TWAIN_EVENT_NONE )
                aNotifyLink.Call( nEvent );

            bFallback = false;
        }
        break;
    }

    if( bFallback )
        ImplFallback( nEvent );
}

IMPL_LINK_NOARG_TYPED( ImpTwain, ImplDestroyHdl, void*, void )
{
    if( hTwainWnd )
        DestroyWindow( hTwainWnd );

    if( hTwainHook )
        UnhookWindowsHookEx( hTwainHook );

    // permit destruction of ourselves (normally, refcount
    // should drop to zero exactly here)
    mxSelfRef = NULL;
    pImpTwainInstance = NULL;
}

uno::Reference< frame::XFrame > ImpTwain::ImplGetActiveFrame()
{
    try
    {
        // query desktop instance
        uno::Reference< frame::XDesktop2 > xDesktop = frame::Desktop::create( ::comphelper::getProcessComponentContext() );

        uno::Reference< frame::XFrame > xActiveFrame = xDesktop->getActiveFrame();

        if( xActiveFrame.is() )
        {
            return xActiveFrame;
        }
    }
    catch( const uno::Exception& )
    {
    }

    OSL_FAIL("ImpTwain::ImplGetActiveFrame: Could not determine active frame!");
    return uno::Reference< frame::XFrame >();
}

uno::Reference< util::XCloseBroadcaster > ImpTwain::ImplGetActiveFrameCloseBroadcaster()
{
    try
    {
        return uno::Reference< util::XCloseBroadcaster >( ImplGetActiveFrame(), uno::UNO_QUERY );
    }
    catch( const uno::Exception& )
    {
    }

    OSL_FAIL("ImpTwain::ImplGetActiveFrameCloseBroadcaster: Could determine close broadcaster on active frame!");
    return uno::Reference< util::XCloseBroadcaster >();
}

void ImpTwain::ImplRegisterCloseListener()
{
    try
    {
        uno::Reference< util::XCloseBroadcaster > xCloseBroadcaster( ImplGetActiveFrameCloseBroadcaster() );

        if( xCloseBroadcaster.is() )
        {
            xCloseBroadcaster->addCloseListener(this);
            return; // successfully registered as a close listener
        }
        else
        {
            // interface unknown. don't register, then
            OSL_FAIL("ImpTwain::ImplRegisterCloseListener: XFrame has no XCloseBroadcaster!");
            return;
        }
    }
    catch( const uno::Exception& )
    {
    }

    OSL_FAIL("ImpTwain::ImplRegisterCloseListener: Could not register as close listener!");
}

void ImpTwain::ImplDeregisterCloseListener()
{
    try
    {
        uno::Reference< util::XCloseBroadcaster > xCloseBroadcaster(
            ImplGetActiveFrameCloseBroadcaster() );

        if( xCloseBroadcaster.is() )
        {
            xCloseBroadcaster->removeCloseListener(this);
            return; // successfully deregistered as a close listener
        }
        else
        {
            // interface unknown. don't deregister, then
            OSL_FAIL("ImpTwain::ImplDeregisterCloseListener: XFrame has no XCloseBroadcaster!");
            return;
        }
    }
    catch( const uno::Exception& )
    {
    }

    OSL_FAIL("ImpTwain::ImplDeregisterCloseListener: Could not deregister as close listener!");
}

void SAL_CALL ImpTwain::queryClosing( const lang::EventObject& /*Source*/, sal_Bool GetsOwnership ) throw (util::CloseVetoException, uno::RuntimeException)
{
    // shall we re-send the close query later on?
    mbCloseFrameOnExit = GetsOwnership;

    // the sole purpose of this listener is to forbid closing of the listened-at frame
    throw util::CloseVetoException();
}

void SAL_CALL ImpTwain::notifyClosing( const lang::EventObject& /*Source*/ ) throw (uno::RuntimeException)
{
    // should not happen
    OSL_FAIL("ImpTwain::notifyClosing called, but we vetoed the closing before!");
}

void SAL_CALL ImpTwain::disposing( const lang::EventObject& /*Source*/ ) throw (uno::RuntimeException)
{
    // we're not holding any references to the frame, thus noop
}

void ImpTwain::ImplSendCloseEvent()
{
    try
    {
        uno::Reference< util::XCloseable > xCloseable( ImplGetActiveFrame(), uno::UNO_QUERY );

        if( xCloseable.is() )
            xCloseable->close( true );
    }
    catch( const uno::Exception& )
    {
    }

    OSL_FAIL("ImpTwain::ImplSendCloseEvent: Could not send required close broadcast!");
}


class Twain
{
    uno::Reference< lang::XEventListener >      mxListener;
    uno::Reference< scanner::XScannerManager >  mxMgr;
    const ScannerManager*                       mpCurMgr;
    ImpTwain*                                   mpImpTwain;
    TwainState                                  meState;

    DECL_LINK_TYPED( ImpNotifyHdl, unsigned long, void );

public:

                                    Twain();
                                    ~Twain();

    bool                            SelectSource( ScannerManager& rMgr );
    bool                            PerformTransfer( ScannerManager& rMgr, const uno::Reference< lang::XEventListener >& rxListener );

    TwainState                      GetState() const { return meState; }
};

Twain::Twain() :
        mpCurMgr( NULL ),
        mpImpTwain( NULL ),
        meState( TWAIN_STATE_NONE )
{
}

Twain::~Twain()
{
    if( mpImpTwain )
        mpImpTwain->Destroy();
}

bool Twain::SelectSource( ScannerManager& rMgr )
{
    bool bRet;

    if( !mpImpTwain )
    {
        // hold reference to ScannerManager, to prevent premature death
        mxMgr.set( static_cast< OWeakObject* >( const_cast< ScannerManager* >( mpCurMgr = &rMgr ) ),
                   uno::UNO_QUERY ),

        meState = TWAIN_STATE_NONE;
        mpImpTwain = new ImpTwain( rMgr, LINK( this, Twain, ImpNotifyHdl ) );
        bRet = mpImpTwain->SelectSource();
    }
    else
        bRet = false;

    return bRet;
}

bool Twain::PerformTransfer( ScannerManager& rMgr, const uno::Reference< lang::XEventListener >& rxListener )
{
    bool bRet;

    if( !mpImpTwain )
    {
        // hold reference to ScannerManager, to prevent premature death
        mxMgr.set( static_cast< OWeakObject* >( const_cast< ScannerManager* >( mpCurMgr = &rMgr ) ),
                   uno::UNO_QUERY ),

        mxListener = rxListener;
        meState = TWAIN_STATE_NONE;
        mpImpTwain = new ImpTwain( rMgr, LINK( this, Twain, ImpNotifyHdl ) );
        bRet = mpImpTwain->InitXfer();
    }
    else
        bRet = false;

    return bRet;
}

IMPL_LINK_TYPED( Twain, ImpNotifyHdl, unsigned long, nEvent, void )
{
    switch( nEvent )
    {
        case TWAIN_EVENT_SCANNING:
            meState = TWAIN_STATE_SCANNING;
        break;

        case TWAIN_EVENT_QUIT:
        {
            if( meState != TWAIN_STATE_DONE )
                meState = TWAIN_STATE_CANCELED;

            if( mpImpTwain )
            {
                mpImpTwain->Destroy();
                mpImpTwain = NULL;
                mpCurMgr = NULL;
            }

            if( mxListener.is() )
                mxListener->disposing( lang::EventObject( mxMgr ) );

            mxListener = NULL;
        }
        break;

        case TWAIN_EVENT_XFER:
        {
            if( mpImpTwain )
            {
                meState = ( mpCurMgr->GetData() ? TWAIN_STATE_DONE : TWAIN_STATE_CANCELED );

                mpImpTwain->Destroy();
                mpImpTwain = NULL;
                mpCurMgr = NULL;

                if( mxListener.is() )
                    mxListener->disposing( lang::EventObject( mxMgr ) );
            }

            mxListener = NULL;
        }
        break;

        default:
        break;
    }
}

static Twain aTwain;

void ScannerManager::AcquireData()
{
}

void ScannerManager::ReleaseData()
{
    if( mpData )
    {
        GlobalFree( (HGLOBAL)(sal_IntPtr) mpData );
        mpData = NULL;
    }
}

awt::Size ScannerManager::getSize() throw(std::exception)
{
    awt::Size   aRet;
    HGLOBAL     hDIB = (HGLOBAL)(sal_IntPtr) mpData;

    if( hDIB )
    {
        BITMAPINFOHEADER* pBIH = (BITMAPINFOHEADER*) GlobalLock( hDIB );

        if( pBIH )
        {
            aRet.Width = pBIH->biWidth;
            aRet.Height = pBIH->biHeight;
        }
        else
            aRet.Width = aRet.Height = 0;

        GlobalUnlock( hDIB );
    }
    else
        aRet.Width = aRet.Height = 0;

    return aRet;
}

uno::Sequence< sal_Int8 > ScannerManager::getDIB() throw(std::exception)
{
    uno::Sequence< sal_Int8 > aRet;

    if( mpData )
    {
        HGLOBAL             hDIB = (HGLOBAL)(sal_IntPtr) mpData;
        const sal_uInt32    nDIBSize = GlobalSize( hDIB );
        BITMAPINFOHEADER*   pBIH = (BITMAPINFOHEADER*) GlobalLock( hDIB );

        if( pBIH )
        {
            sal_uInt32  nColEntries;

            switch( pBIH->biBitCount )
            {
                case 1:
                case 4:
                case 8:
                    nColEntries = pBIH->biClrUsed ? pBIH->biClrUsed : ( 1 << pBIH->biBitCount );
                break;

                case 24:
                    nColEntries = pBIH->biClrUsed ? pBIH->biClrUsed : 0;
                break;

                case 16:
                case 32:
                {
                    nColEntries = pBIH->biClrUsed;

                    if( pBIH->biCompression == BI_BITFIELDS )
                        nColEntries += 3;
                }
                break;

                default:
                    nColEntries = 0;
                break;
            }

            aRet = uno::Sequence< sal_Int8 >( sizeof( BITMAPFILEHEADER ) + nDIBSize );

            sal_Int8*       pBuf = aRet.getArray();
            SvMemoryStream* pMemStm = new SvMemoryStream( (char*) pBuf, sizeof( BITMAPFILEHEADER ), StreamMode::WRITE );

            pMemStm->WriteChar( 'B' ).WriteChar( 'M' ).WriteUInt32( 0 ).WriteUInt32( 0 );
            pMemStm->WriteUInt32( sizeof( BITMAPFILEHEADER ) + pBIH->biSize + ( nColEntries * sizeof( RGBQUAD ) ) );

            delete pMemStm;
            memcpy( pBuf + sizeof( BITMAPFILEHEADER ), pBIH, nDIBSize );
        }

        GlobalUnlock( hDIB );
        ReleaseData();
    }

    return aRet;
}

uno::Sequence< ScannerContext > SAL_CALL ScannerManager::getAvailableScanners() throw(std::exception)
{
    osl::MutexGuard aGuard( maProtector );
    uno::Sequence< ScannerContext >   aRet( 1 );

    aRet.getArray()[0].ScannerName = "TWAIN" ;
    aRet.getArray()[0].InternalData = 0;

    return aRet;
}

sal_Bool SAL_CALL ScannerManager::configureScannerAndScan( ScannerContext& rContext, const uno::Reference< lang::XEventListener >& )
    throw (ScannerException, RuntimeException, std::exception)
{
    osl::MutexGuard aGuard( maProtector );
    uno::Reference< XScannerManager >   xThis( this );

    if( rContext.InternalData != 0 || rContext.ScannerName != "TWAIN" )
        throw ScannerException("Scanner does not exist", xThis, ScanError_InvalidContext );

    ReleaseData();

    return aTwain.SelectSource( *this );
}

void SAL_CALL ScannerManager::startScan( const ScannerContext& rContext, const uno::Reference< lang::XEventListener >& rxListener )
    throw( ScannerException, std::exception )
{
    osl::MutexGuard aGuard( maProtector );
    uno::Reference< XScannerManager >   xThis( this );

    if( rContext.InternalData != 0 || rContext.ScannerName != "TWAIN" )
        throw ScannerException("Scanner does not exist", xThis, ScanError_InvalidContext );

    ReleaseData();
    aTwain.PerformTransfer( *this, rxListener );
}

ScanError SAL_CALL ScannerManager::getError( const ScannerContext& rContext )
    throw( ScannerException, std::exception )
{
    osl::MutexGuard aGuard( maProtector );
    uno::Reference< XScannerManager >   xThis( this );

    if( rContext.InternalData != 0 || rContext.ScannerName != "TWAIN" )
        throw ScannerException("Scanner does not exist", xThis, ScanError_InvalidContext );

    return( ( aTwain.GetState() == TWAIN_STATE_CANCELED ) ? ScanError_ScanCanceled : ScanError_ScanErrorNone );
}

uno::Reference< awt::XBitmap > SAL_CALL ScannerManager::getBitmap( const ScannerContext& /*rContext*/ )
    throw( ScannerException, std::exception )
{
    osl::MutexGuard aGuard( maProtector );
    return uno::Reference< awt::XBitmap >( this );
}

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