Bug Summary

File:home/maarten/src/libreoffice/core/include/rtl/ref.hxx
Warning:line 192, column 9
Use of memory after it is freed

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-unknown-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name menubarmanager.cxx -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 2 -mframe-pointer=all -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -fno-split-dwarf-inlining -debugger-tuning=gdb -resource-dir /usr/lib64/clang/11.0.0 -D BOOST_ERROR_CODE_HEADER_ONLY -D BOOST_SYSTEM_NO_DEPRECATED -D CPPU_ENV=gcc3 -D LINUX -D OSL_DEBUG_LEVEL=1 -D SAL_LOG_INFO -D SAL_LOG_WARN -D UNIX -D UNX -D X86_64 -D _PTHREADS -D _REENTRANT -D FWK_DLLIMPLEMENTATION -D EXCEPTIONS_ON -D LIBO_INTERNAL_ONLY -I /home/maarten/src/libreoffice/core/external/boost/include -I /home/maarten/src/libreoffice/core/workdir/UnpackedTarball/boost -I /home/maarten/src/libreoffice/core/framework/source/inc -I /home/maarten/src/libreoffice/core/framework/inc -I /home/maarten/src/libreoffice/core/workdir/CustomTarget/officecfg/registry -I /home/maarten/src/libreoffice/core/include -I /usr/lib/jvm/java-11-openjdk-11.0.9.10-0.0.ea.fc33.x86_64/include -I /usr/lib/jvm/java-11-openjdk-11.0.9.10-0.0.ea.fc33.x86_64/include/linux -I /home/maarten/src/libreoffice/core/config_host -I /home/maarten/src/libreoffice/core/workdir/CustomTarget/officecfg/registry -I /home/maarten/src/libreoffice/core/workdir/UnoApiHeadersTarget/udkapi/normal -I /home/maarten/src/libreoffice/core/workdir/UnoApiHeadersTarget/offapi/normal -internal-isystem /usr/bin/../lib/gcc/x86_64-redhat-linux/10/../../../../include/c++/10 -internal-isystem /usr/bin/../lib/gcc/x86_64-redhat-linux/10/../../../../include/c++/10/x86_64-redhat-linux -internal-isystem /usr/bin/../lib/gcc/x86_64-redhat-linux/10/../../../../include/c++/10/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib64/clang/11.0.0/include -internal-externc-isystem /include -internal-externc-isystem /usr/include -O0 -Wno-missing-braces -std=c++17 -fdeprecated-macro -fdebug-compilation-dir /home/maarten/src/libreoffice/core -ferror-limit 19 -fvisibility hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcxx-exceptions -fexceptions -debug-info-kind=constructor -analyzer-output=html -faddrsig -o /home/maarten/tmp/wis/scan-build-libreoffice/output/report/2020-10-07-141433-9725-1 -x c++ /home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx

/home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx

1/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2/*
3 * This file is part of the LibreOffice project.
4 *
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/.
8 *
9 * This file incorporates work covered by the following license notice:
10 *
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 .
18 */
19
20#include <uielement/menubarmanager.hxx>
21#include <uielement/styletoolbarcontroller.hxx>
22#include <menuconfiguration.hxx>
23#include <addonmenu.hxx>
24#include <framework/addonsoptions.hxx>
25#include <classes/fwkresid.hxx>
26#include <strings.hrc>
27
28#include <com/sun/star/frame/XDispatch.hpp>
29#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
30#include <com/sun/star/lang/DisposedException.hpp>
31#include <com/sun/star/uno/XComponentContext.hpp>
32#include <com/sun/star/uno/XCurrentContext.hpp>
33#include <com/sun/star/frame/XPopupMenuController.hpp>
34#include <com/sun/star/frame/thePopupMenuControllerFactory.hpp>
35#include <com/sun/star/lang/SystemDependent.hpp>
36#include <com/sun/star/ui/GlobalAcceleratorConfiguration.hpp>
37#include <com/sun/star/ui/ItemType.hpp>
38#include <com/sun/star/ui/ImageType.hpp>
39#include <com/sun/star/ui/theModuleUIConfigurationManagerSupplier.hpp>
40#include <com/sun/star/ui/XUIConfigurationManagerSupplier.hpp>
41#include <com/sun/star/ui/ItemStyle.hpp>
42#include <com/sun/star/frame/status/Visibility.hpp>
43#include <com/sun/star/util/URLTransformer.hpp>
44
45#include <comphelper/processfactory.hxx>
46#include <comphelper/propertysequence.hxx>
47#include <svtools/menuoptions.hxx>
48#include <svtools/javainteractionhandler.hxx>
49#include <uno/current_context.hxx>
50#include <unotools/cmdoptions.hxx>
51#include <toolkit/awt/vclxmenu.hxx>
52#include <vcl/svapp.hxx>
53#include <vcl/sysdata.hxx>
54#include <vcl/menu.hxx>
55#include <vcl/settings.hxx>
56#include <vcl/commandinfoprovider.hxx>
57#include <sal/log.hxx>
58#include <svtools/acceleratorexecute.hxx>
59#include <svtools/miscopt.hxx>
60#include <uielement/menubarmerger.hxx>
61#include <tools/urlobj.hxx>
62
63using namespace ::cppu;
64using namespace ::com::sun::star;
65using namespace ::com::sun::star::uno;
66using namespace ::com::sun::star::util;
67using namespace ::com::sun::star::beans;
68using namespace ::com::sun::star::frame;
69using namespace ::com::sun::star::container;
70using namespace ::com::sun::star::lang;
71using namespace ::com::sun::star::ui;
72
73const sal_uInt16 ADDONMENU_MERGE_ITEMID_START = 1500;
74const sal_uInt16 ITEMID_ADDONLIST = 6678; // used to be a SID in sfx2, now just a unique id...
75
76namespace framework
77{
78
79#define aCmdHelpIndex".uno:HelpIndex" ".uno:HelpIndex"
80#define aCmdToolsMenu".uno:ToolsMenu" ".uno:ToolsMenu"
81#define aCmdHelpMenu".uno:HelpMenu" ".uno:HelpMenu"
82#define aSpecialWindowCommand".uno:WindowList" ".uno:WindowList"
83
84MenuBarManager::MenuBarManager(
85 const Reference< XComponentContext >& rxContext,
86 const Reference< XFrame >& rFrame,
87 const Reference< XURLTransformer >& _xURLTransformer,
88 const Reference< XDispatchProvider >& rDispatchProvider,
89 const OUString& rModuleIdentifier,
90 Menu* pMenu, bool bDelete, bool bHasMenuBar ):
91 WeakComponentImplHelper( m_aMutex )
92 , m_bRetrieveImages( false )
93 , m_bAcceleratorCfg( false )
94 , m_bHasMenuBar( bHasMenuBar )
95 , m_xContext(rxContext)
96 , m_xURLTransformer(_xURLTransformer)
97 , m_sIconTheme( SvtMiscOptions().GetIconTheme() )
98{
99 m_aAsyncSettingsTimer.SetDebugName( "framework::MenuBarManager::Deactivate m_aAsyncSettingsTimer" );
100 m_xPopupMenuControllerFactory = frame::thePopupMenuControllerFactory::get(m_xContext);
101 FillMenuManager( pMenu, rFrame, rDispatchProvider, rModuleIdentifier, bDelete );
102}
103
104Any SAL_CALL MenuBarManager::getMenuHandle( const Sequence< sal_Int8 >& /*ProcessId*/, sal_Int16 SystemType )
105{
106 SolarMutexGuard aSolarGuard;
107
108 if ( rBHelper.bDisposed || rBHelper.bInDispose )
109 throw css::lang::DisposedException();
110
111 Any a;
112
113 if ( m_pVCLMenu )
114 {
115 SystemMenuData aSystemMenuData;
116
117 m_pVCLMenu->GetSystemMenuData( &aSystemMenuData );
118#ifdef _WIN32
119 if( SystemType == SystemDependent::SYSTEM_WIN32 )
120 {
121 a <<= sal_Int64(
122 reinterpret_cast<sal_IntPtr>(aSystemMenuData.hMenu));
123 }
124#else
125 (void) SystemType;
126#endif
127 }
128
129 return a;
130}
131
132MenuBarManager::~MenuBarManager()
133{
134 // stop asynchronous settings timer
135 m_xDeferredItemContainer.clear();
136 m_aAsyncSettingsTimer.Stop();
137
138 SAL_WARN_IF( OWeakObject::m_refCount != 0, "fwk.uielement", "Who wants to delete an object with refcount > 0!" )do { if (true && (OWeakObject::m_refCount != 0)) { switch
(sal_detail_log_report(::SAL_DETAIL_LOG_LEVEL_WARN, "fwk.uielement"
)) { case SAL_DETAIL_LOG_ACTION_IGNORE: break; case SAL_DETAIL_LOG_ACTION_LOG
: if (sizeof ::sal::detail::getResult( ::sal::detail::StreamStart
() << "Who wants to delete an object with refcount > 0!"
) == 1) { ::sal_detail_log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("fwk.uielement"
), ("/home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx"
":" "138" ": "), ::sal::detail::unwrapStream( ::sal::detail::
StreamStart() << "Who wants to delete an object with refcount > 0!"
), 0); } else { ::std::ostringstream sal_detail_stream; sal_detail_stream
<< "Who wants to delete an object with refcount > 0!"
; ::sal::detail::log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("fwk.uielement"
), ("/home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx"
":" "138" ": "), sal_detail_stream, 0); }; break; case SAL_DETAIL_LOG_ACTION_FATAL
: if (sizeof ::sal::detail::getResult( ::sal::detail::StreamStart
() << "Who wants to delete an object with refcount > 0!"
) == 1) { ::sal_detail_log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("fwk.uielement"
), ("/home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx"
":" "138" ": "), ::sal::detail::unwrapStream( ::sal::detail::
StreamStart() << "Who wants to delete an object with refcount > 0!"
), 0); } else { ::std::ostringstream sal_detail_stream; sal_detail_stream
<< "Who wants to delete an object with refcount > 0!"
; ::sal::detail::log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("fwk.uielement"
), ("/home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx"
":" "138" ": "), sal_detail_stream, 0); }; std::abort(); break
; } } } while (false)
;
139}
140
141void MenuBarManager::Destroy()
142{
143 SolarMutexGuard aGuard;
144
145 if ( rBHelper.bDisposed )
2
Assuming field 'bDisposed' is 0
3
Taking false branch
146 return;
147
148 // stop asynchronous settings timer and
149 // release deferred item container reference
150 m_aAsyncSettingsTimer.Stop();
151 m_xDeferredItemContainer.clear();
152 RemoveListener();
153
154 m_aMenuItemHandlerVector.clear();
155
156 if ( m_bDeleteMenu )
4
Assuming field 'm_bDeleteMenu' is true
5
Taking true branch
157 {
158 m_pVCLMenu.disposeAndClear();
6
Calling 'VclPtr::disposeAndClear'
159 }
160}
161
162// XComponent
163void SAL_CALL MenuBarManager::disposing()
164{
165 Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );
166
167 SolarMutexGuard g;
168 Destroy();
1
Calling 'MenuBarManager::Destroy'
169
170 if ( m_xDocImageManager.is() )
171 {
172 try
173 {
174 m_xDocImageManager->removeConfigurationListener(
175 Reference< XUIConfigurationListener >(
176 static_cast< OWeakObject* >( this ), UNO_QUERY ));
177 }
178 catch ( const Exception& )
179 {
180 }
181 }
182 if ( m_xModuleImageManager.is() )
183 {
184 try
185 {
186 m_xModuleImageManager->removeConfigurationListener(
187 Reference< XUIConfigurationListener >(
188 static_cast< OWeakObject* >( this ), UNO_QUERY ));
189 }
190 catch ( const Exception& )
191 {
192 }
193 }
194 m_xDocImageManager.clear();
195 m_xModuleImageManager.clear();
196 m_xGlobalAcceleratorManager.clear();
197 m_xModuleAcceleratorManager.clear();
198 m_xDocAcceleratorManager.clear();
199 m_xPopupMenuControllerFactory.clear();
200 m_xContext.clear();
201}
202
203void SAL_CALL MenuBarManager::elementInserted( const css::ui::ConfigurationEvent& Event )
204{
205 SolarMutexGuard g;
206
207 /* SAFE AREA ----------------------------------------------------------------------------------------------- */
208 if ( rBHelper.bDisposed || rBHelper.bInDispose )
209 return;
210
211 sal_Int16 nImageType = sal_Int16();
212 if (( Event.aInfo >>= nImageType ) && nImageType == 0 )
213 RequestImages();
214}
215
216void SAL_CALL MenuBarManager::elementRemoved( const css::ui::ConfigurationEvent& Event )
217{
218 elementInserted(Event);
219}
220
221void SAL_CALL MenuBarManager::elementReplaced( const css::ui::ConfigurationEvent& Event )
222{
223 elementInserted(Event);
224}
225
226// XFrameActionListener
227void SAL_CALL MenuBarManager::frameAction( const FrameActionEvent& Action )
228{
229 SolarMutexGuard g;
230
231 if ( rBHelper.bDisposed || rBHelper.bInDispose )
232 throw css::lang::DisposedException();
233
234 if ( Action.Action != FrameAction_CONTEXT_CHANGED )
235 return;
236
237 for (auto const& menuItemHandler : m_aMenuItemHandlerVector)
238 {
239 // Clear dispatch reference as we will requery it later
240 if ( menuItemHandler->xMenuItemDispatch.is() )
241 {
242 URL aTargetURL;
243 aTargetURL.Complete = menuItemHandler->aMenuItemURL;
244 m_xURLTransformer->parseStrict( aTargetURL );
245
246 menuItemHandler->xMenuItemDispatch->removeStatusListener( this, aTargetURL );
247 }
248 menuItemHandler->xMenuItemDispatch.clear();
249 }
250}
251
252// XStatusListener
253void SAL_CALL MenuBarManager::statusChanged( const FeatureStateEvent& Event )
254{
255 OUString aFeatureURL = Event.FeatureURL.Complete;
256
257 SolarMutexGuard aSolarGuard;
258 {
259 if ( rBHelper.bDisposed || rBHelper.bInDispose )
260 return;
261
262 // We have to check all menu entries as there can be identical entries in a popup menu.
263 for (auto const& menuItemHandler : m_aMenuItemHandlerVector)
264 {
265 if ( menuItemHandler->aParsedItemURL == aFeatureURL )
266 {
267 bool bCheckmark( false );
268 bool bMenuItemEnabled( m_pVCLMenu->IsItemEnabled( menuItemHandler->nItemId ));
269 bool bEnabledItem( Event.IsEnabled );
270 OUString aItemText;
271 status::Visibility aVisibilityStatus;
272
273 #ifdef UNIX1
274 //enable some slots hardly, because UNIX clipboard does not notify all changes
275 // Can be removed if follow up task will be fixed directly within applications.
276 // Note: PasteSpecial is handled specifically by calc
277 // Calc also disables Paste under some circumstances, do not override.
278 /* TODO: is this workaround even needed anymore? Was introduced
279 * in 2009 with commit 426ab2c0e8f6e3fe2b766f74f6b8da873d860260
280 * as some "metropatch" and the other places it touched seem to
281 * be gone. */
282 if ( (menuItemHandler->aMenuItemURL == ".uno:Paste" &&
283 m_aModuleIdentifier != "com.sun.star.sheet.SpreadsheetDocument")
284 || menuItemHandler->aMenuItemURL == ".uno:PasteClipboard" ) // special for draw/impress
285 bEnabledItem = true;
286 #endif
287
288 // Enable/disable item
289 if ( bEnabledItem != bMenuItemEnabled )
290 {
291 m_pVCLMenu->EnableItem( menuItemHandler->nItemId, bEnabledItem );
292
293 // Remove "checked" mark for disabled menu items.
294 // Initially disabled but checkable menu items do not receive
295 // checked/unchecked state, so can appear inconsistently after
296 // enabling/disabling. Since we can not pass checked state for disabled
297 // items, we will just reset checked state for them, anyway correct state
298 // will be transferred from controller once item enabled.
299 if ( !bEnabledItem && m_pVCLMenu->IsItemChecked( menuItemHandler->nItemId ) )
300 m_pVCLMenu->CheckItem( menuItemHandler->nItemId, false );
301 }
302
303 if ( Event.State >>= bCheckmark )
304 {
305 // Checkmark or RadioButton
306 m_pVCLMenu->CheckItem( menuItemHandler->nItemId, bCheckmark );
307 // If not already designated RadioButton set as CheckMark
308 MenuItemBits nBits = m_pVCLMenu->GetItemBits( menuItemHandler->nItemId );
309 if (!(nBits & MenuItemBits::RADIOCHECK))
310 m_pVCLMenu->SetItemBits( menuItemHandler->nItemId, nBits | MenuItemBits::CHECKABLE );
311
312 if ( menuItemHandler->bMadeInvisible )
313 m_pVCLMenu->ShowItem( menuItemHandler->nItemId );
314 }
315 else if ( Event.State >>= aItemText )
316 {
317 INetURLObject aURL( aFeatureURL );
318 OUString aEnumPart = aURL.GetURLPath().getToken( 1, '.' );
319 if ( !aEnumPart.isEmpty() && aURL.GetProtocol() == INetProtocol::Uno )
320 {
321 // Checkmark or RadioButton
322 m_pVCLMenu->CheckItem( menuItemHandler->nItemId, aItemText == aEnumPart );
323 // If not already designated RadioButton set as CheckMark
324 MenuItemBits nBits = m_pVCLMenu->GetItemBits( menuItemHandler->nItemId );
325 if (!(nBits & MenuItemBits::RADIOCHECK))
326 m_pVCLMenu->SetItemBits( menuItemHandler->nItemId, nBits | MenuItemBits::CHECKABLE );
327 }
328 else
329 {
330 // Replacement for place holders
331 if ( aItemText.startsWith("($1)") )
332 {
333 aItemText = FwkResId(STR_UPDATEDOCreinterpret_cast<char const *>("STR_UPDATEDOC" "\004" u8"~Update"
)
) + " " + aItemText.copy( 4 );
334 }
335 else if ( aItemText.startsWith("($2)") )
336 {
337 aItemText = FwkResId(STR_CLOSEDOC_ANDRETURNreinterpret_cast<char const *>("STR_CLOSEDOC_ANDRETURN"
"\004" u8"~Close & Return to ")
) + aItemText.copy( 4 );
338 }
339 else if ( aItemText.startsWith("($3)") )
340 {
341 aItemText = FwkResId(STR_SAVECOPYDOCreinterpret_cast<char const *>("STR_SAVECOPYDOC" "\004"
u8"Save Copy ~as...")
) + aItemText.copy( 4 );
342 }
343
344 m_pVCLMenu->SetItemText( menuItemHandler->nItemId, aItemText );
345 }
346
347 if ( menuItemHandler->bMadeInvisible )
348 m_pVCLMenu->ShowItem( menuItemHandler->nItemId );
349 }
350 else if ( Event.State >>= aVisibilityStatus )
351 {
352 // Visibility
353 m_pVCLMenu->ShowItem( menuItemHandler->nItemId, aVisibilityStatus.bVisible );
354 menuItemHandler->bMadeInvisible = !aVisibilityStatus.bVisible;
355 }
356 else if ( menuItemHandler->bMadeInvisible )
357 m_pVCLMenu->ShowItem( menuItemHandler->nItemId );
358 }
359
360 if ( Event.Requery )
361 {
362 // Release dispatch object - will be required on the next activate!
363 menuItemHandler->xMenuItemDispatch.clear();
364 }
365 }
366 }
367}
368
369// Helper to retrieve own structure from item ID
370MenuBarManager::MenuItemHandler* MenuBarManager::GetMenuItemHandler( sal_uInt16 nItemId )
371{
372 SolarMutexGuard g;
373
374 for (auto const& menuItemHandler : m_aMenuItemHandlerVector)
375 {
376 if ( menuItemHandler->nItemId == nItemId )
377 return menuItemHandler.get();
378 }
379
380 return nullptr;
381}
382
383// Helper to set request images flag
384void MenuBarManager::RequestImages()
385{
386
387 m_bRetrieveImages = true;
388 for (auto const& menuItemHandler : m_aMenuItemHandlerVector)
389 {
390 if ( menuItemHandler->xSubMenuManager.is() )
391 {
392 MenuBarManager* pMenuBarManager = static_cast<MenuBarManager*>(menuItemHandler->xSubMenuManager.get());
393 pMenuBarManager->RequestImages();
394 }
395 }
396}
397
398// Helper to reset objects to prepare shutdown
399void MenuBarManager::RemoveListener()
400{
401 SolarMutexGuard g;
402
403 for (auto const& menuItemHandler : m_aMenuItemHandlerVector)
404 {
405 if ( menuItemHandler->xMenuItemDispatch.is() )
406 {
407 URL aTargetURL;
408 aTargetURL.Complete = menuItemHandler->aMenuItemURL;
409 m_xURLTransformer->parseStrict( aTargetURL );
410
411 menuItemHandler->xMenuItemDispatch->removeStatusListener(
412 static_cast< XStatusListener* >( this ), aTargetURL );
413 }
414
415 menuItemHandler->xMenuItemDispatch.clear();
416
417 if ( menuItemHandler->xPopupMenu.is() )
418 {
419 {
420 // Remove popup menu from menu structure
421 m_pVCLMenu->SetPopupMenu( menuItemHandler->nItemId, nullptr );
422 }
423
424 Reference< css::lang::XEventListener > xEventListener( menuItemHandler->xPopupMenuController, UNO_QUERY );
425 if ( xEventListener.is() )
426 {
427 EventObject aEventObject;
428 aEventObject.Source = static_cast<OWeakObject *>(this);
429 xEventListener->disposing( aEventObject );
430 }
431
432 // We now provide a popup menu controller to external code.
433 // Therefore the life-time must be explicitly handled via
434 // dispose!!
435 try
436 {
437 Reference< XComponent > xComponent( menuItemHandler->xPopupMenuController, UNO_QUERY );
438 if ( xComponent.is() )
439 xComponent->dispose();
440 }
441 catch ( const RuntimeException& )
442 {
443 throw;
444 }
445 catch ( const Exception& )
446 {
447 }
448
449 // Release references to controller and popup menu
450 menuItemHandler->xPopupMenuController.clear();
451 menuItemHandler->xPopupMenu.clear();
452 }
453
454 Reference< XComponent > xComponent( menuItemHandler->xSubMenuManager, UNO_QUERY );
455 if ( xComponent.is() )
456 xComponent->dispose();
457 }
458
459 try
460 {
461 if ( m_xFrame.is() )
462 m_xFrame->removeFrameActionListener( Reference< XFrameActionListener >(
463 static_cast< OWeakObject* >( this ), UNO_QUERY ));
464 }
465 catch ( const Exception& )
466 {
467 }
468
469 m_xFrame = nullptr;
470}
471
472void SAL_CALL MenuBarManager::disposing( const EventObject& Source )
473{
474 MenuItemHandler* pMenuItemDisposing = nullptr;
475
476 SolarMutexGuard g;
477
478 for (auto const& menuItemHandler : m_aMenuItemHandlerVector)
479 {
480 if ( menuItemHandler->xMenuItemDispatch.is() &&
481 menuItemHandler->xMenuItemDispatch == Source.Source )
482 {
483 // disposing called from menu item dispatcher, remove listener
484 pMenuItemDisposing = menuItemHandler.get();
485 break;
486 }
487 }
488
489 if ( pMenuItemDisposing )
490 {
491 // Release references to the dispatch object
492 URL aTargetURL;
493 aTargetURL.Complete = pMenuItemDisposing->aMenuItemURL;
494
495 m_xURLTransformer->parseStrict( aTargetURL );
496
497 pMenuItemDisposing->xMenuItemDispatch->removeStatusListener(
498 static_cast< XStatusListener* >( this ), aTargetURL );
499 pMenuItemDisposing->xMenuItemDispatch.clear();
500 if ( pMenuItemDisposing->xPopupMenu.is() )
501 {
502 Reference< css::lang::XEventListener > xEventListener( pMenuItemDisposing->xPopupMenuController, UNO_QUERY );
503 if ( xEventListener.is() )
504 xEventListener->disposing( Source );
505
506 {
507 // Remove popup menu from menu structure as we release our reference to
508 // the controller.
509 m_pVCLMenu->SetPopupMenu( pMenuItemDisposing->nItemId, nullptr );
510 }
511
512 pMenuItemDisposing->xPopupMenuController.clear();
513 pMenuItemDisposing->xPopupMenu.clear();
514 }
515 return;
516 }
517 else if ( Source.Source == m_xFrame )
518 {
519 // Our frame gets disposed. We have to remove all our listeners
520 RemoveListener();
521 }
522 else if ( Source.Source == Reference< XInterface >( m_xDocImageManager, UNO_QUERY ))
523 m_xDocImageManager.clear();
524 else if ( Source.Source == Reference< XInterface >( m_xModuleImageManager, UNO_QUERY ))
525 m_xModuleImageManager.clear();
526}
527
528static void lcl_CheckForChildren(Menu* pMenu, sal_uInt16 nItemId)
529{
530 if (PopupMenu* pThisPopup = pMenu->GetPopupMenu( nItemId ))
531 pMenu->EnableItem( nItemId, pThisPopup->GetItemCount() != 0 );
532}
533
534// vcl handler
535
536namespace {
537
538class QuietInteractionContext:
539 public cppu::WeakImplHelper< css::uno::XCurrentContext >
540{
541public:
542 explicit QuietInteractionContext(
543 css::uno::Reference< css::uno::XCurrentContext >
544 const & context):
545 context_(context) {}
546 QuietInteractionContext(const QuietInteractionContext&) = delete;
547 QuietInteractionContext& operator=(const QuietInteractionContext&) = delete;
548
549private:
550 virtual ~QuietInteractionContext() override {}
551
552 virtual css::uno::Any SAL_CALL getValueByName(
553 OUString const & Name) override
554 {
555 return Name != JAVA_INTERACTION_HANDLER_NAME"java-vm.interaction-handler" && context_.is()
556 ? context_->getValueByName(Name)
557 : css::uno::Any();
558 }
559
560 css::uno::Reference< css::uno::XCurrentContext >
561 context_;
562};
563
564}
565
566IMPL_LINK( MenuBarManager, Activate, Menu *, pMenu, bool )bool MenuBarManager::LinkStubActivate(void * instance, Menu *
data) { return static_cast<MenuBarManager *>(instance)
->Activate(data); } bool MenuBarManager::Activate(Menu * pMenu
)
567{
568 if ( pMenu == m_pVCLMenu )
569 {
570 css::uno::ContextLayer layer(
571 new QuietInteractionContext(
572 css::uno::getCurrentContext()));
573
574 // set/unset hiding disabled menu entries
575 bool bDontHide = SvtMenuOptions().IsEntryHidingEnabled();
576 const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
577 bool bShowMenuImages = rSettings.GetUseImagesInMenus();
578 bool bShowShortcuts = m_bHasMenuBar || rSettings.GetContextMenuShortcuts();
579 bool bHasDisabledEntries = SvtCommandOptions().HasEntries( SvtCommandOptions::CMDOPTION_DISABLED );
580
581 SolarMutexGuard g;
582
583 MenuFlags nFlag = pMenu->GetMenuFlags();
584 if ( bDontHide )
585 nFlag &= ~MenuFlags::HideDisabledEntries;
586 else
587 nFlag |= MenuFlags::HideDisabledEntries;
588 pMenu->SetMenuFlags( nFlag );
589
590 if ( m_bActive )
591 return false;
592
593 m_bActive = true;
594
595 // Check if some modes have changed so we have to update our menu images
596 OUString sIconTheme = SvtMiscOptions().GetIconTheme();
597
598 if ( m_bRetrieveImages ||
599 bShowMenuImages != m_bShowMenuImages ||
600 sIconTheme != m_sIconTheme )
601 {
602 m_bShowMenuImages = bShowMenuImages;
603 m_bRetrieveImages = false;
604 m_sIconTheme = sIconTheme;
605 FillMenuImages( m_xFrame, pMenu, bShowMenuImages );
606 }
607
608 // Try to map commands to labels
609 for ( sal_uInt16 nPos = 0; nPos < pMenu->GetItemCount(); nPos++ )
610 {
611 sal_uInt16 nItemId = pMenu->GetItemId( nPos );
612 if (( pMenu->GetItemType( nPos ) != MenuItemType::SEPARATOR ) &&
613 ( pMenu->GetItemText( nItemId ).isEmpty() ))
614 {
615 OUString aCommand = pMenu->GetItemCommand( nItemId );
616 if ( !aCommand.isEmpty() ) {
617 pMenu->SetItemText( nItemId, RetrieveLabelFromCommand( aCommand ));
618 }
619 }
620 }
621
622 // Try to set accelerator keys
623 {
624 if ( bShowShortcuts )
625 RetrieveShortcuts( m_aMenuItemHandlerVector );
626
627 for (auto const& menuItemHandler : m_aMenuItemHandlerVector)
628 {
629 if ( !bShowShortcuts )
630 {
631 pMenu->SetAccelKey( menuItemHandler->nItemId, vcl::KeyCode() );
632 }
633 else if ( menuItemHandler->aMenuItemURL == aCmdHelpIndex".uno:HelpIndex" )
634 {
635 // Set key code, workaround for hard-coded shortcut F1 mapped to .uno:HelpIndex
636 // Only non-popup menu items can have a short-cut
637 vcl::KeyCode aKeyCode( KEY_F1 );
638 pMenu->SetAccelKey( menuItemHandler->nItemId, aKeyCode );
639 }
640 else if ( pMenu->GetPopupMenu( menuItemHandler->nItemId ) == nullptr )
641 pMenu->SetAccelKey( menuItemHandler->nItemId, menuItemHandler->aKeyCode );
642 }
643 }
644
645 URL aTargetURL;
646
647 // Use provided dispatch provider => fallback to frame as dispatch provider
648 Reference< XDispatchProvider > xDispatchProvider;
649 if ( m_xDispatchProvider.is() )
650 xDispatchProvider = m_xDispatchProvider;
651 else
652 xDispatchProvider.set( m_xFrame, UNO_QUERY );
653
654 if ( xDispatchProvider.is() )
655 {
656 SvtCommandOptions aCmdOptions;
657 for (auto const& menuItemHandler : m_aMenuItemHandlerVector)
658 {
659 if (menuItemHandler)
660 {
661 if ( !menuItemHandler->xMenuItemDispatch.is() &&
662 !menuItemHandler->xSubMenuManager.is() )
663 {
664 Reference< XDispatch > xMenuItemDispatch;
665
666 aTargetURL.Complete = menuItemHandler->aMenuItemURL;
667
668 m_xURLTransformer->parseStrict( aTargetURL );
669
670 if ( bHasDisabledEntries )
671 {
672 if ( aCmdOptions.Lookup( SvtCommandOptions::CMDOPTION_DISABLED, aTargetURL.Path ))
673 pMenu->HideItem( menuItemHandler->nItemId );
674 }
675
676 if ( aTargetURL.Complete.startsWith( ".uno:StyleApply?" ) )
677 xMenuItemDispatch = new StyleDispatcher( m_xFrame, m_xURLTransformer, aTargetURL );
678 else
679 xMenuItemDispatch = xDispatchProvider->queryDispatch( aTargetURL, menuItemHandler->aTargetFrame, 0 );
680
681 bool bPopupMenu( false );
682 if ( !menuItemHandler->xPopupMenuController.is() &&
683 m_xPopupMenuControllerFactory->hasController( menuItemHandler->aMenuItemURL, m_aModuleIdentifier ) )
684 {
685 if( xMenuItemDispatch.is() || menuItemHandler->aMenuItemURL != ".uno:RecentFileList" )
686 bPopupMenu = CreatePopupMenuController(menuItemHandler.get(), m_xDispatchProvider, m_aModuleIdentifier);
687 }
688 else if ( menuItemHandler->xPopupMenuController.is() )
689 {
690 // Force update of popup menu
691 menuItemHandler->xPopupMenuController->updatePopupMenu();
692 bPopupMenu = true;
693 if (PopupMenu* pThisPopup = pMenu->GetPopupMenu( menuItemHandler->nItemId ))
694 pMenu->EnableItem( menuItemHandler->nItemId, pThisPopup->GetItemCount() != 0 );
695 }
696 lcl_CheckForChildren(pMenu, menuItemHandler->nItemId);
697
698 if ( xMenuItemDispatch.is() )
699 {
700 menuItemHandler->xMenuItemDispatch = xMenuItemDispatch;
701 menuItemHandler->aParsedItemURL = aTargetURL.Complete;
702
703 if ( !bPopupMenu )
704 {
705 xMenuItemDispatch->addStatusListener( static_cast< XStatusListener* >( this ), aTargetURL );
706 // For the menubar, we have to keep status listening to support Ubuntu's HUD.
707 if ( !m_bHasMenuBar )
708 xMenuItemDispatch->removeStatusListener( static_cast< XStatusListener* >( this ), aTargetURL );
709 }
710 }
711 else if ( !bPopupMenu )
712 pMenu->EnableItem( menuItemHandler->nItemId, false );
713 }
714 else if ( menuItemHandler->xPopupMenuController.is() )
715 {
716 // Force update of popup menu
717 menuItemHandler->xPopupMenuController->updatePopupMenu();
718 lcl_CheckForChildren(pMenu, menuItemHandler->nItemId);
719 }
720 else if ( menuItemHandler->xMenuItemDispatch.is() )
721 {
722 // We need an update to reflect the current state
723 try
724 {
725 aTargetURL.Complete = menuItemHandler->aMenuItemURL;
726 m_xURLTransformer->parseStrict( aTargetURL );
727
728 menuItemHandler->xMenuItemDispatch->addStatusListener(
729 static_cast< XStatusListener* >( this ), aTargetURL );
730 menuItemHandler->xMenuItemDispatch->removeStatusListener(
731 static_cast< XStatusListener* >( this ), aTargetURL );
732 }
733 catch ( const Exception& )
734 {
735 }
736 }
737 else if ( menuItemHandler->xSubMenuManager.is() )
738 lcl_CheckForChildren(pMenu, menuItemHandler->nItemId);
739 }
740 }
741 }
742 }
743
744 return true;
745}
746
747IMPL_LINK( MenuBarManager, Deactivate, Menu *, pMenu, bool )bool MenuBarManager::LinkStubDeactivate(void * instance, Menu
* data) { return static_cast<MenuBarManager *>(instance
)->Deactivate(data); } bool MenuBarManager::Deactivate(Menu
* pMenu)
748{
749 if ( pMenu == m_pVCLMenu )
750 {
751 m_bActive = false;
752 if ( pMenu->IsMenuBar() && m_xDeferredItemContainer.is() )
753 {
754 // Start timer to handle settings asynchronous
755 // Changing the menu inside this handler leads to
756 // a crash under X!
757 m_aAsyncSettingsTimer.SetInvokeHandler(LINK(this, MenuBarManager, AsyncSettingsHdl)::tools::detail::makeLink( ::tools::detail::castTo<MenuBarManager
*>(this), &MenuBarManager::LinkStubAsyncSettingsHdl)
);
758 m_aAsyncSettingsTimer.SetTimeout(10);
759 m_aAsyncSettingsTimer.Start();
760 }
761 }
762
763 return true;
764}
765
766IMPL_LINK_NOARG( MenuBarManager, AsyncSettingsHdl, Timer*, void)void MenuBarManager::LinkStubAsyncSettingsHdl(void * instance
, Timer* data) { return static_cast<MenuBarManager *>(instance
)->AsyncSettingsHdl(data); } void MenuBarManager::AsyncSettingsHdl
(__attribute__ ((unused)) Timer*)
767{
768 SolarMutexGuard g;
769 Reference< XInterface > xSelfHold(
770 static_cast< ::cppu::OWeakObject* >( this ), UNO_QUERY_THROW );
771
772 m_aAsyncSettingsTimer.Stop();
773 if ( !m_bActive && m_xDeferredItemContainer.is() )
774 {
775 SetItemContainer( m_xDeferredItemContainer );
776 m_xDeferredItemContainer.clear();
777 }
778}
779
780IMPL_LINK( MenuBarManager, Select, Menu *, pMenu, bool )bool MenuBarManager::LinkStubSelect(void * instance, Menu * data
) { return static_cast<MenuBarManager *>(instance)->
Select(data); } bool MenuBarManager::Select(Menu * pMenu)
781{
782 URL aTargetURL;
783 Sequence<PropertyValue> aArgs;
784 Reference< XDispatch > xDispatch;
785
786 {
787 SolarMutexGuard g;
788
789 sal_uInt16 nCurItemId = pMenu->GetCurItemId();
790 sal_uInt16 nCurPos = pMenu->GetItemPos( nCurItemId );
791 if ( pMenu == m_pVCLMenu &&
792 pMenu->GetItemType( nCurPos ) != MenuItemType::SEPARATOR )
793 {
794 MenuItemHandler* pMenuItemHandler = GetMenuItemHandler( nCurItemId );
795 if ( pMenuItemHandler && pMenuItemHandler->xMenuItemDispatch.is() )
796 {
797 aTargetURL.Complete = pMenuItemHandler->aMenuItemURL;
798 m_xURLTransformer->parseStrict( aTargetURL );
799
800 if ( pMenu->GetUserValue( nCurItemId ) )
801 {
802 // addon menu item selected
803 aArgs.realloc( 1 );
804 aArgs[0].Name = "Referer";
805 aArgs[0].Value <<= OUString( "private:user" );
806 }
807
808 xDispatch = pMenuItemHandler->xMenuItemDispatch;
809 }
810 }
811 }
812
813 // tdf#126054 don't let dispatch destroy this until after function completes
814 rtl::Reference<MenuBarManager> xKeepAlive(this);
815 if (xDispatch.is())
816 {
817 SolarMutexReleaser aReleaser;
818 xDispatch->dispatch( aTargetURL, aArgs );
819 }
820
821 if ( !m_bHasMenuBar )
822 // Standalone (non-native) popup menu doesn't fire deactivate event
823 // in this case, so we have to reset the active flag here.
824 m_bActive = false;
825
826 return true;
827}
828
829bool MenuBarManager::MustBeHidden( PopupMenu* pPopupMenu, const Reference< XURLTransformer >& rTransformer )
830{
831 if ( pPopupMenu )
832 {
833 URL aTargetURL;
834 SvtCommandOptions aCmdOptions;
835
836 sal_uInt16 nCount = pPopupMenu->GetItemCount();
837 sal_uInt16 nHideCount( 0 );
838
839 for ( sal_uInt16 i = 0; i < nCount; i++ )
840 {
841 sal_uInt16 nId = pPopupMenu->GetItemId( i );
842 if ( nId > 0 )
843 {
844 PopupMenu* pSubPopupMenu = pPopupMenu->GetPopupMenu( nId );
845 if ( pSubPopupMenu )
846 {
847 if ( MustBeHidden( pSubPopupMenu, rTransformer ))
848 {
849 pPopupMenu->HideItem( nId );
850 ++nHideCount;
851 }
852 }
853 else
854 {
855 aTargetURL.Complete = pPopupMenu->GetItemCommand( nId );
856 rTransformer->parseStrict( aTargetURL );
857
858 if ( aCmdOptions.Lookup( SvtCommandOptions::CMDOPTION_DISABLED, aTargetURL.Path ))
859 ++nHideCount;
860 }
861 }
862 else
863 ++nHideCount;
864 }
865
866 return ( nCount == nHideCount );
867 }
868
869 return true;
870}
871
872OUString MenuBarManager::RetrieveLabelFromCommand(const OUString& rCmdURL)
873{
874 auto aProperties = vcl::CommandInfoProvider::GetCommandProperties(rCmdURL, m_aModuleIdentifier);
875 if ( !m_bHasMenuBar )
876 {
877 // This is a context menu, prefer "PopupLabel" over "Label".
878 return vcl::CommandInfoProvider::GetPopupLabelForCommand(aProperties);
879 }
880 return vcl::CommandInfoProvider::GetMenuLabelForCommand(aProperties);
881}
882
883bool MenuBarManager::CreatePopupMenuController( MenuItemHandler* pMenuItemHandler,
884 const css::uno::Reference< css::frame::XDispatchProvider >& rDispatchProvider,
885 const OUString& rModuleIdentifier )
886{
887 OUString aItemCommand( pMenuItemHandler->aMenuItemURL );
888
889 // Try instantiate a popup menu controller. It is stored in the menu item handler.
890 if ( !m_xPopupMenuControllerFactory.is() )
891 return false;
892
893 auto aSeq( comphelper::InitAnyPropertySequence( {
894 { "DispatchProvider", makeAny(rDispatchProvider) },
895 { "ModuleIdentifier", makeAny(rModuleIdentifier) },
896 { "Frame", makeAny(m_xFrame) },
897 { "InToolbar", makeAny(!m_bHasMenuBar) }
898 } ) );
899
900 Reference< XPopupMenuController > xPopupMenuController(
901 m_xPopupMenuControllerFactory->createInstanceWithArgumentsAndContext(
902 aItemCommand,
903 aSeq,
904 m_xContext ),
905 UNO_QUERY );
906
907 if ( xPopupMenuController.is() )
908 {
909 // Provide our awt popup menu to the popup menu controller
910 pMenuItemHandler->xPopupMenuController = xPopupMenuController;
911 xPopupMenuController->setPopupMenu( pMenuItemHandler->xPopupMenu );
912 return true;
913 }
914
915 return false;
916}
917
918void MenuBarManager::FillMenuManager( Menu* pMenu, const Reference< XFrame >& rFrame,
919 const Reference< XDispatchProvider >& rDispatchProvider,
920 const OUString& rModuleIdentifier, bool bDelete )
921{
922 m_xFrame = rFrame;
923 m_bActive = false;
924 m_bDeleteMenu = bDelete;
925 m_pVCLMenu = pMenu;
926 m_xDispatchProvider = rDispatchProvider;
927
928 const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
929 m_bShowMenuImages = rSettings.GetUseImagesInMenus();
930 m_bRetrieveImages = false;
931
932 // Set module identifier when provided from outside
933 if (!rModuleIdentifier.isEmpty())
934 m_aModuleIdentifier = rModuleIdentifier;
935 else
936 m_aModuleIdentifier = vcl::CommandInfoProvider::GetModuleIdentifier(m_xFrame);
937
938 // Add root as ui configuration listener
939 RetrieveImageManagers();
940
941 if ( pMenu->IsMenuBar() && rFrame.is() )
942 {
943 // First merge all addon popup menus into our structure
944 sal_uInt16 nPos = 0;
945 for ( nPos = 0; nPos < pMenu->GetItemCount(); nPos++ )
946 {
947 sal_uInt16 nItemId = pMenu->GetItemId( nPos );
948 OUString aCommand = pMenu->GetItemCommand( nItemId );
949 if ( aCommand == aSpecialWindowCommand".uno:WindowList" || aCommand == aCmdHelpMenu".uno:HelpMenu" )
950 {
951 // Retrieve addon popup menus and add them to our menu bar
952 framework::AddonMenuManager::MergeAddonPopupMenus( rFrame, nPos, static_cast<MenuBar *>(pMenu) );
953 break;
954 }
955 }
956
957 // Merge the Add-Ons help menu items into the Office help menu
958 framework::AddonMenuManager::MergeAddonHelpMenu( rFrame, static_cast<MenuBar *>(pMenu) );
959 }
960
961 bool bAccessibilityEnabled( Application::GetSettings().GetMiscSettings().GetEnableATToolSupport() );
962 sal_uInt16 nItemCount = pMenu->GetItemCount();
963 OUString aItemCommand;
964 m_aMenuItemHandlerVector.reserve(nItemCount);
965 for ( sal_uInt16 i = 0; i < nItemCount; i++ )
966 {
967 sal_uInt16 nItemId = FillItemCommand(aItemCommand,pMenu, i );
968
969 if (( pMenu->IsMenuBar() || bAccessibilityEnabled ) &&
970 ( pMenu->GetItemText( nItemId ).isEmpty() ))
971 {
972 if ( !aItemCommand.isEmpty() )
973 pMenu->SetItemText( nItemId, RetrieveLabelFromCommand( aItemCommand ));
974 }
975
976 // Command can be just an alias to another command.
977 auto aProperties = vcl::CommandInfoProvider::GetCommandProperties(aItemCommand, m_aModuleIdentifier);
978 OUString aRealCommand = vcl::CommandInfoProvider::GetRealCommandForCommand(aProperties);
979 if ( !aRealCommand.isEmpty() )
980 aItemCommand = aRealCommand;
981
982 Reference< XDispatch > xDispatch;
983 Reference< XStatusListener > xStatusListener;
984 VclPtr<PopupMenu> pPopup = pMenu->GetPopupMenu( nItemId );
985 // overwrite the show icons on menu option?
986 MenuItemBits nBits = pMenu->GetItemBits( nItemId ) & ( MenuItemBits::ICON | MenuItemBits::TEXT );
987 bool bItemShowMenuImages = ( m_bShowMenuImages && nBits != MenuItemBits::TEXT ) || nBits & MenuItemBits::ICON;
988
989 if ( pPopup )
990 {
991 // Retrieve module identifier from Help Command entry
992 OUString aModuleIdentifier( rModuleIdentifier );
993 if (!pMenu->GetHelpCommand(nItemId).isEmpty())
994 {
995 aModuleIdentifier = pMenu->GetHelpCommand( nItemId );
996 pMenu->SetHelpCommand( nItemId, "" );
997 }
998
999 // Retrieve possible attributes struct
1000 Reference< XDispatchProvider > xPopupMenuDispatchProvider( rDispatchProvider );
1001 MenuAttributes* pAttributes = static_cast<MenuAttributes *>(pMenu->GetUserValue( nItemId ));
1002 if ( pAttributes )
1003 xPopupMenuDispatchProvider = pAttributes->xDispatchProvider;
1004
1005 if ( m_xPopupMenuControllerFactory.is() &&
1006 m_xPopupMenuControllerFactory->hasController( aItemCommand, aModuleIdentifier )
1007 )
1008 {
1009 // Check if we have to create a popup menu for a uno based popup menu controller.
1010 // We have to set an empty popup menu into our menu structure so the controller also
1011 // works with inplace OLE.
1012 MenuItemHandler* pItemHandler = new MenuItemHandler( nItemId, xStatusListener, xDispatch );
1013 VCLXPopupMenu* pVCLXPopupMenu = new VCLXPopupMenu(pPopup);
1014 pItemHandler->xPopupMenu = pVCLXPopupMenu;
1015 pItemHandler->aMenuItemURL = aItemCommand;
1016 m_aMenuItemHandlerVector.push_back( std::unique_ptr<MenuItemHandler>(pItemHandler) );
1017
1018 if ( bAccessibilityEnabled || pMenu->IsMenuBar())
1019 {
1020 if ( CreatePopupMenuController( pItemHandler, xPopupMenuDispatchProvider, aModuleIdentifier ))
1021 pItemHandler->xPopupMenuController->updatePopupMenu();
1022 }
1023 lcl_CheckForChildren(pMenu, nItemId);
1024 }
1025 else
1026 {
1027 // Check if this is the tools menu. Add menu item if needed
1028 if ( aItemCommand == aCmdToolsMenu".uno:ToolsMenu" && AddonMenuManager::HasAddonMenuElements() )
1029 {
1030 // Create addon popup menu if there exist elements and this is the tools popup menu
1031 VclPtr<PopupMenu> pSubMenu = AddonMenuManager::CreateAddonMenu(rFrame);
1032 if ( pSubMenu && ( pSubMenu->GetItemCount() > 0 ))
1033 {
1034 if ( pPopup->GetItemType( pPopup->GetItemCount() - 1 ) != MenuItemType::SEPARATOR )
1035 pPopup->InsertSeparator();
1036
1037 pPopup->InsertItem( ITEMID_ADDONLIST, OUString() );
1038 pPopup->SetPopupMenu( ITEMID_ADDONLIST, pSubMenu );
1039 pPopup->SetItemCommand( ITEMID_ADDONLIST, ".uno:Addons" );
1040 }
1041 else
1042 pSubMenu.disposeAndClear();
1043 }
1044
1045 MenuBarManager* pSubMenuManager = new MenuBarManager( m_xContext, rFrame, m_xURLTransformer,
1046 xPopupMenuDispatchProvider, aModuleIdentifier, pPopup, false, m_bHasMenuBar );
1047
1048 AddMenu(pSubMenuManager, aItemCommand, nItemId);
1049 }
1050 }
1051 else if ( pMenu->GetItemType( i ) != MenuItemType::SEPARATOR )
1052 {
1053 if ( bItemShowMenuImages )
1054 m_bRetrieveImages = true;
1055
1056 std::unique_ptr<MenuItemHandler> pItemHandler(new MenuItemHandler( nItemId, xStatusListener, xDispatch ));
1057 // Retrieve possible attributes struct
1058 MenuAttributes* pAttributes = static_cast<MenuAttributes *>(pMenu->GetUserValue( nItemId ));
1059 if ( pAttributes )
1060 pItemHandler->aTargetFrame = pAttributes->aTargetFrame;
1061 pItemHandler->aMenuItemURL = aItemCommand;
1062
1063 if ( m_xPopupMenuControllerFactory.is() &&
1064 m_xPopupMenuControllerFactory->hasController( aItemCommand, m_aModuleIdentifier ) )
1065 {
1066 // Check if we have to create a popup menu for a uno based popup menu controller.
1067 // We have to set an empty popup menu into our menu structure so the controller also
1068 // works with inplace OLE.
1069 VCLXPopupMenu* pVCLXPopupMenu = new VCLXPopupMenu;
1070 PopupMenu* pPopupMenu = static_cast<PopupMenu *>(pVCLXPopupMenu->GetMenu());
1071 pMenu->SetPopupMenu( pItemHandler->nItemId, pPopupMenu );
1072 pItemHandler->xPopupMenu = pVCLXPopupMenu;
1073
1074 if ( bAccessibilityEnabled && CreatePopupMenuController( pItemHandler.get(), m_xDispatchProvider, m_aModuleIdentifier ) )
1075 {
1076 pItemHandler->xPopupMenuController->updatePopupMenu();
1077 }
1078
1079 lcl_CheckForChildren(pMenu, pItemHandler->nItemId);
1080 }
1081
1082 m_aMenuItemHandlerVector.push_back( std::move(pItemHandler) );
1083 }
1084 }
1085
1086 if ( m_bHasMenuBar && bAccessibilityEnabled )
1087 {
1088 RetrieveShortcuts( m_aMenuItemHandlerVector );
1089 for (auto const& menuItemHandler : m_aMenuItemHandlerVector)
1090 {
1091 // Set key code, workaround for hard-coded shortcut F1 mapped to .uno:HelpIndex
1092 // Only non-popup menu items can have a short-cut
1093 if ( menuItemHandler->aMenuItemURL == aCmdHelpIndex".uno:HelpIndex" )
1094 {
1095 vcl::KeyCode aKeyCode( KEY_F1 );
1096 pMenu->SetAccelKey( menuItemHandler->nItemId, aKeyCode );
1097 }
1098 else if ( pMenu->GetPopupMenu( menuItemHandler->nItemId ) == nullptr )
1099 pMenu->SetAccelKey( menuItemHandler->nItemId, menuItemHandler->aKeyCode );
1100 }
1101 }
1102
1103 SetHdl();
1104}
1105
1106void MenuBarManager::impl_RetrieveShortcutsFromConfiguration(
1107 const Reference< XAcceleratorConfiguration >& rAccelCfg,
1108 const Sequence< OUString >& rCommands,
1109 std::vector< std::unique_ptr<MenuItemHandler> >& aMenuShortCuts )
1110{
1111 if ( !rAccelCfg.is() )
1112 return;
1113
1114 try
1115 {
1116 css::awt::KeyEvent aKeyEvent;
1117 Sequence< Any > aSeqKeyCode = rAccelCfg->getPreferredKeyEventsForCommandList( rCommands );
1118 for ( sal_Int32 i = 0; i < aSeqKeyCode.getLength(); i++ )
1119 {
1120 if ( aSeqKeyCode[i] >>= aKeyEvent )
1121 aMenuShortCuts[i]->aKeyCode = svt::AcceleratorExecute::st_AWTKey2VCLKey( aKeyEvent );
1122 }
1123 }
1124 catch ( const IllegalArgumentException& )
1125 {
1126 }
1127}
1128
1129void MenuBarManager::RetrieveShortcuts( std::vector< std::unique_ptr<MenuItemHandler> >& aMenuShortCuts )
1130{
1131 Reference< XAcceleratorConfiguration > xDocAccelCfg( m_xDocAcceleratorManager );
1132 Reference< XAcceleratorConfiguration > xModuleAccelCfg( m_xModuleAcceleratorManager );
1133 Reference< XAcceleratorConfiguration > xGlobalAccelCfg( m_xGlobalAcceleratorManager );
1134
1135 if ( !m_bAcceleratorCfg )
1136 {
1137 // Retrieve references on demand
1138 m_bAcceleratorCfg = true;
1139 if ( !xDocAccelCfg.is() )
1140 {
1141 Reference< XController > xController = m_xFrame->getController();
1142 Reference< XModel > xModel;
1143 if ( xController.is() )
1144 {
1145 xModel = xController->getModel();
1146 if ( xModel.is() )
1147 {
1148 Reference< XUIConfigurationManagerSupplier > xSupplier( xModel, UNO_QUERY );
1149 if ( xSupplier.is() )
1150 {
1151 Reference< XUIConfigurationManager > xDocUICfgMgr = xSupplier->getUIConfigurationManager();
1152 if ( xDocUICfgMgr.is() )
1153 {
1154 xDocAccelCfg = xDocUICfgMgr->getShortCutManager();
1155 m_xDocAcceleratorManager = xDocAccelCfg;
1156 }
1157 }
1158 }
1159 }
1160 }
1161
1162 if ( !xModuleAccelCfg.is() )
1163 {
1164 Reference< XModuleUIConfigurationManagerSupplier > xModuleCfgMgrSupplier =
1165 theModuleUIConfigurationManagerSupplier::get( m_xContext );
1166 try
1167 {
1168 Reference< XUIConfigurationManager > xUICfgMgr = xModuleCfgMgrSupplier->getUIConfigurationManager( m_aModuleIdentifier );
1169 if ( xUICfgMgr.is() )
1170 {
1171 xModuleAccelCfg = xUICfgMgr->getShortCutManager();
1172 m_xModuleAcceleratorManager = xModuleAccelCfg;
1173 }
1174 }
1175 catch ( const RuntimeException& )
1176 {
1177 throw;
1178 }
1179 catch ( const Exception& )
1180 {
1181 }
1182 }
1183
1184 if ( !xGlobalAccelCfg.is() ) try
1185 {
1186 xGlobalAccelCfg = GlobalAcceleratorConfiguration::create( m_xContext );
1187 m_xGlobalAcceleratorManager = xGlobalAccelCfg;
1188 }
1189 catch ( const css::uno::DeploymentException& )
1190 {
1191 SAL_WARN("fwk.uielement", "GlobalAcceleratorConfiguration"do { if (true) { switch (sal_detail_log_report(::SAL_DETAIL_LOG_LEVEL_WARN
, "fwk.uielement")) { case SAL_DETAIL_LOG_ACTION_IGNORE: break
; case SAL_DETAIL_LOG_ACTION_LOG: if (sizeof ::sal::detail::getResult
( ::sal::detail::StreamStart() << "GlobalAcceleratorConfiguration"
" not available. This should happen only on mobile platforms."
) == 1) { ::sal_detail_log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("fwk.uielement"
), ("/home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx"
":" "1192" ": "), ::sal::detail::unwrapStream( ::sal::detail
::StreamStart() << "GlobalAcceleratorConfiguration" " not available. This should happen only on mobile platforms."
), 0); } else { ::std::ostringstream sal_detail_stream; sal_detail_stream
<< "GlobalAcceleratorConfiguration" " not available. This should happen only on mobile platforms."
; ::sal::detail::log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("fwk.uielement"
), ("/home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx"
":" "1192" ": "), sal_detail_stream, 0); }; break; case SAL_DETAIL_LOG_ACTION_FATAL
: if (sizeof ::sal::detail::getResult( ::sal::detail::StreamStart
() << "GlobalAcceleratorConfiguration" " not available. This should happen only on mobile platforms."
) == 1) { ::sal_detail_log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("fwk.uielement"
), ("/home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx"
":" "1192" ": "), ::sal::detail::unwrapStream( ::sal::detail
::StreamStart() << "GlobalAcceleratorConfiguration" " not available. This should happen only on mobile platforms."
), 0); } else { ::std::ostringstream sal_detail_stream; sal_detail_stream
<< "GlobalAcceleratorConfiguration" " not available. This should happen only on mobile platforms."
; ::sal::detail::log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("fwk.uielement"
), ("/home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx"
":" "1192" ": "), sal_detail_stream, 0); }; std::abort(); break
; } } } while (false)
1192 " not available. This should happen only on mobile platforms.")do { if (true) { switch (sal_detail_log_report(::SAL_DETAIL_LOG_LEVEL_WARN
, "fwk.uielement")) { case SAL_DETAIL_LOG_ACTION_IGNORE: break
; case SAL_DETAIL_LOG_ACTION_LOG: if (sizeof ::sal::detail::getResult
( ::sal::detail::StreamStart() << "GlobalAcceleratorConfiguration"
" not available. This should happen only on mobile platforms."
) == 1) { ::sal_detail_log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("fwk.uielement"
), ("/home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx"
":" "1192" ": "), ::sal::detail::unwrapStream( ::sal::detail
::StreamStart() << "GlobalAcceleratorConfiguration" " not available. This should happen only on mobile platforms."
), 0); } else { ::std::ostringstream sal_detail_stream; sal_detail_stream
<< "GlobalAcceleratorConfiguration" " not available. This should happen only on mobile platforms."
; ::sal::detail::log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("fwk.uielement"
), ("/home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx"
":" "1192" ": "), sal_detail_stream, 0); }; break; case SAL_DETAIL_LOG_ACTION_FATAL
: if (sizeof ::sal::detail::getResult( ::sal::detail::StreamStart
() << "GlobalAcceleratorConfiguration" " not available. This should happen only on mobile platforms."
) == 1) { ::sal_detail_log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("fwk.uielement"
), ("/home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx"
":" "1192" ": "), ::sal::detail::unwrapStream( ::sal::detail
::StreamStart() << "GlobalAcceleratorConfiguration" " not available. This should happen only on mobile platforms."
), 0); } else { ::std::ostringstream sal_detail_stream; sal_detail_stream
<< "GlobalAcceleratorConfiguration" " not available. This should happen only on mobile platforms."
; ::sal::detail::log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("fwk.uielement"
), ("/home/maarten/src/libreoffice/core/framework/source/uielement/menubarmanager.cxx"
":" "1192" ": "), sal_detail_stream, 0); }; std::abort(); break
; } } } while (false)
;
1193 }
1194 }
1195
1196 vcl::KeyCode aEmptyKeyCode;
1197 Sequence< OUString > aSeq( aMenuShortCuts.size() );
1198 const sal_uInt32 nCount = aMenuShortCuts.size();
1199 for ( sal_uInt32 i = 0; i < nCount; ++i )
1200 {
1201 aSeq[i] = aMenuShortCuts[i]->aMenuItemURL;
1202 aMenuShortCuts[i]->aKeyCode = aEmptyKeyCode;
1203 }
1204
1205 if ( m_xGlobalAcceleratorManager.is() )
1206 impl_RetrieveShortcutsFromConfiguration( xGlobalAccelCfg, aSeq, aMenuShortCuts );
1207 if ( m_xModuleAcceleratorManager.is() )
1208 impl_RetrieveShortcutsFromConfiguration( xModuleAccelCfg, aSeq, aMenuShortCuts );
1209 if ( m_xDocAcceleratorManager.is() )
1210 impl_RetrieveShortcutsFromConfiguration( xDocAccelCfg, aSeq, aMenuShortCuts );
1211}
1212
1213void MenuBarManager::RetrieveImageManagers()
1214{
1215 if ( !m_xDocImageManager.is() )
1216 {
1217 Reference< XController > xController = m_xFrame->getController();
1218 Reference< XModel > xModel;
1219 if ( xController.is() )
1220 {
1221 xModel = xController->getModel();
1222 if ( xModel.is() )
1223 {
1224 Reference< XUIConfigurationManagerSupplier > xSupplier( xModel, UNO_QUERY );
1225 if ( xSupplier.is() )
1226 {
1227 Reference< XUIConfigurationManager > xDocUICfgMgr = xSupplier->getUIConfigurationManager();
1228 m_xDocImageManager.set( xDocUICfgMgr->getImageManager(), UNO_QUERY );
1229 m_xDocImageManager->addConfigurationListener(
1230 Reference< XUIConfigurationListener >(
1231 static_cast< OWeakObject* >( this ), UNO_QUERY ));
1232 }
1233 }
1234 }
1235 }
1236
1237 if ( !m_xModuleImageManager.is() )
1238 {
1239 Reference< XModuleUIConfigurationManagerSupplier > xModuleCfgMgrSupplier =
1240 theModuleUIConfigurationManagerSupplier::get( m_xContext );
1241 Reference< XUIConfigurationManager > xUICfgMgr = xModuleCfgMgrSupplier->getUIConfigurationManager( m_aModuleIdentifier );
1242 m_xModuleImageManager.set( xUICfgMgr->getImageManager(), UNO_QUERY );
1243 m_xModuleImageManager->addConfigurationListener( Reference< XUIConfigurationListener >(
1244 static_cast< OWeakObject* >( this ), UNO_QUERY ));
1245 }
1246}
1247
1248void MenuBarManager::FillMenuWithConfiguration(
1249 sal_uInt16& nId,
1250 Menu* pMenu,
1251 const OUString& rModuleIdentifier,
1252 const Reference< XIndexAccess >& rItemContainer,
1253 const Reference< XURLTransformer >& rTransformer )
1254{
1255 Reference< XDispatchProvider > xEmptyDispatchProvider;
1256 MenuBarManager::FillMenu( nId, pMenu, rModuleIdentifier, rItemContainer, xEmptyDispatchProvider );
1257
1258 // Merge add-on menu entries into the menu bar
1259 MenuBarManager::MergeAddonMenus( pMenu,
1260 AddonsOptions().GetMergeMenuInstructions(),
1261 rModuleIdentifier );
1262
1263 bool bHasDisabledEntries = SvtCommandOptions().HasEntries( SvtCommandOptions::CMDOPTION_DISABLED );
1264 if ( !bHasDisabledEntries )
1265 return;
1266
1267 sal_uInt16 nCount = pMenu->GetItemCount();
1268 for ( sal_uInt16 i = 0; i < nCount; i++ )
1269 {
1270 sal_uInt16 nID = pMenu->GetItemId( i );
1271 if ( nID > 0 )
1272 {
1273 PopupMenu* pPopupMenu = pMenu->GetPopupMenu( nID );
1274 if ( pPopupMenu )
1275 {
1276 if ( MustBeHidden( pPopupMenu, rTransformer ))
1277 pMenu->HideItem( nId );
1278 }
1279 }
1280 }
1281}
1282
1283void MenuBarManager::FillMenu(
1284 sal_uInt16& nId,
1285 Menu* pMenu,
1286 const OUString& rModuleIdentifier,
1287 const Reference< XIndexAccess >& rItemContainer,
1288 const Reference< XDispatchProvider >& rDispatchProvider )
1289{
1290 // Fill menu bar with container contents
1291 for ( sal_Int32 n = 0; n < rItemContainer->getCount(); n++ )
1292 {
1293 Sequence< PropertyValue > aProps;
1294 OUString aCommandURL;
1295 OUString aLabel;
1296 OUString aModuleIdentifier( rModuleIdentifier );
1297 sal_uInt16 nType = 0;
1298 Reference< XIndexAccess > xIndexContainer;
1299 Reference< XDispatchProvider > xDispatchProvider( rDispatchProvider );
1300 sal_Int16 nStyle = 0;
1301 try
1302 {
1303 if ( rItemContainer->getByIndex( n ) >>= aProps )
1304 {
1305 bool bShow = true;
1306 bool bEnabled = true;
1307
1308 for ( beans::PropertyValue const & rProp : std::as_const(aProps) )
1309 {
1310 OUString aPropName = rProp.Name;
1311 if ( aPropName == "CommandURL" )
1312 rProp.Value >>= aCommandURL;
1313 else if ( aPropName == "ItemDescriptorContainer" )
1314 rProp.Value >>= xIndexContainer;
1315 else if ( aPropName == "Label" )
1316 rProp.Value >>= aLabel;
1317 else if ( aPropName == "Type" )
1318 rProp.Value >>= nType;
1319 else if ( aPropName == "ModuleIdentifier" )
1320 rProp.Value >>= aModuleIdentifier;
1321 else if ( aPropName == "DispatchProvider" )
1322 rProp.Value >>= xDispatchProvider;
1323 else if ( aPropName == "Style" )
1324 rProp.Value >>= nStyle;
1325 else if ( aPropName == "IsVisible" )
1326 rProp.Value >>= bShow;
1327 else if ( aPropName == "Enabled" )
1328 rProp.Value >>= bEnabled;
1329 }
1330
1331 if (!aCommandURL.isEmpty() && vcl::CommandInfoProvider::IsExperimental(aCommandURL, rModuleIdentifier) &&
1332 !SvtMiscOptions().IsExperimentalMode())
1333 {
1334 continue;
1335 }
1336
1337 if ( nType == css::ui::ItemType::DEFAULT )
1338 {
1339 pMenu->InsertItem( nId, aLabel );
1340 pMenu->SetItemCommand( nId, aCommandURL );
1341
1342 if ( nStyle )
1343 {
1344 MenuItemBits nBits = pMenu->GetItemBits( nId );
1345 if ( nStyle & css::ui::ItemStyle::ICON )
1346 nBits |= MenuItemBits::ICON;
1347 if ( nStyle & css::ui::ItemStyle::TEXT )
1348 nBits |= MenuItemBits::TEXT;
1349 if ( nStyle & css::ui::ItemStyle::RADIO_CHECK )
1350 nBits |= MenuItemBits::RADIOCHECK;
1351 pMenu->SetItemBits( nId, nBits );
1352 }
1353
1354 if ( !bShow )
1355 pMenu->HideItem( nId );
1356
1357 if ( !bEnabled)
1358 pMenu->EnableItem( nId, false );
1359
1360 if ( xIndexContainer.is() )
1361 {
1362 VclPtr<PopupMenu> pNewPopupMenu = VclPtr<PopupMenu>::Create();
1363 pMenu->SetPopupMenu( nId, pNewPopupMenu );
1364
1365 if ( xDispatchProvider.is() )
1366 {
1367 // Use attributes struct to transport special dispatch provider
1368 void* nAttributePtr = MenuAttributes::CreateAttribute(xDispatchProvider);
1369 pMenu->SetUserValue(nId, nAttributePtr, MenuAttributes::ReleaseAttribute);
1370 }
1371
1372 // Use help command to transport module identifier
1373 if ( !aModuleIdentifier.isEmpty() )
1374 pMenu->SetHelpCommand( nId, aModuleIdentifier );
1375
1376 ++nId;
1377 FillMenu( nId, pNewPopupMenu, aModuleIdentifier, xIndexContainer, xDispatchProvider );
1378 }
1379 else
1380 ++nId;
1381 }
1382 else
1383 {
1384 pMenu->InsertSeparator();
1385 ++nId;
1386 }
1387 }
1388 }
1389 catch ( const IndexOutOfBoundsException& )
1390 {
1391 break;
1392 }
1393 }
1394}
1395
1396void MenuBarManager::MergeAddonMenus(
1397 Menu* pMenuBar,
1398 const MergeMenuInstructionContainer& aMergeInstructionContainer,
1399 const OUString& rModuleIdentifier )
1400{
1401 // set start value for the item ID for the new addon menu items
1402 sal_uInt16 nItemId = ADDONMENU_MERGE_ITEMID_START;
1403
1404 const sal_uInt32 nCount = aMergeInstructionContainer.size();
1405 for ( sal_uInt32 i = 0; i < nCount; i++ )
1406 {
1407 const MergeMenuInstruction& rMergeInstruction = aMergeInstructionContainer[i];
1408
1409 if ( MenuBarMerger::IsCorrectContext( rMergeInstruction.aMergeContext, rModuleIdentifier ))
1410 {
1411 ::std::vector< OUString > aMergePath;
1412
1413 // retrieve the merge path from the merge point string
1414 MenuBarMerger::RetrieveReferencePath( rMergeInstruction.aMergePoint, aMergePath );
1415
1416 // convert the sequence/sequence property value to a more convenient vector<>
1417 AddonMenuContainer aMergeMenuItems;
1418 MenuBarMerger::GetSubMenu( rMergeInstruction.aMergeMenu, aMergeMenuItems );
1419
1420 // try to find the reference point for our merge operation
1421 Menu* pMenu = pMenuBar;
1422 ReferencePathInfo aResult = MenuBarMerger::FindReferencePath( aMergePath, pMenu );
1423
1424 if ( aResult.eResult == RP_OK )
1425 {
1426 // normal merge operation
1427 MenuBarMerger::ProcessMergeOperation( aResult.pPopupMenu,
1428 aResult.nPos,
1429 nItemId,
1430 rMergeInstruction.aMergeCommand,
1431 rMergeInstruction.aMergeCommandParameter,
1432 rModuleIdentifier,
1433 aMergeMenuItems );
1434 }
1435 else
1436 {
1437 // fallback
1438 MenuBarMerger::ProcessFallbackOperation( aResult,
1439 nItemId,
1440 rMergeInstruction.aMergeCommand,
1441 rMergeInstruction.aMergeFallback,
1442 aMergePath,
1443 rModuleIdentifier,
1444 aMergeMenuItems );
1445 }
1446 }
1447 }
1448}
1449
1450void MenuBarManager::SetItemContainer( const Reference< XIndexAccess >& rItemContainer )
1451{
1452 SolarMutexGuard aSolarMutexGuard;
1453
1454 Reference< XFrame > xFrame = m_xFrame;
1455
1456 // Clear MenuBarManager structures
1457 {
1458 // Check active state as we cannot change our VCL menu during activation by the user
1459 if ( m_bActive )
1460 {
1461 m_xDeferredItemContainer = rItemContainer;
1462 return;
1463 }
1464
1465 RemoveListener();
1466 m_aMenuItemHandlerVector.clear();
1467 m_pVCLMenu->Clear();
1468
1469 sal_uInt16 nId = 1;
1470
1471 // Fill menu bar with container contents
1472 FillMenuWithConfiguration( nId, m_pVCLMenu, m_aModuleIdentifier, rItemContainer, m_xURLTransformer );
1473
1474 // Refill menu manager again
1475 Reference< XDispatchProvider > xDispatchProvider;
1476 FillMenuManager( m_pVCLMenu, xFrame, xDispatchProvider, m_aModuleIdentifier, false );
1477
1478 // add itself as frame action listener
1479 m_xFrame->addFrameActionListener( Reference< XFrameActionListener >( static_cast< OWeakObject* >( this ), UNO_QUERY ));
1480 }
1481}
1482
1483void MenuBarManager::GetPopupController( PopupControllerCache& rPopupController )
1484{
1485
1486 SolarMutexGuard aSolarMutexGuard;
1487
1488 for (auto const& menuItemHandler : m_aMenuItemHandlerVector)
1489 {
1490 if ( menuItemHandler->xPopupMenuController.is() )
1491 {
1492 Reference< XDispatchProvider > xDispatchProvider( menuItemHandler->xPopupMenuController, UNO_QUERY );
1493
1494 PopupControllerEntry aPopupControllerEntry;
1495 aPopupControllerEntry.m_xDispatchProvider = xDispatchProvider;
1496
1497 // Just use the main part of the URL for popup menu controllers
1498 sal_Int32 nSchemePart( 0 );
1499 OUString aMenuURL( menuItemHandler->aMenuItemURL );
1500
1501 nSchemePart = aMenuURL.indexOf( ':' );
1502 if (( nSchemePart > 0 ) &&
1503 ( aMenuURL.getLength() > ( nSchemePart+1 )))
1504 {
1505 OUString aMainURL( "vnd.sun.star.popup:" );
1506 sal_Int32 nQueryPart = aMenuURL.indexOf( '?', nSchemePart );
1507 if ( nQueryPart > 0 )
1508 aMainURL += aMenuURL.copy( nSchemePart, nQueryPart-nSchemePart );
1509 else if ( nQueryPart == -1 )
1510 aMainURL += aMenuURL.copy( nSchemePart+1 );
1511
1512 rPopupController.emplace( aMainURL, aPopupControllerEntry );
1513 }
1514 }
1515 if ( menuItemHandler->xSubMenuManager.is() )
1516 {
1517 MenuBarManager* pMenuBarManager = static_cast<MenuBarManager*>(menuItemHandler->xSubMenuManager.get());
1518 if ( pMenuBarManager )
1519 pMenuBarManager->GetPopupController( rPopupController );
1520 }
1521 }
1522}
1523
1524void MenuBarManager::AddMenu(MenuBarManager* pSubMenuManager,const OUString& _sItemCommand,sal_uInt16 _nItemId)
1525{
1526 Reference< XStatusListener > xSubMenuManager( static_cast< OWeakObject *>( pSubMenuManager ), UNO_QUERY );
1527 m_xFrame->addFrameActionListener( Reference< XFrameActionListener >( xSubMenuManager, UNO_QUERY ));
1528
1529 Reference< XDispatch > xDispatch;
1530 std::unique_ptr<MenuItemHandler> pMenuItemHandler(new MenuItemHandler(
1531 _nItemId,
1532 xSubMenuManager,
1533 xDispatch ));
1534 pMenuItemHandler->aMenuItemURL = _sItemCommand;
1535 m_aMenuItemHandlerVector.push_back( std::move(pMenuItemHandler) );
1536}
1537
1538sal_uInt16 MenuBarManager::FillItemCommand(OUString& _rItemCommand, Menu* _pMenu,sal_uInt16 _nIndex) const
1539{
1540 sal_uInt16 nItemId = _pMenu->GetItemId( _nIndex );
1541
1542 _rItemCommand = _pMenu->GetItemCommand( nItemId );
1543 if ( _rItemCommand.isEmpty() )
1544 {
1545 _rItemCommand = "slot:" + OUString::number( nItemId );
1546 _pMenu->SetItemCommand( nItemId, _rItemCommand );
1547 }
1548 return nItemId;
1549}
1550
1551void MenuBarManager::SetHdl()
1552{
1553 m_pVCLMenu->SetActivateHdl( LINK( this, MenuBarManager, Activate )::tools::detail::makeLink( ::tools::detail::castTo<MenuBarManager
*>(this), &MenuBarManager::LinkStubActivate)
);
1554 m_pVCLMenu->SetDeactivateHdl( LINK( this, MenuBarManager, Deactivate )::tools::detail::makeLink( ::tools::detail::castTo<MenuBarManager
*>(this), &MenuBarManager::LinkStubDeactivate)
);
1555 m_pVCLMenu->SetSelectHdl( LINK( this, MenuBarManager, Select )::tools::detail::makeLink( ::tools::detail::castTo<MenuBarManager
*>(this), &MenuBarManager::LinkStubSelect)
);
1556
1557 if ( !m_xURLTransformer.is() && m_xContext.is() )
1558 m_xURLTransformer.set( URLTransformer::create( m_xContext) );
1559}
1560
1561void MenuBarManager::FillMenuImages(Reference< XFrame > const & _xFrame, Menu* _pMenu,bool bShowMenuImages)
1562{
1563 AddonsOptions aAddonOptions;
1564
1565 for ( sal_uInt16 nPos = 0; nPos < _pMenu->GetItemCount(); nPos++ )
1566 {
1567 sal_uInt16 nId = _pMenu->GetItemId( nPos );
1568 if ( _pMenu->GetItemType( nPos ) != MenuItemType::SEPARATOR )
1569 {
1570 // overwrite the show icons on menu option?
1571 MenuItemBits nBits = _pMenu->GetItemBits( nId ) & ( MenuItemBits::ICON | MenuItemBits::TEXT );
1572 bool bTmpShowMenuImages = ( bShowMenuImages && nBits != MenuItemBits::TEXT ) || nBits & MenuItemBits::ICON;
1573
1574 if ( bTmpShowMenuImages )
1575 {
1576 OUString aMenuItemCommand = _pMenu->GetItemCommand( nId );
1577 Image aImage = vcl::CommandInfoProvider::GetImageForCommand(aMenuItemCommand, _xFrame);
1578 if ( !aImage )
1579 aImage = Image(aAddonOptions.GetImageFromURL(aMenuItemCommand, false));
1580
1581 _pMenu->SetItemImage( nId, aImage );
1582 }
1583 else
1584 _pMenu->SetItemImage( nId, Image() );
1585 }
1586 }
1587}
1588
1589}
1590
1591/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

