1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <sal/config.h>
22 #include <com/sun/star/uno/Reference.hxx>
23 #include <com/sun/star/frame/XFrame.hpp>
24 #include <com/sun/star/frame/Desktop.hpp>
25 #include <com/sun/star/scanner/ScannerException.hpp>
27 #include "twain32shim.hxx"
29 #include <comphelper/processfactory.hxx>
30 #include <comphelper/scopeguard.hxx>
31 #include <config_folders.h>
32 #include <o3tl/char16_t2wchar_t.hxx>
33 #include <osl/conditn.hxx>
34 #include <osl/file.hxx>
35 #include <osl/mutex.hxx>
36 #include <rtl/bootstrap.hxx>
37 #include <salhelper/thread.hxx>
38 #include <toolkit/helper/vclunohelper.hxx>
39 #include <tools/stream.hxx>
40 #include <tools/helpers.hxx>
41 #include <vcl/svapp.hxx>
42 #include <vcl/window.hxx>
43 #include "scanner.hxx"
50 TWAIN_STATE_SCANNING
= 1,
52 TWAIN_STATE_CANCELED
= 3
57 using pointer
= HANDLE
;
58 void operator()(HANDLE h
) { CloseHandle(h
); }
61 using ScopedHANDLE
= std::unique_ptr
<HANDLE
, HANDLEDeleter
>;
69 bool SelectSource(ScannerManager
& rMgr
, const VclPtr
<vcl::Window
>& xTopWindow
);
70 bool PerformTransfer(ScannerManager
& rMgr
,
71 const css::uno::Reference
<css::lang::XEventListener
>& rxListener
,
72 const VclPtr
<vcl::Window
>& xTopWindow
);
73 void WaitReadyForNextTask();
75 TwainState
GetState() const { return meState
; }
78 friend class ShimListenerThread
;
79 class ShimListenerThread
: public salhelper::Thread
82 ShimListenerThread(const VclPtr
<vcl::Window
>& xTopWindow
);
83 ~ShimListenerThread() override
;
84 void execute() override
;
85 const OUString
& getError() { return msErrorReported
; }
87 // These methods are executed outside of own thread
88 bool WaitInitialization();
89 bool WaitRequestResult();
90 void DontNotify() { mbDontNotify
= true; }
91 void RequestDestroy();
92 bool RequestSelectSource();
93 bool RequestInitXfer();
96 VclPtr
<vcl::Window
> mxTopWindow
; // the window that we made modal
97 bool mbDontNotify
= false;
98 HWND mhWndShim
= nullptr; // shim main window handle
99 OUString msErrorReported
;
100 osl::Condition mcInitCompleted
; // initially not set
101 bool mbInitSucceeded
= false;
102 osl::Condition mcGotRequestResult
;
103 bool mbRequestResult
= false;
105 void SendShimRequest(WPARAM nRequest
);
106 bool SendShimRequestWithResult(WPARAM nRequest
);
107 void NotificationHdl(WPARAM nEvent
, LPARAM lParam
);
108 void NotifyOwner(WPARAM nEvent
);
109 void NotifyXFerOwner(LPARAM nHandle
);
111 css::uno::Reference
<css::lang::XEventListener
> mxListener
;
112 css::uno::Reference
<css::scanner::XScannerManager
> mxMgr
;
113 ScannerManager
* mpCurMgr
= nullptr;
114 TwainState meState
= TWAIN_STATE_NONE
;
115 rtl::Reference
<ShimListenerThread
> mpThread
;
118 DECL_LINK(ImpNotifyHdl
, void*, void);
119 DECL_LINK(ImpNotifyXferHdl
, void*, void);
120 void Notify(WPARAM nEvent
); // called by shim communication thread to notify me
121 void NotifyXFer(LPARAM nHandle
); // called by shim communication thread to notify me
123 bool InitializeNewShim(ScannerManager
& rMgr
, const VclPtr
<vcl::Window
>& xTopWindow
);
125 void Reset(); // cleanup thread and manager
130 Twain::ShimListenerThread::ShimListenerThread(const VclPtr
<vcl::Window
>& xTopWindow
)
131 : salhelper::Thread("TWAINShimListenerThread")
132 , mxTopWindow(xTopWindow
)
136 mxTopWindow
->IncModalCount(); // the operation is modal to the frame
140 Twain::ShimListenerThread::~ShimListenerThread()
144 mxTopWindow
->DecModalCount(); // unblock the frame
148 bool Twain::ShimListenerThread::WaitInitialization()
150 mcInitCompleted
.wait();
151 return mbInitSucceeded
;
154 bool Twain::ShimListenerThread::WaitRequestResult()
156 mcGotRequestResult
.wait();
157 return mbRequestResult
;
160 void Twain::ShimListenerThread::SendShimRequest(WPARAM nRequest
)
163 PostMessageW(mhWndShim
, WM_TWAIN_REQUEST
, nRequest
, 0);
166 bool Twain::ShimListenerThread::SendShimRequestWithResult(WPARAM nRequest
)
168 mcGotRequestResult
.reset();
169 mbRequestResult
= false;
170 SendShimRequest(nRequest
);
171 return WaitRequestResult();
174 void Twain::ShimListenerThread::RequestDestroy() { SendShimRequest(TWAIN_REQUEST_QUIT
); }
176 bool Twain::ShimListenerThread::RequestSelectSource()
178 assert(mbInitSucceeded
);
179 return SendShimRequestWithResult(TWAIN_REQUEST_SELECTSOURCE
);
182 bool Twain::ShimListenerThread::RequestInitXfer()
184 assert(mbInitSucceeded
);
185 return SendShimRequestWithResult(TWAIN_REQUEST_INITXFER
);
188 void Twain::ShimListenerThread::NotifyOwner(WPARAM nEvent
)
191 aTwain
.Notify(nEvent
);
194 void Twain::ShimListenerThread::NotifyXFerOwner(LPARAM nHandle
)
197 aTwain
.NotifyXFer(nHandle
);
200 // May only be called from the own thread, so no threading issues modifying self
201 void Twain::ShimListenerThread::NotificationHdl(WPARAM nEvent
, LPARAM lParam
)
205 case TWAIN_EVENT_NOTIFYHWND
: // shim reported its main HWND for communications
206 if (!mcInitCompleted
.check()) // only if not yet initialized!
208 // Owner is still waiting mcInitCompleted in its Twain::InitializeNewShim,
209 // holding its access mutex
210 mhWndShim
= reinterpret_cast<HWND
>(lParam
);
212 mbInitSucceeded
= lParam
!= 0;
213 mcInitCompleted
.set();
216 case TWAIN_EVENT_SCANNING
:
219 case TWAIN_EVENT_XFER
:
220 NotifyXFerOwner(lParam
);
222 case TWAIN_EVENT_REQUESTRESULT
:
223 mbRequestResult
= lParam
;
224 mcGotRequestResult
.set();
226 // We don't handle TWAIN_EVENT_QUIT notification from shim, because we send it ourselves
227 // in the end of execute()
231 // Spawn a separate 32-bit process to use TWAIN on Windows, and listen for its notifications
232 void Twain::ShimListenerThread::execute()
235 // Initialize thread message queue before launching shim process
236 PeekMessageW(&msg
, nullptr, 0, 0, PM_NOREMOVE
);
240 ScopedHANDLE hShimProcess
;
242 // Determine twain32shim executable URL:
243 OUString
shimURL("$BRAND_BASE_DIR/" LIBO_BIN_FOLDER
"/twain32shim.exe");
244 rtl::Bootstrap::expandMacros(shimURL
);
247 if (osl::FileBase::getSystemPathFromFileURL(shimURL
, sCmdLine
) != osl::FileBase::E_None
)
248 throw std::exception("getSystemPathFromFileURL failed!");
251 if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(),
252 &hDup
, SYNCHRONIZE
| THREAD_QUERY_LIMITED_INFORMATION
, TRUE
, 0))
253 ThrowLastError("DuplicateHandle");
254 // we will not need our copy as soon as shim has its own inherited one
255 ScopedHANDLE
hScopedDup(hDup
);
256 DWORD nDup
= static_cast<DWORD
>(reinterpret_cast<sal_uIntPtr
>(hDup
));
257 if (reinterpret_cast<HANDLE
>(nDup
) != hDup
)
258 throw std::exception("HANDLE does not fit to 32 bit - cannot pass to shim!");
260 // Send this thread handle as the first parameter
261 sCmdLine
= "\"" + sCmdLine
+ "\" " + OUString::number(nDup
);
263 // We need a WinAPI HANDLE of the process to be able to wait on it and detect the process
264 // termination; so use WinAPI to start the process, not osl_executeProcess.
268 PROCESS_INFORMATION pi
;
270 if (!CreateProcessW(nullptr, const_cast<LPWSTR
>(o3tl::toW(sCmdLine
.getStr())), nullptr,
271 nullptr, TRUE
, CREATE_NO_WINDOW
, nullptr, nullptr, &si
, &pi
))
272 ThrowLastError("CreateProcessW");
274 CloseHandle(pi
.hThread
);
275 hShimProcess
.reset(pi
.hProcess
);
277 HANDLE h
= hShimProcess
.get();
280 DWORD nWaitResult
= MsgWaitForMultipleObjects(1, &h
, FALSE
, INFINITE
, QS_POSTMESSAGE
);
281 // Process any messages in queue before checking if we need to break, to not loose
282 // possible pending notifications
283 while (PeekMessageW(&msg
, nullptr, 0, 0, PM_REMOVE
))
286 if (msg
.message
== WM_TWAIN_EVENT
)
288 NotificationHdl(msg
.wParam
, msg
.lParam
);
291 if (nWaitResult
== WAIT_OBJECT_0
)
293 // shim process exited - return
296 if (nWaitResult
== WAIT_FAILED
)
298 // Some Win32 error - report and return
299 ThrowLastError("MsgWaitForMultipleObjects");
303 catch (const std::exception
& e
)
305 msErrorReported
= OUString(e
.what(), strlen(e
.what()), RTL_TEXTENCODING_UTF8
);
306 // allow owner to resume (in case the condition isn't set yet)
307 mcInitCompleted
.set(); // let mbInitSucceeded keep its (maybe false) value!
309 // allow owner to resume (in case the conditions isn't set yet)
310 mcGotRequestResult
.set();
311 NotifyOwner(TWAIN_EVENT_QUIT
);
318 osl::MutexGuard
aGuard(maMutex
);
321 mpThread
->DontNotify();
322 mpThread
->RequestDestroy();
331 if (!mpThread
->getError().isEmpty())
332 SAL_WARN("extensions.scanner", mpThread
->getError());
338 bool Twain::InitializeNewShim(ScannerManager
& rMgr
, const VclPtr
<vcl::Window
>& xTopWindow
)
340 osl::MutexGuard
aGuard(maMutex
);
342 return false; // Have a shim for another task already!
344 // hold reference to ScannerManager, to prevent premature death
345 mxMgr
= mpCurMgr
= &rMgr
;
347 mpThread
.set(new ShimListenerThread(xTopWindow
));
349 const bool bSuccess
= mpThread
->WaitInitialization();
356 void Twain::Notify(WPARAM nEvent
)
358 Application::PostUserEvent(LINK(this, Twain
, ImpNotifyHdl
), reinterpret_cast<void*>(nEvent
));
361 void Twain::NotifyXFer(LPARAM nHandle
)
363 Application::PostUserEvent(LINK(this, Twain
, ImpNotifyXferHdl
),
364 reinterpret_cast<void*>(nHandle
));
367 bool Twain::SelectSource(ScannerManager
& rMgr
, const VclPtr
<vcl::Window
>& xTopWindow
)
369 osl::MutexGuard
aGuard(maMutex
);
372 if (InitializeNewShim(rMgr
, xTopWindow
))
374 meState
= TWAIN_STATE_NONE
;
375 bRet
= mpThread
->RequestSelectSource();
381 bool Twain::PerformTransfer(ScannerManager
& rMgr
,
382 const css::uno::Reference
<css::lang::XEventListener
>& rxListener
,
383 const VclPtr
<vcl::Window
>& xTopWindow
)
385 osl::MutexGuard
aGuard(maMutex
);
388 if (InitializeNewShim(rMgr
, xTopWindow
))
390 mxListener
= rxListener
;
391 meState
= TWAIN_STATE_NONE
;
392 bRet
= mpThread
->RequestInitXfer();
398 void Twain::WaitReadyForNextTask()
401 osl::MutexGuard
aGuard(maMutex
);
402 return bool(mpThread
);
405 Application::Reschedule(true);
409 IMPL_LINK(Twain
, ImpNotifyHdl
, void*, pParam
, void)
411 osl::MutexGuard
aGuard(maMutex
);
412 WPARAM nEvent
= reinterpret_cast<WPARAM
>(pParam
);
415 case TWAIN_EVENT_SCANNING
:
416 meState
= TWAIN_STATE_SCANNING
;
419 case TWAIN_EVENT_QUIT
:
421 if (meState
!= TWAIN_STATE_DONE
)
422 meState
= TWAIN_STATE_CANCELED
;
424 css::lang::EventObject
event(mxMgr
); // mxMgr will be cleared below
431 mxListener
->disposing(event
);
442 IMPL_LINK(Twain
, ImpNotifyXferHdl
, void*, pParam
, void)
444 osl::MutexGuard
aGuard(maMutex
);
447 mpCurMgr
->SetData(pParam
);
448 meState
= pParam
? TWAIN_STATE_DONE
: TWAIN_STATE_CANCELED
;
450 css::lang::EventObject
event(mxMgr
); // mxMgr will be cleared below
455 mxListener
->disposing(css::lang::EventObject(mxMgr
));
461 VclPtr
<vcl::Window
> ImplGetActiveFrameWindow()
465 // query desktop instance
466 css::uno::Reference
<css::frame::XDesktop2
> xDesktop
467 = css::frame::Desktop::create(comphelper::getProcessComponentContext());
468 if (css::uno::Reference
<css::frame::XFrame
> xActiveFrame
= xDesktop
->getActiveFrame())
469 return VCLUnoHelper::GetWindow(xActiveFrame
->getComponentWindow());
471 catch (const css::uno::Exception
&)
474 SAL_WARN("extensions.scanner", "ImplGetActiveFrame: Could not determine active frame!");
480 void ScannerManager::AcquireData() {}
482 void ScannerManager::ReleaseData()
486 CloseHandle(static_cast<HANDLE
>(mpData
));
491 css::awt::Size
ScannerManager::getSize()
497 HANDLE hMap
= static_cast<HANDLE
>(mpData
);
499 const sal_Int8
* pMap
= static_cast<sal_Int8
*>(MapViewOfFile(hMap
, FILE_MAP_READ
, 0, 0, 0));
502 const BITMAPINFOHEADER
* pBIH
= reinterpret_cast<const BITMAPINFOHEADER
*>(pMap
+ 4);
503 aRet
.Width
= pBIH
->biWidth
;
504 aRet
.Height
= pBIH
->biHeight
;
506 UnmapViewOfFile(pMap
);
513 css::uno::Sequence
<sal_Int8
> ScannerManager::getDIB()
515 css::uno::Sequence
<sal_Int8
> aRet
;
519 HANDLE hMap
= static_cast<HANDLE
>(mpData
);
521 const sal_Int8
* pMap
= static_cast<sal_Int8
*>(MapViewOfFile(hMap
, FILE_MAP_READ
, 0, 0, 0));
525 memcpy(&nDIBSize
, pMap
, 4); // size of the following DIB
527 const BITMAPINFOHEADER
* pBIH
= reinterpret_cast<const BITMAPINFOHEADER
*>(pMap
+ 4);
529 sal_uInt32 nColEntries
= 0;
531 switch (pBIH
->biBitCount
)
536 nColEntries
= pBIH
->biClrUsed
? pBIH
->biClrUsed
: (1 << pBIH
->biBitCount
);
540 nColEntries
= pBIH
->biClrUsed
? pBIH
->biClrUsed
: 0;
545 nColEntries
= pBIH
->biClrUsed
;
546 if (pBIH
->biCompression
== BI_BITFIELDS
)
551 aRet
= css::uno::Sequence
<sal_Int8
>(sizeof(BITMAPFILEHEADER
) + nDIBSize
);
553 sal_Int8
* pBuf
= aRet
.getArray();
554 SvMemoryStream
* pMemStm
555 = new SvMemoryStream(pBuf
, sizeof(BITMAPFILEHEADER
), StreamMode::WRITE
);
557 pMemStm
->WriteChar('B').WriteChar('M').WriteUInt32(0).WriteUInt32(0);
558 pMemStm
->WriteUInt32(sizeof(BITMAPFILEHEADER
) + pBIH
->biSize
559 + (nColEntries
* sizeof(RGBQUAD
)));
562 memcpy(pBuf
+ sizeof(BITMAPFILEHEADER
), pBIH
, nDIBSize
);
564 UnmapViewOfFile(pMap
);
573 css::uno::Sequence
<ScannerContext
> SAL_CALL
ScannerManager::getAvailableScanners()
575 osl::MutexGuard
aGuard(maProtector
);
576 css::uno::Sequence
<ScannerContext
> aRet(1);
578 aRet
.getArray()[0].ScannerName
= "TWAIN";
579 aRet
.getArray()[0].InternalData
= 0;
584 sal_Bool SAL_CALL
ScannerManager::configureScannerAndScan(
585 ScannerContext
& rContext
, const css::uno::Reference
<css::lang::XEventListener
>& rxListener
)
587 osl::MutexGuard
aGuard(maProtector
);
588 css::uno::Reference
<XScannerManager
> xThis(this);
590 if (rContext
.InternalData
!= 0 || rContext
.ScannerName
!= "TWAIN")
591 throw ScannerException("Scanner does not exist", xThis
, ScanError_InvalidContext
);
595 VclPtr
<vcl::Window
> xTopWindow
= ImplGetActiveFrameWindow();
598 ->IncModalCount(); // to avoid changes between the two operations that each block the window
599 comphelper::ScopeGuard
aModalGuard([xTopWindow
]() {
601 xTopWindow
->DecModalCount();
604 const bool bSelected
= aTwain
.SelectSource(*this, xTopWindow
);
607 aTwain
.WaitReadyForNextTask();
608 aTwain
.PerformTransfer(*this, rxListener
, xTopWindow
);
614 ScannerManager::startScan(const ScannerContext
& rContext
,
615 const css::uno::Reference
<css::lang::XEventListener
>& rxListener
)
617 osl::MutexGuard
aGuard(maProtector
);
618 css::uno::Reference
<XScannerManager
> xThis(this);
620 if (rContext
.InternalData
!= 0 || rContext
.ScannerName
!= "TWAIN")
621 throw ScannerException("Scanner does not exist", xThis
, ScanError_InvalidContext
);
624 aTwain
.PerformTransfer(*this, rxListener
, ImplGetActiveFrameWindow());
627 ScanError SAL_CALL
ScannerManager::getError(const ScannerContext
& rContext
)
629 osl::MutexGuard
aGuard(maProtector
);
630 css::uno::Reference
<XScannerManager
> xThis(this);
632 if (rContext
.InternalData
!= 0 || rContext
.ScannerName
!= "TWAIN")
633 throw ScannerException("Scanner does not exist", xThis
, ScanError_InvalidContext
);
635 return ((aTwain
.GetState() == TWAIN_STATE_CANCELED
) ? ScanError_ScanCanceled
636 : ScanError_ScanErrorNone
);
639 css::uno::Reference
<css::awt::XBitmap
>
640 SAL_CALL
ScannerManager::getBitmap(const ScannerContext
& /*rContext*/)
642 osl::MutexGuard
aGuard(maProtector
);
643 return css::uno::Reference
<css::awt::XBitmap
>(this);
646 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */