Get the style color and number just once
[LibreOffice.git] / extensions / source / scanner / scanwin.cxx
blob198b092846cdc7512eeb4f83de9179071ce2ce04
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
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"
45 namespace
47 enum TwainState
49 TWAIN_STATE_NONE = 0,
50 TWAIN_STATE_SCANNING = 1,
51 TWAIN_STATE_DONE = 2,
52 TWAIN_STATE_CANCELED = 3
55 struct HANDLEDeleter
57 using pointer = HANDLE;
58 void operator()(HANDLE h) { CloseHandle(h); }
61 using ScopedHANDLE = std::unique_ptr<HANDLE, HANDLEDeleter>;
63 class Twain
65 public:
66 Twain();
67 ~Twain();
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; }
77 private:
78 friend class ShimListenerThread;
79 class ShimListenerThread : public salhelper::Thread
81 public:
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();
95 private:
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;
116 osl::Mutex maMutex;
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
128 Twain aTwain;
130 Twain::ShimListenerThread::ShimListenerThread(const VclPtr<vcl::Window>& xTopWindow)
131 : salhelper::Thread("TWAINShimListenerThread")
132 , mxTopWindow(xTopWindow)
134 if (mxTopWindow)
136 mxTopWindow->IncModalCount(); // the operation is modal to the frame
140 Twain::ShimListenerThread::~ShimListenerThread()
142 if (mxTopWindow)
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)
162 if (mhWndShim)
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)
190 if (!mbDontNotify)
191 aTwain.Notify(nEvent);
194 void Twain::ShimListenerThread::NotifyXFerOwner(LPARAM nHandle)
196 if (!mbDontNotify)
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)
203 switch (nEvent)
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();
215 break;
216 case TWAIN_EVENT_SCANNING:
217 NotifyOwner(nEvent);
218 break;
219 case TWAIN_EVENT_XFER:
220 NotifyXFerOwner(lParam);
221 break;
222 case TWAIN_EVENT_REQUESTRESULT:
223 mbRequestResult = lParam;
224 mcGotRequestResult.set();
225 break;
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()
234 MSG msg;
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);
246 OUString sCmdLine;
247 if (osl::FileBase::getSystemPathFromFileURL(shimURL, sCmdLine) != osl::FileBase::E_None)
248 throw std::exception("getSystemPathFromFileURL failed!");
250 HANDLE hDup;
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 sal_uIntPtr nDup = reinterpret_cast<sal_uIntPtr>(hDup);
257 if constexpr (sizeof(sal_uIntPtr) > 4)
258 if (nDup > 0xFFFFFFFF)
259 throw std::exception("HANDLE does not fit to 32 bit - cannot pass to shim!");
261 // Send this thread handle as the first parameter
262 sCmdLine = "\"" + sCmdLine + "\" " + OUString::number(nDup);
264 // We need a WinAPI HANDLE of the process to be able to wait on it and detect the process
265 // termination; so use WinAPI to start the process, not osl_executeProcess.
267 STARTUPINFOW si{};
268 si.cb = sizeof(si);
269 PROCESS_INFORMATION pi;
271 if (!CreateProcessW(nullptr, const_cast<LPWSTR>(o3tl::toW(sCmdLine.getStr())), nullptr,
272 nullptr, TRUE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi))
273 ThrowLastError("CreateProcessW");
275 CloseHandle(pi.hThread);
276 hShimProcess.reset(pi.hProcess);
278 HANDLE h = hShimProcess.get();
279 while (true)
281 DWORD nWaitResult = MsgWaitForMultipleObjects(1, &h, FALSE, INFINITE, QS_POSTMESSAGE);
282 // Process any messages in queue before checking if we need to break, to not loose
283 // possible pending notifications
284 while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE))
286 // process it here
287 if (msg.message == WM_TWAIN_EVENT)
289 NotificationHdl(msg.wParam, msg.lParam);
292 if (nWaitResult == WAIT_OBJECT_0)
294 // shim process exited - return
295 break;
297 if (nWaitResult == WAIT_FAILED)
299 // Some Win32 error - report and return
300 ThrowLastError("MsgWaitForMultipleObjects");
304 catch (const std::exception& e)
306 msErrorReported = OUString(e.what(), strlen(e.what()), RTL_TEXTENCODING_UTF8);
307 // allow owner to resume (in case the condition isn't set yet)
308 mcInitCompleted.set(); // let mbInitSucceeded keep its (maybe false) value!
310 // allow owner to resume (in case the conditions isn't set yet)
311 mcGotRequestResult.set();
312 NotifyOwner(TWAIN_EVENT_QUIT);
315 Twain::Twain() {}
317 Twain::~Twain()
319 osl::MutexGuard aGuard(maMutex);
320 if (mpThread)
322 mpThread->DontNotify();
323 mpThread->RequestDestroy();
324 mpThread->join();
325 mpThread.clear();
329 void Twain::Reset()
331 mpThread->join();
332 if (!mpThread->getError().isEmpty())
333 SAL_WARN("extensions.scanner", mpThread->getError());
334 mpThread.clear();
335 mpCurMgr = nullptr;
336 mxMgr.clear();
339 bool Twain::InitializeNewShim(ScannerManager& rMgr, const VclPtr<vcl::Window>& xTopWindow)
341 osl::MutexGuard aGuard(maMutex);
342 if (mpThread)
343 return false; // Have a shim for another task already!
345 // hold reference to ScannerManager, to prevent premature death
346 mxMgr = mpCurMgr = &rMgr;
348 mpThread.set(new ShimListenerThread(xTopWindow));
349 mpThread->launch();
350 const bool bSuccess = mpThread->WaitInitialization();
351 if (!bSuccess)
352 Reset();
354 return bSuccess;
357 void Twain::Notify(WPARAM nEvent)
359 Application::PostUserEvent(LINK(this, Twain, ImpNotifyHdl), reinterpret_cast<void*>(nEvent));
362 void Twain::NotifyXFer(LPARAM nHandle)
364 Application::PostUserEvent(LINK(this, Twain, ImpNotifyXferHdl),
365 reinterpret_cast<void*>(nHandle));
368 bool Twain::SelectSource(ScannerManager& rMgr, const VclPtr<vcl::Window>& xTopWindow)
370 osl::MutexGuard aGuard(maMutex);
371 bool bRet = false;
373 if (InitializeNewShim(rMgr, xTopWindow))
375 meState = TWAIN_STATE_NONE;
376 bRet = mpThread->RequestSelectSource();
379 return bRet;
382 bool Twain::PerformTransfer(ScannerManager& rMgr,
383 const css::uno::Reference<css::lang::XEventListener>& rxListener,
384 const VclPtr<vcl::Window>& xTopWindow)
386 osl::MutexGuard aGuard(maMutex);
387 bool bRet = false;
389 if (InitializeNewShim(rMgr, xTopWindow))
391 mxListener = rxListener;
392 meState = TWAIN_STATE_NONE;
393 bRet = mpThread->RequestInitXfer();
396 return bRet;
399 void Twain::WaitReadyForNextTask()
401 while ([&]() {
402 osl::MutexGuard aGuard(maMutex);
403 return bool(mpThread);
404 }())
406 Application::Reschedule(true);
410 IMPL_LINK(Twain, ImpNotifyHdl, void*, pParam, void)
412 osl::MutexGuard aGuard(maMutex);
413 WPARAM nEvent = reinterpret_cast<WPARAM>(pParam);
414 switch (nEvent)
416 case TWAIN_EVENT_SCANNING:
417 meState = TWAIN_STATE_SCANNING;
418 break;
420 case TWAIN_EVENT_QUIT:
422 if (meState != TWAIN_STATE_DONE)
423 meState = TWAIN_STATE_CANCELED;
425 css::lang::EventObject event(mxMgr); // mxMgr will be cleared below
427 if (mpThread)
428 Reset();
430 if (mxListener.is())
432 mxListener->disposing(event);
433 mxListener.clear();
436 break;
438 default:
439 break;
443 IMPL_LINK(Twain, ImpNotifyXferHdl, void*, pParam, void)
445 osl::MutexGuard aGuard(maMutex);
446 if (mpThread)
448 mpCurMgr->SetData(pParam);
449 meState = pParam ? TWAIN_STATE_DONE : TWAIN_STATE_CANCELED;
451 css::lang::EventObject event(mxMgr); // mxMgr will be cleared below
453 Reset();
455 if (mxListener.is())
456 mxListener->disposing(css::lang::EventObject(mxMgr));
459 mxListener.clear();
462 VclPtr<vcl::Window> ImplGetActiveFrameWindow()
466 // query desktop instance
467 css::uno::Reference<css::frame::XDesktop2> xDesktop
468 = css::frame::Desktop::create(comphelper::getProcessComponentContext());
469 if (css::uno::Reference<css::frame::XFrame> xActiveFrame = xDesktop->getActiveFrame())
470 return VCLUnoHelper::GetWindow(xActiveFrame->getComponentWindow());
472 catch (const css::uno::Exception&)
475 SAL_WARN("extensions.scanner", "ImplGetActiveFrame: Could not determine active frame!");
476 return nullptr;
479 } // namespace
481 void ScannerManager::AcquireData() {}
483 void ScannerManager::ReleaseData()
485 if (mpData)
487 CloseHandle(static_cast<HANDLE>(mpData));
488 mpData = nullptr;
492 css::awt::Size ScannerManager::getSize()
494 css::awt::Size aRet;
496 if (mpData)
498 HANDLE hMap = static_cast<HANDLE>(mpData);
499 // map full size
500 const sal_Int8* pMap = static_cast<sal_Int8*>(MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0));
501 if (pMap)
503 const BITMAPINFOHEADER* pBIH = reinterpret_cast<const BITMAPINFOHEADER*>(pMap + 4);
504 aRet.Width = pBIH->biWidth;
505 aRet.Height = pBIH->biHeight;
507 UnmapViewOfFile(pMap);
511 return aRet;
514 css::uno::Sequence<sal_Int8> ScannerManager::getDIB()
516 css::uno::Sequence<sal_Int8> aRet;
518 if (mpData)
520 HANDLE hMap = static_cast<HANDLE>(mpData);
521 // map full size
522 const sal_Int8* pMap = static_cast<sal_Int8*>(MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0));
523 if (pMap)
525 DWORD nDIBSize;
526 memcpy(&nDIBSize, pMap, 4); // size of the following DIB
528 const BITMAPINFOHEADER* pBIH = reinterpret_cast<const BITMAPINFOHEADER*>(pMap + 4);
530 sal_uInt32 nColEntries = 0;
532 switch (pBIH->biBitCount)
534 case 1:
535 case 4:
536 case 8:
537 nColEntries = pBIH->biClrUsed ? pBIH->biClrUsed : (1 << pBIH->biBitCount);
538 break;
540 case 24:
541 nColEntries = pBIH->biClrUsed ? pBIH->biClrUsed : 0;
542 break;
544 case 16:
545 case 32:
546 nColEntries = pBIH->biClrUsed;
547 if (pBIH->biCompression == BI_BITFIELDS)
548 nColEntries += 3;
549 break;
552 aRet = css::uno::Sequence<sal_Int8>(sizeof(BITMAPFILEHEADER) + nDIBSize);
554 sal_Int8* pBuf = aRet.getArray();
555 SvMemoryStream* pMemStm
556 = new SvMemoryStream(pBuf, sizeof(BITMAPFILEHEADER), StreamMode::WRITE);
558 pMemStm->WriteChar('B').WriteChar('M').WriteUInt32(0).WriteUInt32(0);
559 pMemStm->WriteUInt32(sizeof(BITMAPFILEHEADER) + pBIH->biSize
560 + (nColEntries * sizeof(RGBQUAD)));
562 delete pMemStm;
563 memcpy(pBuf + sizeof(BITMAPFILEHEADER), pBIH, nDIBSize);
565 UnmapViewOfFile(pMap);
568 ReleaseData();
571 return aRet;
574 css::uno::Sequence<ScannerContext> SAL_CALL ScannerManager::getAvailableScanners()
576 osl::MutexGuard aGuard(maProtector);
577 css::uno::Sequence<ScannerContext> aRet(1);
579 aRet.getArray()[0].ScannerName = "TWAIN";
580 aRet.getArray()[0].InternalData = 0;
582 return aRet;
585 sal_Bool SAL_CALL ScannerManager::configureScannerAndScan(
586 ScannerContext& rContext, const css::uno::Reference<css::lang::XEventListener>& rxListener)
588 osl::MutexGuard aGuard(maProtector);
589 css::uno::Reference<XScannerManager> xThis(this);
591 if (rContext.InternalData != 0 || rContext.ScannerName != "TWAIN")
592 throw ScannerException("Scanner does not exist", xThis, ScanError_InvalidContext);
594 ReleaseData();
596 VclPtr<vcl::Window> xTopWindow = ImplGetActiveFrameWindow();
597 if (xTopWindow)
598 xTopWindow
599 ->IncModalCount(); // to avoid changes between the two operations that each block the window
600 comphelper::ScopeGuard aModalGuard([xTopWindow]() {
601 if (xTopWindow)
602 xTopWindow->DecModalCount();
605 const bool bSelected = aTwain.SelectSource(*this, xTopWindow);
606 if (bSelected)
608 aTwain.WaitReadyForNextTask();
609 aTwain.PerformTransfer(*this, rxListener, xTopWindow);
611 return bSelected;
614 void SAL_CALL
615 ScannerManager::startScan(const ScannerContext& rContext,
616 const css::uno::Reference<css::lang::XEventListener>& rxListener)
618 osl::MutexGuard aGuard(maProtector);
619 css::uno::Reference<XScannerManager> xThis(this);
621 if (rContext.InternalData != 0 || rContext.ScannerName != "TWAIN")
622 throw ScannerException("Scanner does not exist", xThis, ScanError_InvalidContext);
624 ReleaseData();
625 aTwain.PerformTransfer(*this, rxListener, ImplGetActiveFrameWindow());
628 ScanError SAL_CALL ScannerManager::getError(const ScannerContext& rContext)
630 osl::MutexGuard aGuard(maProtector);
631 css::uno::Reference<XScannerManager> xThis(this);
633 if (rContext.InternalData != 0 || rContext.ScannerName != "TWAIN")
634 throw ScannerException("Scanner does not exist", xThis, ScanError_InvalidContext);
636 return ((aTwain.GetState() == TWAIN_STATE_CANCELED) ? ScanError_ScanCanceled
637 : ScanError_ScanErrorNone);
640 css::uno::Reference<css::awt::XBitmap>
641 SAL_CALL ScannerManager::getBitmap(const ScannerContext& /*rContext*/)
643 osl::MutexGuard aGuard(maProtector);
644 return css::uno::Reference<css::awt::XBitmap>(this);
647 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */