Avoid potential negative array index access to cached text.
[LibreOffice.git] / extensions / source / scanner / scanwin.cxx
blob109f2944a3b517ca61c3d8f58ef0cd93729a0cf0
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 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.
266 STARTUPINFOW si{};
267 si.cb = sizeof(si);
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();
278 while (true)
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))
285 // process it here
286 if (msg.message == WM_TWAIN_EVENT)
288 NotificationHdl(msg.wParam, msg.lParam);
291 if (nWaitResult == WAIT_OBJECT_0)
293 // shim process exited - return
294 break;
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);
314 Twain::Twain() {}
316 Twain::~Twain()
318 osl::MutexGuard aGuard(maMutex);
319 if (mpThread)
321 mpThread->DontNotify();
322 mpThread->RequestDestroy();
323 mpThread->join();
324 mpThread.clear();
328 void Twain::Reset()
330 mpThread->join();
331 if (!mpThread->getError().isEmpty())
332 SAL_WARN("extensions.scanner", mpThread->getError());
333 mpThread.clear();
334 mpCurMgr = nullptr;
335 mxMgr.clear();
338 bool Twain::InitializeNewShim(ScannerManager& rMgr, const VclPtr<vcl::Window>& xTopWindow)
340 osl::MutexGuard aGuard(maMutex);
341 if (mpThread)
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));
348 mpThread->launch();
349 const bool bSuccess = mpThread->WaitInitialization();
350 if (!bSuccess)
351 Reset();
353 return bSuccess;
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);
370 bool bRet = false;
372 if (InitializeNewShim(rMgr, xTopWindow))
374 meState = TWAIN_STATE_NONE;
375 bRet = mpThread->RequestSelectSource();
378 return bRet;
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);
386 bool bRet = false;
388 if (InitializeNewShim(rMgr, xTopWindow))
390 mxListener = rxListener;
391 meState = TWAIN_STATE_NONE;
392 bRet = mpThread->RequestInitXfer();
395 return bRet;
398 void Twain::WaitReadyForNextTask()
400 while ([&]() {
401 osl::MutexGuard aGuard(maMutex);
402 return bool(mpThread);
403 }())
405 Application::Reschedule(true);
409 IMPL_LINK(Twain, ImpNotifyHdl, void*, pParam, void)
411 osl::MutexGuard aGuard(maMutex);
412 WPARAM nEvent = reinterpret_cast<WPARAM>(pParam);
413 switch (nEvent)
415 case TWAIN_EVENT_SCANNING:
416 meState = TWAIN_STATE_SCANNING;
417 break;
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
426 if (mpThread)
427 Reset();
429 if (mxListener.is())
431 mxListener->disposing(event);
432 mxListener.clear();
435 break;
437 default:
438 break;
442 IMPL_LINK(Twain, ImpNotifyXferHdl, void*, pParam, void)
444 osl::MutexGuard aGuard(maMutex);
445 if (mpThread)
447 mpCurMgr->SetData(pParam);
448 meState = pParam ? TWAIN_STATE_DONE : TWAIN_STATE_CANCELED;
450 css::lang::EventObject event(mxMgr); // mxMgr will be cleared below
452 Reset();
454 if (mxListener.is())
455 mxListener->disposing(css::lang::EventObject(mxMgr));
458 mxListener.clear();
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!");
475 return nullptr;
478 } // namespace
480 void ScannerManager::AcquireData() {}
482 void ScannerManager::ReleaseData()
484 if (mpData)
486 CloseHandle(static_cast<HANDLE>(mpData));
487 mpData = nullptr;
491 css::awt::Size ScannerManager::getSize()
493 css::awt::Size aRet;
495 if (mpData)
497 HANDLE hMap = static_cast<HANDLE>(mpData);
498 // map full size
499 const sal_Int8* pMap = static_cast<sal_Int8*>(MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0));
500 if (pMap)
502 const BITMAPINFOHEADER* pBIH = reinterpret_cast<const BITMAPINFOHEADER*>(pMap + 4);
503 aRet.Width = pBIH->biWidth;
504 aRet.Height = pBIH->biHeight;
506 UnmapViewOfFile(pMap);
510 return aRet;
513 css::uno::Sequence<sal_Int8> ScannerManager::getDIB()
515 css::uno::Sequence<sal_Int8> aRet;
517 if (mpData)
519 HANDLE hMap = static_cast<HANDLE>(mpData);
520 // map full size
521 const sal_Int8* pMap = static_cast<sal_Int8*>(MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0));
522 if (pMap)
524 DWORD nDIBSize;
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)
533 case 1:
534 case 4:
535 case 8:
536 nColEntries = pBIH->biClrUsed ? pBIH->biClrUsed : (1 << pBIH->biBitCount);
537 break;
539 case 24:
540 nColEntries = pBIH->biClrUsed ? pBIH->biClrUsed : 0;
541 break;
543 case 16:
544 case 32:
545 nColEntries = pBIH->biClrUsed;
546 if (pBIH->biCompression == BI_BITFIELDS)
547 nColEntries += 3;
548 break;
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)));
561 delete pMemStm;
562 memcpy(pBuf + sizeof(BITMAPFILEHEADER), pBIH, nDIBSize);
564 UnmapViewOfFile(pMap);
567 ReleaseData();
570 return aRet;
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;
581 return aRet;
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);
593 ReleaseData();
595 VclPtr<vcl::Window> xTopWindow = ImplGetActiveFrameWindow();
596 if (xTopWindow)
597 xTopWindow
598 ->IncModalCount(); // to avoid changes between the two operations that each block the window
599 comphelper::ScopeGuard aModalGuard([xTopWindow]() {
600 if (xTopWindow)
601 xTopWindow->DecModalCount();
604 const bool bSelected = aTwain.SelectSource(*this, xTopWindow);
605 if (bSelected)
607 aTwain.WaitReadyForNextTask();
608 aTwain.PerformTransfer(*this, rxListener, xTopWindow);
610 return bSelected;
613 void SAL_CALL
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);
623 ReleaseData();
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: */