tdf#144694 In direct SQL dialog, activate options 'Run SQL command
[LibreOffice.git] / svl / source / notify / broadcast.cxx
blob6b323a6693291d38442edaf7df8f5bc0e3cdb408
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <svl/broadcast.hxx>
21 #include <svl/listener.hxx>
22 #include <svl/hint.hxx>
23 #include <o3tl/safeint.hxx>
24 #include <cassert>
25 #include <algorithm>
27 /**
28 Design Notes
29 -------------------------------
31 This class is extremely heavily used - we can have millions of broadcasters and listeners and we can also
32 have a broadcaster that has a million listeners.
34 So we do a number of things
35 (*) use a cache-dense listener list (std::vector) because caching effects dominate a lot of operations
36 (*) use a sorted list to speed up find operations
37 (*) only sort the list when we absolutely have to, to speed up sequential add/remove operations
38 (*) defer removing items from the list by (ab)using the last bit of the pointer
40 Also we have some complications around destruction because
41 (*) we broadcast a message to indicate that we are destructing
42 (*) which can trigger arbitrality complicated behaviour, including
43 (*) adding a removing things from the in-destruction object!
47 static bool isDeletedPtr(SvtListener* p)
49 /** mark deleted entries by toggling the last bit,which is effectively unused, since the struct we point
50 * to is at least 16-bit aligned. This allows the binary search to continue working even when we have
51 * deleted entries */
52 return (reinterpret_cast<uintptr_t>(p) & 0x01) == 0x01;
55 static void markDeletedPtr(SvtListener*& rp)
57 reinterpret_cast<uintptr_t&>(rp) |= 0x01;
60 static void sortListeners(std::vector<SvtListener*>& listeners, size_t firstUnsorted)
62 // Add() only appends new values, so often the container will be sorted expect for one
63 // or few last items. For larger containers it is much more efficient to just handle
64 // the unsorted part.
65 auto sortedEnd = firstUnsorted == 0
66 ? std::is_sorted_until(listeners.begin(),listeners.end())
67 : listeners.begin() + firstUnsorted;
68 if( listeners.end() - sortedEnd == 1 )
69 { // Just one item, insert it in the right place.
70 SvtListener* item = listeners.back();
71 listeners.pop_back();
72 listeners.insert( std::upper_bound( listeners.begin(), listeners.end(), item ), item );
74 else if( o3tl::make_unsigned( sortedEnd - listeners.begin()) > listeners.size() * 3 / 4 )
75 { // Sort the unsorted part and then merge.
76 std::sort( sortedEnd, listeners.end());
77 std::inplace_merge( listeners.begin(), sortedEnd, listeners.end());
79 else
81 std::sort(listeners.begin(), listeners.end());
85 void SvtBroadcaster::Normalize() const
87 // clear empty slots first, because then we often have to do very little sorting
88 if (mnEmptySlots)
90 std::erase_if(maListeners, [] (SvtListener* p) { return isDeletedPtr(p); });
91 mnEmptySlots = 0;
94 if (mnListenersFirstUnsorted != static_cast<sal_Int32>(maListeners.size()))
96 sortListeners(maListeners, mnListenersFirstUnsorted);
97 mnListenersFirstUnsorted = maListeners.size();
100 if (!mbDestNormalized)
102 sortListeners(maDestructedListeners, 0);
103 mbDestNormalized = true;
107 void SvtBroadcaster::Add( SvtListener* p )
109 assert(!mbDisposing && "called inside my own destructor?");
110 assert(!mbAboutToDie && "called after PrepareForDestruction()?");
111 if (mbDisposing || mbAboutToDie)
112 return;
113 // Avoid normalizing if the item appended keeps the container sorted.
114 auto nRealSize = static_cast<sal_Int32>(maListeners.size() - mnEmptySlots);
115 auto bSorted = mnListenersFirstUnsorted == nRealSize;
116 if (maListeners.empty() || (bSorted && maListeners.back() <= p))
118 ++mnListenersFirstUnsorted;
119 maListeners.push_back(p);
120 return;
122 // see if we can stuff it into an empty slot, which succeeds surprisingly often in
123 // some calc workloads where it removes and then re-adds the same listener
124 if (mnEmptySlots && bSorted)
126 auto it = std::lower_bound(maListeners.begin(), maListeners.end(), p);
127 if (it != maListeners.end() && isDeletedPtr(*it))
129 *it = p;
130 ++mnListenersFirstUnsorted;
131 --mnEmptySlots;
132 return;
135 maListeners.push_back(p);
138 void SvtBroadcaster::Remove( SvtListener* p )
140 if (mbDisposing)
141 return;
143 if (mbAboutToDie)
145 // only reset mbDestNormalized if we are going to become unsorted
146 if (!maDestructedListeners.empty() && maDestructedListeners.back() > p)
147 mbDestNormalized = false;
148 maDestructedListeners.push_back(p);
149 return;
152 // We only need to fully normalize if one or more Add()s have been performed that make the array unsorted.
153 auto nRealSize = static_cast<sal_Int32>(maListeners.size() - mnEmptySlots);
154 if (mnListenersFirstUnsorted != nRealSize || (maListeners.size() > 1024 && maListeners.size() / nRealSize > 16))
155 Normalize();
157 auto it = std::lower_bound(maListeners.begin(), maListeners.end(), p);
158 assert (it != maListeners.end() && *it == p);
159 if (it != maListeners.end() && *it == p)
161 markDeletedPtr(*it);
162 ++mnEmptySlots;
163 --mnListenersFirstUnsorted;
166 if (!HasListeners())
167 ListenersGone();
170 SvtBroadcaster::SvtBroadcaster( const SvtBroadcaster &rBC ) :
171 mnEmptySlots(0), mnListenersFirstUnsorted(0),
172 mbAboutToDie(false), mbDisposing(false),
173 mbDestNormalized(true)
175 assert(!rBC.mbAboutToDie && "copying an object marked with PrepareForDestruction()?");
176 assert(!rBC.mbDisposing && "copying an object that is in its destructor?");
178 rBC.Normalize(); // so that insert into ourself is in-order, and therefore we do not need to Normalize()
179 maListeners.reserve(rBC.maListeners.size());
180 for (SvtListener* p : rBC.maListeners)
181 p->StartListening(*this); // this will call back into this->Add()
184 SvtBroadcaster::~SvtBroadcaster()
186 mbDisposing = true;
187 Broadcast( SfxHint(SfxHintId::Dying) );
189 Normalize();
191 // now when both lists are sorted, we can linearly unregister all
192 // listeners, with the exception of those that already asked to be removed
193 // during their own destruction
194 ListenersType::const_iterator dest(maDestructedListeners.begin());
195 for (auto& rpListener : maListeners)
197 // skip the destructed ones
198 while (dest != maDestructedListeners.end() && (*dest < rpListener))
199 ++dest;
201 if (dest == maDestructedListeners.end() || *dest != rpListener)
202 rpListener->BroadcasterDying(*this);
206 void SvtBroadcaster::Broadcast( const SfxHint &rHint )
208 Normalize();
210 ListenersType::const_iterator dest(maDestructedListeners.begin());
211 ListenersType aListeners(maListeners); // this copy is important to avoid erasing entries while iterating
212 for (auto& rpListener : aListeners)
214 // skip the destructed ones
215 while (dest != maDestructedListeners.end() && (*dest < rpListener))
216 ++dest;
218 if (dest == maDestructedListeners.end() || *dest != rpListener)
219 rpListener->Notify(rHint);
223 void SvtBroadcaster::ListenersGone() {}
225 SvtBroadcaster::ListenersType& SvtBroadcaster::GetAllListeners()
227 Normalize();
228 return maListeners;
231 const SvtBroadcaster::ListenersType& SvtBroadcaster::GetAllListeners() const
233 Normalize();
234 return maListeners;
237 void SvtBroadcaster::PrepareForDestruction()
239 mbAboutToDie = true;
240 // the reserve() serves two purpose (1) performance (2) makes sure our iterators do not become invalid
241 maDestructedListeners.reserve(maListeners.size());
244 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */