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 richtextimplcontrol.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 SYSTEM_LIBXML -D EXCEPTIONS_ON -D LIBO_INTERNAL_ONLY -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/boost/include -I /home/maarten/src/libreoffice/core/workdir/UnpackedTarball/boost -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/forms/inc -I /home/maarten/src/libreoffice/core/forms/source/inc -I /home/maarten/src/libreoffice/core/forms/source/solar/inc -I /home/maarten/src/libreoffice/core/workdir/YaccTarget/connectivity/source/parse -I /home/maarten/src/libreoffice/core/workdir/UnoApiHeadersTarget/offapi/normal -I /home/maarten/src/libreoffice/core/workdir/UnoApiHeadersTarget/oovbaapi/normal -I /home/maarten/src/libreoffice/core/workdir/UnoApiHeadersTarget/udkapi/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/forms/source/richtext/richtextimplcontrol.cxx

/home/maarten/src/libreoffice/core/forms/source/richtext/richtextimplcontrol.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 "richtextimplcontrol.hxx"
21#include "textattributelistener.hxx"
22#include "richtextengine.hxx"
23#include <sal/log.hxx>
24#include <osl/diagnose.h>
25#include <i18nlangtag/languagetag.hxx>
26#include <editeng/editids.hrc>
27#include <editeng/editview.hxx>
28#include <editeng/editstat.hxx>
29#include <editeng/scripttypeitem.hxx>
30
31#include <svl/itempool.hxx>
32#include <svl/itemset.hxx>
33#include <tools/mapunit.hxx>
34#include <vcl/svapp.hxx>
35#include <vcl/settings.hxx>
36#include <vcl/commandevent.hxx>
37
38#define EMPTY_PAPER_SIZE0x7FFFFFFF 0x7FFFFFFF
39
40
41namespace frm
42{
43
44 RichTextControlImpl::RichTextControlImpl( Control* _pAntiImpl, RichTextEngine* _pEngine, ITextAttributeListener* _pTextAttrListener, ITextSelectionListener* _pSelectionListener )
45 :m_pAntiImpl ( _pAntiImpl )
46 ,m_pViewport ( nullptr )
47 ,m_pHScroll ( nullptr )
48 ,m_pVScroll ( nullptr )
49 ,m_pScrollCorner ( nullptr )
50 ,m_pEngine ( _pEngine )
51 ,m_pTextAttrListener ( _pTextAttrListener )
52 ,m_pSelectionListener ( _pSelectionListener )
53 ,m_bHasEverBeenShown ( false )
54 {
55 OSL_ENSURE( m_pAntiImpl, "RichTextControlImpl::RichTextControlImpl: invalid window!" )do { if (true && (!(m_pAntiImpl))) { sal_detail_logFormat
((SAL_DETAIL_LOG_LEVEL_WARN), ("legacy.osl"), ("/home/maarten/src/libreoffice/core/forms/source/richtext/richtextimplcontrol.cxx"
":" "55" ": "), "%s", "RichTextControlImpl::RichTextControlImpl: invalid window!"
); } } while (false)
;
56 OSL_ENSURE( m_pEngine, "RichTextControlImpl::RichTextControlImpl: invalid edit engine! This will *definitely* crash!" )do { if (true && (!(m_pEngine))) { sal_detail_logFormat
((SAL_DETAIL_LOG_LEVEL_WARN), ("legacy.osl"), ("/home/maarten/src/libreoffice/core/forms/source/richtext/richtextimplcontrol.cxx"
":" "56" ": "), "%s", "RichTextControlImpl::RichTextControlImpl: invalid edit engine! This will *definitely* crash!"
); } } while (false)
;
57
58 m_pViewport = VclPtr<RichTextViewPort>::Create( m_pAntiImpl );
59 m_pViewport->setAttributeInvalidationHandler( LINK( this, RichTextControlImpl, OnInvalidateAllAttributes )::tools::detail::makeLink( ::tools::detail::castTo<RichTextControlImpl
*>(this), &RichTextControlImpl::LinkStubOnInvalidateAllAttributes
)
);
60 m_pViewport->Show();
61
62 // ensure that both the window and the reference device have the same map unit
63 MapMode aRefDeviceMapMode( m_pEngine->GetRefDevice()->GetMapMode() );
64 m_pAntiImpl->SetMapMode( aRefDeviceMapMode );
65 m_pViewport->SetMapMode( aRefDeviceMapMode );
66
67 m_pView.reset(new EditView( m_pEngine, m_pViewport ));
68 m_pEngine->InsertView( m_pView.get() );
69 m_pViewport->setView( *m_pView );
70
71 m_pEngine->registerEngineStatusListener( this );
72
73 {
74 EVControlBits nViewControlWord = m_pView->GetControlWord();
75 nViewControlWord |= EVControlBits::AUTOSCROLL;
76 m_pView->SetControlWord( nViewControlWord );
77 }
78
79 // ensure that it's initially scrolled to the upper left
80 m_pView->SetVisArea( tools::Rectangle( Point( ), m_pViewport->GetOutputSize() ) );
81
82 ensureScrollbars();
83
84 m_pAntiImpl->SetBackground( Wallpaper( m_pAntiImpl->GetSettings().GetStyleSettings().GetFieldColor() ) );
85 }
86
87
88 RichTextControlImpl::~RichTextControlImpl( )
89 {
90 m_pEngine->RemoveView( m_pView.get() );
91 m_pEngine->revokeEngineStatusListener( this );
92 m_pView.reset();
93 m_pViewport.disposeAndClear();
94 m_pHScroll.disposeAndClear();
95 m_pVScroll.disposeAndClear();
96 m_pScrollCorner.disposeAndClear();
1
Calling 'VclPtr::disposeAndClear'
97 }
98
99
100 void RichTextControlImpl::implUpdateAttribute( const AttributeHandlerPool::const_iterator& _pHandler )
101 {
102 if ( ( _pHandler->first == SID_ATTR_CHAR_WEIGHT( 10000 + 9 ) )
103 || ( _pHandler->first == SID_ATTR_CHAR_POSTURE( 10000 + 8 ) )
104 || ( _pHandler->first == SID_ATTR_CHAR_FONT( 10000 + 7 ) )
105 || ( _pHandler->first == SID_ATTR_CHAR_FONTHEIGHT( 10000 + 15 ) )
106 )
107 {
108 // these are attributes whose value depends on the current script type.
109 // I.e., in real, there are *three* items in the ItemSet: One for each script
110 // type (Latin, Asian, Complex). However, if we have an observer who is interested
111 // in the state of this attribute, we have to kind of *merge* the three attributes
112 // to only one.
113 // This is useful in case the observer is for instance a toolbox which contains only
114 // an, e.g., "bold" slot, and thus not interested in the particular script type of the
115 // current selection.
116 SvxScriptSetItem aNormalizedSet( static_cast<WhichId>(_pHandler->first), *m_pView->GetAttribs().GetPool() );
117 normalizeScriptDependentAttribute( aNormalizedSet );
118
119 implCheckUpdateCache( _pHandler->first, _pHandler->second->getState( aNormalizedSet.GetItemSet() ) );
120 }
121 else
122 implCheckUpdateCache( _pHandler->first, _pHandler->second->getState( m_pView->GetAttribs() ) );
123 }
124
125
126 void RichTextControlImpl::updateAttribute( AttributeId _nAttribute )
127 {
128 AttributeHandlerPool::const_iterator pHandler = m_aAttributeHandlers.find( _nAttribute );
129 if ( pHandler != m_aAttributeHandlers.end() )
130 implUpdateAttribute( pHandler );
131 }
132
133
134 void RichTextControlImpl::updateAllAttributes( )
135 {
136 for ( AttributeHandlerPool::const_iterator pHandler = m_aAttributeHandlers.begin();
137 pHandler != m_aAttributeHandlers.end();
138 ++pHandler
139 )
140 {
141 implUpdateAttribute( pHandler );
142 }
143
144 // notify changes of the selection, if necessary
145 if ( m_pSelectionListener && m_pView )
146 {
147 ESelection aCurrentSelection = m_pView->GetSelection();
148 if ( aCurrentSelection != m_aLastKnownSelection )
149 {
150 m_aLastKnownSelection = aCurrentSelection;
151 m_pSelectionListener->onSelectionChanged();
152 }
153 }
154 }
155
156
157 AttributeState RichTextControlImpl::getAttributeState( AttributeId _nAttributeId ) const
158 {
159 StateCache::const_iterator aCachedStatePos = m_aLastKnownStates.find( _nAttributeId );
160 if ( aCachedStatePos == m_aLastKnownStates.end() )
161 {
162 OSL_FAIL( "RichTextControlImpl::getAttributeState: Don't ask for the state of an attribute which I never encountered!" )do { if (true && (((sal_Bool)1))) { sal_detail_logFormat
((SAL_DETAIL_LOG_LEVEL_WARN), ("legacy.osl"), ("/home/maarten/src/libreoffice/core/forms/source/richtext/richtextimplcontrol.cxx"
":" "162" ": "), "%s", "RichTextControlImpl::getAttributeState: Don't ask for the state of an attribute which I never encountered!"
); } } while (false)
;
163 return AttributeState( eIndetermined );
164 }
165 return aCachedStatePos->second;
166 }
167
168
169 bool RichTextControlImpl::executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rAttribs, AttributeId _nAttribute, const SfxPoolItem* _pArgument, SvtScriptType _nForScriptType )
170 {
171 // let's see whether we have a handler for this attribute
172 AttributeHandlerPool::const_iterator aHandlerPos = m_aAttributeHandlers.find( _nAttribute );
173 if ( aHandlerPos != m_aAttributeHandlers.end() )
174 {
175 aHandlerPos->second->executeAttribute( _rCurrentAttribs, _rAttribs, _pArgument, _nForScriptType );
176 return true;
177 }
178 return false;
179 }
180
181
182 void RichTextControlImpl::enableAttributeNotification( AttributeId _nAttributeId, ITextAttributeListener* _pListener )
183 {
184 AttributeHandlerPool::const_iterator aHandlerPos = m_aAttributeHandlers.find( _nAttributeId );
185 if ( aHandlerPos == m_aAttributeHandlers.end() )
186 {
187 ::rtl::Reference< AttributeHandler > aHandler = AttributeHandlerFactory::getHandlerFor( _nAttributeId, *m_pEngine->GetEmptyItemSet().GetPool() );
188 OSL_ENSURE( aHandler.is(), "RichTextControlImpl::enableAttributeNotification: no handler available for this attribute!" )do { if (true && (!(aHandler.is()))) { sal_detail_logFormat
((SAL_DETAIL_LOG_LEVEL_WARN), ("legacy.osl"), ("/home/maarten/src/libreoffice/core/forms/source/richtext/richtextimplcontrol.cxx"
":" "188" ": "), "%s", "RichTextControlImpl::enableAttributeNotification: no handler available for this attribute!"
); } } while (false)
;
189 if ( !aHandler.is() )
190 return;
191 SAL_WARN_IF( _nAttributeId != aHandler->getAttributeId(), "forms.richtext", "RichTextControlImpl::enableAttributeNotification: suspicious handler!" )do { if (true && (_nAttributeId != aHandler->getAttributeId
())) { switch (sal_detail_log_report(::SAL_DETAIL_LOG_LEVEL_WARN
, "forms.richtext")) { case SAL_DETAIL_LOG_ACTION_IGNORE: break
; case SAL_DETAIL_LOG_ACTION_LOG: if (sizeof ::sal::detail::getResult
( ::sal::detail::StreamStart() << "RichTextControlImpl::enableAttributeNotification: suspicious handler!"
) == 1) { ::sal_detail_log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("forms.richtext"
), ("/home/maarten/src/libreoffice/core/forms/source/richtext/richtextimplcontrol.cxx"
":" "191" ": "), ::sal::detail::unwrapStream( ::sal::detail::
StreamStart() << "RichTextControlImpl::enableAttributeNotification: suspicious handler!"
), 0); } else { ::std::ostringstream sal_detail_stream; sal_detail_stream
<< "RichTextControlImpl::enableAttributeNotification: suspicious handler!"
; ::sal::detail::log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("forms.richtext"
), ("/home/maarten/src/libreoffice/core/forms/source/richtext/richtextimplcontrol.cxx"
":" "191" ": "), sal_detail_stream, 0); }; break; case SAL_DETAIL_LOG_ACTION_FATAL
: if (sizeof ::sal::detail::getResult( ::sal::detail::StreamStart
() << "RichTextControlImpl::enableAttributeNotification: suspicious handler!"
) == 1) { ::sal_detail_log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("forms.richtext"
), ("/home/maarten/src/libreoffice/core/forms/source/richtext/richtextimplcontrol.cxx"
":" "191" ": "), ::sal::detail::unwrapStream( ::sal::detail::
StreamStart() << "RichTextControlImpl::enableAttributeNotification: suspicious handler!"
), 0); } else { ::std::ostringstream sal_detail_stream; sal_detail_stream
<< "RichTextControlImpl::enableAttributeNotification: suspicious handler!"
; ::sal::detail::log( (::SAL_DETAIL_LOG_LEVEL_WARN), ("forms.richtext"
), ("/home/maarten/src/libreoffice/core/forms/source/richtext/richtextimplcontrol.cxx"
":" "191" ": "), sal_detail_stream, 0); }; std::abort(); break
; } } } while (false)
;
192
193 aHandlerPos = m_aAttributeHandlers.emplace( _nAttributeId , aHandler ).first;
194 }
195
196 // remember the listener
197 if ( _pListener )
198 m_aAttributeListeners.emplace( _nAttributeId, _pListener );
199
200 // update (and broadcast) the state of this attribute
201 updateAttribute( _nAttributeId );
202 }
203
204
205 void RichTextControlImpl::disableAttributeNotification( AttributeId _nAttributeId )
206 {
207 // forget the handler for this attribute
208 AttributeHandlerPool::iterator aHandlerPos = m_aAttributeHandlers.find( _nAttributeId );
209 if ( aHandlerPos != m_aAttributeHandlers.end() )
210 m_aAttributeHandlers.erase( aHandlerPos );
211
212 // as well as the listener
213 AttributeListenerPool::iterator aListenerPos = m_aAttributeListeners.find( _nAttributeId );
214 if ( aListenerPos != m_aAttributeListeners.end() )
215 m_aAttributeListeners.erase( aListenerPos );
216 }
217
218
219 void RichTextControlImpl::normalizeScriptDependentAttribute( SvxScriptSetItem& _rScriptSetItem )
220 {
221 _rScriptSetItem.GetItemSet().Put( m_pView->GetAttribs(), false );
222 const SfxPoolItem* pNormalizedItem = _rScriptSetItem.GetItemOfScript( getSelectedScriptType() );
223
224 WhichId nNormalizedWhichId = _rScriptSetItem.GetItemSet().GetPool()->GetWhich( _rScriptSetItem.Which() );
225 if ( pNormalizedItem )
226 {
227 _rScriptSetItem.GetItemSet().Put( pNormalizedItem->CloneSetWhich(nNormalizedWhichId) );
228 }
229 else
230 _rScriptSetItem.GetItemSet().InvalidateItem( nNormalizedWhichId );
231 }
232
233
234 void RichTextControlImpl::implCheckUpdateCache( AttributeId _nAttribute, const AttributeState& _rState )
235 {
236 StateCache::iterator aCachePos = m_aLastKnownStates.find( _nAttribute );
237 if ( aCachePos == m_aLastKnownStates.end() )
238 { // nothing known about this attribute, yet
239 m_aLastKnownStates.emplace( _nAttribute, _rState );
240 }
241 else
242 {
243 if ( aCachePos->second == _rState )
244 {
245 // nothing to do
246 return;
247 }
248 aCachePos->second = _rState;
249 }
250
251 // is there a dedicated listener for this particular attribute?
252 AttributeListenerPool::const_iterator aListenerPos = m_aAttributeListeners.find( _nAttribute );
253 if ( aListenerPos != m_aAttributeListeners.end( ) )
254 aListenerPos->second->onAttributeStateChanged( _nAttribute );
255
256 // call our global listener, if there is one
257 if ( m_pTextAttrListener )
258 m_pTextAttrListener->onAttributeStateChanged( _nAttribute );
259 }
260
261
262 SvtScriptType RichTextControlImpl::getSelectedScriptType() const
263 {
264 SvtScriptType nScript = m_pView->GetSelectedScriptType();
265 if ( nScript == SvtScriptType::NONE )
266 nScript = SvtLanguageOptions::GetScriptTypeOfLanguage( Application::GetSettings().GetLanguageTag().getLanguageType() );
267 return nScript;
268 }
269
270
271 void RichTextControlImpl::EditEngineStatusChanged( const EditStatus& _rStatus )
272 {
273 EditStatusFlags nStatusWord( _rStatus.GetStatusWord() );
274 if ( ( nStatusWord & EditStatusFlags::TEXTWIDTHCHANGED )
275 || ( nStatusWord & EditStatusFlags::TextHeightChanged )
276 )
277 {
278 if ( ( nStatusWord & EditStatusFlags::TextHeightChanged ) && windowHasAutomaticLineBreak() )
279 m_pEngine->SetPaperSize( Size( m_pEngine->GetPaperSize().Width(), m_pEngine->GetTextHeight() ) );
280
281 updateScrollbars();
282 }
283
284 bool bHScroll = bool( nStatusWord & EditStatusFlags::HSCROLL );
285 bool bVScroll = bool( nStatusWord & EditStatusFlags::VSCROLL );
286
287 // In case of *no* automatic line breaks, we also need to check for the *range* here.
288 // Normally, we would do this only after an EditStatusFlags::TEXTWIDTHCHANGED. However, due to a bug
289 // in the EditEngine (I believe so) this is not fired when the engine does not have
290 // the AutoPaperSize bits set.
291 // So in order to be properly notified, we would need the AutoPaperSize. But, with
292 // AutoPaperSize, other things do not work anymore: Either, when we set a MaxAutoPaperSize,
293 // then the view does automatic soft line breaks at the paper end - which we definitely do
294 // want. Or, if we did not set a MaxAutoPaperSize, then the view does not automatically scroll
295 // anymore in horizontal direction.
296 // So this is some kind of lose-lose situation ... :(
297 if ( !windowHasAutomaticLineBreak() && bHScroll )
298 {
299 updateScrollbars();
300 return;
301 }
302
303 if ( bHScroll && m_pHScroll )
304 m_pHScroll->SetThumbPos( m_pView->GetVisArea().Left() );
305 if ( bVScroll && m_pVScroll )
306 m_pVScroll->SetThumbPos( m_pView->GetVisArea().Top() );
307 }
308
309
310 IMPL_LINK_NOARG( RichTextControlImpl, OnInvalidateAllAttributes, LinkParamNone*, void )void RichTextControlImpl::LinkStubOnInvalidateAllAttributes(void
* instance, LinkParamNone* data) { return static_cast<RichTextControlImpl
*>(instance)->OnInvalidateAllAttributes(data); } void RichTextControlImpl
::OnInvalidateAllAttributes(__attribute__ ((unused)) LinkParamNone
*)
311 {
312 updateAllAttributes();
313 }
314
315
316 IMPL_LINK( RichTextControlImpl, OnHScroll, ScrollBar*, _pScrollbar, void )void RichTextControlImpl::LinkStubOnHScroll(void * instance, ScrollBar
* data) { return static_cast<RichTextControlImpl *>(instance
)->OnHScroll(data); } void RichTextControlImpl::OnHScroll(
ScrollBar* _pScrollbar)
317 {
318 m_pView->Scroll( -_pScrollbar->GetDelta(), 0, ScrollRangeCheck::PaperWidthTextSize );
319 }
320
321
322 IMPL_LINK( RichTextControlImpl, OnVScroll, ScrollBar*, _pScrollbar, void )void RichTextControlImpl::LinkStubOnVScroll(void * instance, ScrollBar
* data) { return static_cast<RichTextControlImpl *>(instance
)->OnVScroll(data); } void RichTextControlImpl::OnVScroll(
ScrollBar* _pScrollbar)
323 {
324 m_pView->Scroll( 0, -_pScrollbar->GetDelta(), ScrollRangeCheck::PaperWidthTextSize );
325 }
326
327
328 void RichTextControlImpl::ensureScrollbars()
329 {
330 bool bNeedVScroll = 0 != ( m_pAntiImpl->GetStyle() & WB_VSCROLL );
331 bool bNeedHScroll = 0 != ( m_pAntiImpl->GetStyle() & WB_HSCROLL );
332
333 if ( ( bNeedVScroll == hasVScrollBar() ) && ( bNeedHScroll == hasHScrollBar( ) ) )
334 // nothing to do
335 return;
336
337 // create or delete the scrollbars, as necessary
338 if ( !bNeedVScroll )
339 {
340 m_pVScroll.disposeAndClear();
341 }
342 else
343 {
344 m_pVScroll = VclPtr<ScrollBar>::Create( m_pAntiImpl, WB_VSCROLL | WB_DRAG | WB_REPEAT );
345 m_pVScroll->SetScrollHdl ( LINK( this, RichTextControlImpl, OnVScroll )::tools::detail::makeLink( ::tools::detail::castTo<RichTextControlImpl
*>(this), &RichTextControlImpl::LinkStubOnVScroll)
);
346 m_pVScroll->Show();
347 }
348
349 if ( !bNeedHScroll )
350 {
351 m_pHScroll.disposeAndClear();
352 }
353 else
354 {
355 m_pHScroll = VclPtr<ScrollBar>::Create( m_pAntiImpl, WB_HSCROLL | WB_DRAG | WB_REPEAT );
356 m_pHScroll->SetScrollHdl ( LINK( this, RichTextControlImpl, OnHScroll )::tools::detail::makeLink( ::tools::detail::castTo<RichTextControlImpl
*>(this), &RichTextControlImpl::LinkStubOnHScroll)
);
357 m_pHScroll->Show();
358 }
359
360 if ( m_pHScroll && m_pVScroll )
361 {
362 m_pScrollCorner.disposeAndClear();
363 m_pScrollCorner = VclPtr<ScrollBarBox>::Create( m_pAntiImpl );
364 m_pScrollCorner->Show();
365 }
366 else
367 {
368 m_pScrollCorner.disposeAndClear();
369 }
370
371 layoutWindow();
372 }
373
374
375 void RichTextControlImpl::ensureLineBreakSetting()
376 {
377 if ( !windowHasAutomaticLineBreak() )
378 m_pEngine->SetPaperSize( Size( EMPTY_PAPER_SIZE0x7FFFFFFF, EMPTY_PAPER_SIZE0x7FFFFFFF ) );
379
380 layoutWindow();
381 }
382
383
384 void RichTextControlImpl::layoutWindow()
385 {
386 if ( !m_bHasEverBeenShown )
387 // no need to do anything. Especially, no need to set the paper size on the
388 // EditEngine to anything...
389 return;
390
391 const StyleSettings& rStyleSettings = m_pAntiImpl->GetSettings().GetStyleSettings();
392
393 long nScrollBarWidth = m_pVScroll ? rStyleSettings.GetScrollBarSize() : 0;
394 long nScrollBarHeight = m_pHScroll ? rStyleSettings.GetScrollBarSize() : 0;
395
396 if ( m_pAntiImpl->IsZoom() )
397 {
398 nScrollBarWidth = m_pAntiImpl->CalcZoom( nScrollBarWidth );
399 nScrollBarHeight = m_pAntiImpl->CalcZoom( nScrollBarHeight );
400 }
401
402 // the overall size we can use
403 Size aPlaygroundSizePixel( m_pAntiImpl->GetOutputSizePixel() );
404
405 // the size of the viewport - note that the viewport does *not* occupy all the place
406 // which is left when subtracting the scrollbar width/height
407 Size aViewportPlaygroundPixel( aPlaygroundSizePixel );
408 aViewportPlaygroundPixel.setWidth( ::std::max( long( 10 ), long( aViewportPlaygroundPixel.Width() - nScrollBarWidth ) ) );
409 aViewportPlaygroundPixel.setHeight( ::std::max( long( 10 ), long( aViewportPlaygroundPixel.Height() - nScrollBarHeight ) ) );
410 Size aViewportPlaygroundLogic( m_pViewport->PixelToLogic( aViewportPlaygroundPixel ) );
411
412 const long nOffset = 2;
413 Size aViewportSizePixel( aViewportPlaygroundPixel.Width() - 2 * nOffset, aViewportPlaygroundPixel.Height() - 2 * nOffset );
414 Size aViewportSizeLogic( m_pViewport->PixelToLogic( aViewportSizePixel ) );
415
416 // position the viewport
417 m_pViewport->SetPosSizePixel( Point( nOffset, nOffset ), aViewportSizePixel );
418 // position the scrollbars
419 if ( m_pVScroll )
420 m_pVScroll->SetPosSizePixel( Point( aViewportPlaygroundPixel.Width(), 0 ), Size( nScrollBarWidth, aViewportPlaygroundPixel.Height() ) );
421 if ( m_pHScroll )
422 m_pHScroll->SetPosSizePixel( Point( 0, aViewportPlaygroundPixel.Height() ), Size( aViewportPlaygroundPixel.Width(), nScrollBarHeight ) );
423 if ( m_pScrollCorner )
424 m_pScrollCorner->SetPosSizePixel( Point( aViewportPlaygroundPixel.Width(), aViewportPlaygroundPixel.Height() ), Size( nScrollBarWidth, nScrollBarHeight ) );
425
426 // paper size
427 if ( windowHasAutomaticLineBreak() )
428 m_pEngine->SetPaperSize( Size( aViewportSizeLogic.Width(), m_pEngine->GetTextHeight() ) );
429
430 // output area of the view
431 m_pView->SetOutputArea( tools::Rectangle( Point( ), aViewportSizeLogic ) );
432 m_pView->SetVisArea( tools::Rectangle( Point( ), aViewportSizeLogic ) );
433
434 if ( m_pVScroll )
435 {
436 m_pVScroll->SetVisibleSize( aViewportPlaygroundLogic.Height() );
437
438 // the default height of a text line...
439 long nFontHeight = m_pEngine->GetStandardFont(0).GetFontSize().Height();
440 // ... is the scroll size for the vertical scrollbar
441 m_pVScroll->SetLineSize( nFontHeight );
442 // the viewport width, minus one line, is the page scroll size
443 m_pVScroll->SetPageSize( ::std::max( nFontHeight, aViewportPlaygroundLogic.Height() - nFontHeight ) );
444 }
445
446 // the font width
447 if ( m_pHScroll )
448 {
449 m_pHScroll->SetVisibleSize( aViewportPlaygroundLogic.Width() );
450
451 long nFontWidth = m_pEngine->GetStandardFont(0).GetFontSize().Width();
452 if ( !nFontWidth )
453 {
454 m_pViewport->Push( PushFlags::FONT );
455 m_pViewport->SetFont( m_pEngine->GetStandardFont(0) );
456 nFontWidth = m_pViewport->GetTextWidth( "x" );
457 m_pViewport->Pop();
458 }
459 // ... is the scroll size for the horizontal scrollbar
460 m_pHScroll->SetLineSize( 5 * nFontWidth );
461 // the viewport height, minus one character, is the page scroll size
462 m_pHScroll->SetPageSize( ::std::max( nFontWidth, aViewportPlaygroundLogic.Width() - nFontWidth ) );
463 }
464
465 // update range and position of the scrollbars
466 updateScrollbars();
467 }
468
469
470 void RichTextControlImpl::updateScrollbars()
471 {
472 if ( m_pVScroll )
473 {
474 long nOverallTextHeight = m_pEngine->GetTextHeight();
475 m_pVScroll->SetRange( Range( 0, nOverallTextHeight ) );
476 m_pVScroll->SetThumbPos( m_pView->GetVisArea().Top() );
477 }
478
479 if ( m_pHScroll )
480 {
481 Size aPaperSize( m_pEngine->GetPaperSize() );
482 long nOverallTextWidth = ( aPaperSize.Width() == EMPTY_PAPER_SIZE0x7FFFFFFF ) ? m_pEngine->CalcTextWidth() : aPaperSize.Width();
483 m_pHScroll->SetRange( Range( 0, nOverallTextWidth ) );
484 m_pHScroll->SetThumbPos( m_pView->GetVisArea().Left() );
485 }
486 }
487
488
489 void RichTextControlImpl::notifyInitShow()
490 {
491 if ( !m_bHasEverBeenShown )
492 {
493 m_bHasEverBeenShown = true;
494 layoutWindow();
495 }
496 }
497
498
499 void RichTextControlImpl::notifyStyleChanged()
500 {
501 ensureScrollbars();
502 ensureLineBreakSetting();
503 }
504
505
506 void RichTextControlImpl::notifyZoomChanged()
507 {
508 const Fraction& rZoom = m_pAntiImpl->GetZoom();
509
510 MapMode aMapMode( m_pAntiImpl->GetMapMode() );
511 aMapMode.SetScaleX( rZoom );
512 aMapMode.SetScaleY( rZoom );
513 m_pAntiImpl->SetMapMode( aMapMode );
514
515 m_pViewport->SetZoom( rZoom );
516 m_pViewport->SetMapMode( aMapMode );
517
518 layoutWindow();
519 }
520
521
522 bool RichTextControlImpl::windowHasAutomaticLineBreak()
523 {
524 return ( m_pAntiImpl->GetStyle() & WB_WORDBREAK ) != 0;
525 }
526
527
528 void RichTextControlImpl::SetReadOnly( bool _bReadOnly )
529 {
530 m_pView->SetReadOnly( _bReadOnly );
531 }
532
533
534 bool RichTextControlImpl::IsReadOnly() const
535 {
536 return m_pView->IsReadOnly( );
537 }
538
539
540 namespace
541 {
542 void lcl_inflate( tools::Rectangle& _rRect, long _nInflateX, long _nInflateY )
543 {
544 _rRect.AdjustLeft( -_nInflateX );
545 _rRect.AdjustRight(_nInflateX );
546 _rRect.AdjustTop( -_nInflateY );
547 _rRect.AdjustBottom(_nInflateY );
548 }
549 }
550
551 bool RichTextControlImpl::HandleCommand( const CommandEvent& _rEvent )
552 {
553 if ( ( _rEvent.GetCommand() == CommandEventId::Wheel )
554 || ( _rEvent.GetCommand() == CommandEventId::StartAutoScroll )
555 || ( _rEvent.GetCommand() == CommandEventId::AutoScroll )
556 )
557 {
558 m_pAntiImpl->HandleScrollCommand( _rEvent, m_pHScroll, m_pVScroll );
559 return true;
560 }
561 return false;
562 }
563
564
565 void RichTextControlImpl::Draw( OutputDevice* _pDev, const Point& _rPos, const Size& _rSize )
566 {
567 // need to normalize the map mode of the device - every paint operation on any device needs
568 // to use the same map mode
569 _pDev->Push( PushFlags::MAPMODE | PushFlags::LINECOLOR | PushFlags::FILLCOLOR );
570
571 // enforce our "normalize map mode" on the device
572 MapMode aRefMapMode( m_pEngine->GetRefDevice()->GetMapMode() );
573 MapMode aOriginalMapMode( _pDev->GetMapMode() );
574 MapMode aNormalizedMapMode( aRefMapMode.GetMapUnit(), aRefMapMode.GetOrigin(), aOriginalMapMode.GetScaleX(), aOriginalMapMode.GetScaleY() );
575 _pDev->SetMapMode( aNormalizedMapMode );
576
577 // translate coordinates
578 Point aPos( _rPos );
579 Size aSize( _rSize );
580 if ( aOriginalMapMode.GetMapUnit() == MapUnit::MapPixel )
581 {
582 aPos = _pDev->PixelToLogic( _rPos, aNormalizedMapMode );
583 aSize = _pDev->PixelToLogic( _rSize, aNormalizedMapMode );
584 }
585 else
586 {
587 aPos = OutputDevice::LogicToLogic( _rPos, aOriginalMapMode, aNormalizedMapMode );
588 aSize = OutputDevice::LogicToLogic( _rSize, aOriginalMapMode, aNormalizedMapMode );
589 }
590
591 tools::Rectangle aPlayground( aPos, aSize );
592 Size aOnePixel( _pDev->PixelToLogic( Size( 1, 1 ) ) );
593 aPlayground.AdjustRight( -(aOnePixel.Width()) );
594 aPlayground.AdjustBottom( -(aOnePixel.Height()) );
595
596 // background
597 _pDev->SetLineColor();
598 _pDev->DrawRect( aPlayground );
599
600 // do we need to draw a border?
601 bool bBorder = ( m_pAntiImpl->GetStyle() & WB_BORDER );
602 if ( bBorder )
603 _pDev->SetLineColor( m_pAntiImpl->GetSettings().GetStyleSettings().GetMonoColor() );
604 else
605 _pDev->SetLineColor();
606 _pDev->SetFillColor( m_pAntiImpl->GetBackground().GetColor() );
607 _pDev->DrawRect( aPlayground );
608
609 if ( bBorder )
610 // don't draw the text over the border
611 lcl_inflate( aPlayground, -aOnePixel.Width(), -aOnePixel.Height() );
612
613 // leave a space of two pixels between the "surroundings" of the control
614 // and the content
615 lcl_inflate( aPlayground, -aOnePixel.Width(), -aOnePixel.Height() );
616 lcl_inflate( aPlayground, -aOnePixel.Width(), -aOnePixel.Height() );
617
618 // actually draw the content
619 m_pEngine->Draw( _pDev, aPlayground, Point(), true );
620
621 _pDev->Pop();
622 }
623
624
625 void RichTextControlImpl::SetBackgroundColor( )
626 {
627 SetBackgroundColor( Application::GetSettings().GetStyleSettings().GetFieldColor() );
628 }
629
630
631 void RichTextControlImpl::SetBackgroundColor( const Color& _rColor )
632 {
633 Wallpaper aWallpaper( _rColor );
634 m_pAntiImpl->SetBackground( aWallpaper );
635 m_pViewport->SetBackground( aWallpaper );
636 }
637
638
639 void RichTextControlImpl::SetHideInactiveSelection( bool _bHide )
640 {
641 m_pViewport->SetHideInactiveSelection( _bHide );
642 }
643
644
645 bool RichTextControlImpl::GetHideInactiveSelection() const
646 {
647 return m_pViewport->GetHideInactiveSelection( );
648 }
649
650
651} // namespace frm
652
653
654/* 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<ScrollBarBox>'
5
Returning from copy constructor for 'Reference<ScrollBarBox>'
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