LibreOffice Module sc (master)  1
docfunc.cxx
Go to the documentation of this file.
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 <scitems.hxx>
21 
22 #include <comphelper/lok.hxx>
23 #include <o3tl/safeint.hxx>
24 #include <sfx2/app.hxx>
25 #include <editeng/editobj.hxx>
26 #include <editeng/justifyitem.hxx>
27 #include <sfx2/linkmgr.hxx>
28 #include <sfx2/bindings.hxx>
29 #include <vcl/weld.hxx>
30 #include <vcl/stdtext.hxx>
31 #include <vcl/svapp.hxx>
32 #include <svx/svdocapt.hxx>
33 #include <sal/log.hxx>
34 #include <unotools/charclass.hxx>
35 #include <osl/diagnose.h>
36 
37 #include <com/sun/star/container/XNameContainer.hpp>
38 #include <com/sun/star/script/ModuleType.hpp>
39 #include <com/sun/star/script/XLibraryContainer.hpp>
40 #include <com/sun/star/script/vba/XVBAModuleInfo.hpp>
41 
42 #include <docfunc.hxx>
43 
44 #include <sc.hrc>
45 #include <strings.hrc>
46 
47 #include <arealink.hxx>
48 #include <attrib.hxx>
49 #include <dociter.hxx>
50 #include <autoform.hxx>
51 #include <formulacell.hxx>
52 #include <cellmergeoption.hxx>
53 #include <detdata.hxx>
54 #include <detfunc.hxx>
55 #include <docpool.hxx>
56 #include <docsh.hxx>
57 #include <drwlayer.hxx>
58 #include <editutil.hxx>
59 #include <globstr.hrc>
60 #include <olinetab.hxx>
61 #include <patattr.hxx>
62 #include <rangenam.hxx>
63 #include <refundo.hxx>
64 #include <scresid.hxx>
65 #include <stlpool.hxx>
66 #include <stlsheet.hxx>
67 #include <tablink.hxx>
68 #include <tabvwsh.hxx>
69 #include <uiitems.hxx>
70 #include <undoblk.hxx>
71 #include <undocell.hxx>
72 #include <undodraw.hxx>
73 #include <undotab.hxx>
74 #include <sizedev.hxx>
75 #include <scmod.hxx>
76 #include <inputhdl.hxx>
77 #include <editable.hxx>
78 #include <compiler.hxx>
79 #include <scui_def.hxx>
80 #include <tabprotection.hxx>
81 #include <clipparam.hxx>
82 #include <externalrefmgr.hxx>
83 #include <undorangename.hxx>
84 #include <progress.hxx>
85 #include <dpobject.hxx>
86 #include <stringutil.hxx>
87 #include <cellvalue.hxx>
88 #include <tokenarray.hxx>
89 #include <rowheightcontext.hxx>
90 #include <cellvalues.hxx>
91 #include <undoconvert.hxx>
92 #include <docfuncutil.hxx>
93 #include <sheetevents.hxx>
94 #include <conditio.hxx>
95 #include <columnspanset.hxx>
96 #include <validat.hxx>
97 
98 #include <memory>
99 #include <utility>
100 #include <basic/basmgr.hxx>
101 #include <set>
102 #include <vector>
103 #include <sfx2/viewfrm.hxx>
104 
105 using namespace com::sun::star;
106 using ::std::vector;
107 
108 void ScDocFunc::NotifyDrawUndo( std::unique_ptr<SdrUndoAction> pUndoAction)
109 {
110  // #i101118# if drawing layer collects the undo actions, add it there
111  ScDrawLayer* pDrawLayer = rDocShell.GetDocument().GetDrawLayer();
112  if( pDrawLayer && pDrawLayer->IsRecording() )
113  pDrawLayer->AddCalcUndo( std::move(pUndoAction) );
114  else
115  rDocShell.GetUndoManager()->AddUndoAction( std::make_unique<ScUndoDraw>( std::move(pUndoAction), &rDocShell ) );
116  rDocShell.SetDrawModified();
117 
118  // the affected sheet isn't known, so all stream positions are invalidated
119  ScDocument& rDoc = rDocShell.GetDocument();
120  SCTAB nTabCount = rDoc.GetTableCount();
121  for (SCTAB nTab=0; nTab<nTabCount; nTab++)
122  rDoc.SetStreamValid(nTab, false);
123 }
124 
125 // paint row above the range (because of lines after AdjustRowHeight)
126 
127 static void lcl_PaintAbove( ScDocShell& rDocShell, const ScRange& rRange )
128 {
129  SCROW nRow = rRange.aStart.Row();
130  if ( nRow > 0 )
131  {
132  SCTAB nTab = rRange.aStart.Tab();
133  --nRow;
134  ScDocument& rDoc = rDocShell.GetDocument();
135  rDocShell.PostPaint( ScRange(0,nRow,nTab,rDoc.MaxCol(),nRow,nTab), PaintPartFlags::Grid );
136  }
137 }
138 
139 bool ScDocFunc::AdjustRowHeight( const ScRange& rRange, bool bPaint, bool bApi )
140 {
141  ScDocument& rDoc = rDocShell.GetDocument();
142  SfxViewShell* pSomeViewForThisDoc = rDocShell.GetBestViewShell(false);
143  if ( rDoc.IsImportingXML() )
144  {
145  // for XML import, all row heights are updated together after importing
146  return false;
147  }
148  if ( rDoc.IsAdjustHeightLocked() )
149  {
150  return false;
151  }
152 
153  SCTAB nTab = rRange.aStart.Tab();
154  SCROW nStartRow = rRange.aStart.Row();
155  SCROW nEndRow = rRange.aEnd.Row();
156 
157  ScSizeDeviceProvider aProv( &rDocShell );
158  Fraction aOne(1,1);
159 
160  sc::RowHeightContext aCxt(rDoc.MaxRow(), aProv.GetPPTX(), aProv.GetPPTY(), aOne, aOne, aProv.GetDevice());
161  bool bChanged = rDoc.SetOptimalHeight(aCxt, nStartRow, nEndRow, nTab, bApi);
162  // tdf#76183: recalculate objects' positions
163  if (bChanged)
164  {
166  {
167  SfxViewShell* pViewShell = SfxViewShell::GetFirst();
168  while (pViewShell)
169  {
170  ScTabViewShell* pTabViewShell = dynamic_cast<ScTabViewShell*>(pViewShell);
171  if (pTabViewShell && pTabViewShell->GetDocId() == pSomeViewForThisDoc->GetDocId())
172  {
173  pTabViewShell->GetViewData().GetLOKHeightHelper(nTab)->invalidateByIndex(nStartRow);
174  }
175  pViewShell = SfxViewShell::GetNext(*pViewShell);
176  }
177  }
178  rDoc.SetDrawPageSize(nTab);
179  }
180 
181  if ( bPaint && bChanged )
182  rDocShell.PostPaint(ScRange(0, nStartRow, nTab, rDoc.MaxCol(), rDoc.MaxRow(), nTab),
184 
186  {
189  pSomeViewForThisDoc, false /* bColumns */, true /* bRows */, true /* bSizes*/,
190  false /* bHidden */, false /* bFiltered */, false /* bGroups */, nTab);
191  }
192 
193  return bChanged;
194 }
195 
197 {
198  ScDocShellModificator aModificator( rDocShell );
199 
200  rDocShell.MakeDrawLayer();
201  ScDocument& rDoc = rDocShell.GetDocument();
202  bool bUndo (rDoc.IsUndoEnabled());
203  ScDrawLayer* pModel = rDoc.GetDrawLayer();
204  SCCOL nCol = rPos.Col();
205  SCROW nRow = rPos.Row();
206  SCTAB nTab = rPos.Tab();
207 
208  if (bUndo)
209  pModel->BeginCalcUndo(false);
210  bool bDone = ScDetectiveFunc(rDoc, nTab).ShowPred( nCol, nRow );
211  std::unique_ptr<SdrUndoGroup> pUndo;
212  if (bUndo)
213  pUndo = pModel->GetCalcUndo();
214  if (bDone)
215  {
216  ScDetOpData aOperation( ScAddress(nCol,nRow,nTab), SCDETOP_ADDPRED );
217  rDoc.AddDetectiveOperation( aOperation );
218  if (bUndo)
219  {
220  rDocShell.GetUndoManager()->AddUndoAction(
221  std::make_unique<ScUndoDetective>( &rDocShell, std::move(pUndo), &aOperation ) );
222  }
223  aModificator.SetDocumentModified();
224  SfxBindings* pBindings = rDocShell.GetViewBindings();
225  if (pBindings)
226  pBindings->Invalidate( SID_DETECTIVE_REFRESH );
227  }
228 
229  return bDone;
230 }
231 
233 {
234  ScDocument& rDoc = rDocShell.GetDocument();
235 
236  bool bUndo(rDoc.IsUndoEnabled());
237  ScDrawLayer* pModel = rDoc.GetDrawLayer();
238  if (!pModel)
239  return false;
240 
241  ScDocShellModificator aModificator( rDocShell );
242 
243  SCCOL nCol = rPos.Col();
244  SCROW nRow = rPos.Row();
245  SCTAB nTab = rPos.Tab();
246 
247  if (bUndo)
248  pModel->BeginCalcUndo(false);
249  bool bDone = ScDetectiveFunc(rDoc, nTab).DeletePred( nCol, nRow );
250  std::unique_ptr<SdrUndoGroup> pUndo;
251  if (bUndo)
252  pUndo = pModel->GetCalcUndo();
253  if (bDone)
254  {
255  ScDetOpData aOperation( ScAddress(nCol,nRow,nTab), SCDETOP_DELPRED );
256  rDoc.AddDetectiveOperation( aOperation );
257  if (bUndo)
258  {
259  rDocShell.GetUndoManager()->AddUndoAction(
260  std::make_unique<ScUndoDetective>( &rDocShell, std::move(pUndo), &aOperation ) );
261  }
262  aModificator.SetDocumentModified();
263  SfxBindings* pBindings = rDocShell.GetViewBindings();
264  if (pBindings)
265  pBindings->Invalidate( SID_DETECTIVE_REFRESH );
266  }
267 
268  return bDone;
269 }
270 
272 {
273  ScDocShellModificator aModificator( rDocShell );
274 
275  rDocShell.MakeDrawLayer();
276  ScDocument& rDoc = rDocShell.GetDocument();
277 
278  bool bUndo(rDoc.IsUndoEnabled());
279  ScDrawLayer* pModel = rDoc.GetDrawLayer();
280  SCCOL nCol = rPos.Col();
281  SCROW nRow = rPos.Row();
282  SCTAB nTab = rPos.Tab();
283 
284  if (bUndo)
285  pModel->BeginCalcUndo(false);
286  bool bDone = ScDetectiveFunc(rDoc, nTab).ShowSucc( nCol, nRow );
287  std::unique_ptr<SdrUndoGroup> pUndo;
288  if (bUndo)
289  pUndo = pModel->GetCalcUndo();
290  if (bDone)
291  {
292  ScDetOpData aOperation( ScAddress(nCol,nRow,nTab), SCDETOP_ADDSUCC );
293  rDoc.AddDetectiveOperation( aOperation );
294  if (bUndo)
295  {
296  rDocShell.GetUndoManager()->AddUndoAction(
297  std::make_unique<ScUndoDetective>( &rDocShell, std::move(pUndo), &aOperation ) );
298  }
299  aModificator.SetDocumentModified();
300  SfxBindings* pBindings = rDocShell.GetViewBindings();
301  if (pBindings)
302  pBindings->Invalidate( SID_DETECTIVE_REFRESH );
303  }
304 
305  return bDone;
306 }
307 
309 {
310  ScDocument& rDoc = rDocShell.GetDocument();
311 
312  bool bUndo (rDoc.IsUndoEnabled());
313  ScDrawLayer* pModel = rDoc.GetDrawLayer();
314  if (!pModel)
315  return false;
316 
317  ScDocShellModificator aModificator( rDocShell );
318 
319  SCCOL nCol = rPos.Col();
320  SCROW nRow = rPos.Row();
321  SCTAB nTab = rPos.Tab();
322 
323  if (bUndo)
324  pModel->BeginCalcUndo(false);
325  bool bDone = ScDetectiveFunc(rDoc, nTab).DeleteSucc( nCol, nRow );
326  std::unique_ptr<SdrUndoGroup> pUndo;
327  if (bUndo)
328  pUndo = pModel->GetCalcUndo();
329  if (bDone)
330  {
331  ScDetOpData aOperation( ScAddress(nCol,nRow,nTab), SCDETOP_DELSUCC );
332  rDoc.AddDetectiveOperation( aOperation );
333  if (bUndo)
334  {
335  rDocShell.GetUndoManager()->AddUndoAction(
336  std::make_unique<ScUndoDetective>( &rDocShell, std::move(pUndo), &aOperation ) );
337  }
338  aModificator.SetDocumentModified();
339  SfxBindings* pBindings = rDocShell.GetViewBindings();
340  if (pBindings)
341  pBindings->Invalidate( SID_DETECTIVE_REFRESH );
342  }
343 
344  return bDone;
345 }
346 
348 {
349  ScDocShellModificator aModificator( rDocShell );
350 
351  rDocShell.MakeDrawLayer();
352  ScDocument& rDoc = rDocShell.GetDocument();
353 
354  bool bUndo (rDoc.IsUndoEnabled());
355  ScDrawLayer* pModel = rDoc.GetDrawLayer();
356  SCCOL nCol = rPos.Col();
357  SCROW nRow = rPos.Row();
358  SCTAB nTab = rPos.Tab();
359 
360  if (bUndo)
361  pModel->BeginCalcUndo(false);
362  bool bDone = ScDetectiveFunc(rDoc, nTab).ShowError( nCol, nRow );
363  std::unique_ptr<SdrUndoGroup> pUndo;
364  if (bUndo)
365  pUndo = pModel->GetCalcUndo();
366  if (bDone)
367  {
368  ScDetOpData aOperation( ScAddress(nCol,nRow,nTab), SCDETOP_ADDERROR );
369  rDoc.AddDetectiveOperation( aOperation );
370  if (bUndo)
371  {
372  rDocShell.GetUndoManager()->AddUndoAction(
373  std::make_unique<ScUndoDetective>( &rDocShell, std::move(pUndo), &aOperation ) );
374  }
375  aModificator.SetDocumentModified();
376  SfxBindings* pBindings = rDocShell.GetViewBindings();
377  if (pBindings)
378  pBindings->Invalidate( SID_DETECTIVE_REFRESH );
379  }
380 
381  return bDone;
382 }
383 
385 {
386  ScDocShellModificator aModificator( rDocShell );
387 
388  rDocShell.MakeDrawLayer();
389  ScDocument& rDoc = rDocShell.GetDocument();
390 
391  bool bUndo (rDoc.IsUndoEnabled());
392  ScDrawLayer* pModel = rDoc.GetDrawLayer();
393 
394  std::unique_ptr<weld::WaitObject> xWaitWin(new weld::WaitObject(ScDocShell::GetActiveDialogParent()));
395  if (bUndo)
396  pModel->BeginCalcUndo(false);
397  bool bOverflow;
398  bool bDone = ScDetectiveFunc(rDoc, nTab).MarkInvalid( bOverflow );
399  std::unique_ptr<SdrUndoGroup> pUndo;
400  if (bUndo)
401  pUndo = pModel->GetCalcUndo();
402  xWaitWin.reset();
403  if (bDone)
404  {
405  if (pUndo && bUndo)
406  {
407  pUndo->SetComment( ScResId( STR_UNDO_DETINVALID ) );
408  rDocShell.GetUndoManager()->AddUndoAction( std::move(pUndo) );
409  }
410  aModificator.SetDocumentModified();
411  if ( bOverflow )
412  {
413  std::unique_ptr<weld::MessageDialog> xInfoBox(Application::CreateMessageDialog(nullptr,
414  VclMessageType::Info, VclButtonsType::Ok,
415  ScResId(STR_DETINVALID_OVERFLOW)));
416  xInfoBox->run();
417  }
418  }
419 
420  return bDone;
421 }
422 
424 {
425  ScDocument& rDoc = rDocShell.GetDocument();
426 
427  bool bUndo (rDoc.IsUndoEnabled());
428  ScDrawLayer* pModel = rDoc.GetDrawLayer();
429  if (!pModel)
430  return false;
431 
432  ScDocShellModificator aModificator( rDocShell );
433 
434  if (bUndo)
435  pModel->BeginCalcUndo(false);
436  bool bDone = ScDetectiveFunc(rDoc, nTab).DeleteAll( ScDetectiveDelete::Detective );
437  std::unique_ptr<SdrUndoGroup> pUndo;
438  if (bUndo)
439  pUndo = pModel->GetCalcUndo();
440  if (bDone)
441  {
442  ScDetOpList* pOldList = rDoc.GetDetOpList();
443  std::unique_ptr<ScDetOpList> pUndoList;
444  if (bUndo && pOldList)
445  pUndoList.reset(new ScDetOpList(*pOldList));
446 
448 
449  if (bUndo)
450  {
451  rDocShell.GetUndoManager()->AddUndoAction(
452  std::make_unique<ScUndoDetective>( &rDocShell, std::move(pUndo), nullptr, std::move(pUndoList) ) );
453  }
454  aModificator.SetDocumentModified();
455  SfxBindings* pBindings = rDocShell.GetViewBindings();
456  if (pBindings)
457  pBindings->Invalidate( SID_DETECTIVE_REFRESH );
458  }
459 
460  return bDone;
461 }
462 
463 bool ScDocFunc::DetectiveRefresh( bool bAutomatic )
464 {
465  bool bDone = false;
466  ScDocument& rDoc = rDocShell.GetDocument();
467 
468  ScDetOpList* pList = rDoc.GetDetOpList();
469  if ( pList && pList->Count() )
470  {
471  rDocShell.MakeDrawLayer();
472  ScDrawLayer* pModel = rDoc.GetDrawLayer();
473  const bool bUndo (rDoc.IsUndoEnabled());
474  if (bUndo)
475  pModel->BeginCalcUndo(false);
476 
477  // Delete in all sheets
478 
479  SCTAB nTabCount = rDoc.GetTableCount();
480  for (SCTAB nTab=0; nTab<nTabCount; nTab++)
481  ScDetectiveFunc( rDoc,nTab ).DeleteAll( ScDetectiveDelete::Arrows ); // don't remove circles
482 
483  // repeat
484 
485  size_t nCount = pList->Count();
486  for (size_t i=0; i < nCount; ++i)
487  {
488  const ScDetOpData& rData = pList->GetObject(i);
489  const ScAddress& aPos = rData.GetPos();
490  ScDetectiveFunc aFunc( rDoc, aPos.Tab() );
491  SCCOL nCol = aPos.Col();
492  SCROW nRow = aPos.Row();
493  switch (rData.GetOperation())
494  {
495  case SCDETOP_ADDSUCC:
496  aFunc.ShowSucc( nCol, nRow );
497  break;
498  case SCDETOP_DELSUCC:
499  aFunc.DeleteSucc( nCol, nRow );
500  break;
501  case SCDETOP_ADDPRED:
502  aFunc.ShowPred( nCol, nRow );
503  break;
504  case SCDETOP_DELPRED:
505  aFunc.DeletePred( nCol, nRow );
506  break;
507  case SCDETOP_ADDERROR:
508  aFunc.ShowError( nCol, nRow );
509  break;
510  default:
511  OSL_FAIL("wrong operation in DetectiveRefresh");
512  }
513  }
514 
515  if (bUndo)
516  {
517  std::unique_ptr<SdrUndoGroup> pUndo = pModel->GetCalcUndo();
518  if (pUndo)
519  {
520  pUndo->SetComment( ScResId( STR_UNDO_DETREFRESH ) );
521  // associate with the last action
522  rDocShell.GetUndoManager()->AddUndoAction(
523  std::make_unique<ScUndoDraw>( std::move(pUndo), &rDocShell ),
524  bAutomatic );
525  }
526  }
527  rDocShell.SetDrawModified();
528  bDone = true;
529  }
530  return bDone;
531 }
532 
534  const ScRangeList& rSrcRanges, vector<ScTokenRef>& rRefTokens, ScDocShell& rDocShell,
535  bool bPred)
536 {
537  ScDocument& rDoc = rDocShell.GetDocument();
538  vector<ScTokenRef> aRefTokens;
539  if (rSrcRanges.empty())
540  return;
541  ScRange const & rFrontRange = rSrcRanges.front();
542  ScDetectiveFunc aDetFunc(rDoc, rFrontRange.aStart.Tab());
543  for (size_t i = 0, n = rSrcRanges.size(); i < n; ++i)
544  {
545  ScRange const & r = rSrcRanges[i];
546  if (bPred)
547  {
548  aDetFunc.GetAllPreds(
549  r.aStart.Col(), r.aStart.Row(), r.aEnd.Col(), r.aEnd.Row(), aRefTokens);
550  }
551  else
552  {
553  aDetFunc.GetAllSuccs(
554  r.aStart.Col(), r.aStart.Row(), r.aEnd.Col(), r.aEnd.Row(), aRefTokens);
555  }
556  }
557  rRefTokens.swap(aRefTokens);
558 }
559 
560 void ScDocFunc::DetectiveCollectAllPreds(const ScRangeList& rSrcRanges, vector<ScTokenRef>& rRefTokens)
561 {
562  lcl_collectAllPredOrSuccRanges(rSrcRanges, rRefTokens, rDocShell, true);
563 }
564 
565 void ScDocFunc::DetectiveCollectAllSuccs(const ScRangeList& rSrcRanges, vector<ScTokenRef>& rRefTokens)
566 {
567  lcl_collectAllPredOrSuccRanges(rSrcRanges, rRefTokens, rDocShell, false);
568 }
569 
571  const ScMarkData& rMark, InsertDeleteFlags nFlags, bool bRecord, bool bApi )
572 {
573  ScDocShellModificator aModificator( rDocShell );
574 
575  if ( !rMark.IsMarked() && !rMark.IsMultiMarked() )
576  {
577  OSL_FAIL("ScDocFunc::DeleteContents without markings");
578  return false;
579  }
580 
581  ScDocument& rDoc = rDocShell.GetDocument();
582 
583  if (bRecord && !rDoc.IsUndoEnabled())
584  bRecord = false;
585 
586  ScEditableTester aTester( rDoc, rMark );
587  if (!aTester.IsEditable())
588  {
589  if (!bApi)
590  rDocShell.ErrorMessage(aTester.GetMessageId());
591  return false;
592  }
593 
594  ScRange aMarkRange;
595 
596  ScMarkData aMultiMark = rMark;
597  aMultiMark.SetMarking(false); // for MarkToMulti
598 
599  ScDocumentUniquePtr pUndoDoc;
600  bool bMulti = aMultiMark.IsMultiMarked();
601  aMultiMark.MarkToMulti();
602  aMultiMark.GetMultiMarkArea( aMarkRange );
603  ScRange aExtendedRange(aMarkRange);
604  if ( rDoc.ExtendMerge( aExtendedRange, true ) )
605  bMulti = false;
606 
607  // no objects on protected tabs
608  bool bObjects = (nFlags & InsertDeleteFlags::OBJECTS) && !sc::DocFuncUtil::hasProtectedTab(rDoc, rMark);
609 
610  sal_uInt16 nExtFlags = 0; // extra flags are needed only if attributes are deleted
611  if ( nFlags & InsertDeleteFlags::ATTRIB )
612  rDocShell.UpdatePaintExt( nExtFlags, aMarkRange );
613 
614  // order of operations:
615  // 1) BeginDrawUndo
616  // 2) Delete objects (DrawUndo will be filled)
617  // 3) Copy content for undo and set up undo actions
618  // 4) Delete content
619 
620  bool bDrawUndo = bObjects || (nFlags & InsertDeleteFlags::NOTE);
621  if (bRecord && bDrawUndo)
622  rDoc.BeginDrawUndo();
623 
624  if (bObjects)
625  {
626  if (bMulti)
627  rDoc.DeleteObjectsInSelection( aMultiMark );
628  else
629  rDoc.DeleteObjectsInArea( aMarkRange.aStart.Col(), aMarkRange.aStart.Row(),
630  aMarkRange.aEnd.Col(), aMarkRange.aEnd.Row(),
631  aMultiMark );
632  }
633 
634  // To keep track of all non-empty cells within the deleted area.
635  std::shared_ptr<ScSimpleUndo::DataSpansType> pDataSpans;
636 
637  if ( bRecord )
638  {
639  pUndoDoc = sc::DocFuncUtil::createDeleteContentsUndoDoc(rDoc, aMultiMark, aMarkRange, nFlags, bMulti);
640  pDataSpans = sc::DocFuncUtil::getNonEmptyCellSpans(rDoc, aMultiMark, aMarkRange);
641  }
642 
643  rDoc.DeleteSelection( nFlags, aMultiMark );
644 
645  // add undo action after drawing undo is complete (objects and note captions)
646  if( bRecord )
647  {
649  rDocShell.GetUndoManager(), &rDocShell, aMultiMark, aExtendedRange,
650  std::move(pUndoDoc), nFlags, pDataSpans, bMulti, bDrawUndo);
651  }
652 
653  if (!AdjustRowHeight( aExtendedRange, true, bApi ))
654  rDocShell.PostPaint( aExtendedRange, PaintPartFlags::Grid, nExtFlags );
655  else if (nExtFlags & SC_PF_LINES)
656  lcl_PaintAbove( rDocShell, aExtendedRange ); // for lines above the range
657 
658  aModificator.SetDocumentModified();
659 
660  return true;
661 }
662 
664  const ScAddress& rPos, const ScMarkData& rMark, InsertDeleteFlags nFlags, bool bRecord, bool bApi )
665 {
666  ScDocShellModificator aModificator(rDocShell);
667 
668  ScDocument& rDoc = rDocShell.GetDocument();
669 
670  if (bRecord && !rDoc.IsUndoEnabled())
671  bRecord = false;
672 
673  ScEditableTester aTester(rDoc, rPos.Col(), rPos.Row(), rPos.Col(), rPos.Row(), rMark);
674  if (!aTester.IsEditable())
675  {
676  rDocShell.ErrorMessage(aTester.GetMessageId());
677  return false;
678  }
679 
680  // no objects on protected tabs
681  bool bObjects = (nFlags & InsertDeleteFlags::OBJECTS) && !sc::DocFuncUtil::hasProtectedTab(rDoc, rMark);
682 
683  sal_uInt16 nExtFlags = 0; // extra flags are needed only if attributes are deleted
684  if (nFlags & InsertDeleteFlags::ATTRIB)
685  rDocShell.UpdatePaintExt(nExtFlags, rPos);
686 
687  // order of operations:
688  // 1) BeginDrawUndo
689  // 2) delete objects (DrawUndo is filled)
690  // 3) copy contents for undo
691  // 4) delete contents
692  // 5) add undo-action
693 
694  bool bDrawUndo = bObjects || (nFlags & InsertDeleteFlags::NOTE); // needed for shown notes
695  if (bDrawUndo && bRecord)
696  rDoc.BeginDrawUndo();
697 
698  if (bObjects)
699  rDoc.DeleteObjectsInArea(rPos.Col(), rPos.Row(), rPos.Col(), rPos.Row(), rMark);
700 
701  // To keep track of all non-empty cells within the deleted area.
702  std::shared_ptr<ScSimpleUndo::DataSpansType> pDataSpans;
703 
704  ScDocumentUniquePtr pUndoDoc;
705  if (bRecord)
706  {
707  pUndoDoc = sc::DocFuncUtil::createDeleteContentsUndoDoc(rDoc, rMark, rPos, nFlags, false);
708  pDataSpans = sc::DocFuncUtil::getNonEmptyCellSpans(rDoc, rMark, rPos);
709  }
710 
711  rDoc.DeleteArea(rPos.Col(), rPos.Row(), rPos.Col(), rPos.Row(), rMark, nFlags);
712 
713  if (bRecord)
714  {
716  rDocShell.GetUndoManager(), &rDocShell, rMark, rPos, std::move(pUndoDoc),
717  nFlags, pDataSpans, false, bDrawUndo);
718  }
719 
720  if (!AdjustRowHeight(rPos, true, bApi))
721  rDocShell.PostPaint(
722  rPos.Col(), rPos.Row(), rPos.Tab(), rPos.Col(), rPos.Row(), rPos.Tab(),
723  PaintPartFlags::Grid, nExtFlags);
724 
725  aModificator.SetDocumentModified();
726 
727  return true;
728 }
729 
731  bool bApi )
732 {
733  ScDocShellModificator aModificator( rDocShell );
734 
735  ScDocument& rDoc = rDocShell.GetDocument();
736  bool bRecord = true;
737  if (!rDoc.IsUndoEnabled())
738  bRecord = false;
739 
740  ScEditableTester aTester( rDoc, rMark );
741  if (!aTester.IsEditable())
742  {
743  if (!bApi)
744  rDocShell.ErrorMessage(aTester.GetMessageId());
745  return false;
746  }
747 
748  ScRange aMarkRange;
749  ScMarkData aMultiMark = rMark;
750  aMultiMark.SetMarking(false); // for MarkToMulti
751  aMultiMark.MarkToMulti();
752  aMultiMark.GetMultiMarkArea( aMarkRange );
753 
754  if (bRecord)
755  {
756  SCTAB nStartTab = aMarkRange.aStart.Tab();
757  SCTAB nTabCount = rDoc.GetTableCount();
758 
760  pUndoDoc->InitUndo( rDoc, nStartTab, nStartTab );
761  for (const auto& rTab : rMark)
762  {
763  if (rTab >= nTabCount)
764  break;
765 
766  if (rTab != nStartTab)
767  pUndoDoc->AddUndoTab( rTab, rTab );
768  }
769 
770  ScRange aCopyRange = aMarkRange;
771  aCopyRange.aStart.SetTab(0);
772  aCopyRange.aEnd.SetTab(nTabCount-1);
773  rDoc.CopyToDocument(aCopyRange, InsertDeleteFlags::CONTENTS, true, *pUndoDoc, &aMultiMark);
774 
775  rDocShell.GetUndoManager()->AddUndoAction(
776  std::make_unique<ScUndoTransliterate>( &rDocShell, aMultiMark, std::move(pUndoDoc), nType ) );
777  }
778 
779  rDoc.TransliterateText( aMultiMark, nType );
780 
781  if (!AdjustRowHeight( aMarkRange, true, true ))
782  rDocShell.PostPaint( aMarkRange, PaintPartFlags::Grid );
783 
784  aModificator.SetDocumentModified();
785 
786  return true;
787 }
788 
789 bool ScDocFunc::SetNormalString( bool& o_rbNumFmtSet, const ScAddress& rPos, const OUString& rText, bool bApi )
790 {
791  ScDocShellModificator aModificator( rDocShell );
792  ScDocument& rDoc = rDocShell.GetDocument();
793 
794  bool bUndo(rDoc.IsUndoEnabled());
795  ScEditableTester aTester( rDoc, rPos.Tab(), rPos.Col(),rPos.Row(), rPos.Col(),rPos.Row() );
796  if (!aTester.IsEditable())
797  {
798  if (!bApi)
799  rDocShell.ErrorMessage(aTester.GetMessageId());
800  return false;
801  }
802 
803  bool bEditDeleted = (rDoc.GetCellType(rPos) == CELLTYPE_EDIT);
804  ScUndoEnterData::ValuesType aOldValues;
805 
806  if (bUndo)
807  {
808  ScUndoEnterData::Value aOldValue;
809 
810  aOldValue.mnTab = rPos.Tab();
811  aOldValue.maCell.assign(rDoc, rPos);
812 
813  const SfxPoolItem* pItem;
814  const ScPatternAttr* pPattern = rDoc.GetPattern( rPos.Col(),rPos.Row(),rPos.Tab() );
815  if ( SfxItemState::SET == pPattern->GetItemSet().GetItemState(
816  ATTR_VALUE_FORMAT,false,&pItem) )
817  {
818  aOldValue.mbHasFormat = true;
819  aOldValue.mnFormat = static_cast<const SfxUInt32Item*>(pItem)->GetValue();
820  }
821  else
822  aOldValue.mbHasFormat = false;
823 
824  aOldValues.push_back(aOldValue);
825  }
826 
827  o_rbNumFmtSet = rDoc.SetString( rPos.Col(), rPos.Row(), rPos.Tab(), rText );
828 
829  if (bUndo)
830  {
831  // because of ChangeTracking, UndoAction can be created only after SetString was called
832  rDocShell.GetUndoManager()->AddUndoAction(
833  std::make_unique<ScUndoEnterData>(&rDocShell, rPos, aOldValues, rText, nullptr));
834  }
835 
836  if ( bEditDeleted || rDoc.HasAttrib( ScRange(rPos), HasAttrFlags::NeedHeight ) )
837  AdjustRowHeight( ScRange(rPos), true, bApi );
838 
839  rDocShell.PostPaintCell( rPos );
840  aModificator.SetDocumentModified();
841 
842  // notify input handler here the same way as in PutCell
843  if (bApi)
844  NotifyInputHandler( rPos );
845 
846  const SfxUInt32Item* pItem = rDoc.GetAttr(rPos, ATTR_VALIDDATA);
847  const ScValidationData* pData = rDoc.GetValidationEntry(pItem->GetValue());
848  if (pData)
849  {
850  ScRefCellValue aCell(rDoc, rPos);
851  if (pData->IsDataValid(aCell, rPos))
852  ScDetectiveFunc(rDoc, rPos.Tab()).DeleteCirclesAt(rPos.Col(), rPos.Row());
853  }
854 
855  return true;
856 }
857 
858 bool ScDocFunc::SetValueCell( const ScAddress& rPos, double fVal, bool bInteraction )
859 {
860  ScDocShellModificator aModificator( rDocShell );
861  ScDocument& rDoc = rDocShell.GetDocument();
862  bool bUndo = rDoc.IsUndoEnabled();
863 
864  bool bHeight = rDoc.HasAttrib(rPos, HasAttrFlags::NeedHeight);
865 
866  ScCellValue aOldVal;
867  if (bUndo)
868  aOldVal.assign(rDoc, rPos);
869 
870  rDoc.SetValue(rPos, fVal);
871 
872  if (bUndo)
873  {
874  SfxUndoManager* pUndoMgr = rDocShell.GetUndoManager();
875  ScCellValue aNewVal;
876  aNewVal.assign(rDoc, rPos);
877  pUndoMgr->AddUndoAction(std::make_unique<ScUndoSetCell>(&rDocShell, rPos, aOldVal, aNewVal));
878  }
879 
880  if (bHeight)
881  AdjustRowHeight(rPos, true, !bInteraction);
882 
883  rDocShell.PostPaintCell( rPos );
884  aModificator.SetDocumentModified();
885 
886  // #103934#; notify editline and cell in edit mode
887  if (!bInteraction)
888  NotifyInputHandler( rPos );
889 
890  return true;
891 }
892 
893 void ScDocFunc::SetValueCells( const ScAddress& rPos, const std::vector<double>& aVals, bool bInteraction )
894 {
895  ScDocument& rDoc = rDocShell.GetDocument();
896 
897  // Check for invalid range.
898  SCROW nLastRow = rPos.Row() + aVals.size() - 1;
899  if (nLastRow > rDoc.MaxRow())
900  // out of bound.
901  return;
902 
903  ScRange aRange(rPos);
904  aRange.aEnd.SetRow(nLastRow);
905 
906  ScDocShellModificator aModificator(rDocShell);
907 
908  if (rDoc.IsUndoEnabled())
909  {
910  std::unique_ptr<sc::UndoSetCells> pUndoObj(new sc::UndoSetCells(&rDocShell, rPos));
911  rDoc.TransferCellValuesTo(rPos, aVals.size(), pUndoObj->GetOldValues());
912  pUndoObj->SetNewValues(aVals);
913  SfxUndoManager* pUndoMgr = rDocShell.GetUndoManager();
914  pUndoMgr->AddUndoAction(std::move(pUndoObj));
915  }
916 
917  rDoc.SetValues(rPos, aVals);
918 
919  rDocShell.PostPaint(aRange, PaintPartFlags::Grid);
920  aModificator.SetDocumentModified();
921 
922  // #103934#; notify editline and cell in edit mode
923  if (!bInteraction)
924  NotifyInputHandler(rPos);
925 }
926 
927 bool ScDocFunc::SetStringCell( const ScAddress& rPos, const OUString& rStr, bool bInteraction )
928 {
929  ScDocShellModificator aModificator( rDocShell );
930  ScDocument& rDoc = rDocShell.GetDocument();
931  bool bUndo = rDoc.IsUndoEnabled();
932 
933  bool bHeight = rDoc.HasAttrib(rPos, HasAttrFlags::NeedHeight);
934 
935  ScCellValue aOldVal;
936  if (bUndo)
937  aOldVal.assign(rDoc, rPos);
938 
939  ScSetStringParam aParam;
940  aParam.setTextInput();
941  rDoc.SetString(rPos, rStr, &aParam);
942 
943  if (bUndo)
944  {
945  SfxUndoManager* pUndoMgr = rDocShell.GetUndoManager();
946  ScCellValue aNewVal;
947  aNewVal.assign(rDoc, rPos);
948  pUndoMgr->AddUndoAction(std::make_unique<ScUndoSetCell>(&rDocShell, rPos, aOldVal, aNewVal));
949  }
950 
951  if (bHeight)
952  AdjustRowHeight(rPos, true, !bInteraction);
953 
954  rDocShell.PostPaintCell( rPos );
955  aModificator.SetDocumentModified();
956 
957  // #103934#; notify editline and cell in edit mode
958  if (!bInteraction)
959  NotifyInputHandler( rPos );
960 
961  return true;
962 }
963 
964 bool ScDocFunc::SetEditCell( const ScAddress& rPos, const EditTextObject& rStr, bool bInteraction )
965 {
966  ScDocShellModificator aModificator( rDocShell );
967  ScDocument& rDoc = rDocShell.GetDocument();
968  bool bUndo = rDoc.IsUndoEnabled();
969 
970  bool bHeight = rDoc.HasAttrib(rPos, HasAttrFlags::NeedHeight);
971 
972  ScCellValue aOldVal;
973  if (bUndo)
974  aOldVal.assign(rDoc, rPos);
975 
976  rDoc.SetEditText(rPos, rStr.Clone());
977 
978  if (bUndo)
979  {
980  SfxUndoManager* pUndoMgr = rDocShell.GetUndoManager();
981  ScCellValue aNewVal;
982  aNewVal.assign(rDoc, rPos);
983  pUndoMgr->AddUndoAction(std::make_unique<ScUndoSetCell>(&rDocShell, rPos, aOldVal, aNewVal));
984  }
985 
986  if (bHeight)
987  AdjustRowHeight(rPos, true, !bInteraction);
988 
989  rDocShell.PostPaintCell( rPos );
990  aModificator.SetDocumentModified();
991 
992  // #103934#; notify editline and cell in edit mode
993  if (!bInteraction)
994  NotifyInputHandler( rPos );
995 
996  return true;
997 }
998 
999 bool ScDocFunc::SetStringOrEditCell( const ScAddress& rPos, const OUString& rStr, bool bInteraction )
1000 {
1001  ScDocument& rDoc = rDocShell.GetDocument();
1002 
1003  if (ScStringUtil::isMultiline(rStr))
1004  {
1005  ScFieldEditEngine& rEngine = rDoc.GetEditEngine();
1006  rEngine.SetTextCurrentDefaults(rStr);
1007  std::unique_ptr<EditTextObject> pEditText(rEngine.CreateTextObject());
1008  return SetEditCell(rPos, *pEditText, bInteraction);
1009  }
1010  else
1011  return SetStringCell(rPos, rStr, bInteraction);
1012 }
1013 
1014 bool ScDocFunc::SetFormulaCell( const ScAddress& rPos, ScFormulaCell* pCell, bool bInteraction )
1015 {
1016  std::unique_ptr<ScFormulaCell> xCell(pCell);
1017 
1018  ScDocShellModificator aModificator( rDocShell );
1019  ScDocument& rDoc = rDocShell.GetDocument();
1020  bool bUndo = rDoc.IsUndoEnabled();
1021 
1022  bool bHeight = rDoc.HasAttrib(rPos, HasAttrFlags::NeedHeight);
1023 
1024  ScCellValue aOldVal;
1025  if (bUndo)
1026  aOldVal.assign(rDoc, rPos);
1027 
1028  pCell = rDoc.SetFormulaCell(rPos, xCell.release());
1029 
1030  // For performance reasons API calls may disable calculation while
1031  // operating and recalculate once when done. If through user interaction
1032  // and AutoCalc is disabled, calculate the formula (without its
1033  // dependencies) once so the result matches the current document's content.
1034  if (bInteraction && !rDoc.GetAutoCalc() && pCell)
1035  {
1036  // calculate just the cell once and set Dirty again
1037  pCell->Interpret();
1038  pCell->SetDirtyVar();
1039  rDoc.PutInFormulaTree( pCell);
1040  }
1041 
1042  if (bUndo)
1043  {
1044  SfxUndoManager* pUndoMgr = rDocShell.GetUndoManager();
1045  ScCellValue aNewVal;
1046  aNewVal.assign(rDoc, rPos);
1047  pUndoMgr->AddUndoAction(std::make_unique<ScUndoSetCell>(&rDocShell, rPos, aOldVal, aNewVal));
1048  }
1049 
1050  if (bHeight)
1051  AdjustRowHeight(rPos, true, !bInteraction);
1052 
1053  rDocShell.PostPaintCell( rPos );
1054  aModificator.SetDocumentModified();
1055 
1056  // #103934#; notify editline and cell in edit mode
1057  if (!bInteraction)
1058  NotifyInputHandler( rPos );
1059 
1060  return true;
1061 }
1062 
1063 bool ScDocFunc::SetFormulaCells( const ScAddress& rPos, std::vector<ScFormulaCell*>& rCells, bool bInteraction )
1064 {
1065  ScDocument& rDoc = rDocShell.GetDocument();
1066 
1067  const size_t nLength = rCells.size();
1068  if (rPos.Row() + nLength - 1 > o3tl::make_unsigned(rDoc.MaxRow()))
1069  // out of bound
1070  return false;
1071 
1072  ScRange aRange(rPos);
1073  aRange.aEnd.IncRow(nLength - 1);
1074 
1075  ScDocShellModificator aModificator( rDocShell );
1076  bool bUndo = rDoc.IsUndoEnabled();
1077 
1078  std::unique_ptr<sc::UndoSetCells> pUndoObj;
1079  if (bUndo)
1080  {
1081  pUndoObj.reset(new sc::UndoSetCells(&rDocShell, rPos));
1082  rDoc.TransferCellValuesTo(rPos, nLength, pUndoObj->GetOldValues());
1083  }
1084 
1085  rDoc.SetFormulaCells(rPos, rCells);
1086 
1087  // For performance reasons API calls may disable calculation while
1088  // operating and recalculate once when done. If through user interaction
1089  // and AutoCalc is disabled, calculate the formula (without its
1090  // dependencies) once so the result matches the current document's content.
1091  if (bInteraction && !rDoc.GetAutoCalc())
1092  {
1093  for (auto* pCell : rCells)
1094  {
1095  // calculate just the cell once and set Dirty again
1096  pCell->Interpret();
1097  pCell->SetDirtyVar();
1098  rDoc.PutInFormulaTree( pCell);
1099  }
1100  }
1101 
1102  if (bUndo)
1103  {
1104  pUndoObj->SetNewValues(rCells);
1105  SfxUndoManager* pUndoMgr = rDocShell.GetUndoManager();
1106  pUndoMgr->AddUndoAction(std::move(pUndoObj));
1107  }
1108 
1109  rDocShell.PostPaint(aRange, PaintPartFlags::Grid);
1110  aModificator.SetDocumentModified();
1111 
1112  // #103934#; notify editline and cell in edit mode
1113  if (!bInteraction)
1114  NotifyInputHandler( rPos );
1115 
1116  return true;
1117 }
1118 
1120 {
1122  if ( !(pViewSh && pViewSh->GetViewData().GetDocShell() == &rDocShell) )
1123  return;
1124 
1125  ScInputHandler* pInputHdl = SC_MOD()->GetInputHdl();
1126  if ( pInputHdl && pInputHdl->GetCursorPos() == rPos )
1127  {
1128  bool bIsEditMode(pInputHdl->IsEditMode());
1129 
1130  // set modified if in editmode, because so the string is not set in the InputWindow like in the cell
1131  // (the cell shows the same like the InputWindow)
1132  if (bIsEditMode)
1133  pInputHdl->SetModified();
1134  pViewSh->UpdateInputHandler(false, !bIsEditMode);
1135  }
1136 }
1137 
1138 namespace {
1139 
1140  struct ScMyRememberItem
1141  {
1142  sal_Int32 nIndex;
1143  SfxItemSet aItemSet;
1144 
1145  ScMyRememberItem(const SfxItemSet& rItemSet, sal_Int32 nTempIndex) :
1146  nIndex(nTempIndex), aItemSet(rItemSet) {}
1147  };
1148 
1149 }
1150 
1151 void ScDocFunc::PutData( const ScAddress& rPos, ScEditEngineDefaulter& rEngine, bool bApi )
1152 {
1153  // PutData calls PutCell or SetNormalString
1154 
1155  bool bRet = false;
1156  ScDocument& rDoc = rDocShell.GetDocument();
1157  ScEditAttrTester aTester( &rEngine );
1158  bool bEditCell = aTester.NeedsObject();
1159  if ( bEditCell )
1160  {
1161  // #i61702# With bLoseContent set, the content of rEngine isn't restored
1162  // (used in loading XML, where after the removeActionLock call the API object's
1163  // EditEngine isn't accessed again.
1164  bool bLoseContent = rDoc.IsImportingXML();
1165 
1166  bool bUpdateMode(rEngine.GetUpdateMode());
1167  if (bUpdateMode)
1168  rEngine.SetUpdateMode(false);
1169 
1170  std::vector<std::unique_ptr<ScMyRememberItem>> aRememberItems;
1171 
1172  // All paragraph attributes must be removed before calling CreateTextObject,
1173  // not only alignment, so the object doesn't contain the cell attributes as
1174  // paragraph attributes. Before removing the attributes store them in a vector to
1175  // set them back to the EditEngine.
1176  sal_Int32 nCount = rEngine.GetParagraphCount();
1177  for (sal_Int32 i=0; i<nCount; i++)
1178  {
1179  const SfxItemSet& rOld = rEngine.GetParaAttribs( i );
1180  if ( rOld.Count() )
1181  {
1182  if ( !bLoseContent )
1183  {
1184  aRememberItems.push_back(std::make_unique<ScMyRememberItem>(rEngine.GetParaAttribs(i), i));
1185  }
1186  rEngine.SetParaAttribs( i, SfxItemSet( *rOld.GetPool(), rOld.GetRanges() ) );
1187  }
1188  }
1189 
1190  // A copy of pNewData will be stored in the cell.
1191  std::unique_ptr<EditTextObject> pNewData(rEngine.CreateTextObject());
1192  bRet = SetEditCell(rPos, *pNewData, !bApi);
1193 
1194  // Set the paragraph attributes back to the EditEngine.
1195  for (const auto& rxItem : aRememberItems)
1196  {
1197  rEngine.SetParaAttribs(rxItem->nIndex, rxItem->aItemSet);
1198  }
1199 
1200  // #i61702# if the content isn't accessed, there's no need to set the UpdateMode again
1201  if ( bUpdateMode && !bLoseContent )
1202  rEngine.SetUpdateMode(true);
1203  }
1204  else
1205  {
1206  OUString aText = rEngine.GetText();
1207  if (aText.isEmpty())
1208  {
1209  bool bNumFmtSet = false;
1210  bRet = SetNormalString( bNumFmtSet, rPos, aText, bApi );
1211  }
1212  else
1213  bRet = SetStringCell(rPos, aText, !bApi);
1214  }
1215 
1216  if ( !(bRet && aTester.NeedsCellAttr()) )
1217  return;
1218 
1219  const SfxItemSet& rEditAttr = aTester.GetAttribs();
1220  ScPatternAttr aPattern( rDoc.GetPool() );
1221  aPattern.GetFromEditItemSet( &rEditAttr );
1222  aPattern.DeleteUnchanged( rDoc.GetPattern( rPos.Col(), rPos.Row(), rPos.Tab() ) );
1223  aPattern.GetItemSet().ClearItem( ATTR_HOR_JUSTIFY ); // wasn't removed above if no edit object
1224  if ( aPattern.GetItemSet().Count() > 0 )
1225  {
1226  ScMarkData aMark(rDoc.GetSheetLimits());
1227  aMark.SelectTable( rPos.Tab(), true );
1228  aMark.SetMarkArea( ScRange( rPos ) );
1229  ApplyAttributes( aMark, aPattern, bApi );
1230  }
1231 }
1232 
1234  const ScAddress& rPos, const OUString& rText, bool bInterpret, bool bEnglish, bool bApi,
1235  const formula::FormulaGrammar::Grammar eGrammar )
1236 {
1237  bool bSet = false;
1238  if ( bInterpret )
1239  {
1240  if ( bEnglish )
1241  {
1242  ScDocument& rDoc = rDocShell.GetDocument();
1243 
1244  ::std::unique_ptr<ScExternalRefManager::ApiGuard> pExtRefGuard;
1245  if (bApi)
1246  pExtRefGuard.reset(new ScExternalRefManager::ApiGuard(rDoc));
1247 
1248  ScInputStringType aRes =
1250 
1251  switch (aRes.meType)
1252  {
1254  bSet = SetFormulaCell(rPos, new ScFormulaCell(rDoc, rPos, aRes.maText, eGrammar), !bApi);
1255  break;
1257  bSet = SetValueCell(rPos, aRes.mfValue, !bApi);
1258  break;
1260  bSet = SetStringOrEditCell(rPos, aRes.maText, !bApi);
1261  break;
1262  default:
1263  ;
1264  }
1265  }
1266  // otherwise keep Null -> SetString with local formulas/number formats
1267  }
1268  else if (!rText.isEmpty())
1269  {
1270  bSet = SetStringOrEditCell(rPos, rText, !bApi);
1271  }
1272 
1273  if (!bSet)
1274  {
1275  bool bNumFmtSet = false;
1276  bSet = SetNormalString( bNumFmtSet, rPos, rText, bApi );
1277  }
1278  return bSet;
1279 }
1280 
1281 bool ScDocFunc::ShowNote( const ScAddress& rPos, bool bShow )
1282 {
1283  ScDocument& rDoc = rDocShell.GetDocument();
1284  ScPostIt* pNote = rDoc.GetNote( rPos );
1285  if( !pNote || (bShow == pNote->IsCaptionShown()) ||
1287  return false;
1288 
1289  // move the caption to internal or hidden layer and create undo action
1290  pNote->ShowCaption( rPos, bShow );
1291  if( rDoc.IsUndoEnabled() )
1292  rDocShell.GetUndoManager()->AddUndoAction( std::make_unique<ScUndoShowHideNote>( rDocShell, rPos, bShow ) );
1293 
1294  rDoc.SetStreamValid(rPos.Tab(), false);
1295 
1297 
1298  if (ScViewData* pViewData = ScDocShell::GetViewData())
1299  {
1300  if (ScDrawView* pDrawView = pViewData->GetScDrawView())
1301  pDrawView->SyncForGrid( pNote->GetCaption());
1302  }
1303 
1304  rDocShell.SetDocumentModified();
1305 
1306  return true;
1307 }
1308 
1309 void ScDocFunc::SetNoteText( const ScAddress& rPos, const OUString& rText, bool bApi )
1310 {
1311  ScDocShellModificator aModificator( rDocShell );
1312 
1313  ScDocument& rDoc = rDocShell.GetDocument();
1314  ScEditableTester aTester( rDoc, rPos.Tab(), rPos.Col(),rPos.Row(), rPos.Col(),rPos.Row() );
1315  if (!aTester.IsEditable())
1316  {
1317  if (!bApi)
1318  rDocShell.ErrorMessage(aTester.GetMessageId());
1319  return;
1320  }
1321 
1322  OUString aNewText = convertLineEnd(rText, GetSystemLineEnd());
1323 
1324  if( ScPostIt* pNote = (!aNewText.isEmpty()) ? rDoc.GetOrCreateNote( rPos ) : rDoc.GetNote(rPos) )
1325  pNote->SetText( rPos, aNewText );
1326 
1328 
1329  rDoc.SetStreamValid(rPos.Tab(), false);
1330 
1331  rDocShell.PostPaintCell( rPos );
1332  aModificator.SetDocumentModified();
1333 }
1334 
1335 void ScDocFunc::ReplaceNote( const ScAddress& rPos, const OUString& rNoteText, const OUString* pAuthor, const OUString* pDate, bool bApi )
1336 {
1337  ScDocShellModificator aModificator( rDocShell );
1338  ScDocument& rDoc = rDocShell.GetDocument();
1339  ScEditableTester aTester( rDoc, rPos.Tab(), rPos.Col(),rPos.Row(), rPos.Col(),rPos.Row() );
1340  if (aTester.IsEditable())
1341  {
1342  ScDrawLayer* pDrawLayer = rDoc.GetDrawLayer();
1343  SfxUndoManager* pUndoMgr = (pDrawLayer && rDoc.IsUndoEnabled()) ? rDocShell.GetUndoManager() : nullptr;
1344 
1345  ScNoteData aOldData;
1346  std::unique_ptr<ScPostIt> pOldNote = rDoc.ReleaseNote( rPos );
1347  sal_uInt32 nNoteId = 0;
1348  if( pOldNote )
1349  {
1350  nNoteId = pOldNote->GetId();
1351  // ensure existing caption object before draw undo tracking starts
1352  pOldNote->GetOrCreateCaption( rPos );
1353  // rescue note data for undo
1354  aOldData = pOldNote->GetNoteData();
1355  }
1356 
1357  // collect drawing undo actions for deleting/inserting caption objects
1358  if( pUndoMgr )
1359  pDrawLayer->BeginCalcUndo(false);
1360 
1361  // delete the note (creates drawing undo action for the caption object)
1362  bool hadOldNote(pOldNote);
1363  pOldNote.reset();
1364 
1365  // create new note (creates drawing undo action for the new caption object)
1366  ScNoteData aNewData;
1367  ScPostIt* pNewNote = nullptr;
1368  if( (pNewNote = ScNoteUtil::CreateNoteFromString( rDoc, rPos, rNoteText, false, true, nNoteId )) )
1369  {
1370  if( pAuthor ) pNewNote->SetAuthor( *pAuthor );
1371  if( pDate ) pNewNote->SetDate( *pDate );
1372 
1373  // rescue note data for undo
1374  aNewData = pNewNote->GetNoteData();
1375  }
1376 
1377  // create the undo action
1378  if( pUndoMgr && (aOldData.mxCaption || aNewData.mxCaption) )
1379  pUndoMgr->AddUndoAction( std::make_unique<ScUndoReplaceNote>( rDocShell, rPos, aOldData, aNewData, pDrawLayer->GetCalcUndo() ) );
1380 
1381  // repaint cell (to make note marker visible)
1382  rDocShell.PostPaintCell( rPos );
1383 
1384  rDoc.SetStreamValid(rPos.Tab(), false);
1385 
1386  aModificator.SetDocumentModified();
1387 
1388  // Let our LOK clients know about the new/modified note
1389  if (pNewNote)
1390  {
1392  &rDoc, rPos, pNewNote);
1393  }
1394  }
1395  else if (!bApi)
1396  {
1397  rDocShell.ErrorMessage(aTester.GetMessageId());
1398  }
1399 }
1400 
1401 ScPostIt* ScDocFunc::ImportNote( const ScAddress& rPos, const OUString& rNoteText )
1402 {
1403  ScDocShellModificator aModificator( rDocShell );
1404  ScDocument& rDoc = rDocShell.GetDocument();
1405 
1406  std::unique_ptr<ScPostIt> pOldNote = rDoc.ReleaseNote( rPos );
1407  SAL_WARN_IF(pOldNote, "sc.ui", "imported data has >1 notes on same cell? at pos " << rPos);
1408 
1409  // create new note
1410  ScPostIt* pNewNote = ScNoteUtil::CreateNoteFromString( rDoc, rPos, rNoteText, false, true, /*nNoteId*/0 );
1411 
1412  rDoc.SetStreamValid(rPos.Tab(), false);
1413 
1414  aModificator.SetDocumentModified();
1415 
1416  return pNewNote;
1417 }
1418 
1419 bool ScDocFunc::ApplyAttributes( const ScMarkData& rMark, const ScPatternAttr& rPattern,
1420  bool bApi )
1421 {
1422  ScDocument& rDoc = rDocShell.GetDocument();
1423  bool bRecord = true;
1424  if ( !rDoc.IsUndoEnabled() )
1425  bRecord = false;
1426 
1427  bool bImportingXML = rDoc.IsImportingXML();
1428  // Cell formats can still be set if the range isn't editable only because of matrix formulas.
1429  // #i62483# When loading XML, the check can be skipped altogether.
1430  bool bOnlyNotBecauseOfMatrix;
1431  if ( !bImportingXML && !rDoc.IsSelectionEditable( rMark, &bOnlyNotBecauseOfMatrix )
1432  && !bOnlyNotBecauseOfMatrix )
1433  {
1434  if (!bApi)
1435  rDocShell.ErrorMessage(STR_PROTECTIONERR);
1436  return false;
1437  }
1438 
1439  ScDocShellModificator aModificator( rDocShell );
1440 
1442 
1443  ScRange aMultiRange;
1444  bool bMulti = rMark.IsMultiMarked();
1445  if ( bMulti )
1446  rMark.GetMultiMarkArea( aMultiRange );
1447  else
1448  rMark.GetMarkArea( aMultiRange );
1449 
1450  if ( bRecord )
1451  {
1452  ScDocumentUniquePtr pUndoDoc( new ScDocument( SCDOCMODE_UNDO ));
1453  pUndoDoc->InitUndo( rDoc, aMultiRange.aStart.Tab(), aMultiRange.aEnd.Tab() );
1454  rDoc.CopyToDocument(aMultiRange, InsertDeleteFlags::ATTRIB, bMulti, *pUndoDoc, &rMark);
1455 
1456  rDocShell.GetUndoManager()->AddUndoAction(
1457  std::make_unique<ScUndoSelectionAttr>(
1458  &rDocShell, rMark,
1459  aMultiRange.aStart.Col(), aMultiRange.aStart.Row(), aMultiRange.aStart.Tab(),
1460  aMultiRange.aEnd.Col(), aMultiRange.aEnd.Row(), aMultiRange.aEnd.Tab(),
1461  std::move(pUndoDoc), bMulti, &rPattern ) );
1462  }
1463 
1464  // While loading XML it is not necessary to ask HasAttrib. It needs too much time.
1465  sal_uInt16 nExtFlags = 0;
1466  if ( !bImportingXML )
1467  rDocShell.UpdatePaintExt( nExtFlags, aMultiRange ); // content before the change
1468 
1469  bool bChanged = false;
1470  rDoc.ApplySelectionPattern( rPattern, rMark, nullptr, &bChanged );
1471 
1472  if(bChanged)
1473  {
1474  if ( !bImportingXML )
1475  rDocShell.UpdatePaintExt( nExtFlags, aMultiRange ); // content after the change
1476 
1477  if (!AdjustRowHeight( aMultiRange, true, bApi ))
1478  rDocShell.PostPaint( aMultiRange, PaintPartFlags::Grid, nExtFlags );
1479  else if (nExtFlags & SC_PF_LINES)
1480  lcl_PaintAbove( rDocShell, aMultiRange ); // because of lines above the range
1481 
1482  aModificator.SetDocumentModified();
1483  }
1484 
1485  return true;
1486 }
1487 
1488 bool ScDocFunc::ApplyStyle( const ScMarkData& rMark, const OUString& rStyleName,
1489  bool bApi )
1490 {
1491  ScDocument& rDoc = rDocShell.GetDocument();
1492  bool bRecord = true;
1493  if ( !rDoc.IsUndoEnabled() )
1494  bRecord = false;
1495 
1496  bool bImportingXML = rDoc.IsImportingXML();
1497  // Cell formats can still be set if the range isn't editable only because of matrix formulas.
1498  // #i62483# When loading XML, the check can be skipped altogether.
1499  bool bOnlyNotBecauseOfMatrix;
1500  if ( !bImportingXML && !rDoc.IsSelectionEditable( rMark, &bOnlyNotBecauseOfMatrix )
1501  && !bOnlyNotBecauseOfMatrix )
1502  {
1503  if (!bApi)
1504  rDocShell.ErrorMessage(STR_PROTECTIONERR);
1505  return false;
1506  }
1507 
1508  ScStyleSheet* pStyleSheet = static_cast<ScStyleSheet*>( rDoc.GetStyleSheetPool()->Find(
1509  rStyleName, SfxStyleFamily::Para ));
1510  if (!pStyleSheet)
1511  return false;
1512 
1513  ScDocShellModificator aModificator( rDocShell );
1514 
1515  ScRange aMultiRange;
1516  bool bMulti = rMark.IsMultiMarked();
1517  if ( bMulti )
1518  rMark.GetMultiMarkArea( aMultiRange );
1519  else
1520  rMark.GetMarkArea( aMultiRange );
1521 
1522  if ( bRecord )
1523  {
1525  SCTAB nStartTab = aMultiRange.aStart.Tab();
1526  SCTAB nTabCount = rDoc.GetTableCount();
1527  pUndoDoc->InitUndo( rDoc, nStartTab, nStartTab );
1528  for (const auto& rTab : rMark)
1529  {
1530  if (rTab >= nTabCount)
1531  break;
1532 
1533  if (rTab != nStartTab)
1534  pUndoDoc->AddUndoTab( rTab, rTab );
1535  }
1536 
1537  ScRange aCopyRange = aMultiRange;
1538  aCopyRange.aStart.SetTab(0);
1539  aCopyRange.aEnd.SetTab(nTabCount-1);
1540  rDoc.CopyToDocument( aCopyRange, InsertDeleteFlags::ATTRIB, bMulti, *pUndoDoc, &rMark );
1541 
1542  rDocShell.GetUndoManager()->AddUndoAction(
1543  std::make_unique<ScUndoSelectionStyle>(
1544  &rDocShell, rMark, aMultiRange, rStyleName, std::move(pUndoDoc) ) );
1545 
1546  }
1547 
1548  rDoc.ApplySelectionStyle( *pStyleSheet, rMark );
1549 
1550  if (!AdjustRowHeight( aMultiRange, true, bApi ))
1551  rDocShell.PostPaint( aMultiRange, PaintPartFlags::Grid );
1552 
1553  aModificator.SetDocumentModified();
1554 
1555  return true;
1556 }
1557 
1558 namespace {
1559 
1567 bool canInsertCellsByPivot(const ScRange& rRange, const ScMarkData& rMarkData, InsCellCmd eCmd, const ScDocument& rDoc)
1568 {
1569  if (!rDoc.HasPivotTable())
1570  // This document has no pivot tables.
1571  return true;
1572 
1573  const ScDPCollection* pDPs = rDoc.GetDPCollection();
1574 
1575  ScRange aRange(rRange); // local copy
1576  switch (eCmd)
1577  {
1578  case INS_INSROWS_BEFORE:
1579  {
1580  aRange.aStart.SetCol(0);
1581  aRange.aEnd.SetCol(rDoc.MaxCol());
1582  [[fallthrough]];
1583  }
1584  case INS_CELLSDOWN:
1585  {
1586  auto bIntersects = std::any_of(rMarkData.begin(), rMarkData.end(), [&pDPs, &aRange](const SCTAB& rTab) {
1587  return pDPs->IntersectsTableByColumns(aRange.aStart.Col(), aRange.aEnd.Col(), aRange.aStart.Row(), rTab); });
1588  if (bIntersects)
1589  // This column range cuts through at least one pivot table. Not good.
1590  return false;
1591 
1592  // Start row must be either at the top or above any pivot tables.
1593  if (aRange.aStart.Row() < 0)
1594  // I don't know how to handle this case.
1595  return false;
1596 
1597  if (aRange.aStart.Row() == 0)
1598  // First row is always allowed.
1599  return true;
1600 
1601  ScRange aTest(aRange);
1602  aTest.aStart.IncRow(-1); // Test one row up.
1603  aTest.aEnd.SetRow(aTest.aStart.Row());
1604  for (const auto& rTab : rMarkData)
1605  {
1606  aTest.aStart.SetTab(rTab);
1607  aTest.aEnd.SetTab(rTab);
1608  if (pDPs->HasTable(aTest))
1609  return false;
1610  }
1611  }
1612  break;
1613  case INS_INSCOLS_BEFORE:
1614  {
1615  aRange.aStart.SetRow(0);
1616  aRange.aEnd.SetRow(rDoc.MaxRow());
1617  [[fallthrough]];
1618  }
1619  case INS_CELLSRIGHT:
1620  {
1621  auto bIntersects = std::any_of(rMarkData.begin(), rMarkData.end(), [&pDPs, &aRange](const SCTAB& rTab) {
1622  return pDPs->IntersectsTableByRows(aRange.aStart.Col(), aRange.aStart.Row(), aRange.aEnd.Row(), rTab); });
1623  if (bIntersects)
1624  // This column range cuts through at least one pivot table. Not good.
1625  return false;
1626 
1627  // Start row must be either at the top or above any pivot tables.
1628  if (aRange.aStart.Col() < 0)
1629  // I don't know how to handle this case.
1630  return false;
1631 
1632  if (aRange.aStart.Col() == 0)
1633  // First row is always allowed.
1634  return true;
1635 
1636  ScRange aTest(aRange);
1637  aTest.aStart.IncCol(-1); // Test one column to the left.
1638  aTest.aEnd.SetCol(aTest.aStart.Col());
1639  for (const auto& rTab : rMarkData)
1640  {
1641  aTest.aStart.SetTab(rTab);
1642  aTest.aEnd.SetTab(rTab);
1643  if (pDPs->HasTable(aTest))
1644  return false;
1645  }
1646  }
1647  break;
1648  default:
1649  ;
1650  }
1651  return true;
1652 }
1653 
1661 bool canDeleteCellsByPivot(const ScRange& rRange, const ScMarkData& rMarkData, DelCellCmd eCmd, const ScDocument& rDoc)
1662 {
1663  if (!rDoc.HasPivotTable())
1664  // This document has no pivot tables.
1665  return true;
1666 
1667  const ScDPCollection* pDPs = rDoc.GetDPCollection();
1668 
1669  ScRange aRange(rRange); // local copy
1670 
1671  switch (eCmd)
1672  {
1673  case DelCellCmd::Rows:
1674  {
1675  aRange.aStart.SetCol(0);
1676  aRange.aEnd.SetCol(rDoc.MaxCol());
1677  [[fallthrough]];
1678  }
1679  case DelCellCmd::CellsUp:
1680  {
1681  auto bIntersects = std::any_of(rMarkData.begin(), rMarkData.end(), [&pDPs, &aRange](const SCTAB& rTab) {
1682  return pDPs->IntersectsTableByColumns(aRange.aStart.Col(), aRange.aEnd.Col(), aRange.aStart.Row(), rTab); });
1683  if (bIntersects)
1684  // This column range cuts through at least one pivot table. Not good.
1685  return false;
1686 
1687  ScRange aTest(aRange);
1688  for (const auto& rTab : rMarkData)
1689  {
1690  aTest.aStart.SetTab(rTab);
1691  aTest.aEnd.SetTab(rTab);
1692  if (pDPs->HasTable(aTest))
1693  return false;
1694  }
1695  }
1696  break;
1697  case DelCellCmd::Cols:
1698  {
1699  aRange.aStart.SetRow(0);
1700  aRange.aEnd.SetRow(rDoc.MaxRow());
1701  [[fallthrough]];
1702  }
1703  case DelCellCmd::CellsLeft:
1704  {
1705  auto bIntersects = std::any_of(rMarkData.begin(), rMarkData.end(), [&pDPs, &aRange](const SCTAB& rTab) {
1706  return pDPs->IntersectsTableByRows(aRange.aStart.Col(), aRange.aStart.Row(), aRange.aEnd.Row(), rTab); });
1707  if (bIntersects)
1708  // This column range cuts through at least one pivot table. Not good.
1709  return false;
1710 
1711  ScRange aTest(aRange);
1712  for (const auto& rTab : rMarkData)
1713  {
1714  aTest.aStart.SetTab(rTab);
1715  aTest.aEnd.SetTab(rTab);
1716  if (pDPs->HasTable(aTest))
1717  return false;
1718  }
1719  }
1720  break;
1721  default:
1722  ;
1723  }
1724  return true;
1725 }
1726 
1727 }
1728 
1729 bool ScDocFunc::InsertCells( const ScRange& rRange, const ScMarkData* pTabMark, InsCellCmd eCmd,
1730  bool bRecord, bool bApi, bool bPartOfPaste )
1731 {
1732  ScDocShellModificator aModificator( rDocShell );
1733  ScDocument& rDoc = rDocShell.GetDocument();
1734 
1735  if (rDocShell.GetDocument().GetChangeTrack() &&
1736  ((eCmd == INS_CELLSDOWN && (rRange.aStart.Col() != 0 || rRange.aEnd.Col() != rDoc.MaxCol())) ||
1737  (eCmd == INS_CELLSRIGHT && (rRange.aStart.Row() != 0 || rRange.aEnd.Row() != rDoc.MaxRow()))))
1738  {
1739  // We should not reach this via UI disabled slots.
1740  assert(bApi);
1741  SAL_WARN("sc.ui","ScDocFunc::InsertCells - no change-tracking of partial cell shift");
1742  return false;
1743  }
1744 
1745  ScRange aTargetRange( rRange );
1746 
1747  // If insertion is for full cols/rows and after the current
1748  // selection, then shift the range accordingly
1749  if ( eCmd == INS_INSROWS_AFTER )
1750  {
1751  ScRange aErrorRange( ScAddress::UNINITIALIZED );
1752  if (!aTargetRange.Move(0, rRange.aEnd.Row() - rRange.aStart.Row() + 1, 0, aErrorRange))
1753  {
1754  return false;
1755  }
1756  }
1757  if ( eCmd == INS_INSCOLS_AFTER )
1758  {
1759  ScRange aErrorRange( ScAddress::UNINITIALIZED );
1760  if (!aTargetRange.Move(rRange.aEnd.Col() - rRange.aStart.Col() + 1, 0, 0, aErrorRange))
1761  {
1762  return false;
1763  }
1764  }
1765 
1766  SCCOL nStartCol = aTargetRange.aStart.Col();
1767  SCROW nStartRow = aTargetRange.aStart.Row();
1768  SCTAB nStartTab = aTargetRange.aStart.Tab();
1769  SCCOL nEndCol = aTargetRange.aEnd.Col();
1770  SCROW nEndRow = aTargetRange.aEnd.Row();
1771  SCTAB nEndTab = aTargetRange.aEnd.Tab();
1772 
1773  if ( !rDoc.ValidRow(nStartRow) || !rDoc.ValidRow(nEndRow) )
1774  {
1775  OSL_FAIL("invalid row in InsertCells");
1776  return false;
1777  }
1778 
1779  SCTAB nTabCount = rDoc.GetTableCount();
1780  SCCOL nPaintStartCol = nStartCol;
1781  SCROW nPaintStartRow = nStartRow;
1782  SCCOL nPaintEndCol = nEndCol;
1783  SCROW nPaintEndRow = nEndRow;
1784  PaintPartFlags nPaintFlags = PaintPartFlags::Grid;
1785  bool bSuccess;
1786 
1787  ScTabViewShell* pViewSh = rDocShell.GetBestViewShell(); //preserve current cursor position
1788  SCCOL nCursorCol = 0;
1789  SCROW nCursorRow = 0;
1790  if( pViewSh )
1791  {
1792  nCursorCol = pViewSh->GetViewData().GetCurX();
1793  nCursorRow = pViewSh->GetViewData().GetCurY();
1794  }
1795 
1796  if (bRecord && !rDoc.IsUndoEnabled())
1797  bRecord = false;
1798 
1799  ScMarkData aMark(rDoc.GetSheetLimits());
1800  if (pTabMark)
1801  aMark = *pTabMark;
1802  else
1803  {
1804  SCTAB nCount = 0;
1805  for( SCTAB i=0; i<nTabCount; i++ )
1806  {
1807  if( !rDoc.IsScenario(i) )
1808  {
1809  nCount++;
1810  if( nCount == nEndTab+1 )
1811  {
1812  aMark.SelectTable( i, true );
1813  break;
1814  }
1815  }
1816  }
1817  }
1818 
1819  ScMarkData aFullMark( aMark ); // including scenario sheets
1820  for (const auto& rTab : aMark)
1821  {
1822  if (rTab >= nTabCount)
1823  break;
1824 
1825  for( SCTAB j = rTab+1; j<nTabCount && rDoc.IsScenario(j); j++ )
1826  aFullMark.SelectTable( j, true );
1827  }
1828 
1829  SCTAB nSelCount = aMark.GetSelectCount();
1830 
1831  // Adjust also related scenarios
1832 
1833  SCCOL nMergeTestStartCol = nStartCol;
1834  SCROW nMergeTestStartRow = nStartRow;
1835  SCCOL nMergeTestEndCol = nEndCol;
1836  SCROW nMergeTestEndRow = nEndRow;
1837 
1838  ScRange aExtendMergeRange( aTargetRange );
1839 
1840  if( aTargetRange.aStart == aTargetRange.aEnd && rDoc.HasAttrib(aTargetRange, HasAttrFlags::Merged) )
1841  {
1842  rDoc.ExtendMerge( aExtendMergeRange );
1843  rDoc.ExtendOverlapped( aExtendMergeRange );
1844  nMergeTestEndCol = aExtendMergeRange.aEnd.Col();
1845  nMergeTestEndRow = aExtendMergeRange.aEnd.Row();
1846  nPaintEndCol = nMergeTestEndCol;
1847  nPaintEndRow = nMergeTestEndRow;
1848  }
1849 
1850  if ( eCmd == INS_INSROWS_BEFORE || eCmd == INS_INSROWS_AFTER )
1851  {
1852  nMergeTestStartCol = 0;
1853  nMergeTestEndCol = rDoc.MaxCol();
1854  }
1855  if ( eCmd == INS_INSCOLS_BEFORE || eCmd == INS_INSCOLS_AFTER )
1856  {
1857  nMergeTestStartRow = 0;
1858  nMergeTestEndRow = rDoc.MaxRow();
1859  }
1860  if ( eCmd == INS_CELLSDOWN )
1861  nMergeTestEndRow = rDoc.MaxRow();
1862  if ( eCmd == INS_CELLSRIGHT )
1863  nMergeTestEndCol = rDoc.MaxCol();
1864 
1865  bool bNeedRefresh = false;
1866 
1867  SCCOL nEditTestEndCol = (eCmd==INS_INSCOLS_BEFORE || eCmd==INS_INSCOLS_AFTER) ? rDoc.MaxCol() : nMergeTestEndCol;
1868  SCROW nEditTestEndRow = (eCmd==INS_INSROWS_BEFORE || eCmd==INS_INSROWS_AFTER) ? rDoc.MaxRow() : nMergeTestEndRow;
1869 
1870  ScEditableTester aTester;
1871 
1872  switch (eCmd)
1873  {
1874  case INS_INSCOLS_BEFORE:
1875  aTester = ScEditableTester(
1876  rDoc, sc::ColRowEditAction::InsertColumnsBefore, nMergeTestStartCol, nMergeTestEndCol, aMark);
1877  break;
1878  case INS_INSCOLS_AFTER:
1879  aTester = ScEditableTester(
1880  rDoc, sc::ColRowEditAction::InsertColumnsAfter, nMergeTestStartCol, nMergeTestEndCol, aMark);
1881  break;
1882  case INS_INSROWS_BEFORE:
1883  aTester = ScEditableTester(
1884  rDoc, sc::ColRowEditAction::InsertRowsBefore, nMergeTestStartRow, nMergeTestEndRow, aMark);
1885  break;
1886  case INS_INSROWS_AFTER:
1887  aTester = ScEditableTester(
1888  rDoc, sc::ColRowEditAction::InsertRowsAfter, nMergeTestStartRow, nMergeTestEndRow, aMark);
1889  break;
1890  default:
1891  aTester = ScEditableTester(
1892  rDoc, nMergeTestStartCol, nMergeTestStartRow, nEditTestEndCol, nEditTestEndRow, aMark);
1893  }
1894 
1895  if (!aTester.IsEditable())
1896  {
1897  if (!bApi)
1898  rDocShell.ErrorMessage(aTester.GetMessageId());
1899  return false;
1900  }
1901 
1902  // Check if this insertion is allowed with respect to pivot table.
1903  if (!canInsertCellsByPivot(aTargetRange, aMark, eCmd, rDoc))
1904  {
1905  if (!bApi)
1906  rDocShell.ErrorMessage(STR_NO_INSERT_DELETE_OVER_PIVOT_TABLE);
1907  return false;
1908  }
1909 
1910  weld::WaitObject aWait( ScDocShell::GetActiveDialogParent() ); // important due to TrackFormulas at UpdateReference
1911 
1912  ScDocumentUniquePtr pRefUndoDoc;
1913  std::unique_ptr<ScRefUndoData> pUndoData;
1914  if ( bRecord )
1915  {
1916  pRefUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
1917  pRefUndoDoc->InitUndo( rDoc, 0, nTabCount-1 );
1918 
1919  // pRefUndoDoc is filled in InsertCol / InsertRow
1920 
1921  pUndoData.reset(new ScRefUndoData( &rDoc ));
1922 
1923  rDoc.BeginDrawUndo();
1924  }
1925 
1926  // #i8302 : we unmerge overwhelming ranges, before insertion all the actions are put in the same ListAction
1927  // the patch comes from mloiseleur and maoyg
1928  bool bInsertMerge = false;
1929  std::vector<ScRange> qIncreaseRange;
1930  OUString aUndo = ScResId( STR_UNDO_INSERTCELLS );
1931  if (bRecord)
1932  {
1933  ViewShellId nViewShellId(-1);
1934  if (pViewSh)
1935  nViewShellId = pViewSh->GetViewShellId();
1936  rDocShell.GetUndoManager()->EnterListAction( aUndo, aUndo, 0, nViewShellId );
1937  }
1938  std::unique_ptr<ScUndoRemoveMerge> pUndoRemoveMerge;
1939 
1940  for (const SCTAB i : aMark)
1941  {
1942  if (i >= nTabCount)
1943  break;
1944 
1945  if( rDoc.HasAttrib( nMergeTestStartCol, nMergeTestStartRow, i, nMergeTestEndCol, nMergeTestEndRow, i, HasAttrFlags::Merged | HasAttrFlags::Overlapped ) )
1946  {
1947  if (eCmd==INS_CELLSRIGHT)
1948  bNeedRefresh = true;
1949 
1950  SCCOL nMergeStartCol = nMergeTestStartCol;
1951  SCROW nMergeStartRow = nMergeTestStartRow;
1952  SCCOL nMergeEndCol = nMergeTestEndCol;
1953  SCROW nMergeEndRow = nMergeTestEndRow;
1954 
1955  rDoc.ExtendMerge( nMergeStartCol, nMergeStartRow, nMergeEndCol, nMergeEndRow, i );
1956  rDoc.ExtendOverlapped( nMergeStartCol, nMergeStartRow, nMergeEndCol, nMergeEndRow, i );
1957 
1958  if(( eCmd == INS_CELLSDOWN && ( nMergeStartCol != nMergeTestStartCol || nMergeEndCol != nMergeTestEndCol )) ||
1959  (eCmd == INS_CELLSRIGHT && ( nMergeStartRow != nMergeTestStartRow || nMergeEndRow != nMergeTestEndRow )) )
1960  {
1961  if (!bApi)
1962  rDocShell.ErrorMessage(STR_MSSG_INSERTCELLS_0);
1963  rDocShell.GetUndoManager()->LeaveListAction();
1964  return false;
1965  }
1966 
1967  SCCOL nTestCol = -1;
1968  SCROW nTestRow1 = -1;
1969  SCROW nTestRow2 = -1;
1970 
1971  ScDocAttrIterator aTestIter( rDoc, i, nMergeTestStartCol, nMergeTestStartRow, nMergeTestEndCol, nMergeTestEndRow );
1972  ScRange aExtendRange( nMergeTestStartCol, nMergeTestStartRow, i, nMergeTestEndCol, nMergeTestEndRow, i );
1973  const ScPatternAttr* pPattern = nullptr;
1974  while ( ( pPattern = aTestIter.GetNext( nTestCol, nTestRow1, nTestRow2 ) ) != nullptr )
1975  {
1976  const ScMergeAttr& rMergeFlag = pPattern->GetItem(ATTR_MERGE);
1977  const ScMergeFlagAttr& rMergeFlagAttr = pPattern->GetItem(ATTR_MERGE_FLAG);
1978  ScMF nNewFlags = rMergeFlagAttr.GetValue() & (ScMF::Hor | ScMF::Ver);
1979  if (rMergeFlag.IsMerged() || nNewFlags == ScMF::Hor || nNewFlags == ScMF::Ver)
1980  {
1981  ScRange aRange( nTestCol, nTestRow1, i );
1982  rDoc.ExtendOverlapped(aRange);
1983  rDoc.ExtendMerge(aRange, true);
1984 
1985  if( nTestRow1 < nTestRow2 && nNewFlags == ScMF::Hor )
1986  {
1987  for( SCROW nTestRow = nTestRow1; nTestRow <= nTestRow2; nTestRow++ )
1988  {
1989  ScRange aTestRange( nTestCol, nTestRow, i );
1990  rDoc.ExtendOverlapped( aTestRange );
1991  rDoc.ExtendMerge( aTestRange, true);
1992  ScRange aMergeRange( aTestRange.aStart.Col(),aTestRange.aStart.Row(), i );
1993  if( !aExtendRange.In( aMergeRange ) )
1994  {
1995  qIncreaseRange.push_back( aTestRange );
1996  bInsertMerge = true;
1997  }
1998  }
1999  }
2000  else
2001  {
2002  ScRange aMergeRange( aRange.aStart.Col(),aRange.aStart.Row(), i );
2003  if( !aExtendRange.In( aMergeRange ) )
2004  {
2005  qIncreaseRange.push_back( aRange );
2006  }
2007  bInsertMerge = true;
2008  }
2009  }
2010  }
2011 
2012  if( bInsertMerge )
2013  {
2014  if( eCmd == INS_INSROWS_BEFORE || eCmd == INS_INSROWS_AFTER || eCmd == INS_CELLSDOWN )
2015  {
2016  nStartRow = aExtendMergeRange.aStart.Row();
2017  nEndRow = aExtendMergeRange.aEnd.Row();
2018 
2019  if( eCmd == INS_CELLSDOWN )
2020  nEndCol = nMergeTestEndCol;
2021  else
2022  {
2023  nStartCol = 0;
2024  nEndCol = rDoc.MaxCol();
2025  }
2026  }
2027  else if( eCmd == INS_CELLSRIGHT || eCmd == INS_INSCOLS_BEFORE || eCmd == INS_INSCOLS_AFTER )
2028  {
2029 
2030  nStartCol = aExtendMergeRange.aStart.Col();
2031  nEndCol = aExtendMergeRange.aEnd.Col();
2032  if( eCmd == INS_CELLSRIGHT )
2033  {
2034  nEndRow = nMergeTestEndRow;
2035  }
2036  else
2037  {
2038  nStartRow = 0;
2039  nEndRow = rDoc.MaxRow();
2040  }
2041  }
2042 
2043  if( !qIncreaseRange.empty() )
2044  {
2045  if (bRecord && !pUndoRemoveMerge)
2046  {
2048  pUndoDoc->InitUndo( rDoc, *aMark.begin(), *aMark.rbegin());
2049  pUndoRemoveMerge.reset( new ScUndoRemoveMerge( &rDocShell, rRange, std::move(pUndoDoc) ));
2050  }
2051 
2052  for( const ScRange& aRange : qIncreaseRange )
2053  {
2055  {
2056  UnmergeCells( aRange, bRecord, pUndoRemoveMerge.get() );
2057  }
2058  }
2059  }
2060  }
2061  else
2062  {
2063  if (!bApi)
2064  rDocShell.ErrorMessage(STR_MSSG_INSERTCELLS_0);
2065  rDocShell.GetUndoManager()->LeaveListAction();
2066  return false;
2067  }
2068  }
2069  }
2070 
2071  if (bRecord && pUndoRemoveMerge)
2072  {
2073  rDocShell.GetUndoManager()->AddUndoAction( std::move(pUndoRemoveMerge));
2074  }
2075 
2076  switch (eCmd)
2077  {
2078  case INS_CELLSDOWN:
2079  bSuccess = rDoc.InsertRow( nStartCol, 0, nEndCol, MAXTAB, nStartRow, static_cast<SCSIZE>(nEndRow-nStartRow+1), pRefUndoDoc.get(), &aFullMark );
2080  nPaintEndRow = rDoc.MaxRow();
2081  break;
2082  case INS_INSROWS_BEFORE:
2083  case INS_INSROWS_AFTER:
2084  bSuccess = rDoc.InsertRow( 0, 0, rDoc.MaxCol(), MAXTAB, nStartRow, static_cast<SCSIZE>(nEndRow-nStartRow+1), pRefUndoDoc.get(), &aFullMark );
2085  nPaintStartCol = 0;
2086  nPaintEndCol = rDoc.MaxCol();
2087  nPaintEndRow = rDoc.MaxRow();
2088  nPaintFlags |= PaintPartFlags::Left;
2089  break;
2090  case INS_CELLSRIGHT:
2091  bSuccess = rDoc.InsertCol( nStartRow, 0, nEndRow, MAXTAB, nStartCol, static_cast<SCSIZE>(nEndCol-nStartCol+1), pRefUndoDoc.get(), &aFullMark );
2092  nPaintEndCol = rDoc.MaxCol();
2093  break;
2094  case INS_INSCOLS_BEFORE:
2095  case INS_INSCOLS_AFTER:
2096  bSuccess = rDoc.InsertCol( 0, 0, rDoc.MaxRow(), MAXTAB, nStartCol, static_cast<SCSIZE>(nEndCol-nStartCol+1), pRefUndoDoc.get(), &aFullMark );
2097  nPaintStartRow = 0;
2098  nPaintEndRow = rDoc.MaxRow();
2099  nPaintEndCol = rDoc.MaxCol();
2100  nPaintFlags |= PaintPartFlags::Top;
2101  break;
2102  default:
2103  OSL_FAIL("Wrong code at inserting");
2104  bSuccess = false;
2105  break;
2106  }
2107 
2108  if ( bSuccess )
2109  {
2110  SCTAB nUndoPos = 0;
2111 
2112  if ( bRecord )
2113  {
2114  std::unique_ptr<SCTAB[]> pTabs(new SCTAB[nSelCount]);
2115  std::unique_ptr<SCTAB[]> pScenarios(new SCTAB[nSelCount]);
2116  nUndoPos = 0;
2117  for (const auto& rTab : aMark)
2118  {
2119  if (rTab >= nTabCount)
2120  break;
2121 
2122  SCTAB nCount = 0;
2123  for( SCTAB j=rTab+1; j<nTabCount && rDoc.IsScenario(j); j++ )
2124  nCount ++;
2125 
2126  pScenarios[nUndoPos] = nCount;
2127  pTabs[nUndoPos] = rTab;
2128  nUndoPos ++;
2129  }
2130 
2131  if( !bInsertMerge )
2132  {
2133  rDocShell.GetUndoManager()->LeaveListAction();
2134  }
2135 
2136  rDocShell.GetUndoManager()->AddUndoAction( std::make_unique<ScUndoInsertCells>(
2137  &rDocShell, ScRange( nStartCol, nStartRow, nStartTab, nEndCol, nEndRow, nEndTab ),
2138  nUndoPos, std::move(pTabs), std::move(pScenarios), eCmd, std::move(pRefUndoDoc), std::move(pUndoData), bPartOfPaste ) );
2139  }
2140 
2141  // #i8302 : we remerge growing ranges, with the new part inserted
2142 
2143  while( !qIncreaseRange.empty() )
2144  {
2145  ScRange aRange = qIncreaseRange.back();
2147  {
2148  switch (eCmd)
2149  {
2150  case INS_CELLSDOWN:
2151  case INS_INSROWS_BEFORE:
2152  case INS_INSROWS_AFTER:
2153  aRange.aEnd.IncRow(static_cast<SCCOL>(nEndRow-nStartRow+1));
2154  break;
2155  case INS_CELLSRIGHT:
2156  case INS_INSCOLS_BEFORE:
2157  case INS_INSCOLS_AFTER:
2158  aRange.aEnd.IncCol(static_cast<SCCOL>(nEndCol-nStartCol+1));
2159  break;
2160  default:
2161  break;
2162  }
2163  ScCellMergeOption aMergeOption(
2164  aRange.aStart.Col(), aRange.aStart.Row(),
2165  aRange.aEnd.Col(), aRange.aEnd.Row() );
2166  aMergeOption.maTabs.insert(aRange.aStart.Tab());
2167  MergeCells(aMergeOption, false, true, true);
2168  }
2169  qIncreaseRange.pop_back();
2170  }
2171 
2172  if( bInsertMerge )
2173  rDocShell.GetUndoManager()->LeaveListAction();
2174 
2175  for (const SCTAB i : aMark)
2176  {
2177  if (i >= nTabCount)
2178  break;
2179 
2180  rDoc.SetDrawPageSize(i);
2181 
2182  if (bNeedRefresh)
2183  rDoc.ExtendMerge( nMergeTestStartCol, nMergeTestStartRow, nMergeTestEndCol, nMergeTestEndRow, i, true );
2184  else
2185  rDoc.RefreshAutoFilter( nMergeTestStartCol, nMergeTestStartRow, nMergeTestEndCol, nMergeTestEndRow, i );
2186 
2187  if ( eCmd == INS_INSROWS_BEFORE ||eCmd == INS_INSCOLS_BEFORE || eCmd == INS_INSROWS_AFTER ||eCmd == INS_INSCOLS_AFTER )
2188  rDoc.UpdatePageBreaks( i );
2189 
2190  sal_uInt16 nExtFlags = 0;
2191  rDocShell.UpdatePaintExt( nExtFlags, nPaintStartCol, nPaintStartRow, i, nPaintEndCol, nPaintEndRow, i );
2192 
2193  SCTAB nScenarioCount = 0;
2194 
2195  for( SCTAB j = i+1; j<nTabCount && rDoc.IsScenario(j); j++ )
2196  nScenarioCount ++;
2197 
2198  bool bAdjusted = ( eCmd == INS_INSROWS_BEFORE || eCmd == INS_INSROWS_AFTER ) ?
2199  AdjustRowHeight(ScRange(0, nStartRow, i, rDoc.MaxCol(), nEndRow, i+nScenarioCount ), true, bApi) :
2200  AdjustRowHeight(ScRange(0, nPaintStartRow, i, rDoc.MaxCol(), nPaintEndRow, i+nScenarioCount ), true, bApi);
2201  if (bAdjusted)
2202  {
2203  // paint only what is not done by AdjustRowHeight
2204  if (nPaintFlags & PaintPartFlags::Top)
2205  rDocShell.PostPaint( nPaintStartCol, nPaintStartRow, i, nPaintEndCol, nPaintEndRow, i+nScenarioCount, PaintPartFlags::Top );
2206  }
2207  else
2208  rDocShell.PostPaint( nPaintStartCol, nPaintStartRow, i, nPaintEndCol, nPaintEndRow, i+nScenarioCount, nPaintFlags, nExtFlags );
2209  }
2210  }
2211  else
2212  {
2213  if( bInsertMerge )
2214  {
2215  while( !qIncreaseRange.empty() )
2216  {
2217  ScRange aRange = qIncreaseRange.back();
2218  ScCellMergeOption aMergeOption(
2219  aRange.aStart.Col(), aRange.aStart.Row(),
2220  aRange.aEnd.Col(), aRange.aEnd.Row() );
2221  MergeCells(aMergeOption, false, true, true);
2222  qIncreaseRange.pop_back();
2223  }
2224 
2225  if( pViewSh )
2226  {
2227  pViewSh->MarkRange( aTargetRange, false );
2228  pViewSh->SetCursor( nCursorCol, nCursorRow );
2229  }
2230  }
2231 
2232  rDocShell.GetUndoManager()->LeaveListAction();
2233  rDocShell.GetUndoManager()->RemoveLastUndoAction();
2234 
2235  pRefUndoDoc.reset();
2236  if (!bApi)
2237  rDocShell.ErrorMessage(STR_INSERT_FULL); // column/row full
2238  }
2239 
2240  // The cursor position needs to be modified earlier than updating
2241  // any enabled edit view which is triggered by SetDocumentModified below.
2242  if (bSuccess)
2243  {
2244  bool bInsertCols = ( eCmd == INS_INSCOLS_BEFORE || eCmd == INS_INSCOLS_AFTER);
2245  bool bInsertRows = ( eCmd == INS_INSROWS_BEFORE || eCmd == INS_INSROWS_AFTER );
2246 
2247  if (bInsertCols)
2248  {
2249  pViewSh->OnLOKInsertDeleteColumn(rRange.aStart.Col(), 1);
2250  }
2251 
2252  if (bInsertRows)
2253  {
2254  pViewSh->OnLOKInsertDeleteRow(rRange.aStart.Row(), 1);
2255  }
2256  }
2257 
2258  aModificator.SetDocumentModified();
2259 
2260  SfxGetpApp()->Broadcast( SfxHint( SfxHintId::ScAreaLinksChanged ) );
2261  return bSuccess;
2262 }
2263 
2264 bool ScDocFunc::DeleteCells( const ScRange& rRange, const ScMarkData* pTabMark, DelCellCmd eCmd,
2265  bool bApi )
2266 {
2267  ScDocShellModificator aModificator( rDocShell );
2268  ScDocument& rDoc = rDocShell.GetDocument();
2269 
2270  if (rDocShell.GetDocument().GetChangeTrack() &&
2271  ((eCmd == DelCellCmd::CellsUp && (rRange.aStart.Col() != 0 || rRange.aEnd.Col() != rDoc.MaxCol())) ||
2272  (eCmd == DelCellCmd::CellsLeft && (rRange.aStart.Row() != 0 || rRange.aEnd.Row() != rDoc.MaxRow()))))
2273  {
2274  // We should not reach this via UI disabled slots.
2275  assert(bApi);
2276  SAL_WARN("sc.ui","ScDocFunc::DeleteCells - no change-tracking of partial cell shift");
2277  return false;
2278  }
2279 
2280  SCCOL nStartCol = rRange.aStart.Col();
2281  SCROW nStartRow = rRange.aStart.Row();
2282  SCTAB nStartTab = rRange.aStart.Tab();
2283  SCCOL nEndCol = rRange.aEnd.Col();
2284  SCROW nEndRow = rRange.aEnd.Row();
2285  SCTAB nEndTab = rRange.aEnd.Tab();
2286 
2287  if ( !rDoc.ValidRow(nStartRow) || !rDoc.ValidRow(nEndRow) )
2288  {
2289  OSL_FAIL("invalid row in DeleteCells");
2290  return false;
2291  }
2292 
2293  SCTAB nTabCount = rDoc.GetTableCount();
2294  SCCOL nPaintStartCol = nStartCol;
2295  SCROW nPaintStartRow = nStartRow;
2296  SCCOL nPaintEndCol = nEndCol;
2297  SCROW nPaintEndRow = nEndRow;
2298  PaintPartFlags nPaintFlags = PaintPartFlags::Grid;
2299 
2300  bool bRecord = true;
2301  if (!rDoc.IsUndoEnabled())
2302  bRecord = false;
2303 
2304  ScMarkData aMark(rDoc.GetSheetLimits());
2305  if (pTabMark)
2306  aMark = *pTabMark;
2307  else
2308  {
2309  SCTAB nCount = 0;
2310  for(SCTAB i=0; i<nTabCount; i++ )
2311  {
2312  if( !rDoc.IsScenario(i) )
2313  {
2314  nCount++;
2315  if( nCount == nEndTab+1 )
2316  {
2317  aMark.SelectTable(i, true);
2318  break;
2319  }
2320  }
2321  }
2322  }
2323 
2324  ScMarkData aFullMark( aMark ); // including scenario sheets
2325  for (const auto& rTab : aMark)
2326  {
2327  if (rTab >= nTabCount)
2328  break;
2329 
2330  for( SCTAB j = rTab+1; j<nTabCount && rDoc.IsScenario(j); j++ )
2331  aFullMark.SelectTable( j, true );
2332  }
2333 
2334  SCTAB nSelCount = aMark.GetSelectCount();
2335 
2336  SCCOL nUndoStartCol = nStartCol;
2337  SCROW nUndoStartRow = nStartRow;
2338  SCCOL nUndoEndCol = nEndCol;
2339  SCROW nUndoEndRow = nEndRow;
2340 
2341  ScRange aExtendMergeRange( rRange );
2342 
2343  if( rRange.aStart == rRange.aEnd && rDoc.HasAttrib(rRange, HasAttrFlags::Merged) )
2344  {
2345  rDoc.ExtendMerge( aExtendMergeRange );
2346  rDoc.ExtendOverlapped( aExtendMergeRange );
2347  nUndoEndCol = aExtendMergeRange.aEnd.Col();
2348  nUndoEndRow = aExtendMergeRange.aEnd.Row();
2349  nPaintEndCol = nUndoEndCol;
2350  nPaintEndRow = nUndoEndRow;
2351  }
2352 
2353  if (eCmd==DelCellCmd::Rows)
2354  {
2355  nUndoStartCol = 0;
2356  nUndoEndCol = rDoc.MaxCol();
2357  }
2358  if (eCmd==DelCellCmd::Cols)
2359  {
2360  nUndoStartRow = 0;
2361  nUndoEndRow = rDoc.MaxRow();
2362  }
2363  // Test for cell protection
2364 
2365  SCCOL nEditTestEndX = nUndoEndCol;
2366  if ( eCmd==DelCellCmd::Cols || eCmd==DelCellCmd::CellsLeft )
2367  nEditTestEndX = rDoc.MaxCol();
2368  SCROW nEditTestEndY = nUndoEndRow;
2369  if ( eCmd==DelCellCmd::Rows || eCmd==DelCellCmd::CellsUp )
2370  nEditTestEndY = rDoc.MaxRow();
2371 
2372  ScEditableTester aTester;
2373 
2374  switch (eCmd)
2375  {
2376  case DelCellCmd::Cols:
2377  aTester = ScEditableTester(
2378  rDoc, sc::ColRowEditAction::DeleteColumns, nUndoStartCol, nUndoEndCol, aMark);
2379  break;
2380  case DelCellCmd::Rows:
2381  aTester = ScEditableTester(
2382  rDoc, sc::ColRowEditAction::DeleteRows, nUndoStartRow, nUndoEndRow, aMark);
2383  break;
2384  default:
2385  aTester = ScEditableTester(
2386  rDoc, nUndoStartCol, nUndoStartRow, nEditTestEndX, nEditTestEndY, aMark);
2387  }
2388 
2389  if (!aTester.IsEditable())
2390  {
2391  if (!bApi)
2392  rDocShell.ErrorMessage(aTester.GetMessageId());
2393  return false;
2394  }
2395 
2396  if (!canDeleteCellsByPivot(rRange, aMark, eCmd, rDoc))
2397  {
2398  if (!bApi)
2399  rDocShell.ErrorMessage(STR_NO_INSERT_DELETE_OVER_PIVOT_TABLE);
2400  return false;
2401  }
2402  // Test for merged cells
2403 
2404  SCCOL nMergeTestEndCol = (eCmd==DelCellCmd::CellsLeft) ? rDoc.MaxCol() : nUndoEndCol;
2405  SCROW nMergeTestEndRow = (eCmd==DelCellCmd::CellsUp) ? rDoc.MaxRow() : nUndoEndRow;
2406  SCCOL nExtendStartCol = nUndoStartCol;
2407  SCROW nExtendStartRow = nUndoStartRow;
2408  bool bNeedRefresh = false;
2409 
2410  //Issue 8302 want to be able to insert into the middle of merged cells
2411  //the patch comes from maoyg
2412  ::std::vector<ScRange> qDecreaseRange;
2413  bool bDeletingMerge = false;
2414  OUString aUndo = ScResId( STR_UNDO_DELETECELLS );
2415  if (bRecord)
2416  {
2417  ViewShellId nViewShellId(-1);
2419  nViewShellId = pViewSh->GetViewShellId();
2420  rDocShell.GetUndoManager()->EnterListAction( aUndo, aUndo, 0, nViewShellId );
2421  }
2422  std::unique_ptr<ScUndoRemoveMerge> pUndoRemoveMerge;
2423 
2424  for (const SCTAB i : aMark)
2425  {
2426  if (i >= nTabCount)
2427  break;
2428 
2429  if ( rDoc.HasAttrib( nUndoStartCol, nUndoStartRow, i, nMergeTestEndCol, nMergeTestEndRow, i, HasAttrFlags::Merged | HasAttrFlags::Overlapped ))
2430  {
2431  SCCOL nMergeStartCol = nUndoStartCol;
2432  SCROW nMergeStartRow = nUndoStartRow;
2433  SCCOL nMergeEndCol = nMergeTestEndCol;
2434  SCROW nMergeEndRow = nMergeTestEndRow;
2435 
2436  rDoc.ExtendMerge( nMergeStartCol, nMergeStartRow, nMergeEndCol, nMergeEndRow, i );
2437  rDoc.ExtendOverlapped( nMergeStartCol, nMergeStartRow, nMergeEndCol, nMergeEndRow, i );
2438  if( ( eCmd == DelCellCmd::CellsUp && ( nMergeStartCol != nUndoStartCol || nMergeEndCol != nMergeTestEndCol))||
2439  ( eCmd == DelCellCmd::CellsLeft && ( nMergeStartRow != nUndoStartRow || nMergeEndRow != nMergeTestEndRow)))
2440  {
2441  if (!bApi)
2442  rDocShell.ErrorMessage(STR_MSSG_DELETECELLS_0);
2443  rDocShell.GetUndoManager()->LeaveListAction();
2444  return false;
2445  }
2446 
2447  nExtendStartCol = nMergeStartCol;
2448  nExtendStartRow = nMergeStartRow;
2449  SCCOL nTestCol = -1;
2450  SCROW nTestRow1 = -1;
2451  SCROW nTestRow2 = -1;
2452 
2453  ScDocAttrIterator aTestIter( rDoc, i, nUndoStartCol, nUndoStartRow, nMergeTestEndCol, nMergeTestEndRow );
2454  ScRange aExtendRange( nUndoStartCol, nUndoStartRow, i, nMergeTestEndCol, nMergeTestEndRow, i );
2455  const ScPatternAttr* pPattern = nullptr;
2456  while ( ( pPattern = aTestIter.GetNext( nTestCol, nTestRow1, nTestRow2 ) ) != nullptr )
2457  {
2458  const ScMergeAttr& rMergeFlag = pPattern->GetItem(ATTR_MERGE);
2459  const ScMergeFlagAttr& rMergeFlagAttr = pPattern->GetItem(ATTR_MERGE_FLAG);
2460  ScMF nNewFlags = rMergeFlagAttr.GetValue() & (ScMF::Hor | ScMF::Ver);
2461  if (rMergeFlag.IsMerged() || nNewFlags == ScMF::Hor || nNewFlags == ScMF::Ver)
2462  {
2463  ScRange aRange( nTestCol, nTestRow1, i );
2464  rDoc.ExtendOverlapped( aRange );
2465  rDoc.ExtendMerge( aRange, true );
2466 
2467  if( nTestRow1 < nTestRow2 && nNewFlags == ScMF::Hor )
2468  {
2469  for( SCROW nTestRow = nTestRow1; nTestRow <= nTestRow2; nTestRow++ )
2470  {
2471  ScRange aTestRange( nTestCol, nTestRow, i );
2472  rDoc.ExtendOverlapped( aTestRange );
2473  rDoc.ExtendMerge( aTestRange, true );
2474  ScRange aMergeRange( aTestRange.aStart.Col(),aTestRange.aStart.Row(), i );
2475  if( !aExtendRange.In( aMergeRange ) )
2476  {
2477  qDecreaseRange.push_back( aTestRange );
2478  bDeletingMerge = true;
2479  }
2480  }
2481  }
2482  else
2483  {
2484  ScRange aMergeRange( aRange.aStart.Col(),aRange.aStart.Row(), i );
2485  if( !aExtendRange.In( aMergeRange ) )
2486  {
2487  qDecreaseRange.push_back( aRange );
2488  }
2489  bDeletingMerge = true;
2490  }
2491  }
2492  }
2493 
2494  if( bDeletingMerge )
2495  {
2496 
2497  if( eCmd == DelCellCmd::Rows || eCmd == DelCellCmd::CellsUp )
2498  {
2499  nStartRow = aExtendMergeRange.aStart.Row();
2500  nEndRow = aExtendMergeRange.aEnd.Row();
2501  bNeedRefresh = true;
2502 
2503  if( eCmd == DelCellCmd::CellsUp )
2504  {
2505  nEndCol = aExtendMergeRange.aEnd.Col();
2506  }
2507  else
2508  {
2509  nStartCol = 0;
2510  nEndCol = rDoc.MaxCol();
2511  }
2512  }
2513  else if( eCmd == DelCellCmd::CellsLeft || eCmd == DelCellCmd::Cols )
2514  {
2515 
2516  nStartCol = aExtendMergeRange.aStart.Col();
2517  nEndCol = aExtendMergeRange.aEnd.Col();
2518  if( eCmd == DelCellCmd::CellsLeft )
2519  {
2520  nEndRow = aExtendMergeRange.aEnd.Row();
2521  bNeedRefresh = true;
2522  }
2523  else
2524  {
2525  nStartRow = 0;
2526  nEndRow = rDoc.MaxRow();
2527  }
2528  }
2529 
2530  if( !qDecreaseRange.empty() )
2531  {
2532  if (bRecord && !pUndoRemoveMerge)
2533  {
2535  pUndoDoc->InitUndo( rDoc, *aMark.begin(), *aMark.rbegin());
2536  pUndoRemoveMerge.reset( new ScUndoRemoveMerge( &rDocShell, rRange, std::move(pUndoDoc) ));
2537  }
2538 
2539  for( const ScRange& aRange : qDecreaseRange )
2540  {
2542  {
2543  UnmergeCells( aRange, bRecord, pUndoRemoveMerge.get() );
2544  }
2545  }
2546  }
2547  }
2548  else
2549  {
2550  if (!bApi)
2551  rDocShell.ErrorMessage(STR_MSSG_DELETECELLS_0);
2552  rDocShell.GetUndoManager()->LeaveListAction();
2553  return false;
2554  }
2555  }
2556  }
2557 
2558  if (bRecord && pUndoRemoveMerge)
2559  {
2560  rDocShell.GetUndoManager()->AddUndoAction( std::move(pUndoRemoveMerge));
2561  }
2562 
2563  // do it
2564 
2565  weld::WaitObject aWait( ScDocShell::GetActiveDialogParent() ); // important because of TrackFormulas in UpdateReference
2566 
2567  ScDocumentUniquePtr pUndoDoc;
2568  std::unique_ptr<ScDocument> pRefUndoDoc;
2569  std::unique_ptr<ScRefUndoData> pUndoData;
2570  if ( bRecord )
2571  {
2572  // With the fix for #101329#, UpdateRef always puts cells into pRefUndoDoc at their old position,
2573  // so it's no longer necessary to copy more than the deleted range into pUndoDoc.
2574 
2575  pUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
2576  pUndoDoc->InitUndo( rDoc, 0, nTabCount-1, (eCmd==DelCellCmd::Cols), (eCmd==DelCellCmd::Rows) );
2577  for (const auto& rTab : aMark)
2578  {
2579  if (rTab >= nTabCount)
2580  break;
2581 
2582  SCTAB nScenarioCount = 0;
2583 
2584  for( SCTAB j = rTab+1; j<nTabCount && rDoc.IsScenario(j); j++ )
2585  nScenarioCount ++;
2586 
2587  rDoc.CopyToDocument( nUndoStartCol, nUndoStartRow, rTab, nUndoEndCol, nUndoEndRow, rTab+nScenarioCount,
2589  }
2590 
2591  pRefUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
2592  pRefUndoDoc->InitUndo( rDoc, 0, nTabCount-1 );
2593 
2594  pUndoData.reset(new ScRefUndoData( &rDoc ));
2595 
2596  rDoc.BeginDrawUndo();
2597  }
2598 
2599  sal_uInt16 nExtFlags = 0;
2600  for (const auto& rTab : aMark)
2601  {
2602  if (rTab >= nTabCount)
2603  break;
2604 
2605  rDocShell.UpdatePaintExt( nExtFlags, nStartCol, nStartRow, rTab, nEndCol, nEndRow, rTab );
2606  }
2607 
2608  switch (eCmd)
2609  {
2610  case DelCellCmd::CellsUp:
2611  case DelCellCmd::CellsLeft:
2612  rDoc.DeleteObjectsInArea(nStartCol, nStartRow, nEndCol, nEndRow, aMark, true);
2613  break;
2614  case DelCellCmd::Rows:
2615  rDoc.DeleteObjectsInArea(0, nStartRow, rDoc.MaxCol(), nEndRow, aMark, true);
2616  break;
2617  case DelCellCmd::Cols:
2618  rDoc.DeleteObjectsInArea(nStartCol, 0, nEndCol, rDoc.MaxRow(), aMark, true);
2619  break;
2620  default:
2621  break;
2622  }
2623 
2624 
2625  bool bUndoOutline = false;
2626  switch (eCmd)
2627  {
2628  case DelCellCmd::CellsUp:
2629  rDoc.DeleteRow( nStartCol, 0, nEndCol, MAXTAB, nStartRow, static_cast<SCSIZE>(nEndRow-nStartRow+1), pRefUndoDoc.get(), nullptr, &aFullMark );
2630  nPaintEndRow = rDoc.MaxRow();
2631  break;
2632  case DelCellCmd::Rows:
2633  rDoc.DeleteRow( 0, 0, rDoc.MaxCol(), MAXTAB, nStartRow, static_cast<SCSIZE>(nEndRow-nStartRow+1), pRefUndoDoc.get(), &bUndoOutline, &aFullMark );
2634  nPaintStartCol = 0;
2635  nPaintEndCol = rDoc.MaxCol();
2636  nPaintEndRow = rDoc.MaxRow();
2637  nPaintFlags |= PaintPartFlags::Left;
2638  break;
2639  case DelCellCmd::CellsLeft:
2640  rDoc.DeleteCol( nStartRow, 0, nEndRow, MAXTAB, nStartCol, static_cast<SCSIZE>(nEndCol-nStartCol+1), pRefUndoDoc.get(), nullptr, &aFullMark );
2641  nPaintEndCol = rDoc.MaxCol();
2642  break;
2643  case DelCellCmd::Cols:
2644  rDoc.DeleteCol( 0, 0, rDoc.MaxRow(), MAXTAB, nStartCol, static_cast<SCSIZE>(nEndCol-nStartCol+1), pRefUndoDoc.get(), &bUndoOutline, &aFullMark );
2645  nPaintStartRow = 0;
2646  nPaintEndRow = rDoc.MaxRow();
2647  nPaintEndCol = rDoc.MaxCol();
2648  nPaintFlags |= PaintPartFlags::Top;
2649  break;
2650  default:
2651  OSL_FAIL("Wrong code at deleting");
2652  break;
2653  }
2654 
2656 
2657  if ( bRecord )
2658  {
2659  for (const auto& rTab : aFullMark)
2660  {
2661  if (rTab >= nTabCount)
2662  break;
2663 
2664  pRefUndoDoc->DeleteAreaTab(nUndoStartCol,nUndoStartRow,nUndoEndCol,nUndoEndRow, rTab, InsertDeleteFlags::ALL);
2665  }
2666 
2667  // for all sheets, so that formulas can be copied
2668  pUndoDoc->AddUndoTab( 0, nTabCount-1 );
2669 
2670  // copy with bColRowFlags=false (#54194#)
2671  pRefUndoDoc->CopyToDocument(0,0,0,rDoc.MaxCol(),rDoc.MaxRow(),MAXTAB,InsertDeleteFlags::FORMULA,false,*pUndoDoc,nullptr,false);
2672  pRefUndoDoc.reset();
2673 
2674  std::unique_ptr<SCTAB[]> pTabs( new SCTAB[nSelCount]);
2675  std::unique_ptr<SCTAB[]> pScenarios( new SCTAB[nSelCount]);
2676  SCTAB nUndoPos = 0;
2677 
2678  for (const auto& rTab : aMark)
2679  {
2680  if (rTab >= nTabCount)
2681  break;
2682 
2683  SCTAB nCount = 0;
2684  for( SCTAB j=rTab+1; j<nTabCount && rDoc.IsScenario(j); j++ )
2685  nCount ++;
2686 
2687  pScenarios[nUndoPos] = nCount;
2688  pTabs[nUndoPos] = rTab;
2689  nUndoPos ++;
2690  }
2691 
2692  if( !bDeletingMerge )
2693  {
2694  rDocShell.GetUndoManager()->LeaveListAction();
2695  }
2696 
2697  rDocShell.GetUndoManager()->AddUndoAction( std::make_unique<ScUndoDeleteCells>(
2698  &rDocShell, ScRange( nStartCol, nStartRow, nStartTab, nEndCol, nEndRow, nEndTab ),
2699  nUndoPos, std::move(pTabs), std::move(pScenarios),
2700  eCmd, std::move(pUndoDoc), std::move(pUndoData) ) );
2701  }
2702 
2703  // #i8302 want to be able to insert into the middle of merged cells
2704  // the patch comes from maoyg
2705 
2706  while( !qDecreaseRange.empty() )
2707  {
2708  ScRange aRange = qDecreaseRange.back();
2709 
2710  sal_Int32 nDecreaseRowCount = 0;
2711  sal_Int32 nDecreaseColCount = 0;
2712  if( eCmd == DelCellCmd::CellsUp || eCmd == DelCellCmd::Rows )
2713  {
2714  if( nStartRow >= aRange.aStart.Row() && nStartRow <= aRange.aEnd.Row() && nEndRow>= aRange.aStart.Row() && nEndRow <= aRange.aEnd.Row() )
2715  nDecreaseRowCount = nEndRow-nStartRow+1;
2716  else if( nStartRow >= aRange.aStart.Row() && nStartRow <= aRange.aEnd.Row() && nEndRow >= aRange.aStart.Row() && nEndRow >= aRange.aEnd.Row() )
2717  nDecreaseRowCount = aRange.aEnd.Row()-nStartRow+1;
2718  else if( nStartRow >= aRange.aStart.Row() && nStartRow >= aRange.aEnd.Row() && nEndRow>= aRange.aStart.Row() && nEndRow <= aRange.aEnd.Row() )
2719  nDecreaseRowCount = aRange.aEnd.Row()-nEndRow+1;
2720  }
2721  else if( eCmd == DelCellCmd::CellsLeft || eCmd == DelCellCmd::Cols )
2722  {
2723  if( nStartCol >= aRange.aStart.Col() && nStartCol <= aRange.aEnd.Col() && nEndCol>= aRange.aStart.Col() && nEndCol <= aRange.aEnd.Col() )
2724  nDecreaseColCount = nEndCol-nStartCol+1;
2725  else if( nStartCol >= aRange.aStart.Col() && nStartCol <= aRange.aEnd.Col() && nEndCol >= aRange.aStart.Col() && nEndCol >= aRange.aEnd.Col() )
2726  nDecreaseColCount = aRange.aEnd.Col()-nStartCol+1;
2727  else if( nStartCol >= aRange.aStart.Col() && nStartCol >= aRange.aEnd.Col() && nEndCol>= aRange.aStart.Col() && nEndCol <= aRange.aEnd.Col() )
2728  nDecreaseColCount = aRange.aEnd.Col()-nEndCol+1;
2729  }
2730 
2731  switch (eCmd)
2732  {
2733  case DelCellCmd::CellsUp:
2734  case DelCellCmd::Rows:
2735  aRange.aEnd.SetRow(static_cast<SCCOL>( aRange.aEnd.Row()-nDecreaseRowCount));
2736  break;
2737  case DelCellCmd::CellsLeft:
2738  case DelCellCmd::Cols:
2739  aRange.aEnd.SetCol(static_cast<SCCOL>( aRange.aEnd.Col()-nDecreaseColCount));
2740  break;
2741  default:
2742  break;
2743  }
2744 
2746  {
2747  ScCellMergeOption aMergeOption(aRange);
2748  MergeCells( aMergeOption, false, true, true );
2749  }
2750  qDecreaseRange.pop_back();
2751  }
2752 
2753  if( bDeletingMerge )
2754  rDocShell.GetUndoManager()->LeaveListAction();
2755 
2756  if ( eCmd==DelCellCmd::Cols || eCmd==DelCellCmd::CellsLeft )
2757  nMergeTestEndCol = rDoc.MaxCol();
2758  if ( eCmd==DelCellCmd::Rows || eCmd==DelCellCmd::CellsUp )
2759  nMergeTestEndRow = rDoc.MaxRow();
2760  if ( bNeedRefresh )
2761  {
2762  // #i51445# old merge flag attributes must be deleted also for single cells,
2763  // not only for whole columns/rows
2764 
2765  ScPatternAttr aPattern( rDoc.GetPool() );
2766  aPattern.GetItemSet().Put( ScMergeFlagAttr() );
2767 
2768  rDoc.ApplyPatternArea( nExtendStartCol, nExtendStartRow, nMergeTestEndCol, nMergeTestEndRow, aMark, aPattern );
2769 
2770  for (const auto& rTab : aMark)
2771  {
2772  if (rTab >= nTabCount)
2773  break;
2774 
2775  SCTAB nScenarioCount = 0;
2776 
2777  for( SCTAB j = rTab+1; j<nTabCount && rDoc.IsScenario(j); j++ )
2778  nScenarioCount ++;
2779 
2780  ScRange aMergedRange( nExtendStartCol, nExtendStartRow, rTab, nMergeTestEndCol, nMergeTestEndRow, rTab+nScenarioCount );
2781  rDoc.ExtendMerge( aMergedRange, true );
2782  }
2783  }
2784 
2785  for (const auto& rTab : aMark)
2786  {
2787  if (rTab >= nTabCount)
2788  break;
2789 
2790  rDoc.RefreshAutoFilter( nExtendStartCol, nExtendStartRow, nMergeTestEndCol, nMergeTestEndRow, rTab );
2791  }
2792 
2793  for (const auto& rTab : aMark)
2794  {
2795  if (rTab >= nTabCount)
2796  break;
2797 
2798  rDoc.SetDrawPageSize(rTab);
2799 
2800  if ( eCmd == DelCellCmd::Cols || eCmd == DelCellCmd::Rows )
2801  rDoc.UpdatePageBreaks( rTab );
2802 
2803  rDocShell.UpdatePaintExt( nExtFlags, nPaintStartCol, nPaintStartRow, rTab, nPaintEndCol, nPaintEndRow, rTab );
2804 
2805  SCTAB nScenarioCount = 0;
2806 
2807  for( SCTAB j = rTab+1; j<nTabCount && rDoc.IsScenario(j); j++ )
2808  nScenarioCount ++;
2809 
2810  // delete entire rows: do not adjust
2811  if ( eCmd == DelCellCmd::Rows || !AdjustRowHeight(ScRange( 0, nPaintStartRow, rTab, rDoc.MaxCol(), nPaintEndRow, rTab+nScenarioCount ), true, bApi) )
2812  rDocShell.PostPaint( nPaintStartCol, nPaintStartRow, rTab, nPaintEndCol, nPaintEndRow, rTab+nScenarioCount, nPaintFlags, nExtFlags );
2813  else
2814  {
2815  // paint only what is not done by AdjustRowHeight
2816  if (nExtFlags & SC_PF_LINES)
2817  lcl_PaintAbove( rDocShell, ScRange( nPaintStartCol, nPaintStartRow, rTab, nPaintEndCol, nPaintEndRow, rTab+nScenarioCount) );
2818  if (nPaintFlags & PaintPartFlags::Top)
2819  rDocShell.PostPaint( nPaintStartCol, nPaintStartRow, rTab, nPaintEndCol, nPaintEndRow, rTab+nScenarioCount, PaintPartFlags::Top );
2820  }
2821  }
2822 
2823  // The cursor position needs to be modified earlier than updating
2824  // any enabled edit view which is triggered by SetDocumentModified below.
2825  ScTabViewShell* pViewSh = rDocShell.GetBestViewShell();
2826  if (pViewSh)
2827  {
2828  if (eCmd == DelCellCmd::Cols)
2829  {
2830  pViewSh->OnLOKInsertDeleteColumn(rRange.aStart.Col(), -1);
2831  }
2832  if (eCmd == DelCellCmd::Rows)
2833  {
2834  pViewSh->OnLOKInsertDeleteRow(rRange.aStart.Row(), -1);
2835  }
2836  }
2837 
2838  aModificator.SetDocumentModified();
2839 
2840  SfxGetpApp()->Broadcast( SfxHint( SfxHintId::ScAreaLinksChanged ) );
2841 
2842  return true;
2843 }
2844 
2845 bool ScDocFunc::MoveBlock( const ScRange& rSource, const ScAddress& rDestPos,
2846  bool bCut, bool bRecord, bool bPaint, bool bApi )
2847 {
2848  ScDocShellModificator aModificator( rDocShell );
2849 
2850  SCCOL nStartCol = rSource.aStart.Col();
2851  SCROW nStartRow = rSource.aStart.Row();
2852  SCTAB nStartTab = rSource.aStart.Tab();
2853  SCCOL nEndCol = rSource.aEnd.Col();
2854  SCROW nEndRow = rSource.aEnd.Row();
2855  SCTAB nEndTab = rSource.aEnd.Tab();
2856  SCCOL nDestCol = rDestPos.Col();
2857  SCROW nDestRow = rDestPos.Row();
2858  SCTAB nDestTab = rDestPos.Tab();
2859 
2860  ScDocument& rDoc = rDocShell.GetDocument();
2861  if ( !rDoc.ValidRow(nStartRow) || !rDoc.ValidRow(nEndRow) || !rDoc.ValidRow(nDestRow) )
2862  {
2863  OSL_FAIL("invalid row in MoveBlock");
2864  return false;
2865  }
2866 
2867  // adjust related scenarios too - but only when moved within one sheet
2868  bool bScenariosAdded = false;
2869  if (bRecord && !rDoc.IsUndoEnabled())
2870  bRecord = false;
2871 
2872  SCTAB nTabCount = rDoc.GetTableCount();
2873  if ( nDestTab == nStartTab && !rDoc.IsScenario(nEndTab) )
2874  while ( nEndTab+1 < nTabCount && rDoc.IsScenario(nEndTab+1) )
2875  {
2876  ++nEndTab;
2877  bScenariosAdded = true;
2878  }
2879 
2880  SCTAB nSrcTabCount = nEndTab-nStartTab+1;
2881  SCTAB nDestEndTab = nDestTab+nSrcTabCount-1;
2882  SCTAB nTab;
2883 
2885 
2886  ScMarkData aSourceMark(rDoc.GetSheetLimits());
2887  for (nTab=nStartTab; nTab<=nEndTab; nTab++)
2888  aSourceMark.SelectTable( nTab, true ); // select source
2889  aSourceMark.SetMarkArea( rSource );
2890 
2891  ScDocShellRef aDragShellRef;
2892  if ( rDoc.HasOLEObjectsInArea( rSource ) )
2893  {
2894  aDragShellRef = new ScDocShell; // DocShell needs a Ref immediately
2895  aDragShellRef->DoInitNew();
2896  }
2897  ScDrawLayer::SetGlobalDrawPersist( aDragShellRef.get() );
2898 
2899  ScClipParam aClipParam(ScRange(nStartCol, nStartRow, nStartTab, nEndCol, nEndRow, nStartTab), bCut);
2900  rDoc.CopyToClip(aClipParam, pClipDoc.get(), &aSourceMark, bScenariosAdded, true);
2901 
2903 
2904  SCCOL nOldEndCol = nEndCol;
2905  SCROW nOldEndRow = nEndRow;
2906  bool bClipOver = false;
2907  for (nTab=nStartTab; nTab<=nEndTab; nTab++)
2908  {
2909  SCCOL nTmpEndCol = nOldEndCol;
2910  SCROW nTmpEndRow = nOldEndRow;
2911  if (rDoc.ExtendMerge( nStartCol, nStartRow, nTmpEndCol, nTmpEndRow, nTab ))
2912  bClipOver = true;
2913  if ( nTmpEndCol > nEndCol ) nEndCol = nTmpEndCol;
2914  if ( nTmpEndRow > nEndRow ) nEndRow = nTmpEndRow;
2915  }
2916 
2917  SCCOL nDestEndCol = nDestCol + ( nOldEndCol-nStartCol );
2918  SCROW nDestEndRow = nDestRow + ( nOldEndRow-nStartRow );
2919 
2920  SCCOL nUndoEndCol = nDestCol + ( nEndCol-nStartCol ); // extended in destination block
2921  SCROW nUndoEndRow = nDestRow + ( nEndRow-nStartRow );
2922 
2923  bool bIncludeFiltered = bCut;
2924  if ( !bIncludeFiltered )
2925  {
2926  // adjust sizes to include only non-filtered rows
2927 
2928  SCCOL nClipX;
2929  SCROW nClipY;
2930  pClipDoc->GetClipArea( nClipX, nClipY, false );
2931  SCROW nUndoAdd = nUndoEndRow - nDestEndRow;
2932  nDestEndRow = nDestRow + nClipY;
2933  nUndoEndRow = nDestEndRow + nUndoAdd;
2934  }
2935 
2936  if (!rDoc.ValidCol(nUndoEndCol) || !rDoc.ValidRow(nUndoEndRow))
2937  {
2938  if (!bApi)
2939  rDocShell.ErrorMessage(STR_PASTE_FULL);
2940  return false;
2941  }
2942 
2943  // Test for cell protection
2944 
2945  ScEditableTester aTester;
2946  for (nTab=nDestTab; nTab<=nDestEndTab; nTab++)
2947  aTester.TestBlock( rDoc, nTab, nDestCol,nDestRow, nUndoEndCol,nUndoEndRow );
2948  if (bCut)
2949  for (nTab=nStartTab; nTab<=nEndTab; nTab++)
2950  aTester.TestBlock( rDoc, nTab, nStartCol,nStartRow, nEndCol,nEndRow );
2951 
2952  if (!aTester.IsEditable())
2953  {
2954  if (!bApi)
2955  rDocShell.ErrorMessage(aTester.GetMessageId());
2956  return false;
2957  }
2958 
2959  // Test for merged cells- when moving after delete
2960 
2961  if (bClipOver && !bCut)
2962  if (rDoc.HasAttrib( nDestCol,nDestRow,nDestTab, nUndoEndCol,nUndoEndRow,nDestEndTab,
2964  { // "Merge of already merged cells not possible"
2965  if (!bApi)
2966  rDocShell.ErrorMessage(STR_MSSG_MOVEBLOCKTO_0);
2967  return false;
2968  }
2969 
2970  // Are there borders in the cells? (for painting)
2971 
2972  sal_uInt16 nSourceExt = 0;
2973  rDocShell.UpdatePaintExt( nSourceExt, nStartCol,nStartRow,nStartTab, nEndCol,nEndRow,nEndTab );
2974  sal_uInt16 nDestExt = 0;
2975  rDocShell.UpdatePaintExt( nDestExt, nDestCol,nDestRow,nDestTab, nDestEndCol,nDestEndRow,nDestEndTab );
2976 
2977  // do it
2978 
2979  ScDocumentUniquePtr pUndoDoc;
2980 
2981  if (bRecord)
2982  {
2983  bool bWholeCols = ( nStartRow == 0 && nEndRow == rDoc.MaxRow() );
2984  bool bWholeRows = ( nStartCol == 0 && nEndCol == rDoc.MaxCol() );
2986 
2987  pUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
2988  pUndoDoc->InitUndo( rDoc, nStartTab, nEndTab, bWholeCols, bWholeRows );
2989 
2990  if (bCut)
2991  {
2992  rDoc.CopyToDocument( nStartCol, nStartRow, nStartTab, nEndCol, nEndRow, nEndTab,
2993  nUndoFlags, false, *pUndoDoc );
2994  }
2995 
2996  if ( nDestTab != nStartTab )
2997  pUndoDoc->AddUndoTab( nDestTab, nDestEndTab, bWholeCols, bWholeRows );
2998  rDoc.CopyToDocument( nDestCol, nDestRow, nDestTab,
2999  nDestEndCol, nDestEndRow, nDestEndTab,
3000  nUndoFlags, false, *pUndoDoc );
3001  rDoc.BeginDrawUndo();
3002  }
3003 
3004  bool bSourceHeight = false; // adjust heights?
3005  if (bCut)
3006  {
3007  ScMarkData aDelMark(rDoc.GetSheetLimits()); // only for tables
3008  for (nTab=nStartTab; nTab<=nEndTab; nTab++)
3009  {
3010  rDoc.DeleteAreaTab( nStartCol,nStartRow, nOldEndCol,nOldEndRow, nTab, InsertDeleteFlags::ALL );
3011  aDelMark.SelectTable( nTab, true );
3012  }
3013  rDoc.DeleteObjectsInArea( nStartCol,nStartRow, nOldEndCol,nOldEndRow, aDelMark );
3014 
3015  // Test for merged cells
3016 
3017  if (bClipOver)
3018  if (rDoc.HasAttrib( nDestCol,nDestRow,nDestTab,
3019  nUndoEndCol,nUndoEndRow,nDestEndTab,
3021  {
3022  rDoc.CopyFromClip( rSource, aSourceMark, InsertDeleteFlags::ALL, nullptr, pClipDoc.get() );
3023  for (nTab=nStartTab; nTab<=nEndTab; nTab++)
3024  {
3025  SCCOL nTmpEndCol = nEndCol;
3026  SCROW nTmpEndRow = nEndRow;
3027  rDoc.ExtendMerge( nStartCol, nStartRow, nTmpEndCol, nTmpEndRow, nTab, true );
3028  }
3029 
3030  // Report error only after restoring content
3031  if (!bApi) // "Merge of already merged cells not possible"
3032  rDocShell.ErrorMessage(STR_MSSG_MOVEBLOCKTO_0);
3033 
3034  return false;
3035  }
3036 
3037  bSourceHeight = AdjustRowHeight( rSource, false, bApi );
3038  }
3039 
3040  ScRange aPasteDest( nDestCol, nDestRow, nDestTab, nDestEndCol, nDestEndRow, nDestEndTab );
3041 
3042  ScMarkData aDestMark(rDoc.GetSheetLimits());
3043  for (nTab=nDestTab; nTab<=nDestEndTab; nTab++)
3044  aDestMark.SelectTable( nTab, true ); // select destination
3045  aDestMark.SetMarkArea( aPasteDest );
3046 
3047  /* Do not copy drawing objects here. While pasting, the
3048  function ScDocument::UpdateReference() is called which calls
3049  ScDrawLayer::MoveCells() which may move away inserted objects to wrong
3050  positions (e.g. if source and destination range overlaps).*/
3051 
3052  rDoc.CopyFromClip(
3053  aPasteDest, aDestMark, InsertDeleteFlags::ALL & ~InsertDeleteFlags::OBJECTS,
3054  pUndoDoc.get(), pClipDoc.get(), true, false, bIncludeFiltered);
3055 
3056  // skipped rows and merged cells don't mix
3057  if ( !bIncludeFiltered && pClipDoc->HasClipFilteredRows() )
3058  UnmergeCells( aPasteDest, false, nullptr );
3059 
3060  bool bDestHeight = AdjustRowHeight(
3061  ScRange( 0,nDestRow,nDestTab, rDoc.MaxCol(),nDestEndRow,nDestEndTab ),
3062  false, bApi );
3063 
3064  /* Paste drawing objects after adjusting formula references
3065  and row heights. There are no cell notes or drawing objects, if the
3066  clipdoc does not contain a drawing layer.*/
3067  if ( pClipDoc->GetDrawLayer() )
3068  rDoc.CopyFromClip( aPasteDest, aDestMark, InsertDeleteFlags::OBJECTS,
3069  nullptr, pClipDoc.get(), true, false, bIncludeFiltered );
3070 
3071  if (bRecord)
3072  {
3073  ScRange aUndoRange(nStartCol, nStartRow, nStartTab, nOldEndCol, nOldEndRow, nEndTab);
3074  ScAddress aDestPos(nDestCol, nDestRow, nDestTab);
3075 
3076  rDocShell.GetUndoManager()->AddUndoAction(
3077  std::make_unique<ScUndoDragDrop>(
3078  &rDocShell, aUndoRange, aDestPos, bCut, std::move(pUndoDoc), bScenariosAdded));
3079  }
3080 
3081  SCCOL nDestPaintEndCol = nDestEndCol;
3082  SCROW nDestPaintEndRow = nDestEndRow;
3083  for (nTab=nDestTab; nTab<=nDestEndTab; nTab++)
3084  {
3085  SCCOL nTmpEndCol = nDestEndCol;
3086  SCROW nTmpEndRow = nDestEndRow;
3087  rDoc.ExtendMerge( nDestCol, nDestRow, nTmpEndCol, nTmpEndRow, nTab, true );
3088  if (nTmpEndCol > nDestPaintEndCol) nDestPaintEndCol = nTmpEndCol;
3089  if (nTmpEndRow > nDestPaintEndRow) nDestPaintEndRow = nTmpEndRow;
3090  }
3091 
3092  if (bCut)
3093  for (nTab=nStartTab; nTab<=nEndTab; nTab++)
3094  rDoc.RefreshAutoFilter( nStartCol, nStartRow, nEndCol, nEndRow, nTab );
3095 
3096  if (bPaint)
3097  {
3098  // destination range:
3099 
3100  SCCOL nPaintStartX = nDestCol;
3101  SCROW nPaintStartY = nDestRow;
3102  SCCOL nPaintEndX = nDestPaintEndCol;
3103  SCROW nPaintEndY = nDestPaintEndRow;
3105 
3106  if ( nStartRow==0 && nEndRow==rDoc.MaxRow() ) // copy widths too?
3107  {
3108  nPaintEndX = rDoc.MaxCol();
3109  nPaintStartY = 0;
3110  nPaintEndY = rDoc.MaxRow();
3111  nFlags |= PaintPartFlags::Top;
3112  }
3113  if ( bDestHeight || ( nStartCol == 0 && nEndCol == rDoc.MaxCol() ) )
3114  {
3115  nPaintEndY = rDoc.MaxRow();
3116  nPaintStartX = 0;
3117  nPaintEndX = rDoc.MaxCol();
3118  nFlags |= PaintPartFlags::Left;
3119  }
3120  if ( bScenariosAdded )
3121  {
3122  nPaintStartX = 0;
3123  nPaintStartY = 0;
3124  nPaintEndX = rDoc.MaxCol();
3125  nPaintEndY = rDoc.MaxRow();
3126  }
3127 
3128  rDocShell.PostPaint( nPaintStartX,nPaintStartY,nDestTab,
3129  nPaintEndX,nPaintEndY,nDestEndTab, nFlags, nSourceExt | nDestExt );
3130 
3131  if ( bCut )
3132  {
3133  // source range:
3134 
3135  nPaintStartX = nStartCol;
3136  nPaintStartY = nStartRow;
3137  nPaintEndX = nEndCol;
3138  nPaintEndY = nEndRow;
3139  nFlags = PaintPartFlags::Grid;
3140 
3141  if ( bSourceHeight )
3142  {
3143  nPaintEndY = rDoc.MaxRow();
3144  nPaintStartX = 0;
3145  nPaintEndX = rDoc.MaxCol();
3146  nFlags |= PaintPartFlags::Left;
3147  }
3148  if ( bScenariosAdded )
3149  {
3150  nPaintStartX = 0;
3151  nPaintStartY = 0;
3152  nPaintEndX = rDoc.MaxCol();
3153  nPaintEndY = rDoc.MaxRow();
3154  }
3155 
3156  rDocShell.PostPaint( nPaintStartX,nPaintStartY,nStartTab,
3157  nPaintEndX,nPaintEndY,nEndTab, nFlags, nSourceExt );
3158  }
3159  }
3160 
3161  aModificator.SetDocumentModified();
3162 
3163  SfxGetpApp()->Broadcast( SfxHint( SfxHintId::ScAreaLinksChanged ) );
3164 
3165  return true;
3166 }
3167 
3168 static uno::Reference< uno::XInterface > GetDocModuleObject( const SfxObjectShell& rDocSh, const OUString& sCodeName )
3169 {
3170  uno::Reference< lang::XMultiServiceFactory> xSF(rDocSh.GetModel(), uno::UNO_QUERY);
3171  uno::Reference< container::XNameAccess > xVBACodeNamedObjectAccess;
3172  uno::Reference< uno::XInterface > xDocModuleApiObject;
3173  if ( xSF.is() )
3174  {
3175  xVBACodeNamedObjectAccess.set( xSF->createInstance("ooo.vba.VBAObjectModuleObjectProvider"), uno::UNO_QUERY );
3176  xDocModuleApiObject.set( xVBACodeNamedObjectAccess->getByName( sCodeName ), uno::UNO_QUERY );
3177  }
3178  return xDocModuleApiObject;
3179 
3180 }
3181 
3182 static script::ModuleInfo lcl_InitModuleInfo( const SfxObjectShell& rDocSh, const OUString& sModule )
3183 {
3184  script::ModuleInfo sModuleInfo;
3185  sModuleInfo.ModuleType = script::ModuleType::DOCUMENT;
3186  sModuleInfo.ModuleObject = GetDocModuleObject( rDocSh, sModule );
3187  return sModuleInfo;
3188 }
3189 
3190 void VBA_InsertModule( ScDocument& rDoc, SCTAB nTab, const OUString& sSource )
3191 {
3192  SfxObjectShell& rDocSh = *rDoc.GetDocumentShell();
3193  uno::Reference< script::XLibraryContainer > xLibContainer = rDocSh.GetBasicContainer();
3194  OSL_ENSURE( xLibContainer.is(), "No BasicContainer!" );
3195 
3196  uno::Reference< container::XNameContainer > xLib;
3197  if( xLibContainer.is() )
3198  {
3199  OUString aLibName( "Standard" );
3200  if ( rDocSh.GetBasicManager() && !rDocSh.GetBasicManager()->GetName().isEmpty() )
3201  {
3202  aLibName = rDocSh.GetBasicManager()->GetName();
3203  }
3204  uno::Any aLibAny = xLibContainer->getByName( aLibName );
3205  aLibAny >>= xLib;
3206  }
3207  if( !xLib.is() )
3208  return;
3209 
3210  // if the Module with codename exists then find a new name
3211  sal_Int32 nNum = 1;
3212  OUString genModuleName = "Sheet1";
3213  while( xLib->hasByName( genModuleName ) )
3214  genModuleName = "Sheet" + OUString::number( ++nNum );
3215 
3216  uno::Any aSourceAny;
3217  OUString sTmpSource = sSource;
3218  if ( sTmpSource.isEmpty() )
3219  sTmpSource = "Rem Attribute VBA_ModuleType=VBADocumentModule\nOption VBASupport 1\n";
3220  aSourceAny <<= sTmpSource;
3221  uno::Reference< script::vba::XVBAModuleInfo > xVBAModuleInfo( xLib, uno::UNO_QUERY );
3222  if ( xVBAModuleInfo.is() )
3223  {
3224  rDoc.SetCodeName( nTab, genModuleName );
3225  script::ModuleInfo sModuleInfo = lcl_InitModuleInfo( rDocSh, genModuleName );
3226  xVBAModuleInfo->insertModuleInfo( genModuleName, sModuleInfo );
3227  xLib->insertByName( genModuleName, aSourceAny );
3228  }
3229 }
3230 
3231 void VBA_DeleteModule( ScDocShell& rDocSh, const OUString& sModuleName )
3232 {
3233  uno::Reference< script::XLibraryContainer > xLibContainer = rDocSh.GetBasicContainer();
3234  OSL_ENSURE( xLibContainer.is(), "No BasicContainer!" );
3235 
3236  uno::Reference< container::XNameContainer > xLib;
3237  if( xLibContainer.is() )
3238  {
3239  OUString aLibName( "Standard" );
3240  if ( rDocSh.GetBasicManager() && !rDocSh.GetBasicManager()->GetName().isEmpty() )
3241  {
3242  aLibName = rDocSh.GetBasicManager()->GetName();
3243  }
3244  uno::Any aLibAny = xLibContainer->getByName( aLibName );
3245  aLibAny >>= xLib;
3246  }
3247  if( xLib.is() )
3248  {
3249  uno::Reference< script::vba::XVBAModuleInfo > xVBAModuleInfo( xLib, uno::UNO_QUERY );
3250  if( xLib->hasByName( sModuleName ) )
3251  xLib->removeByName( sModuleName );
3252  if ( xVBAModuleInfo.is() && xVBAModuleInfo->hasModuleInfo(sModuleName) )
3253  xVBAModuleInfo->removeModuleInfo( sModuleName );
3254 
3255  }
3256 }
3257 
3258 bool ScDocFunc::InsertTable( SCTAB nTab, const OUString& rName, bool bRecord, bool bApi )
3259 {
3260  bool bSuccess = false;
3262 
3263  ScDocShellModificator aModificator( rDocShell );
3264 
3265  ScDocument& rDoc = rDocShell.GetDocument();
3266 
3267  // Strange loop, also basic is loaded too early ( InsertTable )
3268  // is called via the xml import for sheets in described in ODF
3269  bool bInsertDocModule = false;
3270 
3271  if( !rDocShell.GetDocument().IsImportingXML() )
3272  {
3273  bInsertDocModule = rDoc.IsInVBAMode();
3274  }
3275  if ( bInsertDocModule || ( bRecord && !rDoc.IsUndoEnabled() ) )
3276  bRecord = false;
3277 
3278  if (bRecord)
3279  rDoc.BeginDrawUndo(); // InsertTab generates SdrUndoNewPage
3280 
3281  SCTAB nTabCount = rDoc.GetTableCount();
3282  bool bAppend = ( nTab >= nTabCount );
3283  if ( bAppend )
3284  nTab = nTabCount; // important for Undo
3285 
3286  if (rDoc.InsertTab( nTab, rName ))
3287  {
3288  if (bRecord)
3289  rDocShell.GetUndoManager()->AddUndoAction(
3290  std::make_unique<ScUndoInsertTab>( &rDocShell, nTab, bAppend, rName));
3291  // Update views:
3292  // Only insert vba modules if vba mode ( and not currently importing XML )
3293  if( bInsertDocModule )
3294  {
3295  VBA_InsertModule( rDoc, nTab, OUString() );
3296  }
3297  rDocShell.Broadcast( ScTablesHint( SC_TAB_INSERTED, nTab ) );
3298 
3299  rDocShell.PostPaintExtras();
3300  aModificator.SetDocumentModified();
3301  SfxGetpApp()->Broadcast( SfxHint( SfxHintId::ScTablesChanged ) );
3302  bSuccess = true;
3303  }
3304  else if (!bApi)
3305  rDocShell.ErrorMessage(STR_TABINSERT_ERROR);
3306 
3307  return bSuccess;
3308 }
3309 
3310 bool ScDocFunc::DeleteTable( SCTAB nTab, bool bRecord )
3311 {
3313 
3314  ScDocShellModificator aModificator( rDocShell );
3315 
3316  bool bSuccess = false;
3317  ScDocument& rDoc = rDocShell.GetDocument();
3318  bool bVbaEnabled = rDoc.IsInVBAMode();
3319  if (bRecord && !rDoc.IsUndoEnabled())
3320  bRecord = false;
3321  if ( bVbaEnabled )
3322  bRecord = false;
3323  bool bWasLinked = rDoc.IsLinked(nTab);
3324  ScDocumentUniquePtr pUndoDoc;
3325  std::unique_ptr<ScRefUndoData> pUndoData;
3326  if (bRecord)
3327  {
3328  pUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
3329  SCTAB nCount = rDoc.GetTableCount();
3330 
3331  pUndoDoc->InitUndo( rDoc, nTab, nTab, true, true ); // only nTab with Flags
3332  pUndoDoc->AddUndoTab( 0, nCount-1 ); // all sheets for references
3333 
3334  rDoc.CopyToDocument(0,0,nTab, rDoc.MaxCol(),rDoc.MaxRow(),nTab, InsertDeleteFlags::ALL,false, *pUndoDoc );
3335  OUString aOldName;
3336  rDoc.GetName( nTab, aOldName );
3337  pUndoDoc->RenameTab( nTab, aOldName );
3338  if (bWasLinked)
3339  pUndoDoc->SetLink( nTab, rDoc.GetLinkMode(nTab), rDoc.GetLinkDoc(nTab),
3340  rDoc.GetLinkFlt(nTab), rDoc.GetLinkOpt(nTab),
3341  rDoc.GetLinkTab(nTab),
3342  rDoc.GetLinkRefreshDelay(nTab) );
3343 
3344  if ( rDoc.IsScenario(nTab) )
3345  {
3346  pUndoDoc->SetScenario( nTab, true );
3347  OUString aComment;
3348  Color aColor;
3349  ScScenarioFlags nScenFlags;
3350  rDoc.GetScenarioData( nTab, aComment, aColor, nScenFlags );
3351  pUndoDoc->SetScenarioData( nTab, aComment, aColor, nScenFlags );
3352  bool bActive = rDoc.IsActiveScenario( nTab );
3353  pUndoDoc->SetActiveScenario( nTab, bActive );
3354  }
3355  pUndoDoc->SetVisible( nTab, rDoc.IsVisible( nTab ) );
3356  pUndoDoc->SetTabBgColor( nTab, rDoc.GetTabBgColor(nTab) );
3357  auto pSheetEvents = rDoc.GetSheetEvents( nTab );
3358  pUndoDoc->SetSheetEvents( nTab, std::unique_ptr<ScSheetEvents>(pSheetEvents ? new ScSheetEvents(*pSheetEvents) : nullptr) );
3359 
3360  // Drawing-Layer has to take care of its own undo!!!
3361  rDoc.BeginDrawUndo(); // DeleteTab generates SdrUndoDelPage
3362 
3363  pUndoData.reset(new ScRefUndoData( &rDoc ));
3364  }
3365 
3366  if (rDoc.DeleteTab(nTab))
3367  {
3368  if (bRecord)
3369  {
3370  vector<SCTAB> theTabs;
3371  theTabs.push_back(nTab);
3372  rDocShell.GetUndoManager()->AddUndoAction(
3373  std::make_unique<ScUndoDeleteTab>( &rDocShell, theTabs, std::move(pUndoDoc), std::move(pUndoData) ));
3374  }
3375  // Update views:
3376  if( bVbaEnabled )
3377  {
3378  OUString sCodeName;
3379  if( rDoc.GetCodeName( nTab, sCodeName ) )
3380  {
3381  VBA_DeleteModule( rDocShell, sCodeName );
3382  }
3383  }
3384  rDocShell.Broadcast( ScTablesHint( SC_TAB_DELETED, nTab ) );
3385 
3386  if (bWasLinked)
3387  {
3388  rDocShell.UpdateLinks(); // update Link-Manager
3389  SfxBindings* pBindings = rDocShell.GetViewBindings();
3390  if (pBindings)
3391  pBindings->Invalidate(SID_LINKS);
3392  }
3393 
3394  rDocShell.PostPaintExtras();
3395  aModificator.SetDocumentModified();
3396 
3397  SfxApplication* pSfxApp = SfxGetpApp(); // Navigator
3398  pSfxApp->Broadcast( SfxHint( SfxHintId::ScTablesChanged ) );
3399  pSfxApp->Broadcast( SfxHint( SfxHintId::ScDbAreasChanged ) );
3400  pSfxApp->Broadcast( SfxHint( SfxHintId::ScAreaLinksChanged ) );
3401 
3402  bSuccess = true;
3403  }
3404  return bSuccess;
3405 }
3406 
3407 void ScDocFunc::SetTableVisible( SCTAB nTab, bool bVisible, bool bApi )
3408 {
3409  ScDocument& rDoc = rDocShell.GetDocument();
3410  bool bUndo(rDoc.IsUndoEnabled());
3411  if ( rDoc.IsVisible( nTab ) == bVisible )
3412  return; // nothing to do - ok
3413 
3414  if ( !rDoc.IsDocEditable() )
3415  {
3416  if (!bApi)
3417  rDocShell.ErrorMessage(STR_PROTECTIONERR);
3418  return;
3419  }
3420 
3421  ScDocShellModificator aModificator( rDocShell );
3422 
3423  if ( !bVisible && !rDoc.IsImportingXML() ) // #i57869# allow hiding in any order for loading
3424  {
3425  // do not disable all sheets
3426 
3427  sal_uInt16 nVisCount = 0;
3428  SCTAB nCount = rDoc.GetTableCount();
3429  for (SCTAB i=0; i<nCount && nVisCount<2; i++)
3430  if (rDoc.IsVisible(i))
3431  ++nVisCount;
3432 
3433  if (nVisCount <= 1)
3434  {
3435  if (!bApi)
3436  rDocShell.ErrorMessage(STR_PROTECTIONERR);
3437  return;
3438  }
3439  }
3440 
3441  rDoc.SetVisible( nTab, bVisible );
3442  if (bUndo)
3443  {
3444  std::vector<SCTAB> undoTabs;
3445  undoTabs.push_back(nTab);
3446  rDocShell.GetUndoManager()->AddUndoAction( std::make_unique<ScUndoShowHideTab>( &rDocShell, undoTabs, bVisible ) );
3447  }
3448 
3449  // update views
3450  if (!bVisible)
3451  rDocShell.Broadcast( ScTablesHint( SC_TAB_HIDDEN, nTab ) );
3452 
3453  SfxGetpApp()->Broadcast( SfxHint( SfxHintId::ScTablesChanged ) );
3454  rDocShell.PostPaint(0,0,0,rDoc.MaxCol(),rDoc.MaxRow(),MAXTAB, PaintPartFlags::Extras);
3455  aModificator.SetDocumentModified();
3456 }
3457 
3458 bool ScDocFunc::SetLayoutRTL( SCTAB nTab, bool bRTL )
3459 {
3460  ScDocument& rDoc = rDocShell.GetDocument();
3461  bool bUndo(rDoc.IsUndoEnabled());
3462  if ( rDoc.IsLayoutRTL( nTab ) == bRTL )
3463  return true; // nothing to do - ok
3464 
3466 
3467  ScDocShellModificator aModificator( rDocShell );
3468 
3469  rDoc.SetLayoutRTL( nTab, bRTL, ScObjectHandling::MirrorRTLMode);
3470 
3471  if (bUndo)
3472  {
3473  rDocShell.GetUndoManager()->AddUndoAction( std::make_unique<ScUndoLayoutRTL>( &rDocShell, nTab, bRTL ) );
3474  }
3475 
3476  rDocShell.PostPaint( 0,0,0,rDoc.MaxCol(),rDoc.MaxRow(),MAXTAB, PaintPartFlags::All );
3477  aModificator.SetDocumentModified();
3478 
3479  SfxBindings* pBindings = rDocShell.GetViewBindings();
3480  if (pBindings)
3481  {
3482  pBindings->Invalidate( FID_TAB_RTL );
3483  pBindings->Invalidate( SID_ATTR_SIZE );
3484  }
3485 
3486  return true;
3487 }
3488 
3489 bool ScDocFunc::RenameTable( SCTAB nTab, const OUString& rName, bool bRecord, bool bApi )
3490 {
3491  ScDocument& rDoc = rDocShell.GetDocument();
3492  if (bRecord && !rDoc.IsUndoEnabled())
3493  bRecord = false;
3494  if ( !rDoc.IsDocEditable() )
3495  {
3496  if (!bApi)
3497  rDocShell.ErrorMessage(STR_PROTECTIONERR);
3498  return false;
3499  }
3500 
3501  ScDocShellModificator aModificator( rDocShell );
3502 
3503  bool bSuccess = false;
3504  OUString sOldName;
3505  rDoc.GetName(nTab, sOldName);
3506  if (rDoc.RenameTab( nTab, rName ))
3507  {
3508  if (bRecord)
3509  {
3510  rDocShell.GetUndoManager()->AddUndoAction(
3511  std::make_unique<ScUndoRenameTab>( &rDocShell, nTab, sOldName, rName));
3512  }
3513  rDocShell.PostPaintExtras();
3514  aModificator.SetDocumentModified();
3515  SfxGetpApp()->Broadcast( SfxHint( SfxHintId::ScTablesChanged ) );
3516  SfxGetpApp()->Broadcast( SfxHint( SfxHintId::ScTablesRenamed ) );
3517 
3518  bSuccess = true;
3519  }
3520  return bSuccess;
3521 }
3522 
3523 bool ScDocFunc::SetTabBgColor( SCTAB nTab, const Color& rColor, bool bRecord, bool bApi )
3524 {
3525 
3526  ScDocument& rDoc = rDocShell.GetDocument();
3527  if (bRecord && !rDoc.IsUndoEnabled())
3528  bRecord = false;
3529  if ( !rDoc.IsDocEditable() || rDoc.IsTabProtected(nTab) )
3530  {
3531  if (!bApi)
3532  rDocShell.ErrorMessage(STR_PROTECTIONERR); //TODO Check to see what this string is...
3533  return false;
3534  }
3535 
3536  Color aOldTabBgColor = rDoc.GetTabBgColor(nTab);
3537 
3538  bool bSuccess = false;
3539  rDoc.SetTabBgColor(nTab, rColor);
3540  if ( rDoc.GetTabBgColor(nTab) == rColor)
3541  bSuccess = true;
3542  if (bSuccess)
3543  {
3544  if (bRecord)
3545  {
3546  rDocShell.GetUndoManager()->AddUndoAction(
3547  std::make_unique<ScUndoTabColor>( &rDocShell, nTab, aOldTabBgColor, rColor));
3548  }
3549  rDocShell.PostPaintExtras();
3550  ScDocShellModificator aModificator( rDocShell );
3551  aModificator.SetDocumentModified();
3552  SfxGetpApp()->Broadcast( SfxHint( SfxHintId::ScTablesChanged ) );
3553 
3554  bSuccess = true;
3555  }
3556  return bSuccess;
3557 }
3558 
3560  ScUndoTabColorInfo::List& rUndoTabColorList, bool bApi )
3561 {
3562  ScDocument& rDoc = rDocShell.GetDocument();
3563  bool bRecord = true;
3564  if (!rDoc.IsUndoEnabled())
3565  bRecord = false;
3566 
3567  if ( !rDoc.IsDocEditable() )
3568  {
3569  if (!bApi)
3570  rDocShell.ErrorMessage(STR_PROTECTIONERR); //TODO Get a better String Error...
3571  return false;
3572  }
3573 
3574  sal_uInt16 nTab;
3575  Color aNewTabBgColor;
3576  bool bSuccess = true;
3577  size_t nTabProtectCount = 0;
3578  size_t nTabListCount = rUndoTabColorList.size();
3579  for ( size_t i = 0; i < nTabListCount; ++i )
3580  {
3581  ScUndoTabColorInfo& rInfo = rUndoTabColorList[i];
3582  nTab = rInfo.mnTabId;
3583  if ( !rDoc.IsTabProtected(nTab) )
3584  {
3585  aNewTabBgColor = rInfo.maNewTabBgColor;
3586  rInfo.maOldTabBgColor = rDoc.GetTabBgColor(nTab);
3587  rDoc.SetTabBgColor(nTab, aNewTabBgColor);
3588  if ( rDoc.GetTabBgColor(nTab) != aNewTabBgColor)
3589  {
3590  bSuccess = false;
3591  break;
3592  }
3593  }
3594  else
3595  {
3596  nTabProtectCount++;
3597  }
3598  }
3599 
3600  if ( nTabProtectCount == nTabListCount )
3601  {
3602  if (!bApi)
3603  rDocShell.ErrorMessage(STR_PROTECTIONERR); //TODO Get a better String Error...
3604  return false;
3605  }
3606 
3607  if (bSuccess)
3608  {
3609  if (bRecord)
3610  {
3611  rDocShell.GetUndoManager()->AddUndoAction(
3612  std::make_unique<ScUndoTabColor>( &rDocShell, rUndoTabColorList));
3613  }
3614  rDocShell.PostPaintExtras();
3615  ScDocShellModificator aModificator( rDocShell );
3616  aModificator.SetDocumentModified();
3617  }
3618  return bSuccess;
3619 }
3620 
3625 
3626 static sal_uInt16 lcl_GetOptimalColWidth( ScDocShell& rDocShell, SCCOL nCol, SCTAB nTab )
3627 {
3628  ScSizeDeviceProvider aProv(&rDocShell);
3629  OutputDevice* pDev = aProv.GetDevice(); // has pixel MapMode
3630  double nPPTX = aProv.GetPPTX();
3631  double nPPTY = aProv.GetPPTY();
3632 
3633  ScDocument& rDoc = rDocShell.GetDocument();
3634  Fraction aOne(1,1);
3635  sal_uInt16 nTwips = rDoc.GetOptimalColWidth( nCol, nTab, pDev, nPPTX, nPPTY, aOne, aOne,
3636  false/*bFormula*/ );
3637 
3638  return nTwips;
3639 }
3640 
3642  bool bWidth, const std::vector<sc::ColRowSpan>& rRanges, SCTAB nTab,
3643  ScSizeMode eMode, sal_uInt16 nSizeTwips, bool bRecord, bool bApi )
3644 {
3645  ScDocShellModificator aModificator( rDocShell );
3646 
3647  if (rRanges.empty())
3648  return true;
3649 
3650  ScDocument& rDoc = rDocShell.GetDocument();
3651  if ( bRecord && !rDoc.IsUndoEnabled() )
3652  bRecord = false;
3653 
3654  // import into read-only document is possible
3655  if ( !rDoc.IsChangeReadOnlyEnabled() && !rDocShell.IsEditable() )
3656  {
3657  if (!bApi)
3658  rDocShell.ErrorMessage(STR_PROTECTIONERR);
3659  return false;
3660  }
3661 
3662  SCCOLROW nStart = rRanges[0].mnStart;
3663  SCCOLROW nEnd = rRanges[0].mnEnd;
3664 
3665  if ( eMode == SC_SIZE_OPTIMAL )
3666  {
3668  }
3669 
3670  ScDocumentUniquePtr pUndoDoc;
3671  std::unique_ptr<ScOutlineTable> pUndoTab;
3672  std::vector<sc::ColRowSpan> aUndoRanges;
3673 
3674  if ( bRecord )
3675  {
3676  rDoc.BeginDrawUndo(); // Drawing Updates
3677 
3678  pUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
3679  if (bWidth)
3680  {
3681  pUndoDoc->InitUndo( rDoc, nTab, nTab, true );
3682  rDoc.CopyToDocument( static_cast<SCCOL>(nStart), 0, nTab, static_cast<SCCOL>(nEnd), rDoc.MaxRow(), nTab, InsertDeleteFlags::NONE, false, *pUndoDoc );
3683  }
3684  else
3685  {
3686  pUndoDoc->InitUndo( rDoc, nTab, nTab, false, true );
3687  rDoc.CopyToDocument( 0, static_cast<SCROW>(nStart), nTab, rDoc.MaxCol(), static_cast<SCROW>(nEnd), nTab, InsertDeleteFlags::NONE, false, *pUndoDoc );
3688  }
3689 
3690  aUndoRanges = rRanges;
3691 
3692  ScOutlineTable* pTable = rDoc.GetOutlineTable( nTab );
3693  if (pTable)
3694  pUndoTab.reset(new ScOutlineTable( *pTable ));
3695  }
3696 
3697  bool bShow = nSizeTwips > 0 || eMode != SC_SIZE_DIRECT;
3698  bool bOutline = false;
3699 
3700  for (const sc::ColRowSpan& rRange : rRanges)
3701  {
3702  SCCOLROW nStartNo = rRange.mnStart;
3703  SCCOLROW nEndNo = rRange.mnEnd;
3704 
3705  if ( !bWidth ) // deal with heights always in blocks
3706  {
3707  if ( eMode==SC_SIZE_OPTIMAL || eMode==SC_SIZE_VISOPT )
3708  {
3709  bool bAll = ( eMode==SC_SIZE_OPTIMAL );
3710  if (!bAll)
3711  {
3712  // delete for all that have CRFlags::ManualSize enabled
3713  // then SetOptimalHeight with bShrink = FALSE
3714  for (SCROW nRow=nStartNo; nRow<=nEndNo; nRow++)
3715  {
3716  CRFlags nOld = rDoc.GetRowFlags(nRow,nTab);
3717  SCROW nLastRow = -1;
3718  bool bHidden = rDoc.RowHidden(nRow, nTab, nullptr, &nLastRow);
3719  if ( !bHidden && ( nOld & CRFlags::ManualSize ) )
3720  rDoc.SetRowFlags( nRow, nTab, nOld & ~CRFlags::ManualSize );
3721  }
3722  }
3723 
3724  ScSizeDeviceProvider aProv( &rDocShell );
3725  Fraction aOne(1,1);
3726  sc::RowHeightContext aCxt(rDoc.MaxRow(), aProv.GetPPTX(), aProv.GetPPTY(), aOne, aOne, aProv.GetDevice());
3727  aCxt.setForceAutoSize(bAll);
3728  rDoc.SetOptimalHeight(aCxt, nStartNo, nEndNo, nTab, bApi);
3729 
3730  if (bAll)
3731  rDoc.ShowRows( nStartNo, nEndNo, nTab, true );
3732 
3733  // Manual flag will be set already in SetOptimalHeight if bAll=true
3734  // (it is on when Extra-Height, otherwise off).
3735  }
3736  else if ( eMode==SC_SIZE_DIRECT || eMode==SC_SIZE_ORIGINAL )
3737  {
3738  if (nSizeTwips)
3739  {
3740  rDoc.SetRowHeightRange( nStartNo, nEndNo, nTab, nSizeTwips );
3741  rDoc.SetManualHeight( nStartNo, nEndNo, nTab, true ); // height was set manually
3742  }
3743  if ( eMode != SC_SIZE_ORIGINAL )
3744  rDoc.ShowRows( nStartNo, nEndNo, nTab, nSizeTwips != 0 );
3745  }
3746  else if ( eMode==SC_SIZE_SHOW )
3747  {
3748  rDoc.ShowRows( nStartNo, nEndNo, nTab, true );
3749  }
3750  }
3751  else // Column widths
3752  {
3753  for (SCCOL nCol=static_cast<SCCOL>(nStartNo); nCol<=static_cast<SCCOL>(nEndNo); nCol++)
3754  {
3755  if ( eMode != SC_SIZE_VISOPT || !rDoc.ColHidden(nCol, nTab) )
3756  {
3757  sal_uInt16 nThisSize = nSizeTwips;
3758 
3759  if ( eMode==SC_SIZE_OPTIMAL || eMode==SC_SIZE_VISOPT )
3760  nThisSize = nSizeTwips +
3761  lcl_GetOptimalColWidth( rDocShell, nCol, nTab );
3762  if ( nThisSize )
3763  rDoc.SetColWidth( nCol, nTab, nThisSize );
3764 
3765  if ( eMode != SC_SIZE_ORIGINAL )
3766  rDoc.ShowCol( nCol, nTab, bShow );
3767  }
3768  }
3769  }
3770 
3771  // adjust outlines
3772 
3773  if ( eMode != SC_SIZE_ORIGINAL )
3774  {
3775  if (bWidth)
3776  bOutline = bOutline || rDoc.UpdateOutlineCol(
3777  static_cast<SCCOL>(nStartNo),
3778  static_cast<SCCOL>(nEndNo), nTab, bShow );
3779  else
3780  bOutline = bOutline || rDoc.UpdateOutlineRow(
3781  static_cast<SCROW>(nStartNo),
3782  static_cast<SCROW>(nEndNo), nTab, bShow );
3783  }
3784  }
3785  rDoc.SetDrawPageSize(nTab);
3786 
3787  if (!bOutline)
3788  pUndoTab.reset();
3789 
3790  if (bRecord)
3791  {
3792  ScMarkData aMark(rDoc.GetSheetLimits());
3793  aMark.SelectOneTable( nTab );
3794  rDocShell.GetUndoManager()->AddUndoAction(
3795  std::make_unique<ScUndoWidthOrHeight>(
3796  &rDocShell, aMark, nStart, nTab, nEnd, nTab, std::move(pUndoDoc),
3797  aUndoRanges, std::move(pUndoTab), eMode, nSizeTwips, bWidth));
3798  }
3799 
3800  rDoc.UpdatePageBreaks( nTab );
3801 
3802  ScTabViewShell* pViewSh = rDocShell.GetBestViewShell();
3803  if (pViewSh)
3804  pViewSh->OnLOKSetWidthOrHeight(nStart, bWidth);
3805 
3806  rDocShell.PostPaint(0,0,nTab,rDoc.MaxCol(),rDoc.MaxRow(),nTab,PaintPartFlags::All);
3807  aModificator.SetDocumentModified();
3808 
3809  return false;
3810 }
3811 
3812 bool ScDocFunc::InsertPageBreak( bool bColumn, const ScAddress& rPos,
3813  bool bRecord, bool bSetModified )
3814 {
3815  ScDocShellModificator aModificator( rDocShell );
3816 
3817  ScDocument& rDoc = rDocShell.GetDocument();
3818  if (bRecord && !rDoc.IsUndoEnabled())
3819  bRecord = false;
3820  SCTAB nTab = rPos.Tab();
3821  SfxBindings* pBindings = rDocShell.GetViewBindings();
3822 
3823  SCCOLROW nPos = bColumn ? static_cast<SCCOLROW>(rPos.Col()) :
3824  static_cast<SCCOLROW>(rPos.Row());
3825  if (nPos == 0)
3826  return false; // first column / row
3827 
3828  ScBreakType nBreak = bColumn ?
3829  rDoc.HasColBreak(static_cast<SCCOL>(nPos), nTab) :
3830  rDoc.HasRowBreak(static_cast<SCROW>(nPos), nTab);
3831  if (nBreak & ScBreakType::Manual)
3832  return true;
3833 
3834  if (bRecord)
3835  rDocShell.GetUndoManager()->AddUndoAction(
3836  std::make_unique<ScUndoPageBreak>( &rDocShell, rPos.Col(), rPos.Row(), nTab, bColumn, true ) );
3837 
3838  if (bColumn)
3839  rDoc.SetColBreak(static_cast<SCCOL>(nPos), nTab, false, true);
3840  else
3841  rDoc.SetRowBreak(static_cast<SCROW>(nPos), nTab, false, true);
3842 
3843  rDoc.InvalidatePageBreaks(nTab);
3844  rDoc.UpdatePageBreaks( nTab );
3845 
3846  rDoc.SetStreamValid(nTab, false);
3847 
3848  if (bColumn)
3849  {
3850  rDocShell.PostPaint( static_cast<SCCOL>(nPos)-1, 0, nTab, rDoc.MaxCol(), rDoc.MaxRow(), nTab, PaintPartFlags::Grid );
3851  if (pBindings)
3852  {
3853  pBindings->Invalidate( FID_INS_COLBRK );
3854  pBindings->Invalidate( FID_DEL_COLBRK );
3855  }
3856  }
3857  else
3858  {
3859  rDocShell.PostPaint( 0, static_cast<SCROW>(nPos)-1, nTab, rDoc.MaxCol(), rDoc.MaxRow(), nTab, PaintPartFlags::Grid );
3860  if (pBindings)
3861  {
3862  pBindings->Invalidate( FID_INS_ROWBRK );
3863  pBindings->Invalidate( FID_DEL_ROWBRK );
3864  }
3865  }
3866  if (pBindings)
3867  pBindings->Invalidate( FID_DEL_MANUALBREAKS );
3868 
3869  if (bSetModified)
3870  aModificator.SetDocumentModified();
3871 
3872  return true;
3873 }
3874 
3875 bool ScDocFunc::RemovePageBreak( bool bColumn, const ScAddress& rPos,
3876  bool bRecord, bool bSetModified )
3877 {
3878  ScDocShellModificator aModificator( rDocShell );
3879 
3880  ScDocument& rDoc = rDocShell.GetDocument();
3881  if (bRecord && !rDoc.IsUndoEnabled())
3882  bRecord = false;
3883  SCTAB nTab = rPos.Tab();
3884  SfxBindings* pBindings = rDocShell.GetViewBindings();
3885 
3886  SCCOLROW nPos = bColumn ? static_cast<SCCOLROW>(rPos.Col()) :
3887  static_cast<SCCOLROW>(rPos.Row());
3888 
3889  ScBreakType nBreak;
3890  if (bColumn)
3891  nBreak = rDoc.HasColBreak(static_cast<SCCOL>(nPos), nTab);
3892  else
3893  nBreak = rDoc.HasRowBreak(static_cast<SCROW>(nPos), nTab);
3894  if (!(nBreak & ScBreakType::Manual))
3895  // There is no manual break.
3896  return false;
3897 
3898  if (bRecord)
3899  rDocShell.GetUndoManager()->AddUndoAction(
3900  std::make_unique<ScUndoPageBreak>( &rDocShell, rPos.Col(), rPos.Row(), nTab, bColumn, false ) );
3901 
3902  if (bColumn)
3903  rDoc.RemoveColBreak(static_cast<SCCOL>(nPos), nTab, false, true);
3904  else
3905  rDoc.RemoveRowBreak(static_cast<SCROW>(nPos), nTab, false, true);
3906 
3907  rDoc.UpdatePageBreaks( nTab );
3908 
3909  rDoc.SetStreamValid(nTab, false);
3910 
3911  if (bColumn)
3912  {
3913  rDocShell.PostPaint( static_cast<SCCOL>(nPos)-1, 0, nTab, rDoc.MaxCol(), rDoc.MaxRow(), nTab, PaintPartFlags::Grid );
3914  if (pBindings)
3915  {
3916  pBindings->Invalidate( FID_INS_COLBRK );
3917  pBindings->Invalidate( FID_DEL_COLBRK );
3918  }
3919  }
3920  else
3921  {
3922  rDocShell.PostPaint( 0, nPos-1, nTab, rDoc.MaxCol(), rDoc.MaxRow(), nTab, PaintPartFlags::Grid );
3923  if (pBindings)
3924  {
3925  pBindings->Invalidate( FID_INS_ROWBRK );
3926  pBindings->Invalidate( FID_DEL_ROWBRK );
3927  }
3928  }
3929  if (pBindings)
3930  pBindings->Invalidate( FID_DEL_MANUALBREAKS );
3931 
3932  if (bSetModified)
3933  aModificator.SetDocumentModified();
3934 
3935  return true;
3936 }
3937 
3938 void ScDocFunc::ProtectSheet( SCTAB nTab, const ScTableProtection& rProtect )
3939 {
3940  ScDocument& rDoc = rDocShell.GetDocument();
3941 
3942  std::unique_ptr<ScTableProtection> p;
3943  if (!rProtect.isProtected() && rDoc.IsUndoEnabled())
3944  {
3945  // In case of unprotecting, use a copy of passed ScTableProtection object for undo
3946  p = std::make_unique<ScTableProtection>(rProtect);
3947  }
3948  rDoc.SetTabProtection(nTab, &rProtect);
3949  if (rDoc.IsUndoEnabled())
3950  {
3951  if (!p)
3952  {
3953  // For protection case, use a copy of resulting ScTableProtection for undo
3954  const ScTableProtection* pProtect = rDoc.GetTabProtection(nTab);
3955  p = std::make_unique<ScTableProtection>(*pProtect);
3956  }
3957  rDocShell.GetUndoManager()->AddUndoAction(
3958  std::make_unique<ScUndoTabProtect>(&rDocShell, nTab, std::move(p)));
3959  // ownership of unique_ptr now transferred to ScUndoTabProtect.
3960  }
3961  for (SfxViewFrame* fr = SfxViewFrame::GetFirst(&rDocShell); fr;
3962  fr = SfxViewFrame::GetNext(*fr, &rDocShell))
3963  if (ScTabViewShell* pTabViewShell = dynamic_cast<ScTabViewShell*>(fr->GetViewShell()))
3964  pTabViewShell->SetTabProtectionSymbol(nTab, rProtect.isProtected());
3965  rDocShell.PostPaintGridAll();
3966  ScDocShellModificator aModificator(rDocShell);
3967  aModificator.SetDocumentModified();
3968 }
3969 
3971 {
3972  ScDocument& rDoc = rDocShell.GetDocument();
3973 
3974  std::unique_ptr<ScDocProtection> p;
3975  if (!rProtect.isProtected() && rDoc.IsUndoEnabled())
3976  {
3977  // In case of unprotecting, use a copy of passed ScTableProtection object for undo
3978  p = std::make_unique<ScDocProtection>(rProtect);
3979  }
3980  rDoc.SetDocProtection(&rProtect);
3981  if (rDoc.IsUndoEnabled())
3982  {
3983  if (!p)
3984  {
3985  // For protection case, use a copy of resulting ScTableProtection for undo
3986  ScDocProtection* pProtect = rDoc.GetDocProtection();
3987  p = std::make_unique<ScDocProtection>(*pProtect);
3988  }
3989  rDocShell.GetUndoManager()->AddUndoAction(
3990  std::make_unique<ScUndoDocProtect>(&rDocShell, std::move(p)));
3991  // ownership of unique_ptr now transferred to ScUndoTabProtect.
3992  }
3993 
3994  rDocShell.PostPaintGridAll();
3995  ScDocShellModificator aModificator(rDocShell);
3996  aModificator.SetDocumentModified();
3997 }
3998 
3999 bool ScDocFunc::Protect( SCTAB nTab, const OUString& rPassword )
4000 {
4001  if (nTab == TABLEID_DOC)
4002  {
4003  // document protection
4004  ScDocProtection aProtection;
4005  aProtection.setProtected(true);
4006  aProtection.setPassword(rPassword);
4007  ProtectDocument(aProtection);
4008 
4009  }
4010  else
4011  {
4012  // sheet protection
4013 
4014  const ScTableProtection* pOldProtection = rDocShell.GetDocument().GetTabProtection(nTab);
4015  ::std::unique_ptr<ScTableProtection> pNewProtection(pOldProtection ? new ScTableProtection(*pOldProtection) : new ScTableProtection());
4016  pNewProtection->setProtected(true);
4017  pNewProtection->setPassword(rPassword);
4018  ProtectSheet(nTab, *pNewProtection);
4019  }
4020  return true;
4021 }
4022 
4023 bool ScDocFunc::Unprotect( SCTAB nTab, const OUString& rPassword, bool bApi )
4024 {
4025  ScDocument& rDoc = rDocShell.GetDocument();
4026 
4027  if (nTab == TABLEID_DOC)
4028  {
4029  // document protection
4030 
4031  ScDocProtection* pDocProtect = rDoc.GetDocProtection();
4032  if (!pDocProtect || !pDocProtect->isProtected())
4033  // already unprotected (should not happen)!
4034  return true;
4035 
4036  if (!pDocProtect->verifyPassword(rPassword))
4037  {
4038  if (!bApi)
4039  {
4040  std::unique_ptr<weld::MessageDialog> xInfoBox(Application::CreateMessageDialog(ScDocShell::GetActiveDialogParent(),
4041  VclMessageType::Info, VclButtonsType::Ok,
4042  ScResId(SCSTR_WRONGPASSWORD)));
4043  xInfoBox->run();
4044  }
4045  return false;
4046  }
4047 
4048  ScDocProtection aNewProtection(*pDocProtect);
4049  aNewProtection.setProtected(false);
4050  ProtectDocument(aNewProtection);
4051 
4052  }
4053  else
4054  {
4055  // sheet protection
4056 
4057  const ScTableProtection* pTabProtect = rDoc.GetTabProtection(nTab);
4058  if (!pTabProtect || !pTabProtect->isProtected())
4059  // already unprotected (should not happen)!
4060  return true;
4061  if (!pTabProtect->verifyPassword(rPassword))
4062  {
4063  if (!bApi)
4064  {
4065  std::unique_ptr<weld::MessageDialog> xInfoBox(Application::CreateMessageDialog(ScDocShell::GetActiveDialogParent(),
4066  VclMessageType::Info, VclButtonsType::Ok,
4067  ScResId(SCSTR_WRONGPASSWORD)));
4068  xInfoBox->run();
4069  }
4070  return false;
4071  }
4072 
4073  ScTableProtection aNewProtection(*pTabProtect);
4074  aNewProtection.setProtected(false);
4075  ProtectSheet(nTab, aNewProtection);
4076  }
4077 
4078  return true;
4079 }
4080 
4081 void ScDocFunc::ClearItems( const ScMarkData& rMark, const sal_uInt16* pWhich, bool bApi )
4082 {
4083  ScDocShellModificator aModificator( rDocShell );
4084 
4085  ScDocument& rDoc = rDocShell.GetDocument();
4086  bool bUndo (rDoc.IsUndoEnabled());
4087  ScEditableTester aTester( rDoc, rMark );
4088  if (!aTester.IsEditable())
4089  {
4090  if (!bApi)
4091  rDocShell.ErrorMessage(aTester.GetMessageId());
4092  return;
4093  }
4094 
4095  // #i12940# ClearItems is called (from setPropertyToDefault) directly with uno object's cached
4096  // MarkData (GetMarkData), so rMark must be changed to multi selection for ClearSelectionItems
4097  // here.
4098 
4099  ScRange aMarkRange;
4100  ScMarkData aMultiMark = rMark;
4101  aMultiMark.SetMarking(false); // for MarkToMulti
4102  aMultiMark.MarkToMulti();
4103  aMultiMark.GetMultiMarkArea( aMarkRange );
4104 
4105  if (bUndo)
4106  {
4107  SCTAB nStartTab = aMarkRange.aStart.Tab();
4108  SCTAB nEndTab = aMarkRange.aEnd.Tab();
4109 
4111  pUndoDoc->InitUndo( rDoc, nStartTab, nEndTab );
4112  rDoc.CopyToDocument( aMarkRange, InsertDeleteFlags::ATTRIB, true, *pUndoDoc, &aMultiMark );
4113 
4114  rDocShell.GetUndoManager()->AddUndoAction(
4115  std::make_unique<ScUndoClearItems>( &rDocShell, aMultiMark, std::move(pUndoDoc), pWhich ) );
4116  }
4117 
4118  rDoc.ClearSelectionItems( pWhich, aMultiMark );
4119 
4120  rDocShell.PostPaint( aMarkRange, PaintPartFlags::Grid, SC_PF_LINES | SC_PF_TESTMERGE );
4121  aModificator.SetDocumentModified();
4122 
4124 }
4125 
4126 bool ScDocFunc::ChangeIndent( const ScMarkData& rMark, bool bIncrement, bool bApi )
4127 {
4128  ScDocShellModificator aModificator( rDocShell );
4129 
4130  ScDocument& rDoc = rDocShell.GetDocument();
4131  bool bUndo(rDoc.IsUndoEnabled());
4132  ScEditableTester aTester( rDoc, rMark );
4133  if (!aTester.IsEditable())
4134  {
4135  if (!bApi)
4136  rDocShell.ErrorMessage(aTester.GetMessageId());
4137  return false;
4138  }
4139 
4140  ScRange aMarkRange;
4141  rMark.GetMultiMarkArea( aMarkRange );
4142 
4143  if (bUndo)
4144  {
4145  SCTAB nStartTab = aMarkRange.aStart.Tab();
4146  SCTAB nTabCount = rDoc.GetTableCount();
4147 
4149  pUndoDoc->InitUndo( rDoc, nStartTab, nStartTab );
4150  for (const auto& rTab : rMark)
4151  {
4152  if (rTab >= nTabCount)
4153  break;
4154 
4155  if (rTab != nStartTab)
4156  pUndoDoc->AddUndoTab( rTab, rTab );
4157  }
4158 
4159  ScRange aCopyRange = aMarkRange;
4160  aCopyRange.aStart.SetTab(0);
4161  aCopyRange.aEnd.SetTab(nTabCount-1);
4162  rDoc.CopyToDocument( aCopyRange, InsertDeleteFlags::ATTRIB, true, *pUndoDoc, &rMark );
4163 
4164  rDocShell.GetUndoManager()->AddUndoAction(
4165  std::make_unique<ScUndoIndent>( &rDocShell, rMark, std::move(pUndoDoc), bIncrement ) );
4166  }
4167 
4168  rDoc.ChangeSelectionIndent( bIncrement, rMark );
4169 
4170  rDocShell.PostPaint( aMarkRange, PaintPartFlags::Grid, SC_PF_LINES | SC_PF_TESTMERGE );
4171  aModificator.SetDocumentModified();
4172 
4173  SfxBindings* pBindings = rDocShell.GetViewBindings();
4174  if (pBindings)
4175  {
4176  pBindings->Invalidate( SID_ALIGNLEFT ); // ChangeIndent aligns left
4177  pBindings->Invalidate( SID_ALIGNRIGHT );
4178  pBindings->Invalidate( SID_ALIGNBLOCK );
4179  pBindings->Invalidate( SID_ALIGNCENTERHOR );
4180  pBindings->Invalidate( SID_ATTR_LRSPACE );
4181  pBindings->Invalidate( SID_ATTR_PARA_ADJUST_LEFT );
4182  pBindings->Invalidate( SID_ATTR_PARA_ADJUST_RIGHT );
4183  pBindings->Invalidate( SID_ATTR_PARA_ADJUST_BLOCK );
4184  pBindings->Invalidate( SID_ATTR_PARA_ADJUST_CENTER);
4185  // pseudo slots for Format menu
4186  pBindings->Invalidate( SID_ALIGN_ANY_HDEFAULT );
4187  pBindings->Invalidate( SID_ALIGN_ANY_LEFT );
4188  pBindings->Invalidate( SID_ALIGN_ANY_HCENTER );
4189  pBindings->Invalidate( SID_ALIGN_ANY_RIGHT );
4190  pBindings->Invalidate( SID_ALIGN_ANY_JUSTIFIED );
4191  }
4192 
4193  return true;
4194 }
4195 
4196 bool ScDocFunc::AutoFormat( const ScRange& rRange, const ScMarkData* pTabMark,
4197  sal_uInt16 nFormatNo, bool bApi )
4198 {
4199  ScDocShellModificator aModificator( rDocShell );
4200 
4201  ScDocument& rDoc = rDocShell.GetDocument();
4202  SCCOL nStartCol = rRange.aStart.Col();
4203  SCROW nStartRow = rRange.aStart.Row();
4204  SCTAB nStartTab = rRange.aStart.Tab();
4205  SCCOL nEndCol = rRange.aEnd.Col();
4206  SCROW nEndRow = rRange.aEnd.Row();
4207  SCTAB nEndTab = rRange.aEnd.Tab();
4208 
4209  bool bRecord = true;
4210  if (!rDoc.IsUndoEnabled())
4211  bRecord = false;
4212  ScMarkData aMark(rDoc.GetSheetLimits());
4213  if (pTabMark)
4214  aMark = *pTabMark;
4215  else
4216  {
4217  for (SCTAB nTab=nStartTab; nTab<=nEndTab; nTab++)
4218  aMark.SelectTable( nTab, true );
4219  }
4220 
4222  ScEditableTester aTester( rDoc, nStartCol,nStartRow, nEndCol,nEndRow, aMark );
4223  if ( nFormatNo < pAutoFormat->size() && aTester.IsEditable() )
4224  {
4226 
4227  bool bSize = pAutoFormat->findByIndex(nFormatNo)->GetIncludeWidthHeight();
4228 
4229  SCTAB nTabCount = rDoc.GetTableCount();
4230  ScDocumentUniquePtr pUndoDoc;
4231  if ( bRecord )
4232  {
4233  pUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
4234  pUndoDoc->InitUndo( rDoc, nStartTab, nStartTab, bSize, bSize );
4235  for (const auto& rTab : aMark)
4236  {
4237  if (rTab >= nTabCount)
4238  break;
4239 
4240  if (rTab != nStartTab)
4241  pUndoDoc->AddUndoTab( rTab, rTab, bSize, bSize );
4242  }
4243 
4244  ScRange aCopyRange = rRange;
4245  aCopyRange.aStart.SetTab(0);
4246  aCopyRange.aStart.SetTab(nTabCount-1);
4247  rDoc.CopyToDocument( aCopyRange, InsertDeleteFlags::ATTRIB, false, *pUndoDoc, &aMark );
4248  if (bSize)
4249  {
4250  rDoc.CopyToDocument( nStartCol,0,0, nEndCol,rDoc.MaxRow(),nTabCount-1,
4251  InsertDeleteFlags::NONE, false, *pUndoDoc, &aMark );
4252  rDoc.CopyToDocument( 0,nStartRow,0, rDoc.MaxCol(),nEndRow,nTabCount-1,
4253  InsertDeleteFlags::NONE, false, *pUndoDoc, &aMark );
4254  }
4255  rDoc.BeginDrawUndo();
4256  }
4257 
4258  rDoc.AutoFormat( nStartCol, nStartRow, nEndCol, nEndRow, nFormatNo, aMark );
4259 
4260  if (bSize)
4261  {
4262  std::vector<sc::ColRowSpan> aCols(1, sc::ColRowSpan(nStartCol,nEndCol));
4263  std::vector<sc::ColRowSpan> aRows(1, sc::ColRowSpan(nStartRow,nEndRow));
4264 
4265  for (const auto& rTab : aMark)
4266  {
4267  if (rTab >= nTabCount)
4268  break;
4269 
4270  SetWidthOrHeight(true, aCols, rTab, SC_SIZE_VISOPT, STD_EXTRA_WIDTH, false, true);
4271  SetWidthOrHeight(false, aRows, rTab, SC_SIZE_VISOPT, 0, false, false);
4272  rDocShell.PostPaint( 0,0,rTab, rDoc.MaxCol(),rDoc.MaxRow(),rTab,
4274  }
4275  }
4276  else
4277  {
4278  for (const auto& rTab : aMark)
4279  {
4280  if (rTab >= nTabCount)
4281  break;
4282 
4283  bool bAdj = AdjustRowHeight( ScRange(nStartCol, nStartRow, rTab,
4284  nEndCol, nEndRow, rTab), false, bApi );
4285  if (bAdj)
4286  rDocShell.PostPaint( 0,nStartRow,rTab, rDoc.MaxCol(),rDoc.MaxRow(),rTab,
4288  else
4289  rDocShell.PostPaint( nStartCol, nStartRow, rTab,
4290  nEndCol, nEndRow, rTab, PaintPartFlags::Grid );
4291  }
4292  }
4293 
4294  if ( bRecord ) // only now is Draw-Undo available
4295  {
4296  rDocShell.GetUndoManager()->AddUndoAction(
4297  std::make_unique<ScUndoAutoFormat>( &rDocShell, rRange, std::move(pUndoDoc), aMark, bSize, nFormatNo ) );
4298  }
4299 
4300  aModificator.SetDocumentModified();
4301  }
4302  else if (!bApi)
4303  rDocShell.ErrorMessage(aTester.GetMessageId());
4304 
4305  return false;
4306 }
4307 
4308 bool ScDocFunc::EnterMatrix( const ScRange& rRange, const ScMarkData* pTabMark,
4309  const ScTokenArray* pTokenArray, const OUString& rString, bool bApi, bool bEnglish,
4310  const OUString& rFormulaNmsp, const formula::FormulaGrammar::Grammar eGrammar )
4311 {
4312  if (ScViewData::SelectionFillDOOM( rRange ))
4313  return false;
4314 
4315  ScDocShellModificator aModificator( rDocShell );
4316 
4317  bool bSuccess = false;
4318  ScDocument& rDoc = rDocShell.GetDocument();
4319  SCCOL nStartCol = rRange.aStart.Col();
4320  SCROW nStartRow = rRange.aStart.Row();
4321  SCTAB nStartTab = rRange.aStart.Tab();
4322  SCCOL nEndCol = rRange.aEnd.Col();
4323  SCROW nEndRow = rRange.aEnd.Row();
4324  SCTAB nEndTab = rRange.aEnd.Tab();
4325 
4326  ScMarkData aMark(rDoc.GetSheetLimits());
4327  if (pTabMark)
4328  aMark = *pTabMark;
4329  else
4330  {
4331  for (SCTAB nTab=nStartTab; nTab<=nEndTab; nTab++)
4332  aMark.SelectTable( nTab, true );
4333  }
4334 
4335  ScEditableTester aTester( rDoc, nStartCol,nStartRow, nEndCol,nEndRow, aMark );
4336  if ( aTester.IsEditable() )
4337  {
4339 
4340  ScDocumentUniquePtr pUndoDoc;
4341 
4342  const bool bUndo(rDoc.IsUndoEnabled());
4343  if (bUndo)
4344  {
4346  pUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
4347  pUndoDoc->InitUndo( rDoc, nStartTab, nEndTab );
4348  rDoc.CopyToDocument( rRange, InsertDeleteFlags::ALL & ~InsertDeleteFlags::NOTE, false, *pUndoDoc );
4349  }
4350 
4351  // use TokenArray if given, string (and flags) otherwise
4352  if ( pTokenArray )
4353  {
4354  rDoc.InsertMatrixFormula( nStartCol, nStartRow, nEndCol, nEndRow,
4355  aMark, EMPTY_OUSTRING, pTokenArray, eGrammar);
4356  }
4357  else if ( rDoc.IsImportingXML() )
4358  {
4359  ScTokenArray aCode(rDoc);
4360  aCode.AssignXMLString( rString,
4361  ((eGrammar == formula::FormulaGrammar::GRAM_EXTERNAL) ? rFormulaNmsp : OUString()));
4362  rDoc.InsertMatrixFormula( nStartCol, nStartRow, nEndCol, nEndRow,
4363  aMark, EMPTY_OUSTRING, &aCode, eGrammar);
4364  rDoc.IncXMLImportedFormulaCount( rString.getLength() );
4365  }
4366  else if (bEnglish)
4367  {
4368  ScCompiler aComp( rDoc, rRange.aStart, eGrammar);
4369  std::unique_ptr<ScTokenArray> pCode = aComp.CompileString( rString );
4370  rDoc.InsertMatrixFormula( nStartCol, nStartRow, nEndCol, nEndRow,
4371  aMark, EMPTY_OUSTRING, pCode.get(), eGrammar);
4372  }
4373  else
4374  rDoc.InsertMatrixFormula( nStartCol, nStartRow, nEndCol, nEndRow,
4375  aMark, rString, nullptr, eGrammar);
4376 
4377  if (bUndo)
4378  {
4380  rDocShell.GetUndoManager()->AddUndoAction(
4381  std::make_unique<ScUndoEnterMatrix>( &rDocShell, rRange, std::move(pUndoDoc), rString ) );
4382  }
4383 
4384  // Err522 painting of DDE-Formulas will be intercepted during interpreting
4385  rDocShell.PostPaint( nStartCol,nStartRow,nStartTab,nEndCol,nEndRow,nEndTab, PaintPartFlags::Grid );
4386  aModificator.SetDocumentModified();
4387 
4388  bSuccess = true;
4389  }
4390  else if (!bApi)
4391  rDocShell.ErrorMessage(aTester.GetMessageId());
4392 
4393  return bSuccess;
4394 }
4395 
4396 bool ScDocFunc::TabOp( const ScRange& rRange, const ScMarkData* pTabMark,
4397  const ScTabOpParam& rParam, bool bRecord, bool bApi )
4398 {
4399  ScDocShellModificator aModificator( rDocShell );
4400 
4401  bool bSuccess = false;
4402  ScDocument& rDoc = rDocShell.GetDocument();
4403  SCCOL nStartCol = rRange.aStart.Col();
4404  SCROW nStartRow = rRange.aStart.Row();
4405  SCTAB nStartTab = rRange.aStart.Tab();
4406  SCCOL nEndCol = rRange.aEnd.Col();
4407  SCROW nEndRow = rRange.aEnd.Row();
4408  SCTAB nEndTab = rRange.aEnd.Tab();
4409 
4410  if (bRecord && !rDoc.IsUndoEnabled())
4411  bRecord = false;
4412 
4413  ScMarkData aMark(rDoc.GetSheetLimits());
4414  if (pTabMark)
4415  aMark = *pTabMark;
4416  else
4417  {
4418  for (SCTAB nTab=nStartTab; nTab<=nEndTab; nTab++)
4419  aMark.SelectTable( nTab, true );
4420  }
4421 
4422  ScEditableTester aTester( rDoc, nStartCol,nStartRow, nEndCol,nEndRow, aMark );
4423  if ( aTester.IsEditable() )
4424  {
4426  rDoc.SetDirty( rRange, false );
4427  if ( bRecord )
4428  {
4431  pUndoDoc->InitUndo( rDoc, nStartTab, nEndTab );
4432  rDoc.CopyToDocument( rRange, InsertDeleteFlags::ALL & ~InsertDeleteFlags::NOTE, false, *pUndoDoc );
4433 
4434  rDocShell.GetUndoManager()->AddUndoAction(
4435  std::make_unique<ScUndoTabOp>( &rDocShell,
4436  nStartCol, nStartRow, nStartTab,
4437  nEndCol, nEndRow, nEndTab, std::move(pUndoDoc),
4438  rParam.aRefFormulaCell,
4439  rParam.aRefFormulaEnd,
4440  rParam.aRefRowCell,
4441  rParam.aRefColCell,
4442  rParam.meMode) );
4443  }
4444  rDoc.InsertTableOp(rParam, nStartCol, nStartRow, nEndCol, nEndRow, aMark);
4445  rDocShell.PostPaintGridAll();
4446  aModificator.SetDocumentModified();
4447  bSuccess = true;
4448  }
4449  else if (!bApi)
4450  rDocShell.ErrorMessage(aTester.GetMessageId());
4451 
4452  return bSuccess;
4453 }
4454 
4456 {
4457  if (eDir==FILL_TO_BOTTOM)
4458  return DIR_BOTTOM;
4459  else if (eDir==FILL_TO_RIGHT)
4460  return DIR_RIGHT;
4461  else if (eDir==FILL_TO_TOP)
4462  return DIR_TOP;
4463  else // if (eDir==FILL_TO_LEFT)
4464  return DIR_LEFT;
4465 }
4466 
4467 namespace {
4468 
4473 void adjustFillRangeForAdjacentCopy(const ScDocument &rDoc, ScRange& rRange, FillDir eDir)
4474 {
4475  switch (eDir)
4476  {
4477  case FILL_TO_BOTTOM:
4478  {
4479  if (rRange.aStart.Row() == 0)
4480  return;
4481 
4482  if (rRange.aStart.Row() != rRange.aEnd.Row())
4483  return;
4484 
4485  // Include the above row.
4486  ScAddress& s = rRange.aStart;
4487  s.SetRow(s.Row()-1);
4488  }
4489  break;
4490  case FILL_TO_TOP:
4491  {
4492  if (rRange.aStart.Row() == rDoc.MaxRow())
4493  return;
4494 
4495  if (rRange.aStart.Row() != rRange.aEnd.Row())
4496  return;
4497 
4498  // Include the row below.
4499  ScAddress& e = rRange.aEnd;
4500  e.SetRow(e.Row()+1);
4501  }
4502  break;
4503  case FILL_TO_LEFT:
4504  {
4505  if (rRange.aStart.Col() == rDoc.MaxCol())
4506  return;
4507 
4508  if (rRange.aStart.Col() != rRange.aEnd.Col())
4509  return;
4510 
4511  // Include the column to the right.
4512  ScAddress& e = rRange.aEnd;
4513  e.SetCol(e.Col()+1);
4514  }
4515  break;
4516  case FILL_TO_RIGHT:
4517  {
4518  if (rRange.aStart.Col() == 0)
4519  return;
4520 
4521  if (rRange.aStart.Col() != rRange.aEnd.Col())
4522  return;
4523 
4524  // Include the column to the left.
4525  ScAddress& s = rRange.aStart;
4526  s.SetCol(s.Col()-1);
4527  }
4528  break;
4529  default:
4530  ;
4531  }
4532 }
4533 
4534 }
4535 
4536 bool ScDocFunc::FillSimple( const ScRange& rRange, const ScMarkData* pTabMark,
4537  FillDir eDir, bool bApi )
4538 {
4539  ScDocShellModificator aModificator( rDocShell );
4540  ScDocument& rDoc = rDocShell.GetDocument();
4541 
4542  bool bSuccess = false;
4543  ScRange aRange = rRange;
4544  adjustFillRangeForAdjacentCopy(rDoc, aRange, eDir);
4545 
4546  SCCOL nStartCol = aRange.aStart.Col();
4547  SCROW nStartRow = aRange.aStart.Row();
4548  SCTAB nStartTab = aRange.aStart.Tab();
4549  SCCOL nEndCol = aRange.aEnd.Col();
4550  SCROW nEndRow = aRange.aEnd.Row();
4551  SCTAB nEndTab = aRange.aEnd.Tab();
4552 
4553  bool bRecord = true;
4554  if (!rDoc.IsUndoEnabled())
4555  bRecord = false;
4556 
4557  ScMarkData aMark(rDoc.GetSheetLimits());
4558  if (pTabMark)
4559  aMark = *pTabMark;
4560  else
4561  {
4562  for (SCTAB nTab=nStartTab; nTab<=nEndTab; nTab++)
4563  aMark.SelectTable( nTab, true );
4564  }
4565 
4566  ScEditableTester aTester( rDoc, nStartCol,nStartRow, nEndCol,nEndRow, aMark );
4567  if ( aTester.IsEditable() )
4568  {
4570 
4571  ScRange aSourceArea = aRange;
4572  ScRange aDestArea = aRange;
4573 
4574  SCCOLROW nCount = 0;
4575  switch (eDir)
4576  {
4577  case FILL_TO_BOTTOM:
4578  nCount = aSourceArea.aEnd.Row()-aSourceArea.aStart.Row();
4579  aSourceArea.aEnd.SetRow( aSourceArea.aStart.Row() );
4580  break;
4581  case FILL_TO_RIGHT:
4582  nCount = aSourceArea.aEnd.Col()-aSourceArea.aStart.Col();
4583  aSourceArea.aEnd.SetCol( aSourceArea.aStart.Col() );
4584  break;
4585  case FILL_TO_TOP:
4586  nCount = aSourceArea.aEnd.Row()-aSourceArea.aStart.Row();
4587  aSourceArea.aStart.SetRow( aSourceArea.aEnd.Row() );
4588  break;
4589  case FILL_TO_LEFT:
4590  nCount = aSourceArea.aEnd.Col()-aSourceArea.aStart.Col();
4591  aSourceArea.aStart.SetCol( aSourceArea.aEnd.Col() );
4592  break;
4593  }
4594 
4595  ScDocumentUniquePtr pUndoDoc;
4596  if ( bRecord )
4597  {
4598  SCTAB nTabCount = rDoc.GetTableCount();
4599  SCTAB nDestStartTab = aDestArea.aStart.Tab();
4600 
4601  pUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
4602  pUndoDoc->InitUndo( rDoc, nDestStartTab, nDestStartTab );
4603  for (const auto& rTab : aMark)
4604  {
4605  if (rTab >= nTabCount)
4606  break;
4607 
4608  if (rTab != nDestStartTab)
4609  pUndoDoc->AddUndoTab( rTab, rTab );
4610  }
4611 
4612  ScRange aCopyRange = aDestArea;
4613  aCopyRange.aStart.SetTab(0);
4614  aCopyRange.aEnd.SetTab(nTabCount-1);
4615  rDoc.CopyToDocument( aCopyRange, InsertDeleteFlags::AUTOFILL, false, *pUndoDoc, &aMark );
4616  }
4617 
4618  sal_uLong nProgCount;
4619  if (eDir == FILL_TO_BOTTOM || eDir == FILL_TO_TOP)
4620  nProgCount = aSourceArea.aEnd.Col() - aSourceArea.aStart.Col() + 1;
4621  else
4622  nProgCount = aSourceArea.aEnd.Row() - aSourceArea.aStart.Row() + 1;
4623  nProgCount *= nCount;
4624  ScProgress aProgress( rDoc.GetDocumentShell(),
4625  ScResId(STR_FILL_SERIES_PROGRESS), nProgCount, true );
4626 
4627  rDoc.Fill( aSourceArea.aStart.Col(), aSourceArea.aStart.Row(),
4628  aSourceArea.aEnd.Col(), aSourceArea.aEnd.Row(), &aProgress,
4629  aMark, nCount, eDir, FILL_SIMPLE );
4630  AdjustRowHeight(aRange, true, bApi);
4631 
4632  if ( bRecord ) // only now is Draw-Undo available
4633  {
4634  rDocShell.GetUndoManager()->AddUndoAction(
4635  std::make_unique<ScUndoAutoFill>( &rDocShell, aDestArea, aSourceArea, std::move(pUndoDoc), aMark,
4636  eDir, FILL_SIMPLE, FILL_DAY, MAXDOUBLE, 1.0, 1e307) );
4637  }
4638 
4639  rDocShell.PostPaintGridAll();
4640  aModificator.SetDocumentModified();
4641 
4642  bSuccess = true;
4643  }
4644  else if (!bApi)
4645  rDocShell.ErrorMessage(aTester.GetMessageId());
4646 
4647  return bSuccess;
4648 }
4649 
4650 bool ScDocFunc::FillSeries( const ScRange& rRange, const ScMarkData* pTabMark,
4651  FillDir eDir, FillCmd eCmd, FillDateCmd eDateCmd,
4652  double fStart, double fStep, double fMax,
4653  bool bApi )
4654 {
4655  ScDocShellModificator aModificator( rDocShell );
4656 
4657  bool bSuccess = false;
4658  ScDocument& rDoc = rDocShell.GetDocument();
4659  SCCOL nStartCol = rRange.aStart.Col();
4660  SCROW nStartRow = rRange.aStart.Row();
4661  SCTAB nStartTab = rRange.aStart.Tab();
4662  SCCOL nEndCol = rRange.aEnd.Col();
4663  SCROW nEndRow = rRange.aEnd.Row();
4664  SCTAB nEndTab = rRange.aEnd.Tab();
4665 
4666  bool bRecord = true;
4667  if (!rDoc.IsUndoEnabled())
4668  bRecord = false;
4669 
4670  ScMarkData aMark(rDoc.GetSheetLimits());
4671  if (pTabMark)
4672  aMark = *pTabMark;
4673  else
4674  {
4675  for (SCTAB nTab=nStartTab; nTab<=nEndTab; nTab++)
4676  aMark.SelectTable( nTab, true );
4677  }
4678 
4679  ScEditableTester aTester( rDoc, nStartCol,nStartRow, nEndCol,nEndRow, aMark );
4680  if ( aTester.IsEditable() )
4681  {
4683 
4684  ScRange aSourceArea = rRange;
4685  ScRange aDestArea = rRange;
4686 
4688  aSourceArea.aStart.Col(), aSourceArea.aStart.Row(), aSourceArea.aStart.Tab(),
4689  aSourceArea.aEnd.Col(), aSourceArea.aEnd.Row(), aSourceArea.aEnd.Tab(),
4690  DirFromFillDir(eDir) );
4691 
4692  // keep at least one row/column as source range
4693  SCSIZE nTotLines = ( eDir == FILL_TO_BOTTOM || eDir == FILL_TO_TOP ) ?
4694  static_cast<SCSIZE>( aSourceArea.aEnd.Row() - aSourceArea.aStart.Row() + 1 ) :
4695  static_cast<SCSIZE>( aSourceArea.aEnd.Col() - aSourceArea.aStart.Col() + 1 );
4696  if ( nCount >= nTotLines )
4697  nCount = nTotLines - 1;
4698 
4699  switch (eDir)
4700  {
4701  case FILL_TO_BOTTOM:
4702  aSourceArea.aEnd.SetRow( sal::static_int_cast<SCROW>( aSourceArea.aEnd.Row() - nCount ) );
4703  break;
4704  case FILL_TO_RIGHT:
4705  aSourceArea.aEnd.SetCol( sal::static_int_cast<SCCOL>( aSourceArea.aEnd.Col() - nCount ) );
4706  break;
4707  case FILL_TO_TOP:
4708  aSourceArea.aStart.SetRow( sal::static_int_cast<SCROW>( aSourceArea.aStart.Row() + nCount ) );
4709  break;
4710  case FILL_TO_LEFT:
4711  aSourceArea.aStart.SetCol( sal::static_int_cast<SCCOL>( aSourceArea.aStart.Col() + nCount ) );
4712  break;
4713  }
4714 
4715  ScDocumentUniquePtr pUndoDoc;
4716  if ( bRecord )
4717  {
4718  SCTAB nTabCount = rDoc.GetTableCount();
4719  SCTAB nDestStartTab = aDestArea.aStart.Tab();
4720 
4721  pUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
4722  pUndoDoc->InitUndo( rDoc, nDestStartTab, nDestStartTab );
4723  for (const auto& rTab : aMark)
4724  {
4725  if (rTab >= nTabCount)
4726  break;
4727 
4728  if (rTab != nDestStartTab)
4729  pUndoDoc->AddUndoTab( rTab, rTab );
4730  }
4731 
4732  rDoc.CopyToDocument(
4733  aDestArea.aStart.Col(), aDestArea.aStart.Row(), 0,
4734  aDestArea.aEnd.Col(), aDestArea.aEnd.Row(), nTabCount-1,
4735  InsertDeleteFlags::AUTOFILL, false, *pUndoDoc, &aMark );
4736  }
4737 
4738  if (aDestArea.aStart.Col() <= aDestArea.aEnd.Col() &&
4739  aDestArea.aStart.Row() <= aDestArea.aEnd.Row())
4740  {
4741  if ( fStart != MAXDOUBLE )
4742  {
4743  SCCOL nValX = (eDir == FILL_TO_LEFT) ? aDestArea.aEnd.Col() : aDestArea.aStart.Col();
4744  SCROW nValY = (eDir == FILL_TO_TOP ) ? aDestArea.aEnd.Row() : aDestArea.aStart.Row();
4745  SCTAB nTab = aDestArea.aStart.Tab();
4746  rDoc.SetValue( nValX, nValY, nTab, fStart );
4747  }
4748 
4749  sal_uLong nProgCount;
4750  if (eDir == FILL_TO_BOTTOM || eDir == FILL_TO_TOP)
4751  nProgCount = aSourceArea.aEnd.Col() - aSourceArea.aStart.Col() + 1;
4752  else
4753  nProgCount = aSourceArea.aEnd.Row() - aSourceArea.aStart.Row() + 1;
4754  nProgCount *= nCount;
4755  ScProgress aProgress( rDoc.GetDocumentShell(),
4756  ScResId(STR_FILL_SERIES_PROGRESS), nProgCount, true );
4757 
4758  rDoc.Fill( aSourceArea.aStart.Col(), aSourceArea.aStart.Row(),
4759  aSourceArea.aEnd.Col(), aSourceArea.aEnd.Row(), &aProgress,
4760  aMark, nCount, eDir, eCmd, eDateCmd, fStep, fMax );
4761  AdjustRowHeight(rRange, true, bApi);
4762 
4763  rDocShell.PostPaintGridAll();
4764  aModificator.SetDocumentModified();
4765  }
4766 
4767  if ( bRecord ) // only now is Draw-Undo available
4768  {
4769  rDocShell.GetUndoManager()->AddUndoAction(
4770  std::make_unique<ScUndoAutoFill>( &rDocShell, aDestArea, aSourceArea, std::move(pUndoDoc), aMark,
4771  eDir, eCmd, eDateCmd, fStart, fStep, fMax) );
4772  }
4773 
4774  bSuccess = true;
4775  }
4776  else if (!bApi)
4777  rDocShell.ErrorMessage(aTester.GetMessageId());
4778 
4779  return bSuccess;
4780 }
4781 
4782 bool ScDocFunc::FillAuto( ScRange& rRange, const ScMarkData* pTabMark,
4783  FillDir eDir, sal_uLong nCount, bool bApi )
4784 {
4785  return FillAuto( rRange, pTabMark, eDir, FILL_AUTO, FILL_DAY, nCount, 1.0/*fStep*/, MAXDOUBLE/*fMax*/, true/*bRecord*/, bApi );
4786 }
4787 
4788 bool ScDocFunc::FillAuto( ScRange& rRange, const ScMarkData* pTabMark, FillDir eDir, FillCmd eCmd, FillDateCmd eDateCmd, sal_uLong nCount, double fStep, double fMax, bool bRecord, bool bApi )
4789 {
4790  ScDocShellModificator aModificator( rDocShell );
4791 
4792  ScDocument& rDoc = rDocShell.GetDocument();
4793  SCCOL nStartCol = rRange.aStart.Col();
4794  SCROW nStartRow = rRange.aStart.Row();
4795  SCTAB nStartTab = rRange.aStart.Tab();
4796  SCCOL nEndCol = rRange.aEnd.Col();
4797  SCROW nEndRow = rRange.aEnd.Row();
4798  SCTAB nEndTab = rRange.aEnd.Tab();
4799 
4800  if (bRecord && !rDoc.IsUndoEnabled())
4801  bRecord = false;
4802 
4803  ScMarkData aMark(rDoc.GetSheetLimits());
4804  if (pTabMark)
4805  aMark = *pTabMark;
4806  else
4807  {
4808  for (SCTAB nTab=nStartTab; nTab<=nEndTab; nTab++)
4809  aMark.SelectTable( nTab, true );
4810  }
4811 
4812  ScRange aSourceArea = rRange;
4813  ScRange aDestArea = rRange;
4814 
4815  switch (eDir)
4816  {
4817  case FILL_TO_BOTTOM:
4818  aDestArea.aEnd.SetRow( sal::static_int_cast<SCROW>( aSourceArea.aEnd.Row() + nCount ) );
4819  break;
4820  case FILL_TO_TOP:
4821  if (nCount > sal::static_int_cast<sal_uLong>( aSourceArea.aStart.Row() ))
4822  {
4823  OSL_FAIL("FillAuto: Row < 0");
4824  nCount = aSourceArea.aStart.Row();
4825  }
4826  aDestArea.aStart.SetRow( sal::static_int_cast<SCROW>( aSourceArea.aStart.Row() - nCount ) );
4827  break;
4828  case FILL_TO_RIGHT:
4829  aDestArea.aEnd.SetCol( sal::static_int_cast<SCCOL>( aSourceArea.aEnd.Col() + nCount ) );
4830  break;
4831  case FILL_TO_LEFT:
4832  if (nCount > sal::static_int_cast<sal_uLong>( aSourceArea.aStart.Col() ))
4833  {
4834  OSL_FAIL("FillAuto: Col < 0");
4835  nCount = aSourceArea.aStart.Col();
4836  }
4837  aDestArea.aStart.SetCol( sal::static_int_cast<SCCOL>( aSourceArea.aStart.Col() - nCount ) );
4838  break;
4839  default:
4840  OSL_FAIL("Wrong direction with FillAuto");
4841  break;
4842  }
4843 
4844  // Test for cell protection
4847 
4848  ScEditableTester aTester( rDoc, aDestArea );
4849  if ( !aTester.IsEditable() )
4850  {
4851  if (!bApi)
4852  rDocShell.ErrorMessage(aTester.GetMessageId());
4853  return false;
4854  }
4855 
4856  if ( rDoc.HasSelectedBlockMatrixFragment( nStartCol, nStartRow,
4857  nEndCol, nEndRow, aMark ) )
4858  {
4859  if (!bApi)
4860  rDocShell.ErrorMessage(STR_MATRIXFRAGMENTERR);
4861  return false;
4862  }
4863 
4864  // FID_FILL_... slots should already had been disabled, check here for API
4865  // calls, no message.
4866  if (ScViewData::SelectionFillDOOM( aDestArea))
4867  return false;
4868 
4870 
4871  ScDocumentUniquePtr pUndoDoc;
4872  if ( bRecord )
4873  {
4874  SCTAB nTabCount = rDoc.GetTableCount();
4875  SCTAB nDestStartTab = aDestArea.aStart.Tab();
4876 
4877  pUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
4878  pUndoDoc->InitUndo( rDoc, nDestStartTab, nDestStartTab );
4879  for (const auto& rTab : aMark)
4880  {
4881  if (rTab >= nTabCount)
4882  break;
4883 
4884  if (rTab != nDestStartTab)
4885  pUndoDoc->AddUndoTab( rTab, rTab );
4886  }
4887 
4888  // do not clone note captions in undo document
4889  rDoc.CopyToDocument(
4890  aDestArea.aStart.Col(), aDestArea.aStart.Row(), 0,
4891  aDestArea.aEnd.Col(), aDestArea.aEnd.Row(), nTabCount-1,
4892  InsertDeleteFlags::AUTOFILL, false, *pUndoDoc, &aMark );
4893  }
4894 
4895  sal_uLong nProgCount;
4896  if (eDir == FILL_TO_BOTTOM || eDir == FILL_TO_TOP)
4897  nProgCount = aSourceArea.aEnd.Col() - aSourceArea.aStart.Col() + 1;
4898  else
4899  nProgCount = aSourceArea.aEnd.Row() - aSourceArea.aStart.Row() + 1;
4900  nProgCount *= nCount;
4901  ScProgress aProgress( rDoc.GetDocumentShell(),
4902  ScResId(STR_FILL_SERIES_PROGRESS), nProgCount, true );
4903 
4904  rDoc.Fill( aSourceArea.aStart.Col(), aSourceArea.aStart.Row(),
4905  aSourceArea.aEnd.Col(), aSourceArea.aEnd.Row(), &aProgress,
4906  aMark, nCount, eDir, eCmd, eDateCmd, fStep, fMax );
4907 
4908  AdjustRowHeight(aDestArea, true, bApi);
4909 
4910  if ( bRecord ) // only now is Draw-Undo available
4911  {
4912  rDocShell.GetUndoManager()->AddUndoAction(
4913  std::make_unique<ScUndoAutoFill>( &rDocShell, aDestArea, aSourceArea, std::move(pUndoDoc), aMark,
4914  eDir, eCmd, eDateCmd, MAXDOUBLE, fStep, fMax) );
4915  }
4916 
4917  rDocShell.PostPaintGridAll();
4918  aModificator.SetDocumentModified();
4919 
4920  rRange = aDestArea; // return destination range (for marking)
4921  return true;
4922 }
4923 
4924 bool ScDocFunc::MergeCells( const ScCellMergeOption& rOption, bool bContents, bool bRecord, bool bApi, bool bEmptyMergedCells /*=false*/ )
4925 {
4926  using ::std::set;
4927 
4928  ScDocShellModificator aModificator( rDocShell );
4929 
4930  SCCOL nStartCol = rOption.mnStartCol;
4931  SCROW nStartRow = rOption.mnStartRow;
4932  SCCOL nEndCol = rOption.mnEndCol;
4933  SCROW nEndRow = rOption.mnEndRow;
4934  if ((nStartCol == nEndCol && nStartRow == nEndRow) || rOption.maTabs.empty())
4935  {
4936  // Nothing to do. Bail out quickly
4937  return true;
4938  }
4939 
4940  ScDocument& rDoc = rDocShell.GetDocument();
4941  SCTAB nTab1 = *rOption.maTabs.begin(), nTab2 = *rOption.maTabs.rbegin();
4942 
4943  if (bRecord && !rDoc.IsUndoEnabled())
4944  bRecord = false;
4945 
4946  for (const auto& rTab : rOption.maTabs)
4947  {
4948  ScEditableTester aTester( rDoc, rTab, nStartCol, nStartRow, nEndCol, nEndRow );
4949  if (!aTester.IsEditable())
4950  {
4951  if (!bApi)
4952  rDocShell.ErrorMessage(aTester.GetMessageId());
4953  return false;
4954  }
4955 
4956  if ( rDoc.HasAttrib( nStartCol, nStartRow, rTab, nEndCol, nEndRow, rTab,
4958  {
4959  // "Merge of already merged cells not possible"
4960  if (!bApi)
4961  rDocShell.ErrorMessage(STR_MSSG_MERGECELLS_0);
4962  return false;
4963  }
4964  }
4965 
4966  ScDocumentUniquePtr pUndoDoc;
4967  bool bNeedContentsUndo = false;
4968  for (const SCTAB nTab : rOption.maTabs)
4969  {
4970  bool bIsBlockEmpty = ( nStartRow == nEndRow )
4971  ? rDoc.IsBlockEmpty( nTab, nStartCol+1,nStartRow, nEndCol,nEndRow, true )
4972  : rDoc.IsBlockEmpty( nTab, nStartCol,nStartRow+1, nStartCol,nEndRow, true ) &&
4973  rDoc.IsBlockEmpty( nTab, nStartCol+1,nStartRow, nEndCol,nEndRow, true );
4974  bool bNeedContents = bContents && !bIsBlockEmpty;
4975  bool bNeedEmpty = bEmptyMergedCells && !bIsBlockEmpty && !bNeedContents; // if DoMergeContents then cells are emptied
4976 
4977  if (bRecord)
4978  {
4979  // test if the range contains other notes which also implies that we need an undo document
4980  bool bHasNotes = rDoc.HasNote(nTab, nStartCol, nStartRow, nEndCol, nEndRow);
4981  if (!pUndoDoc)
4982  {
4983  pUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
4984  pUndoDoc->InitUndo(rDoc, nTab1, nTab2);
4985  }
4986  // note captions are collected by drawing undo
4987  rDoc.CopyToDocument( nStartCol, nStartRow, nTab, nEndCol, nEndRow, nTab,
4989  if( bHasNotes )
4990  rDoc.BeginDrawUndo();
4991  }
4992 
4993  if (bNeedContents)
4994  rDoc.DoMergeContents( nTab, nStartCol,nStartRow, nEndCol,nEndRow );
4995  else if ( bNeedEmpty )
4996  rDoc.DoEmptyBlock( nTab, nStartCol,nStartRow, nEndCol,nEndRow );
4997  rDoc.DoMerge( nTab, nStartCol,nStartRow, nEndCol,nEndRow );
4998 
4999  if (rOption.mbCenter)
5000  {
5001  rDoc.ApplyAttr( nStartCol, nStartRow, nTab, SvxHorJustifyItem( SvxCellHorJustify::Center, ATTR_HOR_JUSTIFY ) );
5002  rDoc.ApplyAttr( nStartCol, nStartRow, nTab, SvxVerJustifyItem( SvxCellVerJustify::Center, ATTR_VER_JUSTIFY ) );
5003  }
5004 
5005  if ( !AdjustRowHeight( ScRange( 0,nStartRow,nTab, rDoc.MaxCol(),nEndRow,nTab ), true, bApi ) )
5006  rDocShell.PostPaint( nStartCol, nStartRow, nTab,
5007  nEndCol, nEndRow, nTab, PaintPartFlags::Grid );
5008  if (bNeedContents || rOption.mbCenter)
5009  {
5010  ScRange aRange(nStartCol, nStartRow, nTab, nEndCol, nEndRow, nTab);
5011  rDoc.SetDirty(aRange, true);
5012  }
5013 
5014  bool bDone = ScDetectiveFunc(rDoc, nTab).DeleteAll( ScDetectiveDelete::Circles );
5015  if(bDone)
5016  DetectiveMarkInvalid(nTab);
5017 
5018  bNeedContentsUndo |= bNeedContents;
5019  }
5020 
5021  if (pUndoDoc)
5022  {
5023  std::unique_ptr<SdrUndoGroup> pDrawUndo = rDoc.GetDrawLayer() ? rDoc.GetDrawLayer()->GetCalcUndo() : nullptr;
5024  rDocShell.GetUndoManager()->AddUndoAction(
5025  std::make_unique<ScUndoMerge>(&rDocShell, rOption, bNeedContentsUndo, std::move(pUndoDoc), std::move(pDrawUndo)) );
5026  }
5027 
5028  aModificator.SetDocumentModified();
5029 
5030  SfxBindings* pBindings = rDocShell.GetViewBindings();
5031  if (pBindings)
5032  {
5033  pBindings->Invalidate( FID_MERGE_ON );
5034  pBindings->Invalidate( FID_MERGE_OFF );
5035  pBindings->Invalidate( FID_MERGE_TOGGLE );
5036  }
5037 
5038  return true;
5039 }
5040 
5041 bool ScDocFunc::UnmergeCells( const ScRange& rRange, bool bRecord, ScUndoRemoveMerge* pUndoRemoveMerge )
5042 {
5043  ScCellMergeOption aOption(rRange.aStart.Col(), rRange.aStart.Row(), rRange.aEnd.Col(), rRange.aEnd.Row());
5044  SCTAB nTab1 = rRange.aStart.Tab(), nTab2 = rRange.aEnd.Tab();
5045  for (SCTAB i = nTab1; i <= nTab2; ++i)
5046  aOption.maTabs.insert(i);
5047 
5048  return UnmergeCells(aOption, bRecord, pUndoRemoveMerge);
5049 }
5050 
5051 bool ScDocFunc::UnmergeCells( const ScCellMergeOption& rOption, bool bRecord, ScUndoRemoveMerge* pUndoRemoveMerge )
5052 {
5053  using ::std::set;
5054 
5055  if (rOption.maTabs.empty())
5056  // Nothing to unmerge.
5057  return true;
5058 
5059  ScDocShellModificator aModificator( rDocShell );
5060  ScDocument& rDoc = rDocShell.GetDocument();
5061 
5062  if (bRecord && !rDoc.IsUndoEnabled())
5063  bRecord = false;
5064 
5065  ScDocument* pUndoDoc = (pUndoRemoveMerge ? pUndoRemoveMerge->GetUndoDoc() : nullptr);
5066  assert( pUndoDoc || !pUndoRemoveMerge );
5067  for (const SCTAB nTab : rOption.maTabs)
5068  {
5069  ScRange aRange = rOption.getSingleRange(nTab);
5070  if ( !rDoc.HasAttrib(aRange, HasAttrFlags::Merged) )
5071  continue;
5072 
5073  ScRange aExtended = aRange;
5074  rDoc.ExtendMerge(aExtended);
5075  ScRange aRefresh = aExtended;
5076  rDoc.ExtendOverlapped(aRefresh);
5077 
5078  if (bRecord)
5079  {
5080  if (!pUndoDoc)
5081  {
5082  pUndoDoc = new ScDocument( SCDOCMODE_UNDO );
5083  pUndoDoc->InitUndo(rDoc, *rOption.maTabs.begin(), *rOption.maTabs.rbegin());
5084  }
5085  rDoc.CopyToDocument(aExtended, InsertDeleteFlags::ATTRIB, false, *pUndoDoc);
5086  }
5087 
5088  const SfxPoolItem& rDefAttr = rDoc.GetPool()->GetDefaultItem( ATTR_MERGE );
5089  ScPatternAttr aPattern( rDoc.GetPool() );
5090  aPattern.GetItemSet().Put( rDefAttr );
5091  rDoc.ApplyPatternAreaTab( aRange.aStart.Col(), aRange.aStart.Row(),
5092  aRange.aEnd.Col(), aRange.aEnd.Row(), nTab,
5093  aPattern );
5094 
5095  rDoc.RemoveFlagsTab( aExtended.aStart.Col(), aExtended.aStart.Row(),
5096  aExtended.aEnd.Col(), aExtended.aEnd.Row(), nTab,
5097  ScMF::Hor | ScMF::Ver );
5098 
5099  rDoc.ExtendMerge( aRefresh, true );
5100 
5101  if ( !AdjustRowHeight( aExtended, true, true ) )
5102  rDocShell.PostPaint( aExtended, PaintPartFlags::Grid );
5103 
5104  bool bDone = ScDetectiveFunc(rDoc, nTab).DeleteAll( ScDetectiveDelete::Circles );
5105  if(bDone)
5106  DetectiveMarkInvalid(nTab);
5107  }
5108 
5109  if (bRecord)
5110  {
5111  if (pUndoRemoveMerge)
5112  {
5113  // If pUndoRemoveMerge was passed, the caller is responsible for
5114  // adding it to Undo. Just add the current option.
5115  pUndoRemoveMerge->AddCellMergeOption( rOption);
5116  }
5117  else
5118  {
5119  rDocShell.GetUndoManager()->AddUndoAction(
5120  std::make_unique<ScUndoRemoveMerge>( &rDocShell, rOption, ScDocumentUniquePtr(pUndoDoc) ) );
5121  }
5122  }
5123  aModificator.SetDocumentModified();
5124 
5125  return true;
5126 }
5127 
5128 void ScDocFunc::ModifyRangeNames( const ScRangeName& rNewRanges, SCTAB nTab )
5129 {
5130  SetNewRangeNames( std::unique_ptr<ScRangeName>(new ScRangeName(rNewRanges)), true, nTab );
5131 }
5132 
5133 void ScDocFunc::SetNewRangeNames( std::unique_ptr<ScRangeName> pNewRanges, bool bModifyDoc, SCTAB nTab ) // takes ownership of pNewRanges
5134 {
5135  ScDocShellModificator aModificator( rDocShell );
5136 
5137  OSL_ENSURE( pNewRanges, "pNewRanges is 0" );
5138  ScDocument& rDoc = rDocShell.GetDocument();
5139  bool bUndo(rDoc.IsUndoEnabled());
5140 
5141  if (bUndo)
5142  {
5143  ScRangeName* pOld;
5144  if (nTab >=0)
5145  {
5146  pOld = rDoc.GetRangeName(nTab);
5147  }
5148  else
5149  {
5150  pOld = rDoc.GetRangeName();
5151  }
5152  std::unique_ptr<ScRangeName> pUndoRanges(new ScRangeName(*pOld));
5153  std::unique_ptr<ScRangeName> pRedoRanges(new ScRangeName(*pNewRanges));
5154  rDocShell.GetUndoManager()->AddUndoAction(
5155  std::make_unique<ScUndoRangeNames>( &rDocShell, std::move(pUndoRanges), std::move(pRedoRanges), nTab ) );
5156  }
5157 
5158  // #i55926# While loading XML, formula cells only have a single string token,
5159  // so CompileNameFormula would never find any name (index) tokens, and would
5160  // unnecessarily loop through all cells.
5161  bool bCompile = ( !rDoc.IsImportingXML() && rDoc.GetNamedRangesLockCount() == 0 );
5162 
5163  if ( bCompile )
5165  if (nTab >= 0)
5166  rDoc.SetRangeName( nTab, std::move(pNewRanges) ); // takes ownership
5167  else
5168  rDoc.SetRangeName( std::move(pNewRanges) ); // takes ownership
5169  if ( bCompile )
5170  rDoc.CompileHybridFormula();
5171 
5172  if (bModifyDoc)
5173  {
5174  aModificator.SetDocumentModified();
5175  SfxGetpApp()->Broadcast( SfxHint(SfxHintId::ScAreasChanged) );
5176  }
5177 }
5178 
5179 void ScDocFunc::ModifyAllRangeNames(const std::map<OUString, std::unique_ptr<ScRangeName>>& rRangeMap)
5180 {
5181  ScDocShellModificator aModificator(rDocShell);
5182  ScDocument& rDoc = rDocShell.GetDocument();
5183 
5184  if (rDoc.IsUndoEnabled())
5185  {
5186  std::map<OUString, ScRangeName*> aOldRangeMap;
5187  rDoc.GetRangeNameMap(aOldRangeMap);
5188  rDocShell.GetUndoManager()->AddUndoAction(
5189  std::make_unique<ScUndoAllRangeNames>(&rDocShell, aOldRangeMap, rRangeMap));
5190  }
5191 
5192  rDoc.PreprocessAllRangeNamesUpdate(rRangeMap);
5193  rDoc.SetAllRangeNames(rRangeMap);
5194  rDoc.CompileHybridFormula();
5195 
5196  aModificator.SetDocumentModified();
5197  SfxGetpApp()->Broadcast(SfxHint(SfxHintId::ScAreasChanged));
5198 }
5199 
5201  SCCOL nPosX, SCROW nPosY, SCTAB nTab,
5202  SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
5203  bool& rCancel, bool bApi )
5204 {
5205  if (rCancel)
5206  return;
5207 
5208  ScDocument& rDoc = rDocShell.GetDocument();
5209  if (rDoc.HasValueData( nPosX, nPosY, nTab ))
5210  return;
5211 
5212  OUString aName = rDoc.GetString(nPosX, nPosY, nTab);
5213  ScRangeData::MakeValidName(rDoc, aName);
5214  if (aName.isEmpty())
5215  return;
5216 
5217  OUString aContent( ScRange( nX1, nY1, nTab, nX2, nY2, nTab ).Format(
5218  rDoc, ScRefFlags::RANGE_ABS_3D, ScAddress::Details( rDoc.GetAddressConvention(), nPosY, nPosX)));
5219 
5220  bool bInsert = false;
5221  ScRangeData* pOld = rList.findByUpperName(ScGlobal::getCharClassPtr()->uppercase(aName));
5222  if (pOld)
5223  {
5224  OUString aOldStr;
5225  pOld->GetSymbol( aOldStr );
5226  if (aOldStr != aContent)
5227  {
5228  if (bApi)
5229  bInsert = true; // don't check via API
5230  else
5231  {
5232  OUString aTemplate = ScResId( STR_CREATENAME_REPLACE );
5233  OUString aMessage = aTemplate.getToken( 0, '#' ) + aName + aTemplate.getToken( 1, '#' );
5234 
5235  std::unique_ptr<weld::MessageDialog> xQueryBox(Application::CreateMessageDialog(ScDocShell::GetActiveDialogParent(),
5236  VclMessageType::Question, VclButtonsType::YesNo,
5237  aMessage));
5238  xQueryBox->add_button(GetStandardText(StandardButtonType::Cancel), RET_CANCEL);
5239  xQueryBox->set_default_response(RET_YES);
5240 
5241  short nResult = xQueryBox->run();
5242  if ( nResult == RET_YES )
5243  {
5244  rList.erase(*pOld);
5245  bInsert = true;
5246  }
5247  else if ( nResult == RET_CANCEL )
5248  rCancel = true;
5249  }
5250  }
5251  }
5252  else
5253  bInsert = true;
5254 
5255  if (bInsert)
5256  {
5257  ScRangeData* pData = new ScRangeData( rDoc, aName, aContent,
5258  ScAddress( nPosX, nPosY, nTab));
5259  if (!rList.insert(pData))
5260  {
5261  OSL_FAIL("nanu?");
5262  }
5263  }
5264 }
5265 
5266 bool ScDocFunc::CreateNames( const ScRange& rRange, CreateNameFlags nFlags, bool bApi, SCTAB aTab )
5267 {
5268  if (nFlags == CreateNameFlags::NONE)
5269  return false; // was nothing
5270 
5271  ScDocShellModificator aModificator( rDocShell );
5272 
5273  bool bDone = false;
5274  SCCOL nStartCol = rRange.aStart.Col();
5275  SCROW nStartRow = rRange.aStart.Row();
5276  SCCOL nEndCol = rRange.aEnd.Col();
5277  SCROW nEndRow = rRange.aEnd.Row();
5278  SCTAB nTab = rRange.aStart.Tab();
5279  OSL_ENSURE(rRange.aEnd.Tab() == nTab, "CreateNames: multiple tables not possible");
5280 
5281  bool bValid = true;
5282  if ( nFlags & ( CreateNameFlags::Top | CreateNameFlags::Bottom ) )
5283  if ( nStartRow == nEndRow )
5284  bValid = false;
5285  if ( nFlags & ( CreateNameFlags::Left | CreateNameFlags::Right ) )
5286  if ( nStartCol == nEndCol )
5287  bValid = false;
5288 
5289  if (bValid)
5290  {
5291  ScDocument& rDoc = rDocShell.GetDocument();
5292  ScRangeName* pNames;
5293  if (aTab >=0)
5294  pNames = rDoc.GetRangeName(nTab);
5295  else
5296  pNames = rDoc.GetRangeName();
5297 
5298  if (!pNames)
5299  return false; // shouldn't happen
5300  ScRangeName aNewRanges( *pNames );
5301 
5302  bool bTop ( nFlags & CreateNameFlags::Top );
5303  bool bLeft ( nFlags & CreateNameFlags::Left );
5304  bool bBottom( nFlags & CreateNameFlags::Bottom );
5305  bool bRight ( nFlags & CreateNameFlags::Right );
5306 
5307  SCCOL nContX1 = nStartCol;
5308  SCROW nContY1 = nStartRow;
5309  SCCOL nContX2 = nEndCol;
5310  SCROW nContY2 = nEndRow;
5311 
5312  if ( bTop )
5313  ++nContY1;
5314  if ( bLeft )
5315  ++nContX1;
5316  if ( bBottom )
5317  --nContY2;
5318  if ( bRight )
5319  --nContX2;
5320 
5321  bool bCancel = false;
5322  SCCOL i;
5323  SCROW j;
5324 
5325  if ( bTop )
5326  for (i=nContX1; i<=nContX2; i++)
5327  CreateOneName( aNewRanges, i,nStartRow,nTab, i,nContY1,i,nContY2, bCancel, bApi );
5328  if ( bLeft )
5329  for (j=nContY1; j<=nContY2; j++)
5330  CreateOneName( aNewRanges, nStartCol,j,nTab, nContX1,j,nContX2,j, bCancel, bApi );
5331  if ( bBottom )
5332  for (i=nContX1; i<=nContX2; i++)
5333  CreateOneName( aNewRanges, i,nEndRow,nTab, i,nContY1,i,nContY2, bCancel, bApi );
5334  if ( bRight )
5335  for (j=nContY1; j<=nContY2; j++)
5336  CreateOneName( aNewRanges, nEndCol,j,nTab, nContX1,j,nContX2,j, bCancel, bApi );
5337 
5338  if ( bTop && bLeft )
5339  CreateOneName( aNewRanges, nStartCol,nStartRow,nTab, nContX1,nContY1,nContX2,nContY2, bCancel, bApi );
5340  if ( bTop && bRight )
5341  CreateOneName( aNewRanges, nEndCol,nStartRow,nTab, nContX1,nContY1,nContX2,nContY2, bCancel, bApi );
5342  if ( bBottom && bLeft )
5343  CreateOneName( aNewRanges, nStartCol,nEndRow,nTab, nContX1,nContY1,nContX2,nContY2, bCancel, bApi );
5344  if ( bBottom && bRight )
5345  CreateOneName( aNewRanges, nEndCol,nEndRow,nTab, nContX1,nContY1,nContX2,nContY2, bCancel, bApi );
5346 
5347  ModifyRangeNames( aNewRanges, aTab );
5348  bDone = true;
5349 
5350  }
5351 
5352  return bDone;
5353 }
5354 
5355 bool ScDocFunc::InsertNameList( const ScAddress& rStartPos, bool bApi )
5356 {
5357  ScDocShellModificator aModificator( rDocShell );
5358 
5359  bool bDone = false;
5360  ScDocument& rDoc = rDocShell.GetDocument();
5361  const bool bRecord = rDoc.IsUndoEnabled();
5362  SCTAB nTab = rStartPos.Tab();
5363 
5364  //local names have higher priority than global names
5365  ScRangeName* pLocalList = rDoc.GetRangeName(nTab);
5366  sal_uInt16 nValidCount = 0;
5367  for (const auto& rEntry : *pLocalList)
5368  {
5369  const ScRangeData& r = *rEntry.second;
5371  ++nValidCount;
5372  }
5373  ScRangeName* pList = rDoc.GetRangeName();
5374  for (const auto& rEntry : *pList)
5375  {
5376  const ScRangeData& r = *rEntry.second;
5377  if (!r.HasType(ScRangeData::Type::Database) && !pLocalList->findByUpperName(r.GetUpperName()))
5378  ++nValidCount;
5379  }
5380 
5381  if (nValidCount)
5382  {
5383  SCCOL nStartCol = rStartPos.Col();
5384  SCROW nStartRow = rStartPos.Row();
5385  SCCOL nEndCol = nStartCol + 1;
5386  SCROW nEndRow = nStartRow + static_cast<SCROW>(nValidCount) - 1;
5387 
5388  ScEditableTester aTester( rDoc, nTab, nStartCol,nStartRow, nEndCol,nEndRow );
5389  if (aTester.IsEditable())
5390  {
5391  ScDocumentUniquePtr pUndoDoc;
5392 
5393  if (bRecord)
5394  {
5395  pUndoDoc.reset(new ScDocument( SCDOCMODE_UNDO ));
5396  pUndoDoc->InitUndo( rDoc, nTab, nTab );
5397  rDoc.CopyToDocument(nStartCol,nStartRow,nTab, nEndCol,nEndRow,nTab,
5398  InsertDeleteFlags::ALL, false, *pUndoDoc);
5399 
5400  rDoc.BeginDrawUndo(); // because of adjusting heights
5401  }
5402 
5403  std::unique_ptr<ScRangeData*[]> ppSortArray(new ScRangeData* [ nValidCount ]);
5404  sal_uInt16 j = 0;
5405  for (const auto& rEntry : *pLocalList)
5406  {
5407  ScRangeData& r = *rEntry.second;
5409  ppSortArray[j++] = &r;
5410  }
5411  for (const auto& [rName, rxData] : *pList)
5412  {
5413  ScRangeData& r = *rxData;
5414  if (!r.HasType(ScRangeData::Type::Database) && !pLocalList->findByUpperName(rName))
5415  ppSortArray[j++] = &r;
5416  }
5417  qsort( static_cast<void*>(ppSortArray.get()), nValidCount, sizeof(ScRangeData*),
5419  OUString aName;
5420  OUStringBuffer aContent;
5421  OUString aFormula;
5422  SCROW nOutRow = nStartRow;
5423  for (j=0; j<nValidCount; j++)
5424  {
5425  ScRangeData* pData = ppSortArray[j];
5426  pData->GetName(aName);
5427  // adjust relative references to the left column in Excel-compliant way:
5428  pData->UpdateSymbol(aContent, ScAddress( nStartCol, nOutRow, nTab ));
5429  aFormula = "=" + aContent.toString();
5430  ScSetStringParam aParam;
5431  aParam.setTextInput();
5432  rDoc.SetString(ScAddress(nStartCol,nOutRow,nTab), aName, &aParam);
5433  rDoc.SetString(ScAddress(nEndCol,nOutRow,nTab), aFormula, &aParam);
5434  ++nOutRow;
5435  }
5436 
5437  ppSortArray.reset();
5438 
5439  if (bRecord)
5440  {
5442  pRedoDoc->InitUndo( rDoc, nTab, nTab );
5443  rDoc.CopyToDocument(nStartCol,nStartRow,nTab, nEndCol,nEndRow,nTab,
5444  InsertDeleteFlags::ALL, false, *pRedoDoc);
5445 
5446  rDocShell.GetUndoManager()->AddUndoAction(
5447  std::make_unique<ScUndoListNames>( &rDocShell,
5448  ScRange( nStartCol,nStartRow,nTab, nEndCol,nEndRow,nTab ),
5449  std::move(pUndoDoc), std::move(pRedoDoc) ) );
5450  }
5451 
5452  if (!AdjustRowHeight(ScRange(0,nStartRow,nTab,rDoc.MaxCol(),nEndRow,nTab), true, true))
5453  rDocShell.PostPaint( nStartCol,nStartRow,nTab, nEndCol,nEndRow,nTab, PaintPartFlags::Grid );
5454 
5455  aModificator.SetDocumentModified();
5456  bDone = true;
5457  }
5458  else if (!bApi)
5459  rDocShell.ErrorMessage(aTester.GetMessageId());
5460  }
5461  return bDone;
5462 }
5463 
5464 void ScDocFunc::ResizeMatrix( const ScRange& rOldRange, const ScAddress& rNewEnd )
5465 {
5466  ScDocument& rDoc = rDocShell.GetDocument();
5467  SCCOL nStartCol = rOldRange.aStart.Col();
5468  SCROW nStartRow = rOldRange.aStart.Row();
5469  SCTAB nTab = rOldRange.aStart.Tab();
5470 
5471  OUString aFormula;
5472  rDoc.GetFormula( nStartCol, nStartRow, nTab, aFormula );
5473  if ( !(aFormula.startsWith("{") && aFormula.endsWith("}")) )
5474  return;
5475 
5476  OUString aUndo = ScResId( STR_UNDO_RESIZEMATRIX );
5477  bool bUndo(rDoc.IsUndoEnabled());
5478  if (bUndo)
5479  {
5480  ViewShellId nViewShellId(1);
5482  nViewShellId = pViewSh->GetViewShellId();
5483  rDocShell.GetUndoManager()->EnterListAction( aUndo, aUndo, 0, nViewShellId );
5484  }
5485 
5486  aFormula = aFormula.copy(1, aFormula.getLength()-2);
5487 
5488  ScMarkData aMark(rDoc.GetSheetLimits());
5489  aMark.SetMarkArea( rOldRange );
5490  aMark.SelectTable( nTab, true );
5491  ScRange aNewRange( rOldRange.aStart, rNewEnd );
5492 
5493  if ( DeleteContents( aMark, InsertDeleteFlags::CONTENTS, true, false/*bApi*/ ) )
5494  {
5495  // GRAM_API for API compatibility.
5496  if (!EnterMatrix( aNewRange, &aMark, nullptr, aFormula, false/*bApi*/, false, EMPTY_OUSTRING, formula::FormulaGrammar::GRAM_API ))
5497  {
5498  // try to restore the previous state
5499  EnterMatrix( rOldRange, &aMark, nullptr, aFormula, false/*bApi*/, false, EMPTY_OUSTRING, formula::FormulaGrammar::GRAM_API );
5500  }
5501  }
5502 
5503  if (bUndo)
5504  rDocShell.GetUndoManager()->LeaveListAction();
5505 }
5506 
5507 void ScDocFunc::InsertAreaLink( const OUString& rFile, const OUString& rFilter,
5508  const OUString& rOptions, const OUString& rSource,
5509  const ScRange& rDestRange, sal_uLong nRefresh,
5510  bool bFitBlock, bool bApi )
5511 {
5512  ScDocument& rDoc = rDocShell.GetDocument();
5513  bool bUndo (rDoc.IsUndoEnabled());
5514 
5515  sfx2::LinkManager* pLinkManager = rDoc.GetLinkManager();
5516 
5517  // #i52120# if other area links exist at the same start position,
5518  // remove them first (file format specifies only one link definition
5519  // for a cell)
5520 
5521  sal_uInt16 nLinkCount = pLinkManager->GetLinks().size();
5522  sal_uInt16 nRemoved = 0;
5523  sal_uInt16 nLinkPos = 0;
5524  while (nLinkPos<nLinkCount)
5525  {
5526  ::sfx2::SvBaseLink* pBase = pLinkManager->GetLinks()[nLinkPos].get();
5527  ScAreaLink* pLink = dynamic_cast<ScAreaLink*>(pBase);
5528  if (pLink && pLink->GetDestArea().aStart == rDestRange.aStart)
5529  {
5530  if ( bUndo )
5531  {
5532  if ( !nRemoved )
5533  {
5534  // group all remove and the insert action
5535  OUString aUndo = ScResId( STR_UNDO_INSERTAREALINK );
5536  ViewShellId nViewShellId(-1);
5538  nViewShellId = pViewSh->GetViewShellId();
5539  r