/home/maarten/src/libreoffice/core/include/vcl/vclptr.hxx

1/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2/*
3 * This file is part of the LibreOffice project.
4 *
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/.
8 *
9 * This file incorporates work covered by the following license notice:
10 *
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 .
18 */
19
20#ifndef INCLUDED_VCL_PTR_HXX
21#define INCLUDED_VCL_PTR_HXX
22
23#include <sal/config.h>
24
25#include <rtl/ref.hxx>
26
27#include <utility>
28#include <type_traits>
29
30#ifdef DBG_UTIL
31#ifndef _WIN32
32#include <vcl/vclmain.hxx>
33#endif
34#endif
35
36class VclReferenceBase;
37
38namespace vcl::detail {
39
40template<typename>
41constexpr bool isIncompleteOrDerivedFromVclReferenceBase(...) { return true; }
42
43template<typename T> constexpr bool isIncompleteOrDerivedFromVclReferenceBase(
44 int (*)[sizeof(T)])
45{ return std::is_base_of<VclReferenceBase, T>::value; }
46
47} // namespace vcl::detail
48
49/**
50 * A thin wrapper around rtl::Reference to implement the acquire and dispose semantics we want for references to vcl::Window subclasses.
51 *
52 * For more details on the design please see vcl/README.lifecycle
53 *
54 * @param reference_type must be a subclass of vcl::Window
55 */
56template <class reference_type>
57class VclPtr
58{
59 static_assert(
60 vcl::detail::isIncompleteOrDerivedFromVclReferenceBase<reference_type>(
61 nullptr),
62 "template argument type must be derived from VclReferenceBase");
63
64 ::rtl::Reference<reference_type> m_rInnerRef;
65
66public:
67 /** Constructor...
68 */
69 VclPtr()
70 : m_rInnerRef()
71 {}
72
73 /** Constructor...
74 */
75 VclPtr (reference_type * pBody)
76 : m_rInnerRef(pBody)
77 {}
78
79 /** Constructor... that doesn't take a ref.
80 */
81 VclPtr (reference_type * pBody, __sal_NoAcquire)
82 : m_rInnerRef(pBody, SAL_NO_ACQUIRE)
83 {}
84
85 /** Up-casting conversion constructor: Copies interface reference.
86
87 Does not work for up-casts to ambiguous bases. For the special case of
88 up-casting to Reference< XInterface >, see the corresponding conversion
89 operator.
90
91 @param rRef another reference
92 */
93 template< class derived_type >
94 VclPtr(
95 const VclPtr< derived_type > & rRef,
96 typename std::enable_if<
97 std::is_base_of<reference_type, derived_type>::value, int>::type
98 = 0 )
99 : m_rInnerRef( static_cast<reference_type*>(rRef) )
100 {
101 }
102
103#if defined(DBG_UTIL) && !defined(_WIN32)
104 virtual ~VclPtr()
105 {
106 assert(m_rInnerRef.get() == nullptr || vclmain::isAlive())(static_cast <bool> (m_rInnerRef.get() == nullptr || vclmain
::isAlive()) ? void (0) : __assert_fail ("m_rInnerRef.get() == nullptr || vclmain::isAlive()"
, "/home/maarten/src/libreoffice/core/include/vcl/vclptr.hxx"
, 106, __extension__ __PRETTY_FUNCTION__))
;
107 // We can be one of the intermediate counts, but if we are the last
108 // VclPtr keeping this object alive, then something forgot to call dispose().
109 assert((!m_rInnerRef.get() || m_rInnerRef->isDisposed() || m_rInnerRef->getRefCount() > 1)(static_cast <bool> ((!m_rInnerRef.get() || m_rInnerRef
->isDisposed() || m_rInnerRef->getRefCount() > 1) &&
"someone forgot to call dispose()") ? void (0) : __assert_fail
("(!m_rInnerRef.get() || m_rInnerRef->isDisposed() || m_rInnerRef->getRefCount() > 1) && \"someone forgot to call dispose()\""
, "/home/maarten/src/libreoffice/core/include/vcl/vclptr.hxx"
, 110, __extension__ __PRETTY_FUNCTION__))
110 && "someone forgot to call dispose()")(static_cast <bool> ((!m_rInnerRef.get() || m_rInnerRef
->isDisposed() || m_rInnerRef->getRefCount() > 1) &&
"someone forgot to call dispose()") ? void (0) : __assert_fail
("(!m_rInnerRef.get() || m_rInnerRef->isDisposed() || m_rInnerRef->getRefCount() > 1) && \"someone forgot to call dispose()\""
, "/home/maarten/src/libreoffice/core/include/vcl/vclptr.hxx"
, 110, __extension__ __PRETTY_FUNCTION__))
;
111 }
112 VclPtr(VclPtr const &) = default;
113 VclPtr(VclPtr &&) = default;
114 VclPtr & operator =(VclPtr const &) = default;
115 VclPtr & operator =(VclPtr &&) = default;
116#endif
117
118 /**
119 * A construction helper for VclPtr. Since VclPtr types are created
120 * with a reference-count of one - to help fit into the existing
121 * code-flow; this helps us to construct them easily.
122 *
123 * For more details on the design please see vcl/README.lifecycle
124 *
125 * @tparam reference_type must be a subclass of vcl::Window
126 */
127 template<typename... Arg> [[nodiscard]] static VclPtr< reference_type > Create(Arg &&... arg)
128 {
129 return VclPtr< reference_type >( new reference_type(std::forward<Arg>(arg)...), SAL_NO_ACQUIRE );
130 }
131
132 /** Probably most common used: handle->someBodyOp().
133 */
134 reference_type * operator->() const
135 {
136 return m_rInnerRef.get();
137 }
138
139 /** Get the body. Can be used instead of operator->().
140 I.e. handle->someBodyOp() and handle.get()->someBodyOp()
141 are the same.
142 */
143 reference_type * get() const
144 {
145 return m_rInnerRef.get();
146 }
147
148 void set(reference_type *pBody)
149 {
150 m_rInnerRef.set(pBody);
151 }
152
153 void reset(reference_type *pBody)
154 {
155 m_rInnerRef.set(pBody);
156 }
157
158 /** Up-casting copy assignment operator.
159
160 Does not work for up-casts to ambiguous bases.
161
162 @param rRef another reference
163 */
164 template<typename derived_type>
165 typename std::enable_if<
166 std::is_base_of<reference_type, derived_type>::value,
167 VclPtr &>::type
168 operator =(VclPtr<derived_type> const & rRef)
169 {
170 m_rInnerRef.set(rRef.get());
171 return *this;
172 }
173
174 VclPtr & operator =(reference_type * pBody)
175 {
176 m_rInnerRef.set(pBody);
177 return *this;
178 }
179
180 operator reference_type * () const
181 {
182 return m_rInnerRef.get();
183 }
184
185 explicit operator bool () const
186 {
187 return m_rInnerRef.get() != nullptr;
188 }
189
190 void clear()
191 {
192 m_rInnerRef.clear();
193 }
194
195 void reset()
196 {
197 m_rInnerRef.clear();
198 }
199
200 void disposeAndClear()
201 {
202 // hold it alive for the lifetime of this method
203 ::rtl::Reference<reference_type> aTmp(m_rInnerRef);
7
Calling copy constructor for 'Reference<Menu>'
10
Returning from copy constructor for 'Reference<Menu>'
204 m_rInnerRef.clear(); // we should use some 'swap' method ideally ;-)
11
Calling 'Reference::clear'
18
Returning; memory was released
205 if (aTmp.get()) {
19
Calling 'Reference::get'
206 aTmp->disposeOnce();
207 }
208 }
209
210 /** Needed to place VclPtr's into STL collection.
211 */
212 bool operator< (const VclPtr<reference_type> & handle) const
213 {
214 return (m_rInnerRef < handle.m_rInnerRef);
215 }
216}; // class VclPtr
217
218template<typename T1, typename T2>
219inline bool operator ==(VclPtr<T1> const & p1, VclPtr<T2> const & p2) {
220 return p1.get() == p2.get();
221}
222
223template<typename T> inline bool operator ==(VclPtr<T> const & p1, T const * p2)
224{
225 return p1.get() == p2;
226}
227
228template<typename T> inline bool operator ==(VclPtr<T> const & p1, T * p2) {
229 return p1.get() == p2;
230}
231
232template<typename T> inline bool operator ==(T const * p1, VclPtr<T> const & p2)
233{
234 return p1 == p2.get();
235}
236
237template<typename T> inline bool operator ==(T * p1, VclPtr<T> const & p2) {
238 return p1 == p2.get();
239}
240
241template<typename T1, typename T2>
242inline bool operator !=(VclPtr<T1> const & p1, VclPtr<T2> const & p2) {
243 return !(p1 == p2);
244}
245
246template<typename T> inline bool operator !=(VclPtr<T> const & p1, T const * p2)
247{
248 return !(p1 == p2);
249}
250
251template<typename T> inline bool operator !=(VclPtr<T> const & p1, T * p2) {
252 return !(p1 == p2);
253}
254
255template<typename T> inline bool operator !=(T const * p1, VclPtr<T> const & p2)
256{
257 return !(p1 == p2);
258}
259
260template<typename T> inline bool operator !=(T * p1, VclPtr<T> const & p2) {
261 return !(p1 == p2);
262}
263
264/**
265 * A construction helper for a temporary VclPtr. Since VclPtr types
266 * are created with a reference-count of one - to help fit into
267 * the existing code-flow; this helps us to construct them easily.
268 * see also VclPtr::Create and ScopedVclPtr
269 *
270 * For more details on the design please see vcl/README.lifecycle
271 *
272 * @param reference_type must be a subclass of vcl::Window
273 */
274template <class reference_type>
275class SAL_WARN_UNUSED__attribute__((warn_unused)) VclPtrInstance final : public VclPtr<reference_type>
276{
277public:
278 template<typename... Arg> VclPtrInstance(Arg &&... arg)
279 : VclPtr<reference_type>( new reference_type(std::forward<Arg>(arg)...), SAL_NO_ACQUIRE )
280 {
281 }
282
283 /**
284 * Override and disallow this, to prevent people accidentally calling it and actually
285 * getting VclPtr::Create and getting a naked VclPtr<> instance
286 */
287 template<typename... Arg> static VclPtrInstance< reference_type > Create(Arg &&... ) = delete;
288};
289
290template <class reference_type>
291class ScopedVclPtr : public VclPtr<reference_type>
292{
293public:
294 /** Constructor...
295 */
296 ScopedVclPtr()
297 : VclPtr<reference_type>()
298 {}
299
300 /** Constructor
301 */
302 ScopedVclPtr (reference_type * pBody)
303 : VclPtr<reference_type>(pBody)
304 {}
305
306 /** Copy constructor...
307 */
308 ScopedVclPtr (const VclPtr<reference_type> & handle)
309 : VclPtr<reference_type>(handle)
310 {}
311
312 /**
313 Assignment that releases the last reference.
314 */
315 void disposeAndReset(reference_type *pBody)
316 {
317 if (pBody != this->get()) {
318 VclPtr<reference_type>::disposeAndClear();
319 VclPtr<reference_type>::set(pBody);
320 }
321 }
322
323 /**
324 Assignment that releases the last reference.
325 */
326 ScopedVclPtr<reference_type>& operator = (reference_type * pBody)
327 {
328 disposeAndReset(pBody);
329 return *this;
330 }
331
332 /** Up-casting conversion constructor: Copies interface reference.
333
334 Does not work for up-casts to ambiguous bases. For the special case of
335 up-casting to Reference< XInterface >, see the corresponding conversion
336 operator.
337
338 @param rRef another reference
339 */
340 template< class derived_type >
341 ScopedVclPtr(
342 const VclPtr< derived_type > & rRef,
343 typename std::enable_if<
344 std::is_base_of<reference_type, derived_type>::value, int>::type
345 = 0 )
346 : VclPtr<reference_type>( rRef )
347 {
348 }
349
350 /** Up-casting assignment operator.
351
352 Does not work for up-casts to ambiguous bases.
353
354 @param rRef another VclPtr
355 */
356 template<typename derived_type>
357 typename std::enable_if<
358 std::is_base_of<reference_type, derived_type>::value,
359 ScopedVclPtr &>::type
360 operator =(VclPtr<derived_type> const & rRef)
361 {
362 disposeAndReset(rRef.get());
363 return *this;
364 }
365
366 /**
367 * Override and disallow this, to prevent people accidentally calling it and actually
368 * getting VclPtr::Create and getting a naked VclPtr<> instance
369 */
370 template<typename... Arg> static ScopedVclPtr< reference_type > Create(Arg &&... ) = delete;
371
372 ~ScopedVclPtr()
373 {
374 VclPtr<reference_type>::disposeAndClear();
375 assert(VclPtr<reference_type>::get() == nullptr)(static_cast <bool> (VclPtr<reference_type>::get(
) == nullptr) ? void (0) : __assert_fail ("VclPtr<reference_type>::get() == nullptr"
, "/home/maarten/src/libreoffice/core/include/vcl/vclptr.hxx"
, 375, __extension__ __PRETTY_FUNCTION__))
; // make sure there are no lingering references
376 }
377
378private:
379 // Most likely we don't want this default copy-constructor.
380 ScopedVclPtr (const ScopedVclPtr<reference_type> &) = delete;
381 // And certainly we don't want a default assignment operator.
382 ScopedVclPtr<reference_type>& operator = (const ScopedVclPtr<reference_type> &) = delete;
383 // And disallow reset as that doesn't call disposeAndClear on the original reference
384 void reset() = delete;
385 void reset(reference_type *pBody) = delete;
386
387protected:
388 ScopedVclPtr (reference_type * pBody, __sal_NoAcquire)
389 : VclPtr<reference_type>(pBody, SAL_NO_ACQUIRE)
390 {}
391};
392
393/**
394 * A construction helper for ScopedVclPtr. Since VclPtr types are created
395 * with a reference-count of one - to help fit into the existing
396 * code-flow; this helps us to construct them easily.
397 *
398 * For more details on the design please see vcl/README.lifecycle
399 *
400 * @param reference_type must be a subclass of vcl::Window
401 */
402#if defined _MSC_VER
403#pragma warning(push)
404#pragma warning(disable: 4521) // " multiple copy constructors specified"
405#endif
406template <class reference_type>
407class SAL_WARN_UNUSED__attribute__((warn_unused)) ScopedVclPtrInstance final : public ScopedVclPtr<reference_type>
408{
409public:
410 template<typename... Arg> ScopedVclPtrInstance(Arg &&... arg)
411 : ScopedVclPtr<reference_type>( new reference_type(std::forward<Arg>(arg)...), SAL_NO_ACQUIRE )
412 {
413 }
414
415 /**
416 * Override and disallow this, to prevent people accidentally calling it and actually
417 * getting VclPtr::Create and getting a naked VclPtr<> instance
418 */
419 template<typename... Arg> static ScopedVclPtrInstance< reference_type > Create(Arg &&...) = delete;
420
421private:
422 // Prevent the above perfect forwarding ctor from hijacking (accidental)
423 // attempts at ScopedVclPtrInstance copy construction (where the hijacking
424 // would typically lead to somewhat obscure error messages); both non-const
425 // and const variants are needed here, as the ScopedVclPtr base class has a
426 // const--variant copy ctor, so the implicitly declared copy ctor for
427 // ScopedVclPtrInstance would also be the const variant, so non-const copy
428 // construction attempts would be hijacked by the perfect forwarding ctor;
429 // but if we only declared a non-const variant here, the const variant would
430 // no longer be implicitly declared (as there would already be an explicitly
431 // declared copy ctor), so const copy construction attempts would then be
432 // hijacked by the perfect forwarding ctor:
433 ScopedVclPtrInstance(ScopedVclPtrInstance &) = delete;
434 ScopedVclPtrInstance(ScopedVclPtrInstance const &) = delete;
435};
436#if defined _MSC_VER
437#pragma warning(pop)
438#endif
439
440#endif // INCLUDED_VCL_PTR_HXX
441
442/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

/home/maarten/src/libreoffice/core/include/rtl/ref.hxx

1/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2/*
3 * This file is part of the LibreOffice project.
4 *
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/.
8 *
9 * This file incorporates work covered by the following license notice:
10 *
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 .
18 */
19
20#ifndef INCLUDED_RTL_REF_HXX
21#define INCLUDED_RTL_REF_HXX
22
23#include "sal/config.h"
24
25#include <cassert>
26#include <cstddef>
27#include <functional>
28#ifdef LIBO_INTERNAL_ONLY1
29#include <type_traits>
30#endif
31
32#include "sal/types.h"
33
34namespace rtl
35{
36
37/** Template reference class for reference type.
38*/
39template <class reference_type>
40class Reference
41{
42 /** The <b>reference_type</b> body pointer.
43 */
44 reference_type * m_pBody;
45
46
47public:
48 /** Constructor...
49 */
50 Reference()
51 : m_pBody (NULL__null)
52 {}
53
54
55 /** Constructor...
56 */
57 Reference (reference_type * pBody, __sal_NoAcquire)
58 : m_pBody (pBody)
59 {
60 }
61
62 /** Constructor...
63 */
64 Reference (reference_type * pBody)
65 : m_pBody (pBody)
66 {
67 if (m_pBody)
68 m_pBody->acquire();
69 }
70
71 /** Copy constructor...
72 */
73 Reference (const Reference<reference_type> & handle)
74 : m_pBody (handle.m_pBody)
75 {
76 if (m_pBody)
8
Assuming field 'm_pBody' is non-null
9
Taking true branch
77 m_pBody->acquire();
78 }
79
80#ifdef LIBO_INTERNAL_ONLY1
81 /** Move constructor...
82 */
83 Reference (Reference<reference_type> && handle) noexcept
84 : m_pBody (handle.m_pBody)
85 {
86 handle.m_pBody = nullptr;
87 }
88#endif
89
90#if defined LIBO_INTERNAL_ONLY1
91 /** Up-casting conversion constructor: Copies interface reference.
92
93 Does not work for up-casts to ambiguous bases.
94
95 @param rRef another reference
96 */
97 template< class derived_type >
98 inline Reference(
99 const Reference< derived_type > & rRef,
100 std::enable_if_t<std::is_base_of_v<reference_type, derived_type>, int> = 0 )
101 : m_pBody (rRef.get())
102 {
103 if (m_pBody)
104 m_pBody->acquire();
105 }
106#endif
107
108 /** Destructor...
109 */
110 ~Reference() COVERITY_NOEXCEPT_FALSE
111 {
112 if (m_pBody)
113 m_pBody->release();
114 }
115
116 /** Set...
117 Similar to assignment.
118 */
119 Reference<reference_type> &
120 SAL_CALL set (reference_type * pBody)
121 {
122 if (pBody)
123 pBody->acquire();
124 reference_type * const pOld = m_pBody;
125 m_pBody = pBody;
126 if (pOld)
127 pOld->release();
128 return *this;
129 }
130
131 /** Assignment.
132 Unbinds this instance from its body (if bound) and
133 bind it to the body represented by the handle.
134 */
135 Reference<reference_type> &
136 SAL_CALL operator= (const Reference<reference_type> & handle)
137 {
138 return set( handle.m_pBody );
139 }
140
141#ifdef LIBO_INTERNAL_ONLY1
142 /** Assignment.
143 * Unbinds this instance from its body (if bound),
144 * bind it to the body represented by the handle, and
145 * set the body represented by the handle to nullptr.
146 */
147 Reference<reference_type> &
148 operator= (Reference<reference_type> && handle)
149 {
150 // self-movement guts ourself
151 if (m_pBody)
152 m_pBody->release();
153 m_pBody = handle.m_pBody;
154 handle.m_pBody = nullptr;
155 return *this;
156 }
157#endif
158
159 /** Assignment...
160 */
161 Reference<reference_type> &
162 SAL_CALL operator= (reference_type * pBody)
163 {
164 return set( pBody );
165 }
166
167 /** Unbind the body from this handle.
168 Note that for a handle representing a large body,
169 "handle.clear().set(new body());" _might_
170 perform a little bit better than "handle.set(new body());",
171 since in the second case two large objects exist in memory
172 (the old body and the new body).
173 */
174 Reference<reference_type> & SAL_CALL clear()
175 {
176 if (m_pBody
11.1
Field 'm_pBody' is non-null
11.1
Field 'm_pBody' is non-null
11.1
Field 'm_pBody' is non-null
11.1
Field 'm_pBody' is non-null
)
12
Taking true branch
177 {
178 reference_type * const pOld = m_pBody;
179 m_pBody = NULL__null;
180 pOld->release();
13
Calling 'VclReferenceBase::release'
17
Returning; memory was released
181 }
182 return *this;
183 }
184
185
186 /** Get the body. Can be used instead of operator->().
187 I.e. handle->someBodyOp() and handle.get()->someBodyOp()
188 are the same.
189 */
190 reference_type * SAL_CALL get() const
191 {
192 return m_pBody;
20
Use of memory after it is freed
193 }
194
195
196 /** Probably most common used: handle->someBodyOp().
197 */
198 reference_type * SAL_CALL operator->() const
199 {
200 assert(m_pBody != NULL)(static_cast <bool> (m_pBody != __null) ? void (0) : __assert_fail
("m_pBody != NULL", "/home/maarten/src/libreoffice/core/include/rtl/ref.hxx"
, 200, __extension__ __PRETTY_FUNCTION__))
;
201 return m_pBody;
202 }
203
204
205 /** Allows (*handle).someBodyOp().
206 */
207 reference_type & SAL_CALL operator*() const
208 {
209 assert(m_pBody != NULL)(static_cast <bool> (m_pBody != __null) ? void (0) : __assert_fail
("m_pBody != NULL", "/home/maarten/src/libreoffice/core/include/rtl/ref.hxx"
, 209, __extension__ __PRETTY_FUNCTION__))
;
210 return *m_pBody;
211 }
212
213
214 /** Returns True if the handle does point to a valid body.
215 */
216 bool SAL_CALL is() const
217 {
218 return (m_pBody != NULL__null);
219 }
220
221#if defined LIBO_INTERNAL_ONLY1
222 /** Returns True if the handle does point to a valid body.
223 */
224 explicit operator bool() const
225 {
226 return is();
227 }
228#endif
229
230 /** Returns True if this points to pBody.
231 */
232 bool SAL_CALL operator== (const reference_type * pBody) const
233 {
234 return (m_pBody == pBody);
235 }
236
237
238 /** Returns True if handle points to the same body.
239 */
240 bool
241 SAL_CALL operator== (const Reference<reference_type> & handle) const
242 {
243 return (m_pBody == handle.m_pBody);
244 }
245
246
247 /** Needed to place References into STL collection.
248 */
249 bool
250 SAL_CALL operator!= (const Reference<reference_type> & handle) const
251 {
252 return (m_pBody != handle.m_pBody);
253 }
254
255
256 /** Needed to place References into STL collection.
257 */
258 bool
259 SAL_CALL operator< (const Reference<reference_type> & handle) const
260 {
261 return (m_pBody < handle.m_pBody);
262 }
263
264
265 /** Needed to place References into STL collection.
266 */
267 bool
268 SAL_CALL operator> (const Reference<reference_type> & handle) const
269 {
270 return (m_pBody > handle.m_pBody);
271 }
272};
273
274} // namespace rtl
275
276#if defined LIBO_INTERNAL_ONLY1
277namespace std
278{
279
280/// @cond INTERNAL
281/**
282 Make rtl::Reference hashable by default for use in STL containers.
283
284 @since LibreOffice 6.3
285*/
286template<typename T>
287struct hash<::rtl::Reference<T>>
288{
289 std::size_t operator()(::rtl::Reference<T> const & s) const
290 { return std::size_t(s.get()); }
291};
292/// @endcond
293
294}
295
296#endif
297
298#endif /* ! INCLUDED_RTL_REF_HXX */
299
300/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

