Avoid potential negative array index access to cached text.
[LibreOffice.git] / framework / source / dispatch / closedispatcher.cxx
blob2fd3bc91e39fc12e7c71eace3cacbcf66b3a32dd
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 <dispatch/closedispatcher.hxx>
21 #include <pattern/frame.hxx>
22 #include <framework/framelistanalyzer.hxx>
23 #include <services.h>
25 #include <com/sun/star/bridge/BridgeFactory.hpp>
26 #include <com/sun/star/bridge/XBridgeFactory2.hpp>
27 #include <com/sun/star/frame/Desktop.hpp>
28 #include <com/sun/star/frame/DispatchResultState.hpp>
29 #include <com/sun/star/frame/XController.hpp>
30 #include <com/sun/star/frame/CommandGroup.hpp>
31 #include <com/sun/star/frame/StartModule.hpp>
32 #include <com/sun/star/lang/DisposedException.hpp>
33 #include <com/sun/star/awt/XTopWindow.hpp>
34 #include <com/sun/star/document/XActionLockable.hpp>
35 #include <com/sun/star/beans/XFastPropertySet.hpp>
36 #include <toolkit/helper/vclunohelper.hxx>
38 #include <osl/diagnose.h>
39 #include <utility>
40 #include <vcl/window.hxx>
41 #include <vcl/svapp.hxx>
42 #include <vcl/syswin.hxx>
43 #include <unotools/moduleoptions.hxx>
44 #include <o3tl/string_view.hxx>
46 using namespace com::sun::star;
48 namespace framework{
50 #ifdef fpf
51 #error "Who uses \"fpf\" as define. It will overwrite my namespace alias ..."
52 #endif
53 namespace fpf = ::framework::pattern::frame;
55 constexpr OUString URL_CLOSEDOC = u".uno:CloseDoc"_ustr;
56 constexpr OUString URL_CLOSEWIN = u".uno:CloseWin"_ustr;
57 const char URL_CLOSEFRAME[] = ".uno:CloseFrame";
59 CloseDispatcher::CloseDispatcher(css::uno::Reference< css::uno::XComponentContext > xContext ,
60 const css::uno::Reference< css::frame::XFrame >& xFrame ,
61 std::u16string_view sTarget)
62 : m_xContext(std::move(xContext))
63 , m_aAsyncCallback(
64 new vcl::EventPoster(LINK(this, CloseDispatcher, impl_asyncCallback)))
65 , m_eOperation(E_CLOSE_DOC)
66 , m_pSysWindow(nullptr)
68 uno::Reference<frame::XFrame> xTarget = static_impl_searchRightTargetFrame(xFrame, sTarget);
69 m_xCloseFrame = xTarget;
71 // Try to retrieve the system window instance of the closing frame.
72 uno::Reference<awt::XWindow> xWindow = xTarget->getContainerWindow();
73 if (xWindow.is())
75 VclPtr<vcl::Window> pWindow = VCLUnoHelper::GetWindow(xWindow);
76 if (pWindow->IsSystemWindow())
77 m_pSysWindow = dynamic_cast<SystemWindow*>(pWindow.get());
81 CloseDispatcher::~CloseDispatcher()
83 SolarMutexGuard g;
84 m_aAsyncCallback.reset();
85 m_pSysWindow.reset();
88 void SAL_CALL CloseDispatcher::dispatch(const css::util::URL& aURL ,
89 const css::uno::Sequence< css::beans::PropertyValue >& lArguments)
91 dispatchWithNotification(aURL, lArguments, css::uno::Reference< css::frame::XDispatchResultListener >());
94 css::uno::Sequence< sal_Int16 > SAL_CALL CloseDispatcher::getSupportedCommandGroups()
96 return css::uno::Sequence< sal_Int16 >{css::frame::CommandGroup::VIEW, css::frame::CommandGroup::DOCUMENT};
99 css::uno::Sequence< css::frame::DispatchInformation > SAL_CALL CloseDispatcher::getConfigurableDispatchInformation(sal_Int16 nCommandGroup)
101 if (nCommandGroup == css::frame::CommandGroup::VIEW)
103 /* Attention: Don't add .uno:CloseFrame here. Because it's not really
104 a configurable feature ... and further it does not have
105 a valid UIName entry inside the GenericCommands.xcu ... */
106 css::uno::Sequence< css::frame::DispatchInformation > lViewInfos{
107 { URL_CLOSEWIN, css::frame::CommandGroup::VIEW }
109 return lViewInfos;
111 else if (nCommandGroup == css::frame::CommandGroup::DOCUMENT)
113 css::uno::Sequence< css::frame::DispatchInformation > lDocInfos{
114 { URL_CLOSEDOC, css::frame::CommandGroup::DOCUMENT }
116 return lDocInfos;
119 return css::uno::Sequence< css::frame::DispatchInformation >();
122 void SAL_CALL CloseDispatcher::addStatusListener(const css::uno::Reference< css::frame::XStatusListener >& /*xListener*/,
123 const css::util::URL& /*aURL*/ )
127 void SAL_CALL CloseDispatcher::removeStatusListener(const css::uno::Reference< css::frame::XStatusListener >& /*xListener*/,
128 const css::util::URL& /*aURL*/ )
132 void SAL_CALL CloseDispatcher::dispatchWithNotification(const css::util::URL& aURL ,
133 const css::uno::Sequence< css::beans::PropertyValue >& lArguments,
134 const css::uno::Reference< css::frame::XDispatchResultListener >& xListener )
136 // SAFE -> ----------------------------------
137 SolarMutexClearableGuard aWriteLock;
139 // This reference indicates, that we were already called before and
140 // our asynchronous process was not finished yet.
141 // We have to reject double calls. Otherwise we risk,
142 // that we try to close an already closed resource...
143 // And it is no problem to do nothing then. The UI user will try it again, if
144 // non of these jobs was successful.
145 if (m_xSelfHold.is())
147 aWriteLock.clear();
148 // <- SAFE ------------------------------
150 implts_notifyResultListener(
151 xListener,
152 css::frame::DispatchResultState::DONTKNOW,
153 css::uno::Any());
154 return;
157 // First we have to check, if this dispatcher is used right. Means if valid URLs are used.
158 // If not - we have to break this operation. But an optional listener must be informed.
159 // BTW: We save the information about the requested operation. Because
160 // we need it later.
161 if ( aURL.Complete == URL_CLOSEDOC )
162 m_eOperation = E_CLOSE_DOC;
163 else if ( aURL.Complete == URL_CLOSEWIN )
164 m_eOperation = E_CLOSE_WIN;
165 else if ( aURL.Complete == URL_CLOSEFRAME )
166 m_eOperation = E_CLOSE_FRAME;
167 else
169 aWriteLock.clear();
170 // <- SAFE ------------------------------
172 implts_notifyResultListener(
173 xListener,
174 css::frame::DispatchResultState::FAILURE,
175 css::uno::Any());
176 return;
179 if (m_pSysWindow && m_pSysWindow->GetCloseHdl().IsSet())
181 // The closing frame has its own close handler. Call it instead.
182 m_pSysWindow->GetCloseHdl().Call(*m_pSysWindow);
184 aWriteLock.clear();
185 // <- SAFE ------------------------------
187 implts_notifyResultListener(
188 xListener,
189 css::frame::DispatchResultState::SUCCESS,
190 css::uno::Any());
192 return;
195 // OK - URLs are the right ones.
196 // But we can't execute synchronously :-)
197 // May we are called from a generic key-input handler,
198 // which isn't aware that this call kill its own environment...
199 // Do it asynchronous everytimes!
201 // But don't forget to hold ourselves alive.
202 // We are called back from an environment, which doesn't know a uno reference.
203 // They call us back by using our c++ interface.
205 m_xResultListener = xListener;
206 m_xSelfHold.set(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY);
208 aWriteLock.clear();
209 // <- SAFE ----------------------------------
211 bool bIsSynchron = false;
212 for (const css::beans::PropertyValue& rArg : lArguments )
214 if ( rArg.Name == "SynchronMode" )
216 rArg.Value >>= bIsSynchron;
217 break;
221 if ( bIsSynchron )
222 impl_asyncCallback(nullptr);
223 else
225 SolarMutexGuard g;
226 m_aAsyncCallback->Post();
231 @short asynchronous callback
232 @descr We start all actions inside this object asynchronous
233 (see comments there).
234 Now we do the following:
235 - close all views to the same document, if needed and possible
236 - make the current frame empty
237 ! This step is necessary to handle errors during closing the
238 document inside the frame. May the document shows a dialog and
239 the user ignore it. Then the state of the office can be changed
240 during we try to close frame and document.
241 - check the environment (means count open frames - excluding our
242 current one)
243 - decide then, if we must close this frame only, establish the backing mode
244 or shutdown the whole application.
246 IMPL_LINK_NOARG(CloseDispatcher, impl_asyncCallback, LinkParamNone*, void)
251 // Allow calling of XController->suspend() everytimes.
252 // Dispatch is an UI functionality. We implement such dispatch object here.
253 // And further XController->suspend() was designed to bring an UI ...
254 bool bControllerSuspended = false;
256 bool bCloseAllViewsToo;
257 EOperation eOperation;
258 css::uno::Reference< css::uno::XComponentContext > xContext;
259 css::uno::Reference< css::frame::XFrame > xCloseFrame;
260 css::uno::Reference< css::frame::XDispatchResultListener > xListener;
262 SolarMutexGuard g;
264 // Closing of all views, related to the same document, is allowed
265 // only if the dispatched URL was ".uno:CloseDoc"!
266 bCloseAllViewsToo = (m_eOperation == E_CLOSE_DOC);
268 eOperation = m_eOperation;
269 xContext = m_xContext;
270 xCloseFrame.set(m_xCloseFrame.get(), css::uno::UNO_QUERY);
271 xListener = m_xResultListener;
274 // frame already dead ?!
275 // Nothing to do !
276 if (! xCloseFrame.is())
277 return;
279 bool bCloseFrame = false;
280 bool bEstablishBackingMode = false;
281 bool bTerminateApp = false;
283 // Analyze the environment a first time.
284 // If we found some special cases, we can
285 // make some decisions earlier!
286 css::uno::Reference< css::frame::XFramesSupplier > xDesktop( css::frame::Desktop::create(xContext), css::uno::UNO_QUERY_THROW);
287 FrameListAnalyzer aCheck1(xDesktop, xCloseFrame, FrameAnalyzerFlags::Help | FrameAnalyzerFlags::BackingComponent);
289 // Check for existing UNO connections.
290 // NOTE: There is a race between checking this and connections being created/destroyed before
291 // we close the frame / terminate the app.
292 css::uno::Reference<css::bridge::XBridgeFactory2> bridgeFac( css::bridge::BridgeFactory::create(xContext) );
293 bool bHasActiveConnections = bridgeFac->getExistingBridges().hasElements();
295 // a) If the current frame (where the close dispatch was requested for) does not have
296 // any parent frame ... it will close this frame only. Such frame isn't part of the
297 // global desktop tree ... and such frames are used as "implementation details" only.
298 // E.g. the live previews of our wizards doing such things. And then the owner of the frame
299 // is responsible for closing the application or accepting closing of the application
300 // by others.
301 if ( ! xCloseFrame->getCreator().is())
302 bCloseFrame = true;
304 // b) The help window can't disagree with any request.
305 // Because it doesn't implement a controller - it uses a window only.
306 // Further it can't be the last open frame - if we do all other things
307 // right inside this CloseDispatcher implementation.
308 // => close it!
309 else if (aCheck1.m_bReferenceIsHelp)
310 bCloseFrame = true;
312 // c) If we are already in "backing mode", we terminate the application, if no active UNO connections are found.
313 // If there is an active UNO connection, we only close the frame and leave the application alive.
314 // It doesn't matter, how many other frames (can be the help or hidden frames only) are open then.
315 else if (aCheck1.m_bReferenceIsBacking) {
316 if (bHasActiveConnections)
317 bCloseFrame = true;
318 else
319 bTerminateApp = true;
322 // d) Otherwise we have to: close all views to the same document, close the
323 // document inside our own frame and decide then again, what has to be done!
324 else
326 if (implts_prepareFrameForClosing(m_xCloseFrame, bCloseAllViewsToo, bControllerSuspended))
328 // OK; this frame is empty now.
329 // Check the environment again to decide, what is the next step.
330 FrameListAnalyzer aCheck2(xDesktop, xCloseFrame, FrameAnalyzerFlags::All);
332 // c1) there is as minimum 1 frame open, which is visible and contains a document
333 // different from our one. And it's not the help!
334 // (tdf#30920 consider that closing a frame which is not the backing window (start center) while there is
335 // another frame that is the backing window open only closes the frame, and not terminate the app, so
336 // closing the license frame doesn't terminate the app if launched from the start center)
337 // => close our frame only - nothing else.
338 if (!aCheck2.m_lOtherVisibleFrames.empty() || (!aCheck2.m_bReferenceIsBacking && aCheck2.m_xBackingComponent.is()))
339 bCloseFrame = true;
340 else
342 // c2) if we close the current view ... but not all other views
343 // to the same document, we must close the current frame only!
344 // Because implts_closeView() suspended this view only - does not
345 // close the frame.
346 if (
347 (!bCloseAllViewsToo ) &&
348 (!aCheck2.m_lModelFrames.empty())
350 bCloseFrame = true;
352 else
353 // c3) there is no other (visible) frame open ...
354 // The help module will be ignored everytimes!
355 // But we have to decide if we must terminate the
356 // application or establish the backing mode now.
357 // And that depends from the dispatched URL ...
359 if (eOperation == E_CLOSE_FRAME)
361 if (bHasActiveConnections)
362 bCloseFrame = true;
363 else
364 bTerminateApp = true;
366 else if( SvtModuleOptions().IsModuleInstalled(SvtModuleOptions::EModule::STARTMODULE) )
367 bEstablishBackingMode = true;
368 else if (bHasActiveConnections)
369 bCloseFrame = true;
370 else
371 bTerminateApp = true;
376 // Do it now ...
377 bool bSuccess = false;
378 if (bCloseFrame)
379 bSuccess = implts_closeFrame();
380 else if (bEstablishBackingMode)
381 #if defined MACOSX
383 // on mac close down, quickstarter keeps the process alive
384 // however if someone has shut down the quickstarter
385 // behave as any other platform
387 bool bQuickstarterRunning = false;
388 // get quickstart service
391 css::uno::Reference< css::beans::XFastPropertySet > xSet( xContext->getServiceManager()->createInstanceWithContext(IMPLEMENTATIONNAME_QUICKLAUNCHER, xContext), css::uno::UNO_QUERY_THROW );
392 css::uno::Any aVal( xSet->getFastPropertyValue( 0 ) );
393 bool bState = false;
394 if( aVal >>= bState )
395 bQuickstarterRunning = bState;
397 catch( const css::uno::Exception& )
400 bSuccess = bQuickstarterRunning ? implts_terminateApplication() : implts_establishBackingMode();
402 #else
403 bSuccess = implts_establishBackingMode();
404 #endif
405 else if (bTerminateApp)
406 bSuccess = implts_terminateApplication();
408 if ( ! bSuccess && bControllerSuspended )
410 css::uno::Reference< css::frame::XController > xController = xCloseFrame->getController();
411 if (xController.is())
412 xController->suspend(false);
415 // inform listener
416 sal_Int16 nState = css::frame::DispatchResultState::FAILURE;
417 if (bSuccess)
418 nState = css::frame::DispatchResultState::SUCCESS;
419 implts_notifyResultListener(xListener, nState, css::uno::Any());
421 SolarMutexGuard g;
422 // This method was called asynchronous from our main thread by using a pointer.
423 // We reached this method only, by using a reference to ourself :-)
424 // Further this member is used to detect still running and not yet finished
425 // asynchronous operations. So it's time now to release this reference.
426 // But hold it temp alive. Otherwise we die before we can finish this method really :-))
427 css::uno::Reference< css::uno::XInterface > xTempHold = m_xSelfHold;
428 m_xSelfHold.clear();
429 m_xResultListener.clear();
431 catch(const css::lang::DisposedException&)
436 bool CloseDispatcher::implts_prepareFrameForClosing(const css::uno::Reference< css::frame::XFrame >& xFrame,
437 bool bCloseAllOtherViewsToo,
438 bool& bControllerSuspended )
440 // Frame already dead ... so this view is closed ... is closed ... is ... .-)
441 if (! xFrame.is())
442 return true;
444 // Close all views to the same document ... if forced to do so.
445 // But don't touch our own frame here!
446 // We must do so ... because the may be following controller->suspend()
447 // will show the "save/discard/cancel" dialog for the last view only!
448 if (bCloseAllOtherViewsToo)
450 css::uno::Reference< css::uno::XComponentContext > xContext;
452 SolarMutexGuard g;
453 xContext = m_xContext;
456 css::uno::Reference< css::frame::XFramesSupplier > xDesktop( css::frame::Desktop::create( xContext ), css::uno::UNO_QUERY_THROW);
457 FrameListAnalyzer aCheck(xDesktop, xFrame, FrameAnalyzerFlags::All);
459 size_t c = aCheck.m_lModelFrames.size();
460 size_t i = 0;
461 for (i=0; i<c; ++i)
463 if (!fpf::closeIt(aCheck.m_lModelFrames[i]))
464 return false;
468 // Inform user about modified documents or still running jobs (e.g. printing).
470 css::uno::Reference< css::frame::XController > xController = xFrame->getController();
471 if (xController.is()) // some views don't uses a controller .-( (e.g. the help window)
473 bControllerSuspended = xController->suspend(true);
474 if (! bControllerSuspended)
475 return false;
479 // don't remove the component really by e.g. calling setComponent(null, null).
480 // It's enough to suspend the controller.
481 // If we close the frame later this controller doesn't show the same dialog again.
482 return true;
485 bool CloseDispatcher::implts_closeFrame()
487 css::uno::Reference< css::frame::XFrame > xFrame;
489 SolarMutexGuard g;
490 xFrame.set(m_xCloseFrame.get(), css::uno::UNO_QUERY);
493 // frame already dead ? => so it's closed ... it's closed ...
494 if ( ! xFrame.is() )
495 return true;
497 // don't deliver ownership; our "UI user" will try it again if it failed.
498 // OK - he will get an empty frame then. But normally an empty frame
499 // should be closeable always :-)
500 if (!fpf::closeIt(xFrame))
501 return false;
504 SolarMutexGuard g;
505 m_xCloseFrame.clear();
508 return true;
511 bool CloseDispatcher::implts_establishBackingMode()
513 css::uno::Reference< css::uno::XComponentContext > xContext;
514 css::uno::Reference< css::frame::XFrame > xFrame;
516 SolarMutexGuard g;
517 xContext = m_xContext;
518 xFrame.set(m_xCloseFrame.get(), css::uno::UNO_QUERY);
521 if (!xFrame.is())
522 return false;
524 css::uno::Reference < css::document::XActionLockable > xLock( xFrame, css::uno::UNO_QUERY );
525 if ( xLock.is() && xLock->isActionLocked() )
526 return false;
528 css::uno::Reference< css::awt::XWindow > xContainerWindow = xFrame->getContainerWindow();
530 css::uno::Reference< css::frame::XController > xStartModule = css::frame::StartModule::createWithParentWindow(
531 xContext, xContainerWindow);
533 // Attention: You MUST(!) call setComponent() before you call attachFrame().
534 css::uno::Reference< css::awt::XWindow > xBackingWin(xStartModule, css::uno::UNO_QUERY);
535 xFrame->setComponent(xBackingWin, xStartModule);
536 xStartModule->attachFrame(xFrame);
537 xContainerWindow->setVisible(true);
539 return true;
542 bool CloseDispatcher::implts_terminateApplication()
544 css::uno::Reference< css::uno::XComponentContext > xContext;
546 SolarMutexGuard g;
547 xContext = m_xContext;
550 css::uno::Reference< css::frame::XDesktop2 > xDesktop = css::frame::Desktop::create( xContext );
552 return xDesktop->terminate();
555 void CloseDispatcher::implts_notifyResultListener(const css::uno::Reference< css::frame::XDispatchResultListener >& xListener,
556 sal_Int16 nState ,
557 const css::uno::Any& aResult )
559 if (!xListener.is())
560 return;
562 css::frame::DispatchResultEvent aEvent(
563 css::uno::Reference< css::uno::XInterface >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY),
564 nState,
565 aResult);
567 xListener->dispatchFinished(aEvent);
570 css::uno::Reference< css::frame::XFrame > CloseDispatcher::static_impl_searchRightTargetFrame(const css::uno::Reference< css::frame::XFrame >& xFrame ,
571 std::u16string_view sTarget)
573 if (o3tl::equalsIgnoreAsciiCase(sTarget, u"_self"))
574 return xFrame;
576 OSL_ENSURE(sTarget.empty(), "CloseDispatch used for unexpected target. Magic things will happen now .-)");
578 css::uno::Reference< css::frame::XFrame > xTarget = xFrame;
579 while(true)
581 // a) top frames will be closed
582 if (xTarget->isTop())
583 return xTarget;
585 // b) even child frame containing top level windows (e.g. query designer of database) will be closed
586 css::uno::Reference< css::awt::XWindow > xWindow = xTarget->getContainerWindow();
587 css::uno::Reference< css::awt::XTopWindow > xTopWindowCheck(xWindow, css::uno::UNO_QUERY);
588 if (xTopWindowCheck.is())
590 // b1) Note: Toolkit interface XTopWindow sometimes is used by real VCL-child-windows also .-)
591 // Be sure that these window is really a "top system window".
592 // Attention ! Checking Window->GetParent() isn't the right approach here.
593 // Because sometimes VCL create "implicit border windows" as parents even we created
594 // a simple XWindow using the toolkit only .-(
595 SolarMutexGuard aSolarLock;
596 VclPtr<vcl::Window> pWindow = VCLUnoHelper::GetWindow( xWindow );
597 if ( pWindow && pWindow->IsSystemWindow() )
598 return xTarget;
601 // c) try to find better results on parent frame
602 // If no parent frame exists (because this frame is used outside the desktop tree)
603 // the given frame must be used directly.
604 css::uno::Reference< css::frame::XFrame > xParent = xTarget->getCreator();
605 if ( ! xParent.is())
606 return xTarget;
608 // c1) check parent frame inside next loop ...
609 xTarget = xParent;
613 } // namespace framework
615 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */