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 checklistmenu.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 -isystem /usr/include/libxml2 -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 SC_DLLIMPLEMENTATION -D SC_INFO_OSVERSION="LINUX" -D SYSTEM_LIBXML -D EXCEPTIONS_ON -D LIBO_INTERNAL_ONLY -I /home/maarten/src/libreoffice/core/workdir/UnpackedTarball/liborcus/include -I /home/maarten/src/libreoffice/core/workdir/UnpackedTarball/mdds/include -I /home/maarten/src/libreoffice/core/workdir/UnpackedTarball/icu/source -I /home/maarten/src/libreoffice/core/workdir/UnpackedTarball/icu/source/i18n -I /home/maarten/src/libreoffice/core/workdir/UnpackedTarball/icu/source/common -I /home/maarten/src/libreoffice/core/external/clew/source/include -I /home/maarten/src/libreoffice/core/external/boost/include -I /home/maarten/src/libreoffice/core/workdir/UnpackedTarball/boost -I /home/maarten/src/libreoffice/core/sc/source/core/inc -I /home/maarten/src/libreoffice/core/sc/source/filter/inc -I /home/maarten/src/libreoffice/core/sc/source/ui/inc -I /home/maarten/src/libreoffice/core/sc/inc -I /home/maarten/src/libreoffice/core/workdir/SdiTarget/sc/sdi -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 -I /home/maarten/src/libreoffice/core/workdir/UnoApiHeadersTarget/oovbaapi/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/sc/source/ui/cctrl/checklistmenu.cxx

/home/maarten/src/libreoffice/core/sc/source/ui/cctrl/checklistmenu.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 <checklistmenu.hxx>
21#include <globstr.hrc>
22#include <scresid.hxx>
23#include <strings.hrc>
24#include <bitmaps.hlst>
25
26#include <vcl/decoview.hxx>
27#include <vcl/event.hxx>
28#include <vcl/dockwin.hxx>
29#include <vcl/settings.hxx>
30#include <vcl/svapp.hxx>
31#include <vcl/virdev.hxx>
32#include <rtl/math.hxx>
33#include <tools/wintypes.hxx>
34#include <unotools/charclass.hxx>
35
36#include <document.hxx>
37
38using namespace com::sun::star;
39using ::com::sun::star::uno::Reference;
40
41ScCheckListMenuControl::MenuItemData::MenuItemData()
42 : mbEnabled(true)
43{
44}
45
46ScCheckListMenuControl::SubMenuItemData::SubMenuItemData(ScCheckListMenuControl* pParent)
47 : mpSubMenu(nullptr)
48 , mnMenuPos(MENU_NOT_SELECTED)
49 , mpParent(pParent)
50{
51 maTimer.SetInvokeHandler(LINK(this, ScCheckListMenuControl::SubMenuItemData, TimeoutHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
::SubMenuItemData *>(this), &ScCheckListMenuControl::SubMenuItemData
::LinkStubTimeoutHdl)
);
52 maTimer.SetTimeout(Application::GetSettings().GetMouseSettings().GetMenuDelay());
53}
54
55void ScCheckListMenuControl::SubMenuItemData::reset()
56{
57 mpSubMenu = nullptr;
58 mnMenuPos = MENU_NOT_SELECTED;
59 maTimer.Stop();
60}
61
62IMPL_LINK_NOARG(ScCheckListMenuControl::SubMenuItemData, TimeoutHdl, Timer *, void)void ScCheckListMenuControl::SubMenuItemData::LinkStubTimeoutHdl
(void * instance, Timer * data) { return static_cast<ScCheckListMenuControl
::SubMenuItemData *>(instance)->TimeoutHdl(data); } void
ScCheckListMenuControl::SubMenuItemData::TimeoutHdl(__attribute__
((unused)) Timer *)
63{
64 mpParent->handleMenuTimeout(this);
65}
66
67IMPL_LINK_NOARG(ScCheckListMenuControl, RowActivatedHdl, weld::TreeView&, bool)bool ScCheckListMenuControl::LinkStubRowActivatedHdl(void * instance
, weld::TreeView& data) { return static_cast<ScCheckListMenuControl
*>(instance)->RowActivatedHdl(data); } bool ScCheckListMenuControl
::RowActivatedHdl(__attribute__ ((unused)) weld::TreeView&
)
68{
69 executeMenuItem(mxMenu->get_selected_index());
70 return true;
71}
72
73IMPL_LINK(ScCheckListMenuControl, MenuKeyInputHdl, const KeyEvent&, rKEvt, bool)bool ScCheckListMenuControl::LinkStubMenuKeyInputHdl(void * instance
, const KeyEvent& data) { return static_cast<ScCheckListMenuControl
*>(instance)->MenuKeyInputHdl(data); } bool ScCheckListMenuControl
::MenuKeyInputHdl(const KeyEvent& rKEvt)
74{
75 const vcl::KeyCode& rKeyCode = rKEvt.GetKeyCode();
76
77 switch (rKeyCode.GetCode())
78 {
79 case KEY_LEFT:
80 {
81 ScCheckListMenuWindow* pParentMenu = mxFrame->GetParentMenu();
82 if (pParentMenu)
83 pParentMenu->get_widget().endSubMenu(*this);
84 break;
85 }
86 case KEY_RIGHT:
87 {
88 if (mnSelectedMenu >= maMenuItems.size() || mnSelectedMenu == MENU_NOT_SELECTED)
89 break;
90
91 const MenuItemData& rMenu = maMenuItems[mnSelectedMenu];
92 if (!rMenu.mbEnabled || !rMenu.mxSubMenuWin)
93 break;
94
95 maOpenTimer.mnMenuPos = mnSelectedMenu;
96 maOpenTimer.mpSubMenu = rMenu.mxSubMenuWin.get();
97 launchSubMenu(true);
98 }
99 }
100
101 return false;
102}
103
104IMPL_LINK_NOARG(ScCheckListMenuControl, SelectHdl, weld::TreeView&, void)void ScCheckListMenuControl::LinkStubSelectHdl(void * instance
, weld::TreeView& data) { return static_cast<ScCheckListMenuControl
*>(instance)->SelectHdl(data); } void ScCheckListMenuControl
::SelectHdl(__attribute__ ((unused)) weld::TreeView&)
105{
106 sal_uInt32 nSelectedMenu = MENU_NOT_SELECTED;
107 if (!mxMenu->get_selected(mxScratchIter.get()))
108 {
109 // reselect current item if its submenu is up and the launching item
110 // became unselected
111 if (mnSelectedMenu < maMenuItems.size() &&
112 maMenuItems[mnSelectedMenu].mxSubMenuWin &&
113 maMenuItems[mnSelectedMenu].mxSubMenuWin->IsVisible())
114 {
115 mxMenu->select(mnSelectedMenu);
116 return;
117 }
118 }
119 else
120 nSelectedMenu = mxMenu->get_iter_index_in_parent(*mxScratchIter);
121
122 setSelectedMenuItem(nSelectedMenu, true);
123}
124
125void ScCheckListMenuControl::addMenuItem(const OUString& rText, Action* pAction)
126{
127 MenuItemData aItem;
128 aItem.mbEnabled = true;
129 aItem.mxAction.reset(pAction);
130 maMenuItems.emplace_back(std::move(aItem));
131
132 mxMenu->append_text(rText);
133 if (mbCanHaveSubMenu)
134 mxMenu->set_image(mxMenu->n_children() - 1, css::uno::Reference<css::graphic::XGraphic>(), 1);
135}
136
137void ScCheckListMenuControl::addSeparator()
138{
139 MenuItemData aItem;
140 maMenuItems.emplace_back(std::move(aItem));
141
142 mxMenu->append_separator("separator" + OUString::number(maMenuItems.size()));
143}
144
145IMPL_LINK(ScCheckListMenuControl, TreeSizeAllocHdl, const Size&, rSize, void)void ScCheckListMenuControl::LinkStubTreeSizeAllocHdl(void * instance
, const Size& data) { return static_cast<ScCheckListMenuControl
*>(instance)->TreeSizeAllocHdl(data); } void ScCheckListMenuControl
::TreeSizeAllocHdl(const Size& rSize)
146{
147 assert(mbCanHaveSubMenu)(static_cast <bool> (mbCanHaveSubMenu) ? void (0) : __assert_fail
("mbCanHaveSubMenu", "/home/maarten/src/libreoffice/core/sc/source/ui/cctrl/checklistmenu.cxx"
, 147, __extension__ __PRETTY_FUNCTION__))
;
148 std::vector<int> aWidths;
149 aWidths.push_back(rSize.Width() - (mxMenu->get_text_height() * 3) / 4 - 6);
150 mxMenu->set_column_fixed_widths(aWidths);
151}
152
153void ScCheckListMenuControl::CreateDropDown()
154{
155 int nWidth = (mxMenu->get_text_height() * 3) / 4;
156 mxDropDown->SetOutputSizePixel(Size(nWidth, nWidth));
157 DecorationView aDecoView(mxDropDown.get());
158 aDecoView.DrawSymbol(tools::Rectangle(Point(0, 0), Size(nWidth, nWidth)),
159 SymbolType::SPIN_RIGHT, mxDropDown->GetTextColor(),
160 DrawSymbolFlags::NONE);
161}
162
163ScCheckListMenuWindow* ScCheckListMenuControl::addSubMenuItem(const OUString& rText, bool bEnabled)
164{
165 assert(mbCanHaveSubMenu)(static_cast <bool> (mbCanHaveSubMenu) ? void (0) : __assert_fail
("mbCanHaveSubMenu", "/home/maarten/src/libreoffice/core/sc/source/ui/cctrl/checklistmenu.cxx"
, 165, __extension__ __PRETTY_FUNCTION__))
;
166
167 MenuItemData aItem;
168 aItem.mbEnabled = bEnabled;
169 vcl::Window *pContainer = mxFrame->GetWindow(GetWindowType::FirstChild);
170 aItem.mxSubMenuWin.reset(VclPtr<ScCheckListMenuWindow>::Create(pContainer, mpDoc, false,
171 false, -1, mxFrame.get()));
172 maMenuItems.emplace_back(std::move(aItem));
173
174 mxMenu->append_text(rText);
175 if (mbCanHaveSubMenu)
176 mxMenu->set_image(mxMenu->n_children() - 1, *mxDropDown, 1);
177
178 return maMenuItems.back().mxSubMenuWin.get();
179}
180
181void ScCheckListMenuControl::executeMenuItem(size_t nPos)
182{
183 if (nPos >= maMenuItems.size())
184 return;
185
186 if (!maMenuItems[nPos].mxAction)
187 // no action is defined.
188 return;
189
190 terminateAllPopupMenus();
191
192 maMenuItems[nPos].mxAction->execute();
193}
194
195void ScCheckListMenuControl::setSelectedMenuItem(size_t nPos, bool bSubMenuTimer)
196{
197 if (mnSelectedMenu == nPos)
198 // nothing to do.
199 return;
200
201 selectMenuItem(nPos, bSubMenuTimer);
202}
203
204void ScCheckListMenuControl::handleMenuTimeout(const SubMenuItemData* pTimer)
205{
206 if (pTimer == &maOpenTimer)
207 {
208 // Close any open submenu immediately.
209 if (maCloseTimer.mpSubMenu)
210 {
211 vcl::Window::GetDockingManager()->EndPopupMode(maCloseTimer.mpSubMenu);
212 maCloseTimer.mpSubMenu = nullptr;
213 maCloseTimer.maTimer.Stop();
214 }
215
216 launchSubMenu(false);
217 }
218 else if (pTimer == &maCloseTimer)
219 {
220 // end submenu.
221 if (maCloseTimer.mpSubMenu)
222 {
223 maOpenTimer.mpSubMenu = nullptr;
224
225 vcl::Window::GetDockingManager()->EndPopupMode(maCloseTimer.mpSubMenu);
226 maCloseTimer.mpSubMenu = nullptr;
227
228 maOpenTimer.mnMenuPos = MENU_NOT_SELECTED;
229 }
230 }
231}
232
233void ScCheckListMenuControl::queueLaunchSubMenu(size_t nPos, ScCheckListMenuWindow* pMenu)
234{
235 if (!pMenu)
236 return;
237
238 // Set the submenu on launch queue.
239 if (maOpenTimer.mpSubMenu)
240 {
241 if (maOpenTimer.mpSubMenu == pMenu)
242 {
243 if (pMenu == maCloseTimer.mpSubMenu)
244 maCloseTimer.reset();
245 return;
246 }
247
248 // new submenu is being requested.
249 queueCloseSubMenu();
250 }
251
252 maOpenTimer.mpSubMenu = pMenu;
253 maOpenTimer.mnMenuPos = nPos;
254 maOpenTimer.maTimer.Start();
255}
256
257void ScCheckListMenuControl::queueCloseSubMenu()
258{
259 if (!maOpenTimer.mpSubMenu)
260 // There is no submenu to close.
261 return;
262
263 // Stop any submenu on queue for opening.
264 maOpenTimer.maTimer.Stop();
265
266 maCloseTimer.mpSubMenu = maOpenTimer.mpSubMenu;
267 maCloseTimer.mnMenuPos = maOpenTimer.mnMenuPos;
268 maCloseTimer.maTimer.Start();
269}
270
271void ScCheckListMenuControl::launchSubMenu(bool bSetMenuPos)
272{
273 ScCheckListMenuWindow* pSubMenu = maOpenTimer.mpSubMenu;
274 if (!pSubMenu)
275 return;
276
277 if (!mxMenu->get_selected(mxScratchIter.get()))
278 return;
279
280 tools::Rectangle aRect = mxMenu->get_row_area(*mxScratchIter);
281 ScCheckListMenuControl& rSubMenuControl = pSubMenu->get_widget();
282 rSubMenuControl.StartPopupMode(aRect, FloatWinPopupFlags::Right);
283 if (bSetMenuPos)
284 rSubMenuControl.setSelectedMenuItem(0, false); // select menu item after the popup becomes fully visible.
285
286 mxMenu->select(*mxScratchIter);
287 rSubMenuControl.GrabFocus();
288}
289
290IMPL_LINK_NOARG(ScCheckListMenuControl, PostPopdownHdl, void*, void)void ScCheckListMenuControl::LinkStubPostPopdownHdl(void * instance
, void* data) { return static_cast<ScCheckListMenuControl *
>(instance)->PostPopdownHdl(data); } void ScCheckListMenuControl
::PostPopdownHdl(__attribute__ ((unused)) void*)
291{
292 mnAsyncPostPopdownId = nullptr;
293 mxMenu->grab_focus();
294}
295
296void ScCheckListMenuControl::endSubMenu(ScCheckListMenuControl& rSubMenu)
297{
298 rSubMenu.EndPopupMode();
299 maOpenTimer.reset();
300
301 // EndPopup sends a user event, and we want this focus to be set after that has done its conflicting focus-setting work
302 if (!mnAsyncPostPopdownId)
303 mnAsyncPostPopdownId = Application::PostUserEvent(LINK(this, ScCheckListMenuControl, PostPopdownHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubPostPopdownHdl
)
);
304
305 size_t nMenuPos = getSubMenuPos(&rSubMenu);
306 if (nMenuPos != MENU_NOT_SELECTED)
307 {
308 mnSelectedMenu = nMenuPos;
309 mxMenu->select(mnSelectedMenu);
310 }
311}
312
313void ScCheckListMenuControl::resizeToFitMenuItems()
314{
315 mxMenu->set_size_request(-1, mxMenu->get_preferred_size().Height() + 2);
316}
317
318void ScCheckListMenuControl::selectMenuItem(size_t nPos, bool bSubMenuTimer)
319{
320 mxMenu->select(nPos == MENU_NOT_SELECTED ? -1 : nPos);
321 mnSelectedMenu = nPos;
322
323 if (nPos >= maMenuItems.size() || nPos == MENU_NOT_SELECTED)
324 {
325 queueCloseSubMenu();
326 return;
327 }
328
329 if (!maMenuItems[nPos].mbEnabled)
330 {
331 queueCloseSubMenu();
332 return;
333 }
334
335 ScCheckListMenuWindow* pParentMenu = mxFrame->GetParentMenu();
336 if (pParentMenu)
337 pParentMenu->get_widget().setSubMenuFocused(this);
338
339 if (bSubMenuTimer)
340 {
341 if (maMenuItems[nPos].mxSubMenuWin)
342 {
343 ScCheckListMenuWindow* pSubMenu = maMenuItems[nPos].mxSubMenuWin.get();
344 queueLaunchSubMenu(nPos, pSubMenu);
345 }
346 else
347 queueCloseSubMenu();
348 }
349}
350
351void ScCheckListMenuControl::clearSelectedMenuItem()
352{
353 selectMenuItem(MENU_NOT_SELECTED, false);
354}
355
356size_t ScCheckListMenuControl::getSubMenuPos(const ScCheckListMenuControl* pSubMenu)
357{
358 size_t n = maMenuItems.size();
359 for (size_t i = 0; i < n; ++i)
360 {
361 if (!maMenuItems[i].mxSubMenuWin)
362 continue;
363 if (&maMenuItems[i].mxSubMenuWin->get_widget() == pSubMenu)
364 return i;
365 }
366 return MENU_NOT_SELECTED;
367}
368
369void ScCheckListMenuControl::setSubMenuFocused(const ScCheckListMenuControl* pSubMenu)
370{
371 maCloseTimer.reset();
372 size_t nMenuPos = getSubMenuPos(pSubMenu);
373 if (mnSelectedMenu != nMenuPos)
374 {
375 mnSelectedMenu = nMenuPos;
376 mxMenu->select(mnSelectedMenu);
377 }
378}
379
380void ScCheckListMenuControl::EndPopupMode()
381{
382 vcl::Window::GetDockingManager()->EndPopupMode(mxFrame);
383 mxFrame->EnableDocking(false);
384}
385
386void ScCheckListMenuControl::StartPopupMode(const tools::Rectangle& rRect, FloatWinPopupFlags eFlags)
387{
388 mxFrame->EnableDocking(true);
389 DockingManager* pDockingManager = vcl::Window::GetDockingManager();
390 pDockingManager->SetPopupModeEndHdl(mxFrame, LINK(this, ScCheckListMenuControl, PopupModeEndHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubPopupModeEndHdl
)
);
391 pDockingManager->StartPopupMode(mxFrame, rRect, (eFlags | FloatWinPopupFlags::GrabFocus));
392}
393
394void ScCheckListMenuControl::terminateAllPopupMenus()
395{
396 EndPopupMode();
397 ScCheckListMenuWindow* pParentMenu = mxFrame->GetParentMenu();
398 if (pParentMenu)
399 pParentMenu->get_widget().terminateAllPopupMenus();
400}
401
402ScCheckListMenuControl::Config::Config() :
403 mbAllowEmptySet(true), mbRTL(false)
404{
405}
406
407ScCheckListMember::ScCheckListMember()
408 : mbVisible(true)
409 , mbDate(false)
410 , mbLeaf(false)
411 , meDatePartType(YEAR)
412{
413}
414
415ScCheckListMenuControl::ScCheckListMenuControl(ScCheckListMenuWindow* pParent, vcl::Window* pContainer,
416 ScDocument* pDoc, bool bCanHaveSubMenu,
417 bool bHasDates, int nWidth)
418 : mxFrame(pParent)
419 , mxBuilder(Application::CreateInterimBuilder(pContainer, "modules/scalc/ui/filterdropdown.ui", false))
420 , mxContainer(mxBuilder->weld_container("FilterDropDown"))
421 , mxMenu(mxBuilder->weld_tree_view("menu"))
422 , mxScratchIter(mxMenu->make_iterator())
423 , mxEdSearch(mxBuilder->weld_entry("search_edit"))
424 , mxBox(mxBuilder->weld_widget("box"))
425 , mxListChecks(mxBuilder->weld_tree_view("check_list_box"))
426 , mxTreeChecks(mxBuilder->weld_tree_view("check_tree_box"))
427 , mxChkToggleAll(mxBuilder->weld_check_button("toggle_all"))
428 , mxBtnSelectSingle(mxBuilder->weld_button("select_current"))
429 , mxBtnUnselectSingle(mxBuilder->weld_button("unselect_current"))
430 , mxButtonBox(mxBuilder->weld_box("buttonbox"))
431 , mxBtnOk(mxBuilder->weld_button("ok"))
432 , mxBtnCancel(mxBuilder->weld_button("cancel"))
433 , mxDropDown(mxMenu->create_virtual_device())
434 , mnCheckWidthReq(-1)
435 , mnWndWidth(0)
436 , mePrevToggleAllState(TRISTATE_INDET)
437 , mnSelectedMenu(MENU_NOT_SELECTED)
438 , mpDoc(pDoc)
439 , mnAsyncPostPopdownId(nullptr)
440 , mbHasDates(bHasDates)
441 , mbCanHaveSubMenu(bCanHaveSubMenu)
442 , maOpenTimer(this)
443 , maCloseTimer(this)
444{
445 /*
446 tdf#136559 If we have no dates we don't need a tree
447 structure, just a list. GtkListStore can be then
448 used which is much faster than a GtkTreeStore, so
449 with no dates switch to the treeview which uses the
450 faster GtkListStore
451 */
452 if (mbHasDates)
453 mpChecks = mxTreeChecks.get();
454 else
455 {
456 mxTreeChecks->hide();
457 mxListChecks->show();
458 mpChecks = mxListChecks.get();
459 }
460
461 bool bIsSubMenu = pParent->GetParentMenu();
462
463 int nChecksHeight = mxTreeChecks->get_height_rows(9);
464 if (!bIsSubMenu && nWidth != -1)
465 {
466 mnCheckWidthReq = nWidth - mxFrame->get_border_width() * 2 - 4;
467 mxTreeChecks->set_size_request(mnCheckWidthReq, nChecksHeight);
468 mxListChecks->set_size_request(mnCheckWidthReq, nChecksHeight);
469 }
470
471 // sort ok/cancel into native order, if this was a dialog they would be auto-sorted, but this
472 // popup isn't a true dialog
473 mxButtonBox->sort_native_button_order();
474
475 if (!bIsSubMenu)
476 {
477 mxTreeChecks->enable_toggle_buttons(weld::ColumnToggleType::Check);
478 mxListChecks->enable_toggle_buttons(weld::ColumnToggleType::Check);
479
480 mxBox->show();
481 mxEdSearch->show();
482 mxButtonBox->show();
483 }
484
485 mxContainer->connect_focus_in(LINK(this, ScCheckListMenuControl, FocusHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubFocusHdl)
);
486 mxMenu->connect_row_activated(LINK(this, ScCheckListMenuControl, RowActivatedHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubRowActivatedHdl
)
);
487 mxMenu->connect_changed(LINK(this, ScCheckListMenuControl, SelectHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubSelectHdl)
);
488 mxMenu->connect_key_press(LINK(this, ScCheckListMenuControl, MenuKeyInputHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubMenuKeyInputHdl
)
);
489
490 if (!bIsSubMenu)
491 {
492 mxBtnOk->connect_clicked(LINK(this, ScCheckListMenuControl, ButtonHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubButtonHdl)
);
493 mxBtnCancel->connect_clicked(LINK(this, ScCheckListMenuControl, ButtonHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubButtonHdl)
);
494 mxEdSearch->connect_changed(LINK(this, ScCheckListMenuControl, EdModifyHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubEdModifyHdl
)
);
495 mxEdSearch->connect_activate(LINK(this, ScCheckListMenuControl, EdActivateHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubEdActivateHdl
)
);
496 mxTreeChecks->connect_toggled(LINK(this, ScCheckListMenuControl, CheckHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubCheckHdl)
);
497 mxTreeChecks->connect_key_press(LINK(this, ScCheckListMenuControl, KeyInputHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubKeyInputHdl
)
);
498 mxListChecks->connect_toggled(LINK(this, ScCheckListMenuControl, CheckHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubCheckHdl)
);
499 mxListChecks->connect_key_press(LINK(this, ScCheckListMenuControl, KeyInputHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubKeyInputHdl
)
);
500 mxChkToggleAll->connect_toggled(LINK(this, ScCheckListMenuControl, TriStateHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubTriStateHdl
)
);
501 mxBtnSelectSingle->connect_clicked(LINK(this, ScCheckListMenuControl, ButtonHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubButtonHdl)
);
502 mxBtnUnselectSingle->connect_clicked(LINK(this, ScCheckListMenuControl, ButtonHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubButtonHdl)
);
503 }
504
505 if (mbCanHaveSubMenu)
506 {
507 CreateDropDown();
508 mxMenu->connect_size_allocate(LINK(this, ScCheckListMenuControl, TreeSizeAllocHdl)::tools::detail::makeLink( ::tools::detail::castTo<ScCheckListMenuControl
*>(this), &ScCheckListMenuControl::LinkStubTreeSizeAllocHdl
)
);
509 }
510
511 if (!bIsSubMenu)
512 {
513 // determine what width the checklist will end up with
514 mnCheckWidthReq = mxContainer->get_preferred_size().Width();
515 // make that size fixed now, we can now use mnCheckWidthReq to speed up
516 // bulk_insert_for_each
517 mxTreeChecks->set_size_request(mnCheckWidthReq, nChecksHeight);
518 mxListChecks->set_size_request(mnCheckWidthReq, nChecksHeight);
519 }
520}
521
522IMPL_LINK_NOARG(ScCheckListMenuControl, FocusHdl, weld::Widget&, void)void ScCheckListMenuControl::LinkStubFocusHdl(void * instance
, weld::Widget& data) { return static_cast<ScCheckListMenuControl
*>(instance)->FocusHdl(data); } void ScCheckListMenuControl
::FocusHdl(__attribute__ ((unused)) weld::Widget&)
523{
524 GrabFocus();
525}
526
527void ScCheckListMenuControl::GrabFocus()
528{
529 if (mxEdSearch->get_visible())
530 mxEdSearch->grab_focus();
531 else
532 {
533 mxMenu->set_cursor(0);
534 mxMenu->grab_focus();
535 }
536}
537
538ScCheckListMenuControl::~ScCheckListMenuControl()
539{
540 EndPopupMode();
541 for (auto& rMenuItem : maMenuItems)
542 rMenuItem.mxSubMenuWin.disposeAndClear();
543 if (mnAsyncPostPopdownId)
544 {
545 Application::RemoveUserEvent(mnAsyncPostPopdownId);
546 mnAsyncPostPopdownId = nullptr;
547 }
548}
549
550ScCheckListMenuWindow::ScCheckListMenuWindow(vcl::Window* pParent, ScDocument* pDoc, bool bCanHaveSubMenu,
551 bool bTreeMode, int nWidth, ScCheckListMenuWindow* pParentMenu)
552 : DockingWindow(pParent, "InterimDockParent", "svx/ui/interimdockparent.ui")
553 , mxParentMenu(pParentMenu)
554 , mxBox(get("box"))
555{
556 setDeferredProperties();
557 mxControl.reset(new ScCheckListMenuControl(this, mxBox.get(), pDoc, bCanHaveSubMenu, bTreeMode, nWidth));
558 SetBackground(Application::GetSettings().GetStyleSettings().GetMenuColor());
559 set_id("check_list_menu");
560}
561
562bool ScCheckListMenuWindow::EventNotify(NotifyEvent& rNEvt)
563{
564 if (rNEvt.GetType() == MouseNotifyEvent::MOUSEMOVE)
565 {
566 ScCheckListMenuControl& rMenuControl = get_widget();
567 rMenuControl.queueCloseSubMenu();
568 rMenuControl.clearSelectedMenuItem();
569 }
570 return DockingWindow::EventNotify(rNEvt);
571}
572
573ScCheckListMenuWindow::~ScCheckListMenuWindow()
574{
575 disposeOnce();
576}
577
578void ScCheckListMenuWindow::dispose()
579{
580 mxControl.reset();
581 mxBox.disposeAndClear();
1
Calling 'VclPtr::disposeAndClear'
582 mxParentMenu.clear();
583 DockingWindow::dispose();
584}
585
586void ScCheckListMenuWindow::GetFocus()
587{
588 DockingWindow::GetFocus();
589 if (!mxControl)
590 return;
591 mxControl->GrabFocus();
592}
593
594void ScCheckListMenuControl::prepWindow()
595{
596 mxMenu->set_size_request(-1, mxMenu->get_preferred_size().Height() + 2);
597 mnSelectedMenu = 0;
598 mxMenu->set_cursor(mnSelectedMenu);
599 mxMenu->unselect_all();
600
601 mnWndWidth = mxContainer->get_preferred_size().Width() + mxFrame->get_border_width() * 2 + 4;
602}
603
604void ScCheckListMenuControl::setAllMemberState(bool bSet)
605{
606 mpChecks->all_foreach([this, bSet](weld::TreeIter& rEntry){
607 mpChecks->set_toggle(rEntry, bSet ? TRISTATE_TRUE : TRISTATE_FALSE);
608 return false;
609 });
610
611 if (!maConfig.mbAllowEmptySet)
612 {
613 // We need to have at least one member selected.
614 mxBtnOk->set_sensitive(GetCheckedEntryCount() != 0);
615 }
616}
617
618void ScCheckListMenuControl::selectCurrentMemberOnly(bool bSet)
619{
620 setAllMemberState(!bSet);
621 std::unique_ptr<weld::TreeIter> xEntry = mpChecks->make_iterator();
622 if (!mpChecks->get_cursor(xEntry.get()))
623 return;
624 mpChecks->set_toggle(*xEntry, bSet ? TRISTATE_TRUE : TRISTATE_FALSE);
625}
626
627IMPL_LINK(ScCheckListMenuControl, ButtonHdl, weld::Button&, rBtn, void)void ScCheckListMenuControl::LinkStubButtonHdl(void * instance
, weld::Button& data) { return static_cast<ScCheckListMenuControl
*>(instance)->ButtonHdl(data); } void ScCheckListMenuControl
::ButtonHdl(weld::Button& rBtn)
628{
629 if (&rBtn == mxBtnOk.get())
630 close(true);
631 else if (&rBtn == mxBtnCancel.get())
632 close(false);
633 else if (&rBtn == mxBtnSelectSingle.get() || &rBtn == mxBtnUnselectSingle.get())
634 {
635 selectCurrentMemberOnly(&rBtn == mxBtnSelectSingle.get());
636 std::unique_ptr<weld::TreeIter> xEntry = mpChecks->make_iterator();
637 if (!mpChecks->get_cursor(xEntry.get()))
638 xEntry.reset();
639 Check(xEntry.get());
640 }
641}
642
643IMPL_LINK_NOARG(ScCheckListMenuControl, TriStateHdl, weld::ToggleButton&, void)void ScCheckListMenuControl::LinkStubTriStateHdl(void * instance
, weld::ToggleButton& data) { return static_cast<ScCheckListMenuControl
*>(instance)->TriStateHdl(data); } void ScCheckListMenuControl
::TriStateHdl(__attribute__ ((unused)) weld::ToggleButton&
)
644{
645 switch (mePrevToggleAllState)
646 {
647 case TRISTATE_FALSE:
648 mxChkToggleAll->set_state(TRISTATE_TRUE);
649 setAllMemberState(true);
650 break;
651 case TRISTATE_TRUE:
652 mxChkToggleAll->set_state(TRISTATE_FALSE);
653 setAllMemberState(false);
654 break;
655 case TRISTATE_INDET:
656 default:
657 mxChkToggleAll->set_state(TRISTATE_TRUE);
658 setAllMemberState(true);
659 break;
660 }
661
662 mePrevToggleAllState = mxChkToggleAll->get_state();
663}
664
665IMPL_LINK_NOARG(ScCheckListMenuControl, EdModifyHdl, weld::Entry&, void)void ScCheckListMenuControl::LinkStubEdModifyHdl(void * instance
, weld::Entry& data) { return static_cast<ScCheckListMenuControl
*>(instance)->EdModifyHdl(data); } void ScCheckListMenuControl
::EdModifyHdl(__attribute__ ((unused)) weld::Entry&)
666{
667 OUString aSearchText = mxEdSearch->get_text();
668 aSearchText = ScGlobal::getCharClassPtr()->lowercase( aSearchText );
669 bool bSearchTextEmpty = aSearchText.isEmpty();
670 size_t n = maMembers.size();
671 size_t nSelCount = 0;
672 bool bSomeDateDeletes = false;
673
674 mpChecks->freeze();
675
676 if (bSearchTextEmpty && !mbHasDates)
677 {
678 // when there are a lot of rows, it is cheaper to simply clear the tree and re-initialise
679 mpChecks->clear();
680 nSelCount = initMembers();
681 }
682 else
683 {
684 for (size_t i = 0; i < n; ++i)
685 {
686 bool bIsDate = maMembers[i].mbDate;
687 bool bPartialMatch = false;
688
689 OUString aLabelDisp = maMembers[i].maName;
690 if ( aLabelDisp.isEmpty() )
691 aLabelDisp = ScResId( STR_EMPTYDATAreinterpret_cast<char const *>("STR_EMPTYDATA" "\004" u8"(empty)"
)
);
692
693 if ( !bSearchTextEmpty )
694 {
695 if ( !bIsDate )
696 bPartialMatch = ( ScGlobal::getCharClassPtr()->lowercase( aLabelDisp ).indexOf( aSearchText ) != -1 );
697 else if ( maMembers[i].meDatePartType == ScCheckListMember::DAY ) // Match with both numerical and text version of month
698 bPartialMatch = (ScGlobal::getCharClassPtr()->lowercase( OUString(
699 maMembers[i].maRealName + maMembers[i].maDateParts[1] )).indexOf( aSearchText ) != -1);
700 else
701 continue;
702 }
703 else if ( bIsDate && maMembers[i].meDatePartType != ScCheckListMember::DAY )
704 continue;
705
706 if ( bSearchTextEmpty )
707 {
708 auto xLeaf = ShowCheckEntry(aLabelDisp, maMembers[i], true, maMembers[i].mbVisible);
709 updateMemberParents(xLeaf.get(), i);
710 if ( maMembers[i].mbVisible )
711 ++nSelCount;
712 continue;
713 }
714
715 if ( bPartialMatch )
716 {
717 auto xLeaf = ShowCheckEntry(aLabelDisp, maMembers[i]);
718 updateMemberParents(xLeaf.get(), i);
719 ++nSelCount;
720 }
721 else
722 {
723 ShowCheckEntry(aLabelDisp, maMembers[i], false, false);
724 if( bIsDate )
725 bSomeDateDeletes = true;
726 }
727 }
728 }
729
730 if ( bSomeDateDeletes )
731 {
732 for (size_t i = 0; i < n; ++i)
733 {
734 if (!maMembers[i].mbDate)
735 continue;
736 if (maMembers[i].meDatePartType != ScCheckListMember::DAY)
737 continue;
738 updateMemberParents(nullptr, i);
739 }
740 }
741
742 mpChecks->thaw();
743
744 if ( nSelCount == n )
745 mxChkToggleAll->set_state( TRISTATE_TRUE );
746 else if ( nSelCount == 0 )
747 mxChkToggleAll->set_state( TRISTATE_FALSE );
748 else
749 mxChkToggleAll->set_state( TRISTATE_INDET );
750
751 if ( !maConfig.mbAllowEmptySet )
752 {
753 const bool bEmptySet( nSelCount == 0 );
754 mpChecks->set_sensitive(!bEmptySet);
755 mxChkToggleAll->set_sensitive(!bEmptySet);
756 mxBtnSelectSingle->set_sensitive(!bEmptySet);
757 mxBtnUnselectSingle->set_sensitive(!bEmptySet);
758 mxBtnOk->set_sensitive(!bEmptySet);
759 }
760}
761
762IMPL_LINK_NOARG(ScCheckListMenuControl, EdActivateHdl, weld::Entry&, bool)bool ScCheckListMenuControl::LinkStubEdActivateHdl(void * instance
, weld::Entry& data) { return static_cast<ScCheckListMenuControl
*>(instance)->EdActivateHdl(data); } bool ScCheckListMenuControl
::EdActivateHdl(__attribute__ ((unused)) weld::Entry&)
763{
764 if (mxBtnOk->get_sensitive())
765 close(true);
766 return true;
767}
768
769IMPL_LINK( ScCheckListMenuControl, CheckHdl, const weld::TreeView::iter_col&, rRowCol, void )void ScCheckListMenuControl::LinkStubCheckHdl(void * instance
, const weld::TreeView::iter_col& data) { return static_cast
<ScCheckListMenuControl *>(instance)->CheckHdl(data)
; } void ScCheckListMenuControl::CheckHdl(const weld::TreeView
::iter_col& rRowCol)
770{
771 Check(&rRowCol.first);
772}
773
774void ScCheckListMenuControl::Check(const weld::TreeIter* pEntry)
775{
776 if (pEntry)
777 CheckEntry(*pEntry, mpChecks->get_toggle(*pEntry) == TRISTATE_TRUE);
778 size_t nNumChecked = GetCheckedEntryCount();
779 if (nNumChecked == maMembers.size())
780 // all members visible
781 mxChkToggleAll->set_state(TRISTATE_TRUE);
782 else if (nNumChecked == 0)
783 // no members visible
784 mxChkToggleAll->set_state(TRISTATE_FALSE);
785 else
786 mxChkToggleAll->set_state(TRISTATE_INDET);
787
788 if (!maConfig.mbAllowEmptySet)
789 // We need to have at least one member selected.
790 mxBtnOk->set_sensitive(nNumChecked != 0);
791
792 mePrevToggleAllState = mxChkToggleAll->get_state();
793}
794
795void ScCheckListMenuControl::updateMemberParents(const weld::TreeIter* pLeaf, size_t nIdx)
796{
797 if ( !maMembers[nIdx].mbDate || maMembers[nIdx].meDatePartType != ScCheckListMember::DAY )
798 return;
799
800 OUString aYearName = maMembers[nIdx].maDateParts[0];
801 OUString aMonthName = maMembers[nIdx].maDateParts[1];
802 auto aItr = maYearMonthMap.find(aYearName + aMonthName);
803
804 if ( pLeaf )
805 {
806 std::unique_ptr<weld::TreeIter> xYearEntry;
807 std::unique_ptr<weld::TreeIter> xMonthEntry = mpChecks->make_iterator(pLeaf);
808 if (!mpChecks->iter_parent(*xMonthEntry))
809 xMonthEntry.reset();
810 else
811 {
812 xYearEntry = mpChecks->make_iterator(xMonthEntry.get());
813 if (!mpChecks->iter_parent(*xYearEntry))
814 xYearEntry.reset();
815 }
816
817 maMembers[nIdx].mxParent = std::move(xMonthEntry);
818 if ( aItr != maYearMonthMap.end() )
819 {
820 size_t nMonthIdx = aItr->second;
821 maMembers[nMonthIdx].mxParent = std::move(xYearEntry);
822 }
823 }
824 else
825 {
826 std::unique_ptr<weld::TreeIter> xYearEntry = FindEntry(nullptr, aYearName);
827 if (aItr != maYearMonthMap.end() && !xYearEntry)
828 {
829 size_t nMonthIdx = aItr->second;
830 maMembers[nMonthIdx].mxParent.reset();
831 maMembers[nIdx].mxParent.reset();
832 }
833 else if (xYearEntry && !FindEntry(xYearEntry.get(), aMonthName))
834 maMembers[nIdx].mxParent.reset();
835 }
836}
837
838void ScCheckListMenuControl::setMemberSize(size_t n)
839{
840 maMembers.reserve(n);
841}
842
843void ScCheckListMenuControl::addDateMember(const OUString& rsName, double nVal, bool bVisible)
844{
845 SvNumberFormatter* pFormatter = mpDoc->GetFormatTable();
846
847 // Convert the numeric date value to a date object.
848 Date aDate = pFormatter->GetNullDate();
849 aDate.AddDays(rtl::math::approxFloor(nVal));
850
851 sal_Int16 nYear = aDate.GetYear();
852 sal_uInt16 nMonth = aDate.GetMonth();
853 sal_uInt16 nDay = aDate.GetDay();
854
855 // Get the localized month name list.
856 CalendarWrapper* pCalendar = ScGlobal::GetCalendar();
857 uno::Sequence<i18n::CalendarItem2> aMonths = pCalendar->getMonths();
858 if (aMonths.getLength() < nMonth)
859 return;
860
861 OUString aYearName = OUString::number(nYear);
862 OUString aMonthName = aMonths[nMonth-1].FullName;
863 OUString aDayName = OUString::number(nDay);
864
865 if ( aDayName.getLength() == 1 )
866 aDayName = "0" + aDayName;
867
868 mpChecks->freeze();
869
870 std::unique_ptr<weld::TreeIter> xYearEntry = FindEntry(nullptr, aYearName);
871 if (!xYearEntry)
872 {
873 xYearEntry = mpChecks->make_iterator();
874 mpChecks->insert(nullptr, -1, nullptr, nullptr, nullptr, nullptr, false, xYearEntry.get());
875 mpChecks->set_toggle(*xYearEntry, TRISTATE_FALSE);
876 mpChecks->set_text(*xYearEntry, aYearName, 0);
877 ScCheckListMember aMemYear;
878 aMemYear.maName = aYearName;
879 aMemYear.maRealName = rsName;
880 aMemYear.mbDate = true;
881 aMemYear.mbLeaf = false;
882 aMemYear.mbVisible = bVisible;
883 aMemYear.mxParent.reset();
884 aMemYear.meDatePartType = ScCheckListMember::YEAR;
885 maMembers.emplace_back(std::move(aMemYear));
886 }
887
888 std::unique_ptr<weld::TreeIter> xMonthEntry = FindEntry(xYearEntry.get(), aMonthName);
889 if (!xMonthEntry)
890 {
891 xMonthEntry = mpChecks->make_iterator();
892 mpChecks->insert(xYearEntry.get(), -1, nullptr, nullptr, nullptr, nullptr, false, xMonthEntry.get());
893 mpChecks->set_toggle(*xMonthEntry, TRISTATE_FALSE);
894 mpChecks->set_text(*xMonthEntry, aMonthName, 0);
895 ScCheckListMember aMemMonth;
896 aMemMonth.maName = aMonthName;
897 aMemMonth.maRealName = rsName;
898 aMemMonth.mbDate = true;
899 aMemMonth.mbLeaf = false;
900 aMemMonth.mbVisible = bVisible;
901 aMemMonth.mxParent = std::move(xYearEntry);
902 aMemMonth.meDatePartType = ScCheckListMember::MONTH;
903 maMembers.emplace_back(std::move(aMemMonth));
904 maYearMonthMap[aYearName + aMonthName] = maMembers.size() - 1;
905 }
906
907 std::unique_ptr<weld::TreeIter> xDayEntry = FindEntry(xMonthEntry.get(), aDayName);
908 if (!xDayEntry)
909 {
910 xDayEntry = mpChecks->make_iterator();
911 mpChecks->insert(xMonthEntry.get(), -1, nullptr, nullptr, nullptr, nullptr, false, xDayEntry.get());
912 mpChecks->set_toggle(*xDayEntry, TRISTATE_FALSE);
913 mpChecks->set_text(*xDayEntry, aDayName, 0);
914 ScCheckListMember aMemDay;
915 aMemDay.maName = aDayName;
916 aMemDay.maRealName = rsName;
917 aMemDay.maDateParts.resize(2);
918 aMemDay.maDateParts[0] = aYearName;
919 aMemDay.maDateParts[1] = aMonthName;
920 aMemDay.mbDate = true;
921 aMemDay.mbLeaf = true;
922 aMemDay.mbVisible = bVisible;
923 aMemDay.mxParent = std::move(xMonthEntry);
924 aMemDay.meDatePartType = ScCheckListMember::DAY;
925 maMembers.emplace_back(std::move(aMemDay));
926 }
927
928 mpChecks->thaw();
929}
930
931void ScCheckListMenuControl::addMember(const OUString& rName, bool bVisible)
932{
933 ScCheckListMember aMember;
934 aMember.maName = rName;
935 aMember.mbDate = false;
936 aMember.mbLeaf = true;
937 aMember.mbVisible = bVisible;
938 aMember.mxParent.reset();
939 maMembers.emplace_back(std::move(aMember));
940}
941
942std::unique_ptr<weld::TreeIter> ScCheckListMenuControl::FindEntry(const weld::TreeIter* pParent, const OUString& sNode)
943{
944 std::unique_ptr<weld::TreeIter> xEntry = mpChecks->make_iterator(pParent);
945 bool bEntry = pParent ? mpChecks->iter_children(*xEntry) : mpChecks->get_iter_first(*xEntry);
946 while (bEntry)
947 {
948 if (sNode == mpChecks->get_text(*xEntry, 0))
949 return xEntry;
950 bEntry = mpChecks->iter_next_sibling(*xEntry);
951 }
952 return nullptr;
953}
954
955void ScCheckListMenuControl::GetRecursiveChecked(const weld::TreeIter* pEntry, std::unordered_set<OUString>& vOut,
956 OUString& rLabel)
957{
958 if (mpChecks->get_toggle(*pEntry) != TRISTATE_TRUE)
959 return;
960
961 // We have to hash parents and children together.
962 // Per convention for easy access in getResult()
963 // "child;parent;grandparent" while descending.
964 if (rLabel.isEmpty())
965 rLabel = mpChecks->get_text(*pEntry, 0);
966 else
967 rLabel = mpChecks->get_text(*pEntry, 0) + ";" + rLabel;
968
969 // Prerequisite: the selection mechanism guarantees that if a child is
970 // selected then also the parent is selected, so we only have to
971 // inspect the children in case the parent is selected.
972 if (!mpChecks->iter_has_child(*pEntry))
973 return;
974
975 std::unique_ptr<weld::TreeIter> xChild(mpChecks->make_iterator(pEntry));
976 bool bChild = mpChecks->iter_children(*xChild);
977 while (bChild)
978 {
979 OUString aLabel = rLabel;
980 GetRecursiveChecked(xChild.get(), vOut, aLabel);
981 if (!aLabel.isEmpty() && aLabel != rLabel)
982 vOut.insert(aLabel);
983 bChild = mpChecks->iter_next_sibling(*xChild);
984 }
985 // Let the caller not add the parent alone.
986 rLabel.clear();
987}
988
989std::unordered_set<OUString> ScCheckListMenuControl::GetAllChecked()
990{
991 std::unordered_set<OUString> vResults(0);
992
993 std::unique_ptr<weld::TreeIter> xEntry = mpChecks->make_iterator();
994 bool bEntry = mpChecks->get_iter_first(*xEntry);
995 while (bEntry)
996 {
997 OUString aLabel;
998 GetRecursiveChecked(xEntry.get(), vResults, aLabel);
999 if (!aLabel.isEmpty())
1000 vResults.insert(aLabel);
1001 bEntry = mpChecks->iter_next_sibling(*xEntry);
1002 }
1003
1004 return vResults;
1005}
1006
1007bool ScCheckListMenuControl::IsChecked(const OUString& sName, const weld::TreeIter* pParent)
1008{
1009 std::unique_ptr<weld::TreeIter> xEntry = FindEntry(pParent, sName);
1010 return xEntry && mpChecks->get_toggle(*xEntry) == TRISTATE_TRUE;
1011}
1012
1013void ScCheckListMenuControl::CheckEntry(const OUString& sName, const weld::TreeIter* pParent, bool bCheck)
1014{
1015 std::unique_ptr<weld::TreeIter> xEntry = FindEntry(pParent, sName);
1016 if (xEntry)
1017 CheckEntry(*xEntry, bCheck);
1018}
1019
1020// Recursively check all children of rParent
1021void ScCheckListMenuControl::CheckAllChildren(const weld::TreeIter& rParent, bool bCheck)
1022{
1023 mpChecks->set_toggle(rParent, bCheck ? TRISTATE_TRUE : TRISTATE_FALSE);
1024 std::unique_ptr<weld::TreeIter> xEntry = mpChecks->make_iterator(&rParent);
1025 bool bEntry = mpChecks->iter_children(*xEntry);
1026 while (bEntry)
1027 {
1028 CheckAllChildren(*xEntry, bCheck);
1029 bEntry = mpChecks->iter_next_sibling(*xEntry);
1030 }
1031}
1032
1033void ScCheckListMenuControl::CheckEntry(const weld::TreeIter& rParent, bool bCheck)
1034{
1035 // recursively check all items below rParent
1036 CheckAllChildren(rParent, bCheck);
1037 // checking rParent can affect ancestors, e.g. if ancestor is unchecked and rParent is
1038 // now checked then the ancestor needs to be checked also
1039 if (!mpChecks->get_iter_depth(rParent))
1040 return;
1041
1042 std::unique_ptr<weld::TreeIter> xAncestor(mpChecks->make_iterator(&rParent));
1043 bool bAncestor = mpChecks->iter_parent(*xAncestor);
1044 while (bAncestor)
1045 {
1046 // if any first level children checked then ancestor
1047 // needs to be checked, similarly if no first level children
1048 // checked then ancestor needs to be unchecked
1049 std::unique_ptr<weld::TreeIter> xChild(mpChecks->make_iterator(xAncestor.get()));
1050 bool bChild = mpChecks->iter_children(*xChild);
1051 bool bChildChecked = false;
1052
1053 while (bChild)
1054 {
1055 if (mpChecks->get_toggle(*xChild) == TRISTATE_TRUE)
1056 {
1057 bChildChecked = true;
1058 break;
1059 }
1060 bChild = mpChecks->iter_next_sibling(*xChild);
1061 }
1062 mpChecks->set_toggle(*xAncestor, bChildChecked ? TRISTATE_TRUE : TRISTATE_FALSE);
1063 bAncestor = mpChecks->iter_parent(*xAncestor);
1064 }
1065}
1066
1067std::unique_ptr<weld::TreeIter> ScCheckListMenuControl::ShowCheckEntry(const OUString& sName, ScCheckListMember& rMember, bool bShow, bool bCheck)
1068{
1069 std::unique_ptr<weld::TreeIter> xEntry;
1070 if (!rMember.mbDate || rMember.mxParent)
1071 xEntry = FindEntry(rMember.mxParent.get(), sName);
1072
1073 if ( bShow )
1074 {
1075 if (!xEntry)
1076 {
1077 if (rMember.mbDate)
1078 {
1079 if (rMember.maDateParts.empty())
1080 return nullptr;
1081
1082 std::unique_ptr<weld::TreeIter> xYearEntry = FindEntry(nullptr, rMember.maDateParts[0]);
1083 if (!xYearEntry)
1084 {
1085 xYearEntry = mpChecks->make_iterator();
1086 mpChecks->insert(nullptr, -1, nullptr, nullptr, nullptr, nullptr, false, xYearEntry.get());
1087 mpChecks->set_toggle(*xYearEntry, TRISTATE_FALSE);
1088 mpChecks->set_text(*xYearEntry, rMember.maDateParts[0], 0);
1089 }
1090 std::unique_ptr<weld::TreeIter> xMonthEntry = FindEntry(xYearEntry.get(), rMember.maDateParts[1]);
1091 if (!xMonthEntry)
1092 {
1093 xMonthEntry = mpChecks->make_iterator();
1094 mpChecks->insert(xYearEntry.get(), -1, nullptr, nullptr, nullptr, nullptr, false, xMonthEntry.get());
1095 mpChecks->set_toggle(*xMonthEntry, TRISTATE_FALSE);
1096 mpChecks->set_text(*xMonthEntry, rMember.maDateParts[1], 0);
1097 }
1098 std::unique_ptr<weld::TreeIter> xDayEntry = FindEntry(xMonthEntry.get(), rMember.maName);
1099 if (!xDayEntry)
1100 {
1101 xDayEntry = mpChecks->make_iterator();
1102 mpChecks->insert(xMonthEntry.get(), -1, nullptr, nullptr, nullptr, nullptr, false, xDayEntry.get());
1103 mpChecks->set_toggle(*xDayEntry, TRISTATE_FALSE);
1104 mpChecks->set_text(*xDayEntry, rMember.maName, 0);
1105 }
1106 return xDayEntry; // Return leaf node
1107 }
1108
1109 xEntry = mpChecks->make_iterator();
1110 mpChecks->append(xEntry.get());
1111 mpChecks->set_toggle(*xEntry, bCheck ? TRISTATE_TRUE : TRISTATE_FALSE);
1112 mpChecks->set_text(*xEntry, sName, 0);
1113 }
1114 else
1115 CheckEntry(*xEntry, bCheck);
1116 }
1117 else if (xEntry)
1118 {
1119 mpChecks->remove(*xEntry);
1120 if (rMember.mxParent)
1121 {
1122 std::unique_ptr<weld::TreeIter> xParent(mpChecks->make_iterator(rMember.mxParent.get()));
1123 while (xParent && !mpChecks->iter_has_child(*xParent))
1124 {
1125 std::unique_ptr<weld::TreeIter> xTmp(mpChecks->make_iterator(xParent.get()));
1126 if (!mpChecks->iter_parent(*xParent))
1127 xParent.reset();
1128 mpChecks->remove(*xTmp);
1129 }
1130 }
1131 }
1132 return nullptr;
1133}
1134
1135int ScCheckListMenuControl::GetCheckedEntryCount() const
1136{
1137 int nRet = 0;
1138
1139 mpChecks->all_foreach([this, &nRet](weld::TreeIter& rEntry){
1140 if (mpChecks->get_toggle(rEntry) == TRISTATE_TRUE)
1141 ++nRet;
1142 return false;
1143 });
1144
1145 return nRet;
1146}
1147
1148IMPL_LINK(ScCheckListMenuControl, KeyInputHdl, const KeyEvent&, rKEvt, bool)bool ScCheckListMenuControl::LinkStubKeyInputHdl(void * instance
, const KeyEvent& data) { return static_cast<ScCheckListMenuControl
*>(instance)->KeyInputHdl(data); } bool ScCheckListMenuControl
::KeyInputHdl(const KeyEvent& rKEvt)
1149{
1150 const vcl::KeyCode& rKey = rKEvt.GetKeyCode();
1151
1152 if ( rKey.GetCode() == KEY_RETURN || rKey.GetCode() == KEY_SPACE )
1153 {
1154 std::unique_ptr<weld::TreeIter> xEntry = mpChecks->make_iterator();
1155 bool bEntry = mpChecks->get_cursor(xEntry.get());
1156 if (bEntry)
1157 {
1158 bool bOldCheck = mpChecks->get_toggle(*xEntry) == TRISTATE_TRUE;
1159 CheckEntry(*xEntry, !bOldCheck);
1160 bool bNewCheck = mpChecks->get_toggle(*xEntry) == TRISTATE_TRUE;
1161 if (bOldCheck != bNewCheck)
1162 Check(xEntry.get());
1163 }
1164 return true;
1165 }
1166
1167 return false;
1168}
1169
1170namespace
1171{
1172 void insertMember(weld::TreeView& rView, const weld::TreeIter& rIter, const ScCheckListMember& rMember)
1173 {
1174 OUString aLabel = rMember.maName;
1175 if (aLabel.isEmpty())
1176 aLabel = ScResId(STR_EMPTYDATAreinterpret_cast<char const *>("STR_EMPTYDATA" "\004" u8"(empty)"
)
);
1177 rView.set_toggle(rIter, rMember.mbVisible ? TRISTATE_TRUE : TRISTATE_FALSE);
1178 rView.set_text(rIter, aLabel, 0);
1179 }
1180}
1181
1182size_t ScCheckListMenuControl::initMembers(int nMaxMemberWidth)
1183{
1184 size_t n = maMembers.size();
1185 size_t nVisMemCount = 0;
1186
1187 if (nMaxMemberWidth == -1)
1188 nMaxMemberWidth = mnCheckWidthReq;
1189
1190 if (!mpChecks->n_children() && !mbHasDates)
1191 {
1192 std::vector<int> aFixedWidths { nMaxMemberWidth };
1193 // tdf#134038 insert in the fastest order, this might be backwards so only do it for
1194 // the !mbHasDates case where no entry depends on another to exist before getting
1195 // inserted. We cannot retain pre-existing treeview content, only clear and fill it.
1196 mpChecks->bulk_insert_for_each(n, [this, &nVisMemCount](weld::TreeIter& rIter, int i) {
1197 assert(!maMembers[i].mbDate)(static_cast <bool> (!maMembers[i].mbDate) ? void (0) :
__assert_fail ("!maMembers[i].mbDate", "/home/maarten/src/libreoffice/core/sc/source/ui/cctrl/checklistmenu.cxx"
, 1197, __extension__ __PRETTY_FUNCTION__))
;
1198 insertMember(*mpChecks, rIter, maMembers[i]);
1199 if (maMembers[i].mbVisible)
1200 ++nVisMemCount;
1201 }, &aFixedWidths);
1202 }
1203 else
1204 {
1205 mpChecks->freeze();
1206
1207 std::unique_ptr<weld::TreeIter> xEntry = mpChecks->make_iterator();
1208 std::vector<std::unique_ptr<weld::TreeIter>> aExpandRows;
1209
1210 for (size_t i = 0; i < n; ++i)
1211 {
1212 if (maMembers[i].mbDate)
1213 {
1214 CheckEntry(maMembers[i].maName, maMembers[i].mxParent.get(), maMembers[i].mbVisible);
1215 // Expand first node of checked dates
1216 if (!maMembers[i].mxParent && IsChecked(maMembers[i].maName, maMembers[i].mxParent.get()))
1217 {
1218 std::unique_ptr<weld::TreeIter> xDateEntry = FindEntry(nullptr, maMembers[i].maName);
1219 if (xDateEntry)
1220 aExpandRows.emplace_back(std::move(xDateEntry));
1221 }
1222 }
1223 else
1224 {
1225 mpChecks->append(xEntry.get());
1226 insertMember(*mpChecks, *xEntry, maMembers[i]);
1227 }
1228
1229 if (maMembers[i].mbVisible)
1230 ++nVisMemCount;
1231 }
1232
1233 mpChecks->thaw();
1234
1235 for (auto& rRow : aExpandRows)
1236 mpChecks->expand_row(*rRow);
1237 }
1238
1239 if (nVisMemCount == n)
1240 {
1241 // all members visible
1242 mxChkToggleAll->set_state(TRISTATE_TRUE);
1243 mePrevToggleAllState = TRISTATE_TRUE;
1244 }
1245 else if (nVisMemCount == 0)
1246 {
1247 // no members visible
1248 mxChkToggleAll->set_state(TRISTATE_FALSE);
1249 mePrevToggleAllState = TRISTATE_FALSE;
1250 }
1251 else
1252 {
1253 mxChkToggleAll->set_state(TRISTATE_INDET);
1254 mePrevToggleAllState = TRISTATE_INDET;
1255 }
1256
1257 if (nVisMemCount)
1258 mpChecks->select(0);
1259
1260 return nVisMemCount;
1261}
1262
1263void ScCheckListMenuControl::setConfig(const Config& rConfig)
1264{
1265 maConfig = rConfig;
1266}
1267
1268bool ScCheckListMenuControl::isAllSelected() const
1269{
1270 return mxChkToggleAll->get_state() == TRISTATE_TRUE;
1271}
1272
1273void ScCheckListMenuControl::getResult(ResultType& rResult)
1274{
1275 ResultType aResult;
1276 std::unordered_set<OUString> vCheckeds = GetAllChecked();
1277 size_t n = maMembers.size();
1278 for (size_t i = 0; i < n; ++i)
1279 {
1280 if ( maMembers[i].mbLeaf )
1281 {
1282 OUStringBuffer aLabel = maMembers[i].maName;
1283 if (aLabel.isEmpty())
1284 aLabel = ScResId(STR_EMPTYDATAreinterpret_cast<char const *>("STR_EMPTYDATA" "\004" u8"(empty)"
)
);
1285
1286 /* TODO: performance-wise this looks suspicious, concatenating to
1287 * do the lookup for each leaf item seems wasteful. */
1288 // Checked labels are in the form "child;parent;grandparent".
1289 if (maMembers[i].mxParent)
1290 {
1291 std::unique_ptr<weld::TreeIter> xIter(mpChecks->make_iterator(maMembers[i].mxParent.get()));
1292 do
1293 {
1294 aLabel.append(";").append(mpChecks->get_text(*xIter));
1295 }
1296 while (mpChecks->iter_parent(*xIter));
1297 }
1298
1299 bool bState = vCheckeds.find(aLabel.makeStringAndClear()) != vCheckeds.end();
1300
1301 ResultEntry aResultEntry;
1302 aResultEntry.bValid = bState;
1303 if ( maMembers[i].mbDate )
1304 aResultEntry.aName = maMembers[i].maRealName;
1305 else
1306 aResultEntry.aName = maMembers[i].maName;
1307 aResultEntry.bDate = maMembers[i].mbDate;
1308 aResult.insert(aResultEntry);
1309 }
1310 }
1311 rResult.swap(aResult);
1312}
1313
1314void ScCheckListMenuControl::launch(const tools::Rectangle& rRect)
1315{
1316 prepWindow();
1317 if (!maConfig.mbAllowEmptySet)
1318 // We need to have at least one member selected.
1319 mxBtnOk->set_sensitive(GetCheckedEntryCount() != 0);
1320
1321 tools::Rectangle aRect(rRect);
1322 if (maConfig.mbRTL)
1323 {
1324 // In RTL mode, the logical "left" is visual "right".
1325 long nLeft = aRect.Left() - aRect.GetWidth();
1326 aRect.SetLeft( nLeft );
1327 }
1328 else if (mnWndWidth < aRect.GetWidth())
1329 {
1330 // Target rectangle (i.e. cell width) is wider than the window.
1331 // Simulate right-aligned launch by modifying the target rectangle
1332 // size.
1333 long nDiff = aRect.GetWidth() - mnWndWidth;
1334 aRect.AdjustLeft(nDiff );
1335 }
1336
1337 StartPopupMode(aRect, FloatWinPopupFlags::Down);
1338}
1339
1340void ScCheckListMenuControl::close(bool bOK)
1341{
1342 if (bOK && mxOKAction)
1343 mxOKAction->execute();
1344 EndPopupMode();
1345}
1346
1347void ScCheckListMenuControl::setExtendedData(std::unique_ptr<ExtendedData> p)
1348{
1349 mxExtendedData = std::move(p);
1350}
1351
1352ScCheckListMenuControl::ExtendedData* ScCheckListMenuControl::getExtendedData()
1353{
1354 return mxExtendedData.get();
1355}
1356
1357void ScCheckListMenuControl::setOKAction(Action* p)
1358{
1359 mxOKAction.reset(p);
1360}
1361
1362void ScCheckListMenuControl::setPopupEndAction(Action* p)
1363{
1364 mxPopupEndAction.reset(p);
1365}
1366
1367IMPL_LINK_NOARG(ScCheckListMenuControl, PopupModeEndHdl, FloatingWindow*, void)void ScCheckListMenuControl::LinkStubPopupModeEndHdl(void * instance
, FloatingWindow* data) { return static_cast<ScCheckListMenuControl
*>(instance)->PopupModeEndHdl(data); } void ScCheckListMenuControl
::PopupModeEndHdl(__attribute__ ((unused)) FloatingWindow*)
1368{
1369 clearSelectedMenuItem();
1370 if (mxPopupEndAction)
1371 mxPopupEndAction->execute();
1372}
1373
1374int ScCheckListMenuControl::GetTextWidth(const OUString& rsName) const
1375{
1376 return mxDropDown->GetTextWidth(rsName);
1377}
1378
1379int ScCheckListMenuControl::IncreaseWindowWidthToFitText(int nMaxTextWidth)
1380{
1381 int nBorder = mxFrame->get_border_width() * 2 + 4;
1382 int nNewWidth = nMaxTextWidth - nBorder;
1383 if (nNewWidth > mnCheckWidthReq)
1384 {
1385 mnCheckWidthReq = nNewWidth;
1386 int nChecksHeight = mpChecks->get_height_rows(9);
1387 mpChecks->set_size_request(mnCheckWidthReq, nChecksHeight);
1388 }
1389 return mnCheckWidthReq + nBorder;
1390}
1391
1392/* 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);
2
Calling copy constructor for 'Reference<vcl::Window>'
5
Returning from copy constructor for 'Reference<vcl::Window>'
204 m_rInnerRef.clear(); // we should use some 'swap' method ideally ;-)
6
Calling 'Reference::clear'
13
Returning; memory was released
205 if (aTmp.get()) {
14
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)
3
Assuming field 'm_pBody' is non-null
4
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
6.1
Field 'm_pBody' is non-null
6.1
Field 'm_pBody' is non-null
6.1
Field 'm_pBody' is non-null
6.1
Field 'm_pBody' is non-null
)
7
Taking true branch
177 {
178 reference_type * const pOld = m_pBody;
179 m_pBody = NULL__null;
180 pOld->release();
8
Calling 'VclReferenceBase::release'
12
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;
15
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)
9
Assuming the condition is true
10
Taking true branch
40 delete this;
11
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