/home/maarten/src/libreoffice/core/include/vcl/vclreferencebase.hxx

1/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2/*
3 * This file is part of the LibreOffice project.
4 *
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/.
8 *
9 * This file incorporates work covered by the following license notice:
10 *
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 .
18 */
19#ifndef INCLUDED_VCL_Reference_HXX
20#define INCLUDED_VCL_Reference_HXX
21
22#include <vcl/dllapi.h>
23#include <osl/interlck.h>
24
25class VCL_DLLPUBLIC__attribute__ ((visibility("default"))) VclReferenceBase
26{
27 mutable oslInterlockedCount mnRefCnt;
28
29 template<typename T> friend class VclPtr;
30
31public:
32 void acquire() const
33 {
34 osl_atomic_increment(&mnRefCnt)__sync_add_and_fetch((&mnRefCnt), 1);
35 }
36
37 void release() const
38 {
39 if (osl_atomic_decrement(&mnRefCnt)__sync_sub_and_fetch((&mnRefCnt), 1) == 0)
14
Assuming the condition is true
15
Taking true branch
40 delete this;
16
Memory is released
41 }
42#ifdef DBG_UTIL
43#ifndef _WIN32
44 sal_Int32 getRefCount() const { return mnRefCnt; }
45#endif
46#endif
47
48
49private:
50 VclReferenceBase(const VclReferenceBase&) = delete;
51 VclReferenceBase& operator=(const VclReferenceBase&) = delete;
52
53 bool mbDisposed : 1;
54
55protected:
56 VclReferenceBase();
57protected:
58 virtual ~VclReferenceBase();
59
60protected:
61 virtual void dispose();
62
63public:
64 void disposeOnce();
65 bool isDisposed() const { return mbDisposed; }
66
67};
68#endif