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 viewfun4.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/view/viewfun4.cxx

/home/maarten/src/libreoffice/core/sc/source/ui/view/viewfun4.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 <config_features.h>
21
22#include <memory>
23#include <editeng/eeitem.hxx>
24
25#include <editeng/editobj.hxx>
26#include <editeng/editstat.hxx>
27#include <editeng/editview.hxx>
28#include <editeng/flditem.hxx>
29#include <sot/storage.hxx>
30#include <svx/hlnkitem.hxx>
31#include <editeng/unolingu.hxx>
32
33#include <sfx2/bindings.hxx>
34#include <sfx2/dispatch.hxx>
35#include <sfx2/docfile.hxx>
36#include <sfx2/docfilt.hxx>
37#include <sfx2/fcontnr.hxx>
38#include <svtools/langtab.hxx>
39#include <vcl/graphicfilter.hxx>
40#include <svl/stritem.hxx>
41#include <vcl/transfer.hxx>
42#include <svl/urlbmk.hxx>
43#include <svl/sharedstringpool.hxx>
44#include <vcl/svapp.hxx>
45#include <vcl/weld.hxx>
46#include <avmedia/mediawindow.hxx>
47
48#include <comphelper/storagehelper.hxx>
49
50#include <viewfunc.hxx>
51#include <docsh.hxx>
52#include <document.hxx>
53#include <globstr.hrc>
54#include <global.hxx>
55#include <scresid.hxx>
56#include <undoblk.hxx>
57#include <undocell.hxx>
58#include <formulacell.hxx>
59#include <scmod.hxx>
60#include <spelleng.hxx>
61#include <patattr.hxx>
62#include <sc.hrc>
63#include <tabvwsh.hxx>
64#include <impex.hxx>
65#include <editutil.hxx>
66#include <editable.hxx>
67#include <dociter.hxx>
68#include <reffind.hxx>
69#include <compiler.hxx>
70#include <tokenarray.hxx>
71#include <refupdatecontext.hxx>
72#include <gridwin.hxx>
73#include <refundo.hxx>
74
75using namespace com::sun::star;
76
77void ScViewFunc::PasteRTF( SCCOL nStartCol, SCROW nStartRow,
78 const css::uno::Reference< css::datatransfer::XTransferable >& rxTransferable )
79{
80 TransferableDataHelper aDataHelper( rxTransferable );
81 if ( aDataHelper.HasFormat( SotClipboardFormatId::EDITENGINE_ODF_TEXT_FLAT ) )
1
Assuming the condition is true
2
Taking true branch
82 {
83 HideAllCursors();
84
85 ScDocShell* pDocSh = GetViewData().GetDocShell();
86 ScDocument& rDoc = pDocSh->GetDocument();
87 SCTAB nTab = GetViewData().GetTabNo();
88 const bool bRecord (rDoc.IsUndoEnabled());
89
90 const ScPatternAttr* pPattern = rDoc.GetPattern( nStartCol, nStartRow, nTab );
91 std::unique_ptr<ScTabEditEngine> pEngine(new ScTabEditEngine( *pPattern, rDoc.GetEnginePool(), &rDoc ));
92 pEngine->EnableUndo( false );
93
94 vcl::Window* pActWin = GetActiveWin();
95 if (pActWin)
3
Assuming 'pActWin' is non-null
4
Taking true branch
96 {
97 pEngine->SetPaperSize(Size(100000,100000));
98 ScopedVclPtrInstance< vcl::Window > aWin( pActWin );
5
Calling constructor for 'ScopedVclPtrInstance<vcl::Window>'
7
Returning from constructor for 'ScopedVclPtrInstance<vcl::Window>'
99 EditView aEditView( pEngine.get(), aWin.get() );
100 aEditView.SetOutputArea(tools::Rectangle(0,0,100000,100000));
101
102 // same method now for clipboard or drag&drop
103 // mba: clipboard always must contain absolute URLs (could be from alien source)
104 aEditView.InsertText( rxTransferable, OUString(), true );
105 }
8
Calling implicit destructor for 'ScopedVclPtrInstance<vcl::Window>'
9
Calling '~ScopedVclPtr'
106
107 sal_Int32 nParCnt = pEngine->GetParagraphCount();
108 if (nParCnt)
109 {
110 SCROW nEndRow = nStartRow + static_cast<SCROW>(nParCnt) - 1;
111 if (nEndRow > rDoc.MaxRow())
112 nEndRow = rDoc.MaxRow();
113
114 ScDocumentUniquePtr pUndoDoc;
115 if (bRecord)
116 {
117 pUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
118 pUndoDoc->InitUndo( rDoc, nTab, nTab );
119 rDoc.CopyToDocument( nStartCol,nStartRow,nTab, nStartCol,nEndRow,nTab, InsertDeleteFlags::ALL, false, *pUndoDoc );
120 }
121
122 SCROW nRow = nStartRow;
123
124 // Temporarily turn off undo generation for this lot
125 bool bUndoEnabled = rDoc.IsUndoEnabled();
126 rDoc.EnableUndo( false );
127 for( sal_Int32 n = 0; n < nParCnt; n++ )
128 {
129 std::unique_ptr<EditTextObject> pObject(pEngine->CreateTextObject(n));
130 EnterData(nStartCol, nRow, nTab, *pObject, true);
131 if( ++nRow > rDoc.MaxRow() )
132 break;
133 }
134 rDoc.EnableUndo(bUndoEnabled);
135
136 if (bRecord)
137 {
138 ScDocumentUniquePtr pRedoDoc(new ScDocument( SCDOCMODE_UNDO ));
139 pRedoDoc->InitUndo( rDoc, nTab, nTab );
140 rDoc.CopyToDocument( nStartCol,nStartRow,nTab, nStartCol,nEndRow,nTab, InsertDeleteFlags::ALL|InsertDeleteFlags::NOCAPTIONS, false, *pRedoDoc );
141
142 ScRange aMarkRange(nStartCol, nStartRow, nTab, nStartCol, nEndRow, nTab);
143 ScMarkData aDestMark(rDoc.GetSheetLimits());
144 aDestMark.SetMarkArea( aMarkRange );
145 pDocSh->GetUndoManager()->AddUndoAction(
146 std::make_unique<ScUndoPaste>( pDocSh, aMarkRange, aDestMark,
147 std::move(pUndoDoc), std::move(pRedoDoc), InsertDeleteFlags::ALL, nullptr));
148 }
149 }
150
151 pEngine.reset();
152
153 ShowAllCursors();
154 }
155 else
156 {
157 HideAllCursors();
158 ScDocShell* pDocSh = GetViewData().GetDocShell();
159 ScImportExport aImpEx( pDocSh->GetDocument(),
160 ScAddress( nStartCol, nStartRow, GetViewData().GetTabNo() ) );
161
162 OUString aStr;
163 tools::SvRef<SotStorageStream> xStream;
164 if ( aDataHelper.GetSotStorageStream( SotClipboardFormatId::RTF, xStream ) && xStream.is() )
165 // mba: clipboard always must contain absolute URLs (could be from alien source)
166 aImpEx.ImportStream( *xStream, OUString(), SotClipboardFormatId::RTF );
167 else if ( aDataHelper.GetString( SotClipboardFormatId::RTF, aStr ) )
168 aImpEx.ImportString( aStr, SotClipboardFormatId::RTF );
169 else if ( aDataHelper.GetSotStorageStream( SotClipboardFormatId::RICHTEXT, xStream ) && xStream.is() )
170 aImpEx.ImportStream( *xStream, OUString(), SotClipboardFormatId::RICHTEXT );
171 else if ( aDataHelper.GetString( SotClipboardFormatId::RICHTEXT, aStr ) )
172 aImpEx.ImportString( aStr, SotClipboardFormatId::RICHTEXT );
173
174 AdjustRowHeight( nStartRow, aImpEx.GetRange().aEnd.Row() );
175 pDocSh->UpdateOle(GetViewData());
176 ShowAllCursors();
177 }
178}
179void ScViewFunc::DoRefConversion()
180{
181 ScDocument& rDoc = GetViewData().GetDocument();
182 ScMarkData& rMark = GetViewData().GetMarkData();
183 SCTAB nTabCount = rDoc.GetTableCount();
184 bool bRecord = true;
185 if (!rDoc.IsUndoEnabled())
186 bRecord = false;
187
188 ScRange aMarkRange;
189 rMark.MarkToSimple();
190 bool bMulti = rMark.IsMultiMarked();
191 if (bMulti)
192 rMark.GetMultiMarkArea( aMarkRange );
193 else if (rMark.IsMarked())
194 rMark.GetMarkArea( aMarkRange );
195 else
196 {
197 aMarkRange = ScRange( GetViewData().GetCurX(),
198 GetViewData().GetCurY(), GetViewData().GetTabNo() );
199 }
200 ScEditableTester aTester( rDoc, aMarkRange.aStart.Col(), aMarkRange.aStart.Row(),
201 aMarkRange.aEnd.Col(), aMarkRange.aEnd.Row(),rMark );
202 if (!aTester.IsEditable())
203 {
204 ErrorMessage(aTester.GetMessageId());
205 return;
206 }
207
208 ScDocShell* pDocSh = GetViewData().GetDocShell();
209 bool bOk = false;
210
211 ScDocumentUniquePtr pUndoDoc;
212 if (bRecord)
213 {
214 pUndoDoc.reset( new ScDocument( SCDOCMODE_UNDO ) );
215 SCTAB nTab = aMarkRange.aStart.Tab();
216 pUndoDoc->InitUndo( rDoc, nTab, nTab );
217
218 if ( rMark.GetSelectCount() > 1 )
219 {
220 for (const auto& rTab : rMark)
221 if ( rTab != nTab )
222 pUndoDoc->AddUndoTab( rTab, rTab );
223 }
224 ScRange aCopyRange = aMarkRange;
225 aCopyRange.aStart.SetTab(0);
226 aCopyRange.aEnd.SetTab(nTabCount-1);
227 rDoc.CopyToDocument( aCopyRange, InsertDeleteFlags::ALL, bMulti, *pUndoDoc, &rMark );
228 }
229
230 ScRangeListRef xRanges;
231 GetViewData().GetMultiArea( xRanges );
232 size_t nCount = xRanges->size();
233
234 for (const SCTAB& i : rMark)
235 {
236 for (size_t j = 0; j < nCount; ++j)
237 {
238 ScRange aRange = (*xRanges)[j];
239 aRange.aStart.SetTab(i);
240 aRange.aEnd.SetTab(i);
241 ScCellIterator aIter( rDoc, aRange );
242 for (bool bHas = aIter.first(); bHas; bHas = aIter.next())
243 {
244 if (aIter.getType() != CELLTYPE_FORMULA)
245 continue;
246
247 ScFormulaCell* pCell = aIter.getFormulaCell();
248 ScMatrixMode eMatrixMode = pCell->GetMatrixFlag();
249 if (eMatrixMode == ScMatrixMode::Reference)
250 continue;
251
252 OUString aOld;
253 pCell->GetFormula(aOld);
254 sal_Int32 nLen = aOld.getLength();
255 if (eMatrixMode == ScMatrixMode::Formula)
256 {
257 assert(nLen >= 2 && aOld[0] == '{' && aOld[nLen-1] == '}')(static_cast <bool> (nLen >= 2 && aOld[0] ==
'{' && aOld[nLen-1] == '}') ? void (0) : __assert_fail
("nLen >= 2 && aOld[0] == '{' && aOld[nLen-1] == '}'"
, "/home/maarten/src/libreoffice/core/sc/source/ui/view/viewfun4.cxx"
, 257, __extension__ __PRETTY_FUNCTION__))
;
258 nLen -= 2;
259 aOld = aOld.copy( 1, nLen);
260 }
261 ScRefFinder aFinder( aOld, aIter.GetPos(), rDoc, rDoc.GetAddressConvention() );
262 aFinder.ToggleRel( 0, nLen );
263 if (aFinder.GetFound())
264 {
265 ScAddress aPos = pCell->aPos;
266 const OUString& aNew = aFinder.GetText();
267 ScCompiler aComp( rDoc, aPos, rDoc.GetGrammar());
268 std::unique_ptr<ScTokenArray> pArr(aComp.CompileString(aNew));
269 ScFormulaCell* pNewCell =
270 new ScFormulaCell(
271 rDoc, aPos, *pArr, formula::FormulaGrammar::GRAM_DEFAULT, eMatrixMode);
272
273 rDoc.SetFormulaCell(aPos, pNewCell);
274 bOk = true;
275 }
276 }
277 }
278 }
279 if (bRecord)
280 {
281 ScDocumentUniquePtr pRedoDoc(new ScDocument( SCDOCMODE_UNDO ));
282 SCTAB nTab = aMarkRange.aStart.Tab();
283 pRedoDoc->InitUndo( rDoc, nTab, nTab );
284
285 if ( rMark.GetSelectCount() > 1 )
286 {
287 for (const auto& rTab : rMark)
288 if ( rTab != nTab )
289 pRedoDoc->AddUndoTab( rTab, rTab );
290 }
291 ScRange aCopyRange = aMarkRange;
292 aCopyRange.aStart.SetTab(0);
293 aCopyRange.aEnd.SetTab(nTabCount-1);
294 rDoc.CopyToDocument( aCopyRange, InsertDeleteFlags::ALL, bMulti, *pRedoDoc, &rMark );
295
296 pDocSh->GetUndoManager()->AddUndoAction(
297 std::make_unique<ScUndoRefConversion>( pDocSh,
298 aMarkRange, rMark, std::move(pUndoDoc), std::move(pRedoDoc), bMulti) );
299 }
300
301 pDocSh->PostPaint( aMarkRange, PaintPartFlags::Grid );
302 pDocSh->UpdateOle(GetViewData());
303 pDocSh->SetDocumentModified();
304 CellContentChanged();
305
306 if (!bOk)
307 ErrorMessage(STR_ERR_NOREFreinterpret_cast<char const *>("STR_ERR_NOREF" "\004" u8"No cell references are found in the selected cells."
)
);
308}
309// Thesaurus - Undo ok
310void ScViewFunc::DoThesaurus()
311{
312 SCCOL nCol;
313 SCROW nRow;
314 SCTAB nTab;
315 ScDocShell* pDocSh = GetViewData().GetDocShell();
316 ScDocument& rDoc = pDocSh->GetDocument();
317 ScMarkData& rMark = GetViewData().GetMarkData();
318 ScSplitPos eWhich = GetViewData().GetActivePart();
319 EESpellState eState;
320 EditView* pEditView = nullptr;
321 std::unique_ptr<ESelection> pEditSel;
322 std::unique_ptr<ScEditEngineDefaulter> pThesaurusEngine;
323 bool bIsEditMode = GetViewData().HasEditView(eWhich);
324 bool bRecord = true;
325 if (!rDoc.IsUndoEnabled())
326 bRecord = false;
327 if (bIsEditMode) // edit mode active
328 {
329 GetViewData().GetEditView(eWhich, pEditView, nCol, nRow);
330 pEditSel.reset(new ESelection(pEditView->GetSelection()));
331 SC_MOD()( static_cast<ScModule*>(SfxApplication::GetModule(SfxToolsModule
::Calc)) )
->InputEnterHandler();
332 GetViewData().GetBindings().Update(); // otherwise the Sfx becomes mixed-up...
333 }
334 else
335 {
336 nCol = GetViewData().GetCurX();
337 nRow = GetViewData().GetCurY();
338 }
339 nTab = GetViewData().GetTabNo();
340
341 ScAddress aPos(nCol, nRow, nTab);
342 ScEditableTester aTester( rDoc, nCol, nRow, nCol, nRow, rMark );
343 if (!aTester.IsEditable())
344 {
345 ErrorMessage(aTester.GetMessageId());
346 return;
347 }
348
349 ScCellValue aOldText;
350 aOldText.assign(rDoc, aPos);
351 if (aOldText.meType != CELLTYPE_STRING && aOldText.meType != CELLTYPE_EDIT)
352 {
353 ErrorMessage(STR_THESAURUS_NO_STRINGreinterpret_cast<char const *>("STR_THESAURUS_NO_STRING"
"\004" u8"Thesaurus can only be used in text cells!")
);
354 return;
355 }
356
357 uno::Reference<linguistic2::XSpellChecker1> xSpeller = LinguMgr::GetSpellChecker();
358
359 pThesaurusEngine.reset(new ScEditEngineDefaulter(rDoc.GetEnginePool()));
360 pThesaurusEngine->SetEditTextObjectPool( rDoc.GetEditPool() );
361 pThesaurusEngine->SetRefDevice(GetViewData().GetActiveWin());
362 pThesaurusEngine->SetSpeller(xSpeller);
363 MakeEditView(pThesaurusEngine.get(), nCol, nRow );
364 std::unique_ptr<SfxItemSet> pEditDefaults(
365 new SfxItemSet(pThesaurusEngine->GetEmptyItemSet()));
366 const ScPatternAttr* pPattern = rDoc.GetPattern(nCol, nRow, nTab);
367 if (pPattern)
368 {
369 pPattern->FillEditItemSet( pEditDefaults.get() );
370 pThesaurusEngine->SetDefaults( *pEditDefaults );
371 }
372
373 if (aOldText.meType == CELLTYPE_EDIT)
374 pThesaurusEngine->SetTextCurrentDefaults(*aOldText.mpEditText);
375 else
376 pThesaurusEngine->SetTextCurrentDefaults(aOldText.getString(rDoc));
377
378 pEditView = GetViewData().GetEditView(GetViewData().GetActivePart());
379 if (pEditSel)
380 pEditView->SetSelection(*pEditSel);
381 else
382 pEditView->SetSelection(ESelection(0,0,0,0));
383
384 pThesaurusEngine->ClearModifyFlag();
385
386 // language is now in EditEngine attributes -> no longer passed to StartThesaurus
387
388 eState = pEditView->StartThesaurus();
389 OSL_ENSURE(eState != EESpellState::NoSpeller, "No SpellChecker")do { if (true && (!(eState != EESpellState::NoSpeller
))) { sal_detail_logFormat((SAL_DETAIL_LOG_LEVEL_WARN), ("legacy.osl"
), ("/home/maarten/src/libreoffice/core/sc/source/ui/view/viewfun4.cxx"
":" "389" ": "), "%s", "No SpellChecker"); } } while (false)
;
390
391 if (eState == EESpellState::ErrorFound) // should happen later through Wrapper!
392 {
393 LanguageType eLnge = ScViewUtil::GetEffLanguage( rDoc, ScAddress( nCol, nRow, nTab ) );
394 OUString aErr = SvtLanguageTable::GetLanguageString(eLnge) + ScResId( STR_SPELLING_NO_LANGreinterpret_cast<char const *>("STR_SPELLING_NO_LANG" "\004"
u8"is not available for the thesaurus.\nPlease check your installation and install \nthe desired language if necessary"
)
);
395
396 std::unique_ptr<weld::MessageDialog> xInfoBox(Application::CreateMessageDialog(GetViewData().GetDialogParent(),
397 VclMessageType::Info, VclButtonsType::Ok,
398 aErr));
399 xInfoBox->run();
400 }
401 if (pThesaurusEngine->IsModified())
402 {
403 ScCellValue aNewText;
404
405 if (aOldText.meType == CELLTYPE_EDIT)
406 {
407 // The cell will own the text object instance.
408 std::unique_ptr<EditTextObject> pText = pThesaurusEngine->CreateTextObject();
409 auto tmp = pText.get();
410 if (rDoc.SetEditText(ScAddress(nCol,nRow,nTab), std::move(pText)))
411 aNewText.set(*tmp);
412 }
413 else
414 {
415 OUString aStr = pThesaurusEngine->GetText();
416 aNewText.set(rDoc.GetSharedStringPool().intern(aStr));
417 rDoc.SetString(nCol, nRow, nTab, aStr);
418 }
419
420 pDocSh->SetDocumentModified();
421 if (bRecord)
422 {
423 GetViewData().GetDocShell()->GetUndoManager()->AddUndoAction(
424 std::make_unique<ScUndoThesaurus>(
425 GetViewData().GetDocShell(), nCol, nRow, nTab, aOldText, aNewText));
426 }
427 }
428
429 KillEditView(true);
430 pDocSh->PostPaintGridAll();
431}
432
433void ScViewFunc::DoHangulHanjaConversion()
434{
435 ScConversionParam aConvParam( SC_CONVERSION_HANGULHANJA, LANGUAGE_KOREANLanguageType(0x0412), 0, true );
436 DoSheetConversion( aConvParam );
437}
438
439void ScViewFunc::DoSheetConversion( const ScConversionParam& rConvParam )
440{
441 SCCOL nCol;
442 SCROW nRow;
443 SCTAB nTab;
444 ScViewData& rViewData = GetViewData();
445 ScDocShell* pDocSh = rViewData.GetDocShell();
446 ScDocument& rDoc = pDocSh->GetDocument();
447 ScMarkData& rMark = rViewData.GetMarkData();
448 ScSplitPos eWhich = rViewData.GetActivePart();
449 EditView* pEditView = nullptr;
450 bool bIsEditMode = rViewData.HasEditView(eWhich);
451 bool bRecord = true;
452 if (!rDoc.IsUndoEnabled())
453 bRecord = false;
454 if (bIsEditMode) // edit mode active
455 {
456 rViewData.GetEditView(eWhich, pEditView, nCol, nRow);
457 SC_MOD()( static_cast<ScModule*>(SfxApplication::GetModule(SfxToolsModule
::Calc)) )
->InputEnterHandler();
458 }
459 else
460 {
461 nCol = rViewData.GetCurX();
462 nRow = rViewData.GetCurY();
463
464 AlignToCursor( nCol, nRow, SC_FOLLOW_JUMP);
465 }
466 nTab = rViewData.GetTabNo();
467
468 rMark.MarkToMulti();
469 bool bMarked = rMark.IsMultiMarked();
470 if (bMarked)
471 {
472 ScEditableTester aTester( rDoc, rMark );
473 if (!aTester.IsEditable())
474 {
475 ErrorMessage(aTester.GetMessageId());
476 return;
477 }
478 }
479
480 ScDocumentUniquePtr pUndoDoc;
481 ScDocumentUniquePtr pRedoDoc;
482 if (bRecord)
483 {
484 pUndoDoc.reset( new ScDocument( SCDOCMODE_UNDO ) );
485 pUndoDoc->InitUndo( rDoc, nTab, nTab );
486 pRedoDoc.reset( new ScDocument( SCDOCMODE_UNDO ) );
487 pRedoDoc->InitUndo( rDoc, nTab, nTab );
488
489 if ( rMark.GetSelectCount() > 1 )
490 {
491 for (const auto& rTab : rMark)
492 if ( rTab != nTab )
493 {
494 pUndoDoc->AddUndoTab( rTab, rTab );
495 pRedoDoc->AddUndoTab( rTab, rTab );
496 }
497 }
498 }
499
500 // from here no return
501
502 bool bOldEnabled = rDoc.IsIdleEnabled();
503 rDoc.EnableIdle(false); // stop online spelling
504
505 // *** create and init the edit engine *** --------------------------------
506
507 std::unique_ptr<ScConversionEngineBase> pEngine;
508 switch( rConvParam.GetType() )
509 {
510 case SC_CONVERSION_SPELLCHECK:
511 pEngine.reset(new ScSpellingEngine(
512 rDoc.GetEnginePool(), rViewData, pUndoDoc.get(), pRedoDoc.get(), LinguMgr::GetSpellChecker() ));
513 break;
514 case SC_CONVERSION_HANGULHANJA:
515 case SC_CONVERSION_CHINESE_TRANSL:
516 pEngine.reset(new ScTextConversionEngine(
517 rDoc.GetEnginePool(), rViewData, rConvParam, pUndoDoc.get(), pRedoDoc.get() ));
518 break;
519 default:
520 OSL_FAIL( "ScViewFunc::DoSheetConversion - unknown conversion type" )do { if (true && (((sal_Bool)1))) { sal_detail_logFormat
((SAL_DETAIL_LOG_LEVEL_WARN), ("legacy.osl"), ("/home/maarten/src/libreoffice/core/sc/source/ui/view/viewfun4.cxx"
":" "520" ": "), "%s", "ScViewFunc::DoSheetConversion - unknown conversion type"
); } } while (false)
;
521 }
522
523 MakeEditView( pEngine.get(), nCol, nRow );
524 pEngine->SetRefDevice( rViewData.GetActiveWin() );
525 // simulate dummy cell:
526 pEditView = rViewData.GetEditView( rViewData.GetActivePart() );
527 rViewData.SetSpellingView( pEditView );
528 tools::Rectangle aRect( Point( 0, 0 ), Point( 0, 0 ) );
529 pEditView->SetOutputArea( aRect );
530 pEngine->SetControlWord( EEControlBits::USECHARATTRIBS );
531 pEngine->EnableUndo( false );
532 pEngine->SetPaperSize( aRect.GetSize() );
533 pEngine->SetTextCurrentDefaults( EMPTY_OUSTRINGScGlobal::GetEmptyOUString() );
534
535 // *** do the conversion *** ----------------------------------------------
536
537 pEngine->ClearModifyFlag();
538 pEngine->ConvertAll( *pEditView );
539
540 // *** undo/redo *** ------------------------------------------------------
541
542 if( pEngine->IsAnyModified() )
543 {
544 if (bRecord)
545 {
546 SCCOL nNewCol = rViewData.GetCurX();
547 SCROW nNewRow = rViewData.GetCurY();
548 rViewData.GetDocShell()->GetUndoManager()->AddUndoAction(
549 std::make_unique<ScUndoConversion>(
550 pDocSh, rMark,
551 nCol, nRow, nTab, std::move(pUndoDoc),
552 nNewCol, nNewRow, nTab, std::move(pRedoDoc), rConvParam ) );
553 }
554
555 sc::SetFormulaDirtyContext aCxt;
556 rDoc.SetAllFormulasDirty(aCxt);
557
558 pDocSh->SetDocumentModified();
559 }
560 else
561 {
562 pUndoDoc.reset();
563 pRedoDoc.reset();
564 }
565
566 // *** final cleanup *** --------------------------------------------------
567
568 rViewData.SetSpellingView( nullptr );
569 KillEditView(true);
570 pEngine.reset();
571 pDocSh->PostPaintGridAll();
572 rViewData.GetViewShell()->UpdateInputHandler();
573 rDoc.EnableIdle(bOldEnabled);
574}
575
576// past from SotClipboardFormatId::FILE items
577// is not called directly from Drop, but asynchronously -> dialogs are allowed
578
579bool ScViewFunc::PasteFile( const Point& rPos, const OUString& rFile, bool bLink )
580{
581 INetURLObject aURL;
582 aURL.SetSmartURL( rFile );
583 OUString aStrURL = aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE );
584
585 // is it a media URL?
586#if HAVE_FEATURE_AVMEDIA1
587 if( ::avmedia::MediaWindow::isMediaURL( aStrURL, ""/*TODO?*/ ) )
588 {
589 const SfxStringItem aMediaURLItem( SID_INSERT_AVMEDIA(5000 + 1696), aStrURL );
590 return ( nullptr != GetViewData().GetDispatcher().ExecuteList(
591 SID_INSERT_AVMEDIA(5000 + 1696), SfxCallMode::SYNCHRON,
592 { &aMediaURLItem }) );
593 }
594#endif
595
596 if (!bLink) // for bLink only graphics or URL
597 {
598 // 1. can I open the file?
599 std::shared_ptr<const SfxFilter> pFlt;
600
601 // search only for its own filters, without selection box (as in ScDocumentLoader)
602 SfxFilterMatcher aMatcher( ScDocShell::Factory().GetFilterContainer()->GetName() );
603 SfxMedium aSfxMedium( aStrURL, (StreamMode::READ | StreamMode::SHARE_DENYNONE) );
604 // #i73992# GuessFilter no longer calls UseInteractionHandler.
605 // This is UI, so it can be called here.
606 aSfxMedium.UseInteractionHandler(true);
607 ErrCode nErr = aMatcher.GuessFilter( aSfxMedium, pFlt );
608
609 if ( pFlt && !nErr )
610 {
611 // code stolen from the SFX!
612 SfxDispatcher &rDispatcher = GetViewData().GetDispatcher();
613 SfxStringItem aFileNameItem( SID_FILE_NAME(5000 + 507), aStrURL );
614 SfxStringItem aFilterItem( SID_FILTER_NAME(5000 + 530), pFlt->GetName() );
615 // #i69524# add target, as in SfxApplication when the Open dialog is used
616 SfxStringItem aTargetItem( SID_TARGETNAME(5000 + 560), "_default" );
617
618 // Open Asynchronously, because it can also happen from D&D
619 // and that is not so good for the MAC...
620 return (nullptr != rDispatcher.ExecuteList(SID_OPENDOC(5000 + 501),
621 SfxCallMode::ASYNCHRON,
622 { &aFileNameItem, &aFilterItem, &aTargetItem}));
623 }
624 }
625
626 // 2. can the file be inserted using the graphics filter?
627 // (as a link, since the Gallery provides it in this way)
628
629 sal_uInt16 nFilterFormat;
630 Graphic aGraphic;
631 GraphicFilter& rGraphicFilter = GraphicFilter::GetGraphicFilter();
632
633 if (!rGraphicFilter.ImportGraphic(aGraphic, aURL,
634 GRFILTER_FORMAT_DONTKNOW(sal_uInt16(0xFFFF)), &nFilterFormat ))
635 {
636 if ( bLink )
637 {
638 OUString aFltName = rGraphicFilter.GetImportFormatName(nFilterFormat);
639 return PasteGraphic( rPos, aGraphic, aStrURL, aFltName );
640 }
641 else
642 {
643 // #i76709# if bLink isn't set, pass empty URL/filter, so a non-linked image is inserted
644 return PasteGraphic( rPos, aGraphic, EMPTY_OUSTRINGScGlobal::GetEmptyOUString(), EMPTY_OUSTRINGScGlobal::GetEmptyOUString() );
645 }
646 }
647
648 if (bLink) // for bLink everything, which is not graphics, as URL
649 {
650 tools::Rectangle aRect( rPos, Size(0,0) );
651 ScRange aRange = GetViewData().GetDocument().
652 GetRange( GetViewData().GetTabNo(), aRect );
653 SCCOL nPosX = aRange.aStart.Col();
654 SCROW nPosY = aRange.aStart.Row();
655
656 InsertBookmark( aStrURL, aStrURL, nPosX, nPosY );
657 return true;
658 }
659 else
660 {
661 // 3. can the file be inserted as OLE?
662 // also non-storages, for instance sounds (#38282#)
663 uno::Reference < embed::XStorage > xStorage = comphelper::OStorageHelper::GetTemporaryStorage();
664
665 //TODO/LATER: what about "bLink"?
666
667 uno::Sequence < beans::PropertyValue > aMedium(1);
668 aMedium[0].Name = "URL";
669 aMedium[0].Value <<= aStrURL;
670
671 comphelper::EmbeddedObjectContainer aCnt( xStorage );
672 OUString aName;
673 uno::Reference < embed::XEmbeddedObject > xObj = aCnt.InsertEmbeddedObject( aMedium, aName );
674 if( xObj.is() )
675 return PasteObject( rPos, xObj, nullptr );
676
677 // If an OLE object can't be created, insert a URL button
678
679 GetViewData().GetViewShell()->InsertURLButton( aStrURL, aStrURL, EMPTY_OUSTRINGScGlobal::GetEmptyOUString(), &rPos );
680 return true;
681 }
682}
683
684bool ScViewFunc::PasteBookmark( SotClipboardFormatId nFormatId,
685 const css::uno::Reference< css::datatransfer::XTransferable >& rxTransferable,
686 SCCOL nPosX, SCROW nPosY )
687{
688 INetBookmark aBookmark;
689 TransferableDataHelper aDataHelper( rxTransferable );
690 if ( !aDataHelper.GetINetBookmark( nFormatId, aBookmark ) )
691 return false;
692
693 InsertBookmark( aBookmark.GetDescription(), aBookmark.GetURL(), nPosX, nPosY );
694 return true;
695}
696
697void ScViewFunc::InsertBookmark( const OUString& rDescription, const OUString& rURL,
698 SCCOL nPosX, SCROW nPosY, const OUString* pTarget,
699 bool bTryReplace )
700{
701 ScViewData& rViewData = GetViewData();
702 if ( rViewData.HasEditView( rViewData.GetActivePart() ) &&
703 nPosX >= rViewData.GetEditStartCol() && nPosX <= rViewData.GetEditEndCol() &&
704 nPosY >= rViewData.GetEditStartRow() && nPosY <= rViewData.GetEditEndRow() )
705 {
706 // insert into the cell which just got edited
707
708 OUString aTargetFrame;
709 if (pTarget)
710 aTargetFrame = *pTarget;
711 rViewData.GetViewShell()->InsertURLField( rDescription, rURL, aTargetFrame );
712 return;
713 }
714
715 // insert into not edited cell
716
717 ScDocument& rDoc = GetViewData().GetDocument();
718 SCTAB nTab = GetViewData().GetTabNo();
719 ScAddress aCellPos( nPosX, nPosY, nTab );
720 EditEngine aEngine( rDoc.GetEnginePool() );
721
722 const EditTextObject* pOld = rDoc.GetEditText(aCellPos);
723 if (pOld)
724 aEngine.SetText(*pOld);
725 else
726 {
727 OUString aOld;
728 rDoc.GetInputString(nPosX, nPosY, nTab, aOld);
729 if (!aOld.isEmpty())
730 aEngine.SetText(aOld);
731 }
732
733 sal_Int32 nPara = aEngine.GetParagraphCount();
734 if (nPara)
735 --nPara;
736 sal_Int32 nTxtLen = aEngine.GetTextLen(nPara);
737 ESelection aInsSel( nPara, nTxtLen, nPara, nTxtLen );
738
739 if ( bTryReplace && HasBookmarkAtCursor( nullptr ) )
740 {
741 // if called from hyperlink slot and cell contains only a URL,
742 // replace old URL with new one
743
744 aInsSel = ESelection( 0, 0, 0, 1 ); // replace first character (field)
745 }
746
747 SvxURLField aField( rURL, rDescription, SvxURLFormat::AppDefault );
748 if (pTarget)
749 aField.SetTargetFrame(*pTarget);
750 aEngine.QuickInsertField( SvxFieldItem( aField, EE_FEATURE_FIELD ), aInsSel );
751
752 std::unique_ptr<EditTextObject> pData(aEngine.CreateTextObject());
753 EnterData(nPosX, nPosY, nTab, *pData);
754}
755
756bool ScViewFunc::HasBookmarkAtCursor( SvxHyperlinkItem* pContent )
757{
758 ScAddress aPos( GetViewData().GetCurX(), GetViewData().GetCurY(), GetViewData().GetTabNo() );
759 ScDocument& rDoc = GetViewData().GetDocShell()->GetDocument();
760
761 const EditTextObject* pData = rDoc.GetEditText(aPos);
762 if (!pData)
763 return false;
764
765 if (!pData->IsFieldObject())
766 // not a field object.
767 return false;
768
769 const SvxFieldItem* pFieldItem = pData->GetField();
770 if (!pFieldItem)
771 // doesn't have a field item.
772 return false;
773
774 const SvxFieldData* pField = pFieldItem->GetField();
775 if (!pField)
776 // doesn't have a field item data.
777 return false;
778
779 if (pField->GetClassId() != css::text::textfield::Type::URL)
780 // not a URL field.
781 return false;
782
783 if (pContent)
784 {
785 const SvxURLField* pURLField = static_cast<const SvxURLField*>(pField);
786 pContent->SetName( pURLField->GetRepresentation() );
787 pContent->SetURL( pURLField->GetURL() );
788 pContent->SetTargetFrame( pURLField->GetTargetFrame() );
789 }
790 return true;
791}
792
793/* 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);
204 m_rInnerRef.clear(); // we should use some 'swap' method ideally ;-)
11
Calling 'Reference::clear'
18
Returning; memory was released
205 if (aTmp.get()) {
19
Calling 'Reference::get'
206 aTmp->disposeOnce();
207 }
208 }
209
210 /** Needed to place VclPtr's into STL collection.
211 */
212 bool operator< (const VclPtr<reference_type> & handle) const
213 {
214 return (m_rInnerRef < handle.m_rInnerRef);
215 }
216}; // class VclPtr
217
218template<typename T1, typename T2>
219inline bool operator ==(VclPtr<T1> const & p1, VclPtr<T2> const & p2) {
220 return p1.get() == p2.get();
221}
222
223template<typename T> inline bool operator ==(VclPtr<T> const & p1, T const * p2)
224{
225 return p1.get() == p2;
226}
227
228template<typename T> inline bool operator ==(VclPtr<T> const & p1, T * p2) {
229 return p1.get() == p2;
230}
231
232template<typename T> inline bool operator ==(T const * p1, VclPtr<T> const & p2)
233{
234 return p1 == p2.get();
235}
236
237template<typename T> inline bool operator ==(T * p1, VclPtr<T> const & p2) {
238 return p1 == p2.get();
239}
240
241template<typename T1, typename T2>
242inline bool operator !=(VclPtr<T1> const & p1, VclPtr<T2> const & p2) {
243 return !(p1 == p2);
244}
245
246template<typename T> inline bool operator !=(VclPtr<T> const & p1, T const * p2)
247{
248 return !(p1 == p2);
249}
250
251template<typename T> inline bool operator !=(VclPtr<T> const & p1, T * p2) {
252 return !(p1 == p2);
253}
254
255template<typename T> inline bool operator !=(T const * p1, VclPtr<T> const & p2)
256{
257 return !(p1 == p2);
258}
259
260template<typename T> inline bool operator !=(T * p1, VclPtr<T> const & p2) {
261 return !(p1 == p2);
262}
263
264/**
265 * A construction helper for a temporary VclPtr. Since VclPtr types
266 * are created with a reference-count of one - to help fit into
267 * the existing code-flow; this helps us to construct them easily.
268 * see also VclPtr::Create and ScopedVclPtr
269 *
270 * For more details on the design please see vcl/README.lifecycle
271 *
272 * @param reference_type must be a subclass of vcl::Window
273 */
274template <class reference_type>
275class SAL_WARN_UNUSED__attribute__((warn_unused)) VclPtrInstance final : public VclPtr<reference_type>
276{
277public:
278 template<typename... Arg> VclPtrInstance(Arg &&... arg)
279 : VclPtr<reference_type>( new reference_type(std::forward<Arg>(arg)...), SAL_NO_ACQUIRE )
280 {
281 }
282
283 /**
284 * Override and disallow this, to prevent people accidentally calling it and actually
285 * getting VclPtr::Create and getting a naked VclPtr<> instance
286 */
287 template<typename... Arg> static VclPtrInstance< reference_type > Create(Arg &&... ) = delete;
288};
289
290template <class reference_type>
291class ScopedVclPtr : public VclPtr<reference_type>
292{
293public:
294 /** Constructor...
295 */
296 ScopedVclPtr()
297 : VclPtr<reference_type>()
298 {}
299
300 /** Constructor
301 */
302 ScopedVclPtr (reference_type * pBody)
303 : VclPtr<reference_type>(pBody)
304 {}
305
306 /** Copy constructor...
307 */
308 ScopedVclPtr (const VclPtr<reference_type> & handle)
309 : VclPtr<reference_type>(handle)
310 {}
311
312 /**
313 Assignment that releases the last reference.
314 */
315 void disposeAndReset(reference_type *pBody)
316 {
317 if (pBody != this->get()) {
318 VclPtr<reference_type>::disposeAndClear();
319 VclPtr<reference_type>::set(pBody);
320 }
321 }
322
323 /**
324 Assignment that releases the last reference.
325 */
326 ScopedVclPtr<reference_type>& operator = (reference_type * pBody)
327 {
328 disposeAndReset(pBody);
329 return *this;
330 }
331
332 /** Up-casting conversion constructor: Copies interface reference.
333
334 Does not work for up-casts to ambiguous bases. For the special case of
335 up-casting to Reference< XInterface >, see the corresponding conversion
336 operator.
337
338 @param rRef another reference
339 */
340 template< class derived_type >
341 ScopedVclPtr(
342 const VclPtr< derived_type > & rRef,
343 typename std::enable_if<
344 std::is_base_of<reference_type, derived_type>::value, int>::type
345 = 0 )
346 : VclPtr<reference_type>( rRef )
347 {
348 }
349
350 /** Up-casting assignment operator.
351
352 Does not work for up-casts to ambiguous bases.
353
354 @param rRef another VclPtr
355 */
356 template<typename derived_type>
357 typename std::enable_if<
358 std::is_base_of<reference_type, derived_type>::value,
359 ScopedVclPtr &>::type
360 operator =(VclPtr<derived_type> const & rRef)
361 {
362 disposeAndReset(rRef.get());
363 return *this;
364 }
365
366 /**
367 * Override and disallow this, to prevent people accidentally calling it and actually
368 * getting VclPtr::Create and getting a naked VclPtr<> instance
369 */
370 template<typename... Arg> static ScopedVclPtr< reference_type > Create(Arg &&... ) = delete;
371
372 ~ScopedVclPtr()
373 {
374 VclPtr<reference_type>::disposeAndClear();
10
Calling 'VclPtr::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 )
6
Memory is allocated
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)
77 m_pBody->acquire();
78 }
79
80#ifdef LIBO_INTERNAL_ONLY1
81 /** Move constructor...
82 */
83 Reference (Reference<reference_type> && handle) noexcept
84 : m_pBody (handle.m_pBody)
85 {
86 handle.m_pBody = nullptr;
87 }
88#endif
89
90#if defined LIBO_INTERNAL_ONLY1
91 /** Up-casting conversion constructor: Copies interface reference.
92
93 Does not work for up-casts to ambiguous bases.
94
95 @param rRef another reference
96 */
97 template< class derived_type >
98 inline Reference(
99 const Reference< derived_type > & rRef,
100 std::enable_if_t<std::is_base_of_v<reference_type, derived_type>, int> = 0 )
101 : m_pBody (rRef.get())
102 {
103 if (m_pBody)
104 m_pBody->acquire();
105 }
106#endif
107
108 /** Destructor...
109 */
110 ~Reference() COVERITY_NOEXCEPT_FALSE
111 {
112 if (m_pBody)
113 m_pBody->release();
114 }
115
116 /** Set...
117 Similar to assignment.
118 */
119 Reference<reference_type> &
120 SAL_CALL set (reference_type * pBody)
121 {
122 if (pBody)
123 pBody->acquire();
124 reference_type * const pOld = m_pBody;
125 m_pBody = pBody;
126 if (pOld)
127 pOld->release();
128 return *this;
129 }
130
131 /** Assignment.
132 Unbinds this instance from its body (if bound) and
133 bind it to the body represented by the handle.
134 */
135 Reference<reference_type> &
136 SAL_CALL operator= (const Reference<reference_type> & handle)
137 {
138 return set( handle.m_pBody );
139 }
140
141#ifdef LIBO_INTERNAL_ONLY1
142 /** Assignment.
143 * Unbinds this instance from its body (if bound),
144 * bind it to the body represented by the handle, and
145 * set the body represented by the handle to nullptr.
146 */
147 Reference<reference_type> &
148 operator= (Reference<reference_type> && handle)
149 {
150 // self-movement guts ourself
151 if (m_pBody)
152 m_pBody->release();
153 m_pBody = handle.m_pBody;
154 handle.m_pBody = nullptr;
155 return *this;
156 }
157#endif
158
159 /** Assignment...
160 */
161 Reference<reference_type> &
162 SAL_CALL operator= (reference_type * pBody)
163 {
164 return set( pBody );
165 }
166
167 /** Unbind the body from this handle.
168 Note that for a handle representing a large body,
169 "handle.clear().set(new body());" _might_
170 perform a little bit better than "handle.set(new body());",
171 since in the second case two large objects exist in memory
172 (the old body and the new body).
173 */
174 Reference<reference_type> & SAL_CALL clear()
175 {
176 if (m_pBody
11.1
Field 'm_pBody' is non-null
11.1
Field 'm_pBody' is non-null
11.1
Field 'm_pBody' is non-null
11.1
Field 'm_pBody' is non-null
)
12
Taking true branch
177 {
178 reference_type * const pOld = m_pBody;
179 m_pBody = NULL__null;
180 pOld->release();
13
Calling 'VclReferenceBase::release'
17
Returning; memory was released
181 }
182 return *this;
183 }
184
185
186 /** Get the body. Can be used instead of operator->().
187 I.e. handle->someBodyOp() and handle.get()->someBodyOp()
188 are the same.
189 */
190 reference_type * SAL_CALL get() const
191 {
192 return m_pBody;
20
Use of memory after it is freed
193 }
194
195
196 /** Probably most common used: handle->someBodyOp().
197 */
198 reference_type * SAL_CALL operator->() const
199 {
200 assert(m_pBody != NULL)(static_cast <bool> (m_pBody != __null) ? void (0) : __assert_fail
("m_pBody != NULL", "/home/maarten/src/libreoffice/core/include/rtl/ref.hxx"
, 200, __extension__ __PRETTY_FUNCTION__))
;
201 return m_pBody;
202 }
203
204
205 /** Allows (*handle).someBodyOp().
206 */
207 reference_type & SAL_CALL operator*() const
208 {
209 assert(m_pBody != NULL)(static_cast <bool> (m_pBody != __null) ? void (0) : __assert_fail
("m_pBody != NULL", "/home/maarten/src/libreoffice/core/include/rtl/ref.hxx"
, 209, __extension__ __PRETTY_FUNCTION__))
;
210 return *m_pBody;
211 }
212
213
214 /** Returns True if the handle does point to a valid body.
215 */
216 bool SAL_CALL is() const
217 {
218 return (m_pBody != NULL__null);
219 }
220
221#if defined LIBO_INTERNAL_ONLY1
222 /** Returns True if the handle does point to a valid body.
223 */
224 explicit operator bool() const
225 {
226 return is();
227 }
228#endif
229
230 /** Returns True if this points to pBody.
231 */
232 bool SAL_CALL operator== (const reference_type * pBody) const
233 {
234 return (m_pBody == pBody);
235 }
236
237
238 /** Returns True if handle points to the same body.
239 */
240 bool
241 SAL_CALL operator== (const Reference<reference_type> & handle) const
242 {
243 return (m_pBody == handle.m_pBody);
244 }
245
246
247 /** Needed to place References into STL collection.
248 */
249 bool
250 SAL_CALL operator!= (const Reference<reference_type> & handle) const
251 {
252 return (m_pBody != handle.m_pBody);
253 }
254
255
256 /** Needed to place References into STL collection.
257 */
258 bool
259 SAL_CALL operator< (const Reference<reference_type> & handle) const
260 {
261 return (m_pBody < handle.m_pBody);
262 }
263
264
265 /** Needed to place References into STL collection.
266 */
267 bool
268 SAL_CALL operator> (const Reference<reference_type> & handle) const
269 {
270 return (m_pBody > handle.m_pBody);
271 }
272};
273
274} // namespace rtl
275
276#if defined LIBO_INTERNAL_ONLY1
277namespace std
278{
279
280/// @cond INTERNAL
281/**
282 Make rtl::Reference hashable by default for use in STL containers.
283
284 @since LibreOffice 6.3
285*/
286template<typename T>
287struct hash<::rtl::Reference<T>>
288{
289 std::size_t operator()(::rtl::Reference<T> const & s) const
290 { return std::size_t(s.get()); }
291};
292/// @endcond
293
294}
295
296#endif
297
298#endif /* ! INCLUDED_RTL_REF_HXX */
299
300/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

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

1/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2/*
3 * This file is part of the LibreOffice project.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 * This file incorporates work covered by the following license notice:
10 *
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 */
19#ifndef INCLUDED_VCL_Reference_HXX
20#define INCLUDED_VCL_Reference_HXX
21
22#include <vcl/dllapi.h>
23#include <osl/interlck.h>
24
25class VCL_DLLPUBLIC__attribute__ ((visibility("default"))) VclReferenceBase
26{
27 mutable oslInterlockedCount mnRefCnt;
28
29 template<typename T> friend class VclPtr;
30
31public:
32 void acquire() const
33 {
34 osl_atomic_increment(&mnRefCnt)__sync_add_and_fetch((&mnRefCnt), 1);
35 }
36
37 void release() const
38 {
39 if (osl_atomic_decrement(&mnRefCnt)__sync_sub_and_fetch((&mnRefCnt), 1) == 0)
14
Assuming the condition is true
15
Taking true branch
40 delete this;
16
Memory is released
41 }
42#ifdef DBG_UTIL
43#ifndef _WIN32
44 sal_Int32 getRefCount() const { return mnRefCnt; }
45#endif
46#endif
47
48
49private:
50 VclReferenceBase(const VclReferenceBase&) = delete;
51 VclReferenceBase& operator=(const VclReferenceBase&) = delete;
52
53 bool mbDisposed : 1;
54
55protected:
56 VclReferenceBase();
57protected:
58 virtual ~VclReferenceBase();
59
60protected:
61 virtual void dispose();
62
63public:
64 void disposeOnce();
65 bool isDisposed() const { return mbDisposed; }
66
67};
68#endif