Version 5.2.6.1, tag libreoffice-5.2.6.1
[LibreOffice.git] / sc / source / ui / view / dbfunc3.cxx
blobc2904091f8371f9bb1768e2d1685a17668cd78e2
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include "dbfunc.hxx"
21 #include "scitems.hxx"
22 #include <sfx2/bindings.hxx>
23 #include <vcl/svapp.hxx>
24 #include <vcl/msgbox.hxx>
25 #include <vcl/waitobj.hxx>
26 #include <svl/zforlist.hxx>
27 #include <sfx2/app.hxx>
28 #include <com/sun/star/beans/XPropertySet.hpp>
29 #include <com/sun/star/container/XNameAccess.hpp>
30 #include <com/sun/star/sheet/DataPilotFieldFilter.hpp>
31 #include <com/sun/star/sheet/DataPilotFieldGroupBy.hpp>
32 #include <com/sun/star/sheet/DataPilotFieldOrientation.hpp>
33 #include <com/sun/star/sheet/DataPilotFieldSortMode.hpp>
34 #include <com/sun/star/sheet/DataPilotTableHeaderData.hpp>
35 #include <com/sun/star/sheet/GeneralFunction.hpp>
36 #include <com/sun/star/sheet/MemberResultFlags.hpp>
37 #include <com/sun/star/sheet/XDimensionsSupplier.hpp>
38 #include <com/sun/star/sheet/XDrillDownDataSupplier.hpp>
40 #include "global.hxx"
41 #include "globstr.hrc"
42 #include "sc.hrc"
43 #include "undotab.hxx"
44 #include "undodat.hxx"
45 #include "dbdata.hxx"
46 #include "rangenam.hxx"
47 #include "rangeutl.hxx"
48 #include "docsh.hxx"
49 #include "olinetab.hxx"
50 #include "consoli.hxx"
51 #include "olinefun.hxx"
52 #include "dpobject.hxx"
53 #include "dpsave.hxx"
54 #include "dpdimsave.hxx"
55 #include "dbdocfun.hxx"
56 #include "dpoutput.hxx"
57 #include "dptabsrc.hxx"
58 #include "dpshttab.hxx"
59 #include "dpsdbtab.hxx"
60 #include "editable.hxx"
61 #include "docpool.hxx"
62 #include "patattr.hxx"
63 #include "unonames.hxx"
64 #include "formulacell.hxx"
65 #include "userlist.hxx"
66 #include "queryentry.hxx"
67 #include "markdata.hxx"
68 #include "stringutil.hxx"
70 #include <list>
71 #include <memory>
72 #include <unordered_set>
73 #include <unordered_map>
74 #include <vector>
76 using namespace com::sun::star;
77 using ::com::sun::star::uno::Any;
78 using ::com::sun::star::uno::Sequence;
79 using ::com::sun::star::uno::Reference;
80 using ::com::sun::star::uno::UNO_QUERY;
81 using ::com::sun::star::beans::XPropertySet;
82 using ::com::sun::star::container::XNameAccess;
83 using ::com::sun::star::sheet::XDimensionsSupplier;
84 using ::std::list;
85 using ::std::vector;
87 // outliner
89 // create outline grouping
91 void ScDBFunc::MakeOutline( bool bColumns, bool bRecord )
93 ScRange aRange;
94 if (GetViewData().GetSimpleArea(aRange) == SC_MARK_SIMPLE)
96 ScDocShell* pDocSh = GetViewData().GetDocShell();
97 ScOutlineDocFunc aFunc(*pDocSh);
98 aFunc.MakeOutline( aRange, bColumns, bRecord, false );
100 else
101 ErrorMessage(STR_NOMULTISELECT);
104 // delete outline grouping
106 void ScDBFunc::RemoveOutline( bool bColumns, bool bRecord )
108 ScRange aRange;
109 if (GetViewData().GetSimpleArea(aRange) == SC_MARK_SIMPLE)
111 ScDocShell* pDocSh = GetViewData().GetDocShell();
112 ScOutlineDocFunc aFunc(*pDocSh);
113 aFunc.RemoveOutline( aRange, bColumns, bRecord, false );
115 else
116 ErrorMessage(STR_NOMULTISELECT);
119 // menu status: delete outlines
121 void ScDBFunc::TestRemoveOutline( bool& rCol, bool& rRow )
123 bool bColFound = false;
124 bool bRowFound = false;
126 SCCOL nStartCol, nEndCol;
127 SCROW nStartRow, nEndRow;
128 SCTAB nStartTab, nEndTab;
129 if (GetViewData().GetSimpleArea(nStartCol,nStartRow,nStartTab,nEndCol,nEndRow,nEndTab) == SC_MARK_SIMPLE)
131 SCTAB nTab = nStartTab;
132 ScDocument* pDoc = GetViewData().GetDocument();
133 ScOutlineTable* pTable = pDoc->GetOutlineTable( nTab );
134 if (pTable)
136 ScOutlineEntry* pEntry;
137 SCCOLROW nStart;
138 SCCOLROW nEnd;
139 bool bColMarked = ( nStartRow == 0 && nEndRow == MAXROW );
140 bool bRowMarked = ( nStartCol == 0 && nEndCol == MAXCOL );
142 // columns
144 if ( !bRowMarked || bColMarked ) // not when entire rows are marked
146 ScOutlineArray& rArray = pTable->GetColArray();
147 ScSubOutlineIterator aColIter( &rArray );
148 while ((pEntry=aColIter.GetNext()) != nullptr && !bColFound)
150 nStart = pEntry->GetStart();
151 nEnd = pEntry->GetEnd();
152 if ( nStartCol<=static_cast<SCCOL>(nEnd) && nEndCol>=static_cast<SCCOL>(nStart) )
153 bColFound = true;
157 // rows
159 if ( !bColMarked || bRowMarked ) // not when entire columns are marked
161 ScOutlineArray& rArray = pTable->GetRowArray();
162 ScSubOutlineIterator aRowIter( &rArray );
163 while ((pEntry=aRowIter.GetNext()) != nullptr && !bRowFound)
165 nStart = pEntry->GetStart();
166 nEnd = pEntry->GetEnd();
167 if ( nStartRow<=nEnd && nEndRow>=nStart )
168 bRowFound = true;
174 rCol = bColFound;
175 rRow = bRowFound;
178 void ScDBFunc::RemoveAllOutlines( bool bRecord )
180 SCTAB nTab = GetViewData().GetTabNo();
181 ScDocShell* pDocSh = GetViewData().GetDocShell();
182 ScOutlineDocFunc aFunc(*pDocSh);
184 bool bOk = aFunc.RemoveAllOutlines( nTab, bRecord );
186 if (bOk)
187 UpdateScrollBars();
190 // auto outlines
192 void ScDBFunc::AutoOutline( )
194 SCTAB nTab = GetViewData().GetTabNo();
195 ScRange aRange( 0,0,nTab, MAXCOL,MAXROW,nTab ); // the complete sheet, if nothing is marked
196 ScMarkData& rMark = GetViewData().GetMarkData();
197 if ( rMark.IsMarked() || rMark.IsMultiMarked() )
199 rMark.MarkToMulti();
200 rMark.GetMultiMarkArea( aRange );
203 ScDocShell* pDocSh = GetViewData().GetDocShell();
204 ScOutlineDocFunc aFunc(*pDocSh);
205 aFunc.AutoOutline( aRange, true );
208 // select outline level
210 void ScDBFunc::SelectLevel( bool bColumns, sal_uInt16 nLevel, bool bRecord )
212 SCTAB nTab = GetViewData().GetTabNo();
213 ScDocShell* pDocSh = GetViewData().GetDocShell();
214 ScOutlineDocFunc aFunc(*pDocSh);
216 bool bOk = aFunc.SelectLevel( nTab, bColumns, nLevel, bRecord, true/*bPaint*/ );
218 if (bOk)
219 UpdateScrollBars();
222 // show individual outline groups
224 void ScDBFunc::ShowOutline( bool bColumns, sal_uInt16 nLevel, sal_uInt16 nEntry, bool bRecord, bool bPaint )
226 SCTAB nTab = GetViewData().GetTabNo();
227 ScDocShell* pDocSh = GetViewData().GetDocShell();
228 ScOutlineDocFunc aFunc(*pDocSh);
230 bool bOk = aFunc.ShowOutline( nTab, bColumns, nLevel, nEntry, bRecord, bPaint );
232 if ( bOk && bPaint )
233 UpdateScrollBars();
236 // hide individual outline groups
238 void ScDBFunc::HideOutline( bool bColumns, sal_uInt16 nLevel, sal_uInt16 nEntry, bool bRecord, bool bPaint )
240 SCTAB nTab = GetViewData().GetTabNo();
241 ScDocShell* pDocSh = GetViewData().GetDocShell();
242 ScOutlineDocFunc aFunc(*pDocSh);
244 bool bOk = aFunc.HideOutline( nTab, bColumns, nLevel, nEntry, bRecord, bPaint );
246 if ( bOk && bPaint )
247 UpdateScrollBars();
250 // menu status: show/hide marked range
252 bool ScDBFunc::OutlinePossible(bool bHide)
254 bool bEnable = false;
256 SCCOL nStartCol;
257 SCROW nStartRow;
258 SCTAB nStartTab;
259 SCCOL nEndCol;
260 SCROW nEndRow;
261 SCTAB nEndTab;
263 if (GetViewData().GetSimpleArea(nStartCol,nStartRow,nStartTab,nEndCol,nEndRow,nEndTab) == SC_MARK_SIMPLE)
265 ScDocument* pDoc = GetViewData().GetDocument();
266 SCTAB nTab = GetViewData().GetTabNo();
267 ScOutlineTable* pTable = pDoc->GetOutlineTable( nTab );
268 if (pTable)
270 ScOutlineEntry* pEntry;
271 SCCOLROW nStart;
272 SCCOLROW nEnd;
274 // columns
276 ScOutlineArray& rColArray = pTable->GetColArray();
277 ScSubOutlineIterator aColIter( &rColArray );
278 while ((pEntry=aColIter.GetNext()) != nullptr && !bEnable)
280 nStart = pEntry->GetStart();
281 nEnd = pEntry->GetEnd();
282 if ( bHide )
284 if ( nStartCol<=static_cast<SCCOL>(nEnd) && nEndCol>=static_cast<SCCOL>(nStart) )
285 if (!pEntry->IsHidden())
286 bEnable = true;
288 else
290 if ( nStart>=nStartCol && nEnd<=nEndCol )
291 if (pEntry->IsHidden())
292 bEnable = true;
296 // rows
298 ScOutlineArray& rRowArray = pTable->GetRowArray();
299 ScSubOutlineIterator aRowIter( &rRowArray );
300 while ((pEntry=aRowIter.GetNext()) != nullptr)
302 nStart = pEntry->GetStart();
303 nEnd = pEntry->GetEnd();
304 if ( bHide )
306 if ( nStartRow<=nEnd && nEndRow>=nStart )
307 if (!pEntry->IsHidden())
308 bEnable = true;
310 else
312 if ( nStart>=nStartRow && nEnd<=nEndRow )
313 if (pEntry->IsHidden())
314 bEnable = true;
320 return bEnable;
323 // show marked range
325 void ScDBFunc::ShowMarkedOutlines( bool bRecord )
327 ScRange aRange;
328 if (GetViewData().GetSimpleArea(aRange) == SC_MARK_SIMPLE)
330 ScDocShell* pDocSh = GetViewData().GetDocShell();
331 ScOutlineDocFunc aFunc(*pDocSh);
332 bool bDone = aFunc.ShowMarkedOutlines( aRange, bRecord );
333 if (bDone)
334 UpdateScrollBars();
336 else
337 ErrorMessage(STR_NOMULTISELECT);
340 // hide marked range
342 void ScDBFunc::HideMarkedOutlines( bool bRecord )
344 ScRange aRange;
345 if (GetViewData().GetSimpleArea(aRange) == SC_MARK_SIMPLE)
347 ScDocShell* pDocSh = GetViewData().GetDocShell();
348 ScOutlineDocFunc aFunc(*pDocSh);
349 bool bDone = aFunc.HideMarkedOutlines( aRange, bRecord );
350 if (bDone)
351 UpdateScrollBars();
353 else
354 ErrorMessage(STR_NOMULTISELECT);
357 // sub totals
359 void ScDBFunc::DoSubTotals( const ScSubTotalParam& rParam, bool bRecord,
360 const ScSortParam* pForceNewSort )
362 bool bDo = !rParam.bRemoveOnly; // sal_False = only delete
364 ScDocShell* pDocSh = GetViewData().GetDocShell();
365 ScDocument& rDoc = pDocSh->GetDocument();
366 ScMarkData& rMark = GetViewData().GetMarkData();
367 SCTAB nTab = GetViewData().GetTabNo();
368 if (bRecord && !rDoc.IsUndoEnabled())
369 bRecord = false;
371 ScDBData* pDBData = rDoc.GetDBAtArea( nTab, rParam.nCol1, rParam.nRow1,
372 rParam.nCol2, rParam.nRow2 );
373 if (!pDBData)
375 OSL_FAIL( "SubTotals: no DBData" );
376 return;
379 ScEditableTester aTester( &rDoc, nTab, 0,rParam.nRow1+1, MAXCOL,MAXROW );
380 if (!aTester.IsEditable())
382 ErrorMessage(aTester.GetMessageId());
383 return;
386 if (rDoc.HasAttrib( rParam.nCol1, rParam.nRow1+1, nTab,
387 rParam.nCol2, rParam.nRow2, nTab, HASATTR_MERGED | HASATTR_OVERLAPPED ))
389 ErrorMessage(STR_MSSG_INSERTCELLS_0); // do not insert into merged
390 return;
393 WaitObject aWait( GetViewData().GetDialogParent() );
394 bool bOk = true;
395 if (rParam.bReplace)
396 if (rDoc.TestRemoveSubTotals( nTab, rParam ))
398 bOk = ( ScopedVclPtrInstance<MessBox>( GetViewData().GetDialogParent(), WinBits(WB_YES_NO | WB_DEF_YES),
399 // "StarCalc" "delete data?"
400 ScGlobal::GetRscString( STR_MSSG_DOSUBTOTALS_0 ),
401 ScGlobal::GetRscString( STR_MSSG_DOSUBTOTALS_1 ) )->Execute()
402 == RET_YES );
405 if (bOk)
407 ScDocShellModificator aModificator( *pDocSh );
409 ScSubTotalParam aNewParam( rParam ); // change end of range
410 ScDocument* pUndoDoc = nullptr;
411 ScOutlineTable* pUndoTab = nullptr;
412 ScRangeName* pUndoRange = nullptr;
413 ScDBCollection* pUndoDB = nullptr;
415 if (bRecord) // record old data
417 bool bOldFilter = bDo && rParam.bDoSort;
418 SCTAB nTabCount = rDoc.GetTableCount();
419 pUndoDoc = new ScDocument( SCDOCMODE_UNDO );
420 ScOutlineTable* pTable = rDoc.GetOutlineTable( nTab );
421 if (pTable)
423 pUndoTab = new ScOutlineTable( *pTable );
425 SCCOLROW nOutStartCol; // row/column status
426 SCCOLROW nOutStartRow;
427 SCCOLROW nOutEndCol;
428 SCCOLROW nOutEndRow;
429 pTable->GetColArray().GetRange( nOutStartCol, nOutEndCol );
430 pTable->GetRowArray().GetRange( nOutStartRow, nOutEndRow );
432 pUndoDoc->InitUndo( &rDoc, nTab, nTab, true, true );
433 rDoc.CopyToDocument( static_cast<SCCOL>(nOutStartCol), 0, nTab, static_cast<SCCOL>(nOutEndCol), MAXROW, nTab, InsertDeleteFlags::NONE, false, pUndoDoc );
434 rDoc.CopyToDocument( 0, nOutStartRow, nTab, MAXCOL, nOutEndRow, nTab, InsertDeleteFlags::NONE, false, pUndoDoc );
436 else
437 pUndoDoc->InitUndo( &rDoc, nTab, nTab, false, bOldFilter );
439 // record data range - including filter results
440 rDoc.CopyToDocument( 0,rParam.nRow1+1,nTab, MAXCOL,rParam.nRow2,nTab,
441 InsertDeleteFlags::ALL, false, pUndoDoc );
443 // all formulas for reference
444 rDoc.CopyToDocument( 0,0,0, MAXCOL,MAXROW,nTabCount-1,
445 InsertDeleteFlags::FORMULA, false, pUndoDoc );
447 // data base and othe ranges
448 ScRangeName* pDocRange = rDoc.GetRangeName();
449 if (!pDocRange->empty())
450 pUndoRange = new ScRangeName( *pDocRange );
451 ScDBCollection* pDocDB = rDoc.GetDBCollection();
452 if (!pDocDB->empty())
453 pUndoDB = new ScDBCollection( *pDocDB );
456 ScOutlineTable* pOut = rDoc.GetOutlineTable( nTab );
457 if (pOut)
459 // Remove all existing outlines in the specified range.
460 ScOutlineArray& rRowArray = pOut->GetRowArray();
461 sal_uInt16 nDepth = rRowArray.GetDepth();
462 for (sal_uInt16 i = 0; i < nDepth; ++i)
464 bool bSize;
465 rRowArray.Remove(aNewParam.nRow1, aNewParam.nRow2, bSize);
469 if (rParam.bReplace)
470 rDoc.RemoveSubTotals( nTab, aNewParam );
471 bool bSuccess = true;
472 if (bDo)
474 // Sort
475 if ( rParam.bDoSort || pForceNewSort )
477 pDBData->SetArea( nTab, aNewParam.nCol1,aNewParam.nRow1, aNewParam.nCol2,aNewParam.nRow2 );
479 // set subtotal fields before sorting
480 // (duplicate values are dropped, so that they can be called again)
482 ScSortParam aOldSort;
483 pDBData->GetSortParam( aOldSort );
484 ScSortParam aSortParam( aNewParam, pForceNewSort ? *pForceNewSort : aOldSort );
485 Sort( aSortParam, false, false );
488 bSuccess = rDoc.DoSubTotals( nTab, aNewParam );
490 ScRange aDirtyRange( aNewParam.nCol1, aNewParam.nRow1, nTab,
491 aNewParam.nCol2, aNewParam.nRow2, nTab );
492 rDoc.SetDirty( aDirtyRange, true );
494 if (bRecord)
496 pDocSh->GetUndoManager()->AddUndoAction(
497 new ScUndoSubTotals( pDocSh, nTab,
498 rParam, aNewParam.nRow2,
499 pUndoDoc, pUndoTab, // pUndoDBData,
500 pUndoRange, pUndoDB ) );
503 if (!bSuccess)
505 // "Can not insert any rows"
506 ErrorMessage(STR_MSSG_DOSUBTOTALS_2);
509 // store
510 pDBData->SetSubTotalParam( aNewParam );
511 pDBData->SetArea( nTab, aNewParam.nCol1,aNewParam.nRow1, aNewParam.nCol2,aNewParam.nRow2 );
512 rDoc.CompileDBFormula();
514 DoneBlockMode();
515 InitOwnBlockMode();
516 rMark.SetMarkArea( ScRange( aNewParam.nCol1,aNewParam.nRow1,nTab,
517 aNewParam.nCol2,aNewParam.nRow2,nTab ) );
518 MarkDataChanged();
520 pDocSh->PostPaint(ScRange(0, 0, nTab, MAXCOL, MAXROW, nTab),
521 PAINT_GRID | PAINT_LEFT | PAINT_TOP | PAINT_SIZE);
523 aModificator.SetDocumentModified();
525 SelectionChanged();
529 // consolidate
531 void ScDBFunc::Consolidate( const ScConsolidateParam& rParam )
533 ScDocShell* pDocShell = GetViewData().GetDocShell();
534 pDocShell->DoConsolidate( rParam );
535 SetTabNo( rParam.nTab, true );
538 // pivot
540 static OUString lcl_MakePivotTabName( const OUString& rPrefix, SCTAB nNumber )
542 OUString aName = rPrefix + OUString::number( nNumber );
543 return aName;
546 bool ScDBFunc::MakePivotTable(
547 const ScDPSaveData& rData, const ScRange& rDest, bool bNewTable,
548 const ScDPObject& rSource )
550 // error message if no fields are set
551 // this must be removed when drag&drop of fields from a toolbox is available
553 if ( rData.IsEmpty() )
555 ErrorMessage(STR_PIVOT_NODATA);
556 return false;
559 ScDocShell* pDocSh = GetViewData().GetDocShell();
560 ScDocument* pDoc = GetViewData().GetDocument();
561 bool bUndo = pDoc->IsUndoEnabled();
563 ScRange aDestRange = rDest;
564 if ( bNewTable )
566 SCTAB nSrcTab = GetViewData().GetTabNo();
568 OUString aName( ScGlobal::GetRscString(STR_PIVOT_TABLE) );
569 OUString aStr;
571 pDoc->GetName( nSrcTab, aStr );
572 aName += "_";
573 aName += aStr;
574 aName += "_";
576 SCTAB nNewTab = nSrcTab+1;
578 SCTAB i=1;
579 while ( !pDoc->InsertTab( nNewTab, lcl_MakePivotTabName( aName, i ) ) && i <= MAXTAB )
580 i++;
582 bool bAppend = ( nNewTab+1 == pDoc->GetTableCount() );
583 if (bUndo)
585 pDocSh->GetUndoManager()->AddUndoAction(
586 new ScUndoInsertTab( pDocSh, nNewTab, bAppend, lcl_MakePivotTabName( aName, i ) ));
589 GetViewData().InsertTab( nNewTab );
590 SetTabNo(nNewTab, true);
592 aDestRange = ScRange( 0, 0, nNewTab );
595 ScDPObject* pDPObj = pDoc->GetDPAtCursor(
596 aDestRange.aStart.Col(), aDestRange.aStart.Row(), aDestRange.aStart.Tab() );
598 ScDPObject aObj( rSource );
599 aObj.SetOutRange( aDestRange );
600 if ( pDPObj && !rData.GetExistingDimensionData() )
602 // copy dimension data from old object - lost in the dialog
603 //! change the dialog to keep the dimension data
605 ScDPSaveData aNewData( rData );
606 const ScDPSaveData* pOldData = pDPObj->GetSaveData();
607 if ( pOldData )
609 const ScDPDimensionSaveData* pDimSave = pOldData->GetExistingDimensionData();
610 aNewData.SetDimensionData( pDimSave );
612 aObj.SetSaveData( aNewData );
614 else
615 aObj.SetSaveData( rData );
617 bool bAllowMove = (pDPObj != nullptr); // allow re-positioning when editing existing table
619 ScDBDocFunc aFunc( *pDocSh );
620 bool bSuccess = aFunc.DataPilotUpdate(pDPObj, &aObj, true, false, bAllowMove);
622 CursorPosChanged(); // shells may be switched
624 if ( bNewTable )
626 pDocSh->PostPaintExtras();
627 SfxGetpApp()->Broadcast( SfxSimpleHint( SC_HINT_TABLES_CHANGED ) );
630 return bSuccess;
633 void ScDBFunc::DeletePivotTable()
635 ScDocShell* pDocSh = GetViewData().GetDocShell();
636 ScDocument& rDoc = pDocSh->GetDocument();
637 ScDPObject* pDPObj = rDoc.GetDPAtCursor( GetViewData().GetCurX(),
638 GetViewData().GetCurY(),
639 GetViewData().GetTabNo() );
640 if ( pDPObj )
642 ScDBDocFunc aFunc( *pDocSh );
643 aFunc.RemovePivotTable(*pDPObj, true, false);
644 CursorPosChanged(); // shells may be switched
646 else
647 ErrorMessage(STR_PIVOT_NOTFOUND);
650 void ScDBFunc::RecalcPivotTable()
652 ScDocShell* pDocSh = GetViewData().GetDocShell();
653 ScDocument* pDoc = GetViewData().GetDocument();
655 ScDPObject* pDPObj = pDoc->GetDPAtCursor( GetViewData().GetCurX(),
656 GetViewData().GetCurY(),
657 GetViewData().GetTabNo() );
658 if (pDPObj)
660 // Remove existing data cache for the data that this datapilot uses,
661 // to force re-build data cache.
662 ScDBDocFunc aFunc(*pDocSh);
663 aFunc.RefreshPivotTables(pDPObj, false);
665 CursorPosChanged(); // shells may be switched
667 else
668 ErrorMessage(STR_PIVOT_NOTFOUND);
671 void ScDBFunc::GetSelectedMemberList(ScDPUniqueStringSet& rEntries, long& rDimension)
673 ScDPObject* pDPObj = GetViewData().GetDocument()->GetDPAtCursor( GetViewData().GetCurX(),
674 GetViewData().GetCurY(), GetViewData().GetTabNo() );
675 if ( !pDPObj )
676 return;
678 long nStartDimension = -1;
679 long nStartHierarchy = -1;
680 long nStartLevel = -1;
682 ScRangeListRef xRanges;
683 GetViewData().GetMultiArea( xRanges ); // incl. cursor if nothing is selected
684 size_t nRangeCount = xRanges->size();
685 bool bContinue = true;
687 for (size_t nRangePos=0; nRangePos < nRangeCount && bContinue; nRangePos++)
689 ScRange aRange = *(*xRanges)[nRangePos];
690 SCCOL nStartCol = aRange.aStart.Col();
691 SCROW nStartRow = aRange.aStart.Row();
692 SCCOL nEndCol = aRange.aEnd.Col();
693 SCROW nEndRow = aRange.aEnd.Row();
694 SCTAB nTab = aRange.aStart.Tab();
696 for (SCROW nRow=nStartRow; nRow<=nEndRow && bContinue; nRow++)
697 for (SCCOL nCol=nStartCol; nCol<=nEndCol && bContinue; nCol++)
699 sheet::DataPilotTableHeaderData aData;
700 pDPObj->GetHeaderPositionData(ScAddress(nCol, nRow, nTab), aData);
701 if ( aData.Dimension < 0 )
702 bContinue = false; // not part of any dimension
703 else
705 if ( nStartDimension < 0 ) // first member?
707 nStartDimension = aData.Dimension;
708 nStartHierarchy = aData.Hierarchy;
709 nStartLevel = aData.Level;
711 if ( aData.Dimension != nStartDimension ||
712 aData.Hierarchy != nStartHierarchy ||
713 aData.Level != nStartLevel )
715 bContinue = false; // cannot mix dimensions
718 if ( bContinue )
720 // accept any part of a member description, also subtotals,
721 // but don't stop if empty parts are contained
722 if ( aData.Flags & sheet::MemberResultFlags::HASMEMBER )
723 rEntries.insert(aData.MemberName);
728 rDimension = nStartDimension; // dimension from which the found members came
729 if (!bContinue)
730 rEntries.clear(); // remove all if not valid
733 bool ScDBFunc::HasSelectionForDateGroup( ScDPNumGroupInfo& rOldInfo, sal_Int32& rParts )
735 // determine if the date group dialog has to be shown for the current selection
737 bool bFound = false;
739 SCCOL nCurX = GetViewData().GetCurX();
740 SCROW nCurY = GetViewData().GetCurY();
741 SCTAB nTab = GetViewData().GetTabNo();
742 ScDocument* pDoc = GetViewData().GetDocument();
744 ScDPObject* pDPObj = pDoc->GetDPAtCursor( nCurX, nCurY, nTab );
745 if ( pDPObj )
747 ScDPUniqueStringSet aEntries;
748 long nSelectDimension = -1;
749 GetSelectedMemberList( aEntries, nSelectDimension );
751 if (!aEntries.empty())
753 bool bIsDataLayout;
754 OUString aDimName = pDPObj->GetDimName( nSelectDimension, bIsDataLayout );
755 OUString aBaseDimName( aDimName );
757 bool bInGroupDim = false;
758 bool bFoundParts = false;
760 ScDPDimensionSaveData* pDimData =
761 const_cast<ScDPDimensionSaveData*>( pDPObj->GetSaveData()->GetExistingDimensionData() );
762 if ( pDimData )
764 const ScDPSaveNumGroupDimension* pNumGroupDim = pDimData->GetNumGroupDim( aDimName );
765 const ScDPSaveGroupDimension* pGroupDim = pDimData->GetNamedGroupDim( aDimName );
766 if ( pNumGroupDim )
768 // existing num group dimension
770 if ( pNumGroupDim->GetDatePart() != 0 )
772 // dimension has date info -> edit settings of this dimension
773 // (parts are collected below)
775 rOldInfo = pNumGroupDim->GetDateInfo();
776 bFound = true;
778 else if ( pNumGroupDim->GetInfo().mbDateValues )
780 // Numerical grouping with DateValues flag is used for grouping
781 // of days with a "Number of days" value.
783 rOldInfo = pNumGroupDim->GetInfo();
784 rParts = css::sheet::DataPilotFieldGroupBy::DAYS; // not found in CollectDateParts
785 bFoundParts = true;
786 bFound = true;
788 bInGroupDim = true;
790 else if ( pGroupDim )
792 // existing additional group dimension
794 if ( pGroupDim->GetDatePart() != 0 )
796 // dimension has date info -> edit settings of this dimension
797 // (parts are collected below)
799 rOldInfo = pGroupDim->GetDateInfo();
800 aBaseDimName = pGroupDim->GetSourceDimName();
801 bFound = true;
803 bInGroupDim = true;
806 if ( bFound && !bFoundParts )
808 // collect date parts from all group dimensions
809 rParts = pDimData->CollectDateParts( aBaseDimName );
811 if ( !bFound && !bInGroupDim )
813 // create new date group dimensions if the selection is a single cell
814 // in a normal dimension with date content
816 ScRange aSelRange;
817 if ( (GetViewData().GetSimpleArea( aSelRange ) == SC_MARK_SIMPLE) &&
818 aSelRange.aStart == aSelRange.aEnd )
820 SCCOL nSelCol = aSelRange.aStart.Col();
821 SCROW nSelRow = aSelRange.aStart.Row();
822 SCTAB nSelTab = aSelRange.aStart.Tab();
823 if ( pDoc->HasValueData( nSelCol, nSelRow, nSelTab ) )
825 sal_uLong nIndex = static_cast<const SfxUInt32Item*>(pDoc->GetAttr(
826 nSelCol, nSelRow, nSelTab, ATTR_VALUE_FORMAT))->GetValue();
827 short nType = pDoc->GetFormatTable()->GetType(nIndex);
828 if ( nType == css::util::NumberFormat::DATE || nType == css::util::NumberFormat::TIME || nType == css::util::NumberFormat::DATETIME )
830 bFound = true;
831 // use currently selected value for automatic limits
832 if( rOldInfo.mbAutoStart )
833 rOldInfo.mfStart = pDoc->GetValue( aSelRange.aStart );
834 if( rOldInfo.mbAutoEnd )
835 rOldInfo.mfEnd = pDoc->GetValue( aSelRange.aStart );
843 return bFound;
846 bool ScDBFunc::HasSelectionForNumGroup( ScDPNumGroupInfo& rOldInfo )
848 // determine if the numeric group dialog has to be shown for the current selection
850 bool bFound = false;
852 SCCOL nCurX = GetViewData().GetCurX();
853 SCROW nCurY = GetViewData().GetCurY();
854 SCTAB nTab = GetViewData().GetTabNo();
855 ScDocument* pDoc = GetViewData().GetDocument();
857 ScDPObject* pDPObj = pDoc->GetDPAtCursor( nCurX, nCurY, nTab );
858 if ( pDPObj )
860 ScDPUniqueStringSet aEntries;
861 long nSelectDimension = -1;
862 GetSelectedMemberList( aEntries, nSelectDimension );
864 if (!aEntries.empty())
866 bool bIsDataLayout;
867 OUString aDimName = pDPObj->GetDimName( nSelectDimension, bIsDataLayout );
869 bool bInGroupDim = false;
871 ScDPDimensionSaveData* pDimData =
872 const_cast<ScDPDimensionSaveData*>( pDPObj->GetSaveData()->GetExistingDimensionData() );
873 if ( pDimData )
875 const ScDPSaveNumGroupDimension* pNumGroupDim = pDimData->GetNumGroupDim( aDimName );
876 if ( pNumGroupDim )
878 // existing num group dimension
879 // -> edit settings of this dimension
881 rOldInfo = pNumGroupDim->GetInfo();
882 bFound = true;
884 else if ( pDimData->GetNamedGroupDim( aDimName ) )
885 bInGroupDim = true; // in a group dimension
887 if ( !bFound && !bInGroupDim )
889 // create a new num group dimension if the selection is a single cell
890 // in a normal dimension with numeric content
892 ScRange aSelRange;
893 if ( (GetViewData().GetSimpleArea( aSelRange ) == SC_MARK_SIMPLE) &&
894 aSelRange.aStart == aSelRange.aEnd )
896 if ( pDoc->HasValueData( aSelRange.aStart.Col(), aSelRange.aStart.Row(),
897 aSelRange.aStart.Tab() ) )
899 bFound = true;
900 // use currently selected value for automatic limits
901 if( rOldInfo.mbAutoStart )
902 rOldInfo.mfStart = pDoc->GetValue( aSelRange.aStart );
903 if( rOldInfo.mbAutoEnd )
904 rOldInfo.mfEnd = pDoc->GetValue( aSelRange.aStart );
911 return bFound;
914 void ScDBFunc::DateGroupDataPilot( const ScDPNumGroupInfo& rInfo, sal_Int32 nParts )
916 ScDPObject* pDPObj = GetViewData().GetDocument()->GetDPAtCursor( GetViewData().GetCurX(),
917 GetViewData().GetCurY(), GetViewData().GetTabNo() );
918 if (!pDPObj)
919 return;
921 ScDPUniqueStringSet aEntries;
922 long nSelectDimension = -1;
923 GetSelectedMemberList( aEntries, nSelectDimension );
925 if (aEntries.empty())
926 return;
928 std::vector<OUString> aDeletedNames;
929 bool bIsDataLayout;
930 OUString aDimName = pDPObj->GetDimName( nSelectDimension, bIsDataLayout );
932 ScDPSaveData aData( *pDPObj->GetSaveData() );
933 ScDPDimensionSaveData* pDimData = aData.GetDimensionData(); // created if not there
935 // find the source dimension name.
936 OUString aBaseDimName = aDimName;
937 if( const ScDPSaveGroupDimension* pBaseGroupDim = pDimData->GetNamedGroupDim( aDimName ) )
938 aBaseDimName = pBaseGroupDim->GetSourceDimName();
940 // Remove all group dimensions associated with this source dimension. For
941 // date grouping, we need to remove all existing groups for the affected
942 // source dimension and build new one(s) from scratch. Keep the deleted
943 // names so that they can be reused during re-construction.
944 aData.RemoveAllGroupDimensions(aBaseDimName, &aDeletedNames);
946 if ( nParts )
948 // create date group dimensions
950 ScDPNumGroupInfo aEmpty;
951 bool bFirst = true;
952 sal_Int32 nMask = 1;
953 for (sal_uInt16 nBit=0; nBit<32; nBit++)
955 if ( nParts & nMask )
957 if ( bFirst )
959 // innermost part: create NumGroupDimension (replacing original values)
960 // Dimension name is left unchanged
962 if ( (nParts == sheet::DataPilotFieldGroupBy::DAYS) && (rInfo.mfStep >= 1.0) )
964 // only days, and a step value specified: use numerical grouping
965 // with DateValues flag, not date grouping
967 ScDPNumGroupInfo aNumInfo( rInfo );
968 aNumInfo.mbDateValues = true;
970 ScDPSaveNumGroupDimension aNumGroupDim( aBaseDimName, aNumInfo );
971 pDimData->AddNumGroupDimension( aNumGroupDim );
973 else
975 ScDPSaveNumGroupDimension aNumGroupDim( aBaseDimName, rInfo, nMask );
976 pDimData->AddNumGroupDimension( aNumGroupDim );
979 bFirst = false;
981 else
983 // additional parts: create GroupDimension (shown as additional dimensions)
984 OUString aGroupDimName =
985 pDimData->CreateDateGroupDimName(nMask, *pDPObj, true, &aDeletedNames);
986 ScDPSaveGroupDimension aGroupDim( aBaseDimName, aGroupDimName );
987 aGroupDim.SetDateInfo( rInfo, nMask );
988 pDimData->AddGroupDimension( aGroupDim );
990 // set orientation
991 ScDPSaveDimension* pSaveDimension = aData.GetDimensionByName( aGroupDimName );
992 if ( pSaveDimension->GetOrientation() == sheet::DataPilotFieldOrientation_HIDDEN )
994 ScDPSaveDimension* pOldDimension = aData.GetDimensionByName( aBaseDimName );
995 pSaveDimension->SetOrientation( pOldDimension->GetOrientation() );
996 long nPosition = 0; //! before (immediate) base
997 aData.SetPosition( pSaveDimension, nPosition );
1001 nMask *= 2;
1005 // apply changes
1006 ScDBDocFunc aFunc( *GetViewData().GetDocShell() );
1007 pDPObj->SetSaveData( aData );
1008 aFunc.RefreshPivotTableGroups(pDPObj);
1010 // unmark cell selection
1011 Unmark();
1014 void ScDBFunc::NumGroupDataPilot( const ScDPNumGroupInfo& rInfo )
1016 ScDPObject* pDPObj = GetViewData().GetDocument()->GetDPAtCursor( GetViewData().GetCurX(),
1017 GetViewData().GetCurY(), GetViewData().GetTabNo() );
1018 if (!pDPObj)
1019 return;
1021 ScDPUniqueStringSet aEntries;
1022 long nSelectDimension = -1;
1023 GetSelectedMemberList( aEntries, nSelectDimension );
1025 if (aEntries.empty())
1026 return;
1028 bool bIsDataLayout;
1029 OUString aDimName = pDPObj->GetDimName( nSelectDimension, bIsDataLayout );
1031 ScDPSaveData aData( *pDPObj->GetSaveData() );
1032 ScDPDimensionSaveData* pDimData = aData.GetDimensionData(); // created if not there
1034 ScDPSaveNumGroupDimension* pExisting = pDimData->GetNumGroupDimAcc( aDimName );
1035 if ( pExisting )
1037 // modify existing group dimension
1038 pExisting->SetGroupInfo( rInfo );
1040 else
1042 // create new group dimension
1043 ScDPSaveNumGroupDimension aNumGroupDim( aDimName, rInfo );
1044 pDimData->AddNumGroupDimension( aNumGroupDim );
1047 // apply changes
1048 ScDBDocFunc aFunc( *GetViewData().GetDocShell() );
1049 pDPObj->SetSaveData( aData );
1050 aFunc.RefreshPivotTableGroups(pDPObj);
1052 // unmark cell selection
1053 Unmark();
1056 void ScDBFunc::GroupDataPilot()
1058 ScDPObject* pDPObj = GetViewData().GetDocument()->GetDPAtCursor( GetViewData().GetCurX(),
1059 GetViewData().GetCurY(), GetViewData().GetTabNo() );
1060 if (!pDPObj)
1061 return;
1063 ScDPUniqueStringSet aEntries;
1064 long nSelectDimension = -1;
1065 GetSelectedMemberList( aEntries, nSelectDimension );
1067 if (aEntries.empty())
1068 return;
1070 bool bIsDataLayout;
1071 OUString aDimName = pDPObj->GetDimName( nSelectDimension, bIsDataLayout );
1073 ScDPSaveData aData( *pDPObj->GetSaveData() );
1074 ScDPDimensionSaveData* pDimData = aData.GetDimensionData(); // created if not there
1076 // find original base
1077 OUString aBaseDimName = aDimName;
1078 const ScDPSaveGroupDimension* pBaseGroupDim = pDimData->GetNamedGroupDim( aDimName );
1079 if ( pBaseGroupDim )
1081 // any entry's SourceDimName is the original base
1082 aBaseDimName = pBaseGroupDim->GetSourceDimName();
1085 // find existing group dimension
1086 // (using the selected dim, can be intermediate group dim)
1087 ScDPSaveGroupDimension* pGroupDimension = pDimData->GetGroupDimAccForBase( aDimName );
1089 // remove the selected items from their groups
1090 // (empty groups are removed, too)
1091 if ( pGroupDimension )
1093 ScDPUniqueStringSet::const_iterator it = aEntries.begin(), itEnd = aEntries.end();
1094 for (; it != itEnd; ++it)
1096 const OUString& aEntryName = *it;
1097 if ( pBaseGroupDim )
1099 // for each selected (intermediate) group, remove all its items
1100 // (same logic as for adding, below)
1101 const ScDPSaveGroupItem* pBaseGroup = pBaseGroupDim->GetNamedGroup( aEntryName );
1102 if ( pBaseGroup )
1103 pBaseGroup->RemoveElementsFromGroups( *pGroupDimension ); // remove all elements
1104 else
1105 pGroupDimension->RemoveFromGroups( aEntryName );
1107 else
1108 pGroupDimension->RemoveFromGroups( aEntryName );
1112 ScDPSaveGroupDimension* pNewGroupDim = nullptr;
1113 if ( !pGroupDimension )
1115 // create a new group dimension
1116 OUString aGroupDimName =
1117 pDimData->CreateGroupDimName(aBaseDimName, *pDPObj, false, nullptr);
1118 pNewGroupDim = new ScDPSaveGroupDimension( aBaseDimName, aGroupDimName );
1120 pGroupDimension = pNewGroupDim; // make changes to the new dim if none existed
1122 if ( pBaseGroupDim )
1124 // If it's a higher-order group dimension, pre-allocate groups for all
1125 // non-selected original groups, so the individual base members aren't
1126 // used for automatic groups (this would make the original groups hard
1127 // to find).
1128 //! Also do this when removing groups?
1129 //! Handle this case dynamically with automatic groups?
1131 long nGroupCount = pBaseGroupDim->GetGroupCount();
1132 for ( long nGroup = 0; nGroup < nGroupCount; nGroup++ )
1134 const ScDPSaveGroupItem& rBaseGroup = pBaseGroupDim->GetGroupByIndex( nGroup );
1136 if (!aEntries.count(rBaseGroup.GetGroupName()))
1138 // add an additional group for each item that is not in the selection
1139 ScDPSaveGroupItem aGroup( rBaseGroup.GetGroupName() );
1140 aGroup.AddElementsFromGroup( rBaseGroup );
1141 pGroupDimension->AddGroupItem( aGroup );
1146 OUString aGroupDimName = pGroupDimension->GetGroupDimName();
1148 OUString aGroupName = pGroupDimension->CreateGroupName(ScGlobal::GetRscString(STR_PIVOT_GROUP));
1149 ScDPSaveGroupItem aGroup( aGroupName );
1150 ScDPUniqueStringSet::const_iterator it = aEntries.begin(), itEnd = aEntries.end();
1151 for (; it != itEnd; ++it)
1153 const OUString& aEntryName = *it;
1154 if ( pBaseGroupDim )
1156 // for each selected (intermediate) group, add all its items
1157 const ScDPSaveGroupItem* pBaseGroup = pBaseGroupDim->GetNamedGroup( aEntryName );
1158 if ( pBaseGroup )
1159 aGroup.AddElementsFromGroup( *pBaseGroup );
1160 else
1161 aGroup.AddElement( aEntryName ); // no group found -> automatic group, add the item itself
1163 else
1164 aGroup.AddElement( aEntryName ); // no group dimension, add all items directly
1167 pGroupDimension->AddGroupItem( aGroup );
1169 if ( pNewGroupDim )
1171 pDimData->AddGroupDimension( *pNewGroupDim );
1172 delete pNewGroupDim; // AddGroupDimension copies the object
1173 // don't access pGroupDimension after here
1175 pGroupDimension = pNewGroupDim = nullptr;
1177 // set orientation
1178 ScDPSaveDimension* pSaveDimension = aData.GetDimensionByName( aGroupDimName );
1179 if ( pSaveDimension->GetOrientation() == sheet::DataPilotFieldOrientation_HIDDEN )
1181 ScDPSaveDimension* pOldDimension = aData.GetDimensionByName( aDimName );
1182 pSaveDimension->SetOrientation( pOldDimension->GetOrientation() );
1183 long nPosition = 0; //! before (immediate) base
1184 aData.SetPosition( pSaveDimension, nPosition );
1187 // apply changes
1188 ScDBDocFunc aFunc( *GetViewData().GetDocShell() );
1189 pDPObj->SetSaveData( aData );
1190 aFunc.RefreshPivotTableGroups(pDPObj);
1192 // unmark cell selection
1193 Unmark();
1196 void ScDBFunc::UngroupDataPilot()
1198 ScDPObject* pDPObj = GetViewData().GetDocument()->GetDPAtCursor( GetViewData().GetCurX(),
1199 GetViewData().GetCurY(), GetViewData().GetTabNo() );
1200 if (!pDPObj)
1201 return;
1203 ScDPUniqueStringSet aEntries;
1204 long nSelectDimension = -1;
1205 GetSelectedMemberList( aEntries, nSelectDimension );
1207 if (aEntries.empty())
1208 return;
1210 bool bIsDataLayout;
1211 OUString aDimName = pDPObj->GetDimName( nSelectDimension, bIsDataLayout );
1213 ScDPSaveData aData( *pDPObj->GetSaveData() );
1214 if (!aData.GetExistingDimensionData())
1215 // There is nothing to ungroup.
1216 return;
1218 ScDPDimensionSaveData* pDimData = aData.GetDimensionData();
1220 ScDPSaveGroupDimension* pGroupDim = pDimData->GetNamedGroupDimAcc( aDimName );
1221 const ScDPSaveNumGroupDimension* pNumGroupDim = pDimData->GetNumGroupDim( aDimName );
1222 if ( ( pGroupDim && pGroupDim->GetDatePart() != 0 ) ||
1223 ( pNumGroupDim && pNumGroupDim->GetDatePart() != 0 ) )
1225 // Date grouping: need to remove all affected group dimensions.
1226 // This is done using DateGroupDataPilot with nParts=0.
1228 DateGroupDataPilot( ScDPNumGroupInfo(), 0 );
1229 return;
1232 if ( pGroupDim )
1234 ScDPUniqueStringSet::const_iterator it = aEntries.begin(), itEnd = aEntries.end();
1235 for (; it != itEnd; ++it)
1236 pGroupDim->RemoveGroup(*it);
1238 // remove group dimension if empty
1239 bool bEmptyDim = pGroupDim->IsEmpty();
1240 if ( !bEmptyDim )
1242 // If all remaining groups in the dimension aren't shown, remove
1243 // the dimension too, as if it was completely empty.
1244 ScDPUniqueStringSet aVisibleEntries;
1245 pDPObj->GetMemberResultNames( aVisibleEntries, nSelectDimension );
1246 bEmptyDim = pGroupDim->HasOnlyHidden( aVisibleEntries );
1248 if ( bEmptyDim )
1250 pDimData->RemoveGroupDimension( aDimName ); // pGroupDim is deleted
1252 // also remove SaveData settings for the dimension that no longer exists
1253 aData.RemoveDimensionByName( aDimName );
1256 else if ( pNumGroupDim )
1258 // remove the numerical grouping
1259 pDimData->RemoveNumGroupDimension( aDimName );
1260 // SaveData settings can remain unchanged - the same dimension still exists
1263 // apply changes
1264 ScDBDocFunc aFunc( *GetViewData().GetDocShell() );
1265 pDPObj->SetSaveData( aData );
1266 aFunc.RefreshPivotTableGroups(pDPObj);
1268 // unmark cell selection
1269 Unmark();
1272 static OUString lcl_replaceMemberNameInSubtotal(const OUString& rSubtotal, const OUString& rMemberName)
1274 sal_Int32 n = rSubtotal.getLength();
1275 const sal_Unicode* p = rSubtotal.getStr();
1276 OUStringBuffer aBuf, aWordBuf;
1277 for (sal_Int32 i = 0; i < n; ++i)
1279 sal_Unicode c = p[i];
1280 if (c == ' ')
1282 OUString aWord = aWordBuf.makeStringAndClear();
1283 if (aWord.equals(rMemberName))
1284 aBuf.append('?');
1285 else
1286 aBuf.append(aWord);
1287 aBuf.append(c);
1289 else if (c == '\\')
1291 // Escape a backslash character.
1292 aWordBuf.append(c);
1293 aWordBuf.append(c);
1295 else if (c == '?')
1297 // A literal '?' must be escaped with a backslash ('\');
1298 aWordBuf.append('\\');
1299 aWordBuf.append(c);
1301 else
1302 aWordBuf.append(c);
1305 if (!aWordBuf.isEmpty())
1307 OUString aWord = aWordBuf.makeStringAndClear();
1308 if (aWord.equals(rMemberName))
1309 aBuf.append('?');
1310 else
1311 aBuf.append(aWord);
1314 return aBuf.makeStringAndClear();
1317 void ScDBFunc::DataPilotInput( const ScAddress& rPos, const OUString& rString )
1319 using namespace ::com::sun::star::sheet;
1321 ScDocument* pDoc = GetViewData().GetDocument();
1322 ScDPObject* pDPObj = pDoc->GetDPAtCursor( rPos.Col(), rPos.Row(), rPos.Tab() );
1323 if (!pDPObj)
1324 return;
1326 OUString aOldText = pDoc->GetString(rPos.Col(), rPos.Row(), rPos.Tab());
1328 if ( aOldText == rString )
1330 // nothing to do: silently exit
1331 return;
1334 sal_uInt16 nErrorId = 0;
1336 pDPObj->BuildAllDimensionMembers();
1337 ScDPSaveData aData( *pDPObj->GetSaveData() );
1338 bool bChange = false;
1340 sal_uInt16 nOrient = DataPilotFieldOrientation_HIDDEN;
1341 long nField = pDPObj->GetHeaderDim( rPos, nOrient );
1342 if ( nField >= 0 )
1344 // changing a field title
1345 if ( aData.GetExistingDimensionData() )
1347 // only group dimensions can be renamed
1349 ScDPDimensionSaveData* pDimData = aData.GetDimensionData();
1350 ScDPSaveGroupDimension* pGroupDim = pDimData->GetNamedGroupDimAcc( aOldText );
1351 if ( pGroupDim )
1353 // valid name: not empty, no existing dimension (group or other)
1354 if (!rString.isEmpty() && !pDPObj->IsDimNameInUse(rString))
1356 pGroupDim->Rename( rString );
1358 // also rename in SaveData to preserve the field settings
1359 ScDPSaveDimension* pSaveDim = aData.GetDimensionByName( aOldText );
1360 pSaveDim->SetName( rString );
1362 bChange = true;
1364 else
1365 nErrorId = STR_INVALIDNAME;
1368 else if (nOrient == DataPilotFieldOrientation_COLUMN || nOrient == DataPilotFieldOrientation_ROW)
1370 bool bDataLayout = false;
1371 OUString aDimName = pDPObj->GetDimName(nField, bDataLayout);
1372 ScDPSaveDimension* pDim = bDataLayout ? aData.GetDataLayoutDimension() : aData.GetDimensionByName(aDimName);
1373 if (pDim)
1375 if (!rString.isEmpty())
1377 if (rString.equalsIgnoreAsciiCase(aDimName))
1379 pDim->RemoveLayoutName();
1380 bChange = true;
1382 else if (!pDPObj->IsDimNameInUse(rString))
1384 pDim->SetLayoutName(rString);
1385 bChange = true;
1387 else
1388 nErrorId = STR_INVALIDNAME;
1390 else
1391 nErrorId = STR_INVALIDNAME;
1395 else if (pDPObj->IsDataDescriptionCell(rPos))
1397 // There is only one data dimension.
1398 ScDPSaveDimension* pDim = aData.GetFirstDimension(sheet::DataPilotFieldOrientation_DATA);
1399 if (pDim)
1401 if (!rString.isEmpty())
1403 if (pDim->GetName().equalsIgnoreAsciiCase(rString))
1405 pDim->RemoveLayoutName();
1406 bChange = true;
1408 else if (!pDPObj->IsDimNameInUse(rString))
1410 pDim->SetLayoutName(rString);
1411 bChange = true;
1413 else
1414 nErrorId = STR_INVALIDNAME;
1416 else
1417 nErrorId = STR_INVALIDNAME;
1420 else
1422 // This is not a field header.
1423 sheet::DataPilotTableHeaderData aPosData;
1424 pDPObj->GetHeaderPositionData(rPos, aPosData);
1426 if ((aPosData.Flags & MemberResultFlags::HASMEMBER) && !aOldText.isEmpty())
1428 if ( aData.GetExistingDimensionData() && !(aPosData.Flags & MemberResultFlags::SUBTOTAL))
1430 bool bIsDataLayout;
1431 OUString aDimName = pDPObj->GetDimName( aPosData.Dimension, bIsDataLayout );
1433 ScDPDimensionSaveData* pDimData = aData.GetDimensionData();
1434 ScDPSaveGroupDimension* pGroupDim = pDimData->GetNamedGroupDimAcc( aDimName );
1435 if ( pGroupDim )
1437 // valid name: not empty, no existing group in this dimension
1438 //! ignore case?
1439 if (!rString.isEmpty() && !pGroupDim->GetNamedGroup(rString))
1441 ScDPSaveGroupItem* pGroup = pGroupDim->GetNamedGroupAcc( aOldText );
1442 if ( pGroup )
1443 pGroup->Rename( rString ); // rename the existing group
1444 else
1446 // create a new group to replace the automatic group
1447 ScDPSaveGroupItem aGroup( rString );
1448 aGroup.AddElement( aOldText );
1449 pGroupDim->AddGroupItem( aGroup );
1452 // in both cases also adjust savedata, to preserve member settings (show details)
1453 ScDPSaveDimension* pSaveDim = aData.GetDimensionByName( aDimName );
1454 ScDPSaveMember* pSaveMember = pSaveDim->GetExistingMemberByName( aOldText );
1455 if ( pSaveMember )
1456 pSaveMember->SetName( rString );
1458 bChange = true;
1460 else
1461 nErrorId = STR_INVALIDNAME;
1464 else if ((aPosData.Flags & MemberResultFlags::GRANDTOTAL))
1466 aData.SetGrandTotalName(rString);
1467 bChange = true;
1469 else if (aPosData.Dimension >= 0 && !aPosData.MemberName.isEmpty())
1471 bool bDataLayout = false;
1472 OUString aDimName = pDPObj->GetDimName(static_cast<long>(aPosData.Dimension), bDataLayout);
1473 if (bDataLayout)
1475 // data dimension
1478 if ((aPosData.Flags & MemberResultFlags::SUBTOTAL))
1479 break;
1481 ScDPSaveDimension* pDim = aData.GetDimensionByName(aPosData.MemberName);
1482 if (!pDim)
1483 break;
1485 if (rString.isEmpty())
1487 nErrorId = STR_INVALIDNAME;
1488 break;
1491 if (aPosData.MemberName.equalsIgnoreAsciiCase(rString))
1493 pDim->RemoveLayoutName();
1494 bChange = true;
1496 else if (!pDPObj->IsDimNameInUse(rString))
1498 pDim->SetLayoutName(rString);
1499 bChange = true;
1501 else
1502 nErrorId = STR_INVALIDNAME;
1504 while (false);
1506 else
1508 // field member
1511 ScDPSaveDimension* pDim = aData.GetDimensionByName(aDimName);
1512 if (!pDim)
1513 break;
1515 ScDPSaveMember* pMem = pDim->GetExistingMemberByName(aPosData.MemberName);
1516 if (!pMem)
1517 break;
1519 if ((aPosData.Flags & MemberResultFlags::SUBTOTAL))
1521 // Change subtotal only when the table has one data dimension.
1522 if (aData.GetDataDimensionCount() > 1)
1523 break;
1525 // display name for subtotal is allowed only if the subtotal type is 'Automatic'.
1526 if (pDim->GetSubTotalsCount() != 1)
1527 break;
1529 if (pDim->GetSubTotalFunc(0) != sheet::GeneralFunction_AUTO)
1530 break;
1532 const OUString* pLayoutName = pMem->GetLayoutName();
1533 OUString aMemberName;
1534 if (pLayoutName)
1535 aMemberName = *pLayoutName;
1536 else
1537 aMemberName = aPosData.MemberName;
1539 OUString aNew = lcl_replaceMemberNameInSubtotal(rString, aMemberName);
1540 pDim->SetSubtotalName(aNew);
1541 bChange = true;
1543 else
1545 // Check to make sure the member name isn't
1546 // already used.
1547 if (!rString.isEmpty())
1549 if (rString.equalsIgnoreAsciiCase(pMem->GetName()))
1551 pMem->RemoveLayoutName();
1552 bChange = true;
1554 else if (!pDim->IsMemberNameInUse(rString))
1556 pMem->SetLayoutName(rString);
1557 bChange = true;
1559 else
1560 nErrorId = STR_INVALIDNAME;
1562 else
1563 nErrorId = STR_INVALIDNAME;
1566 while (false);
1572 if ( bChange )
1574 // apply changes
1575 ScDBDocFunc aFunc( *GetViewData().GetDocShell() );
1576 pDPObj->SetSaveData( aData );
1577 aFunc.UpdatePivotTable(*pDPObj, true, false);
1579 else
1581 if ( !nErrorId )
1582 nErrorId = STR_ERR_DATAPILOT_INPUT;
1583 ErrorMessage( nErrorId );
1587 static void lcl_MoveToEnd( ScDPSaveDimension& rDim, const OUString& rItemName )
1589 ScDPSaveMember* pNewMember = nullptr;
1590 const ScDPSaveMember* pOldMember = rDim.GetExistingMemberByName( rItemName );
1591 if ( pOldMember )
1592 pNewMember = new ScDPSaveMember( *pOldMember );
1593 else
1594 pNewMember = new ScDPSaveMember( rItemName );
1595 rDim.AddMember( pNewMember );
1596 // AddMember takes ownership of the new pointer,
1597 // puts it to the end of the list even if it was in the list before.
1600 struct ScOUStringCollate
1602 CollatorWrapper* mpCollator;
1604 explicit ScOUStringCollate(CollatorWrapper* pColl) : mpCollator(pColl) {}
1606 bool operator()(const OUString& rStr1, const OUString& rStr2) const
1608 return ( mpCollator->compareString(rStr1, rStr2) < 0 );
1612 void ScDBFunc::DataPilotSort( const ScAddress& rPos, bool bAscending, sal_uInt16* pUserListId )
1614 ScDocument* pDoc = GetViewData().GetDocument();
1615 ScDPObject* pDPObj = pDoc->GetDPAtCursor(rPos.Col(), rPos.Row(), rPos.Tab());
1616 if (!pDPObj)
1617 return;
1619 // We need to run this to get all members later.
1620 if ( pUserListId )
1621 pDPObj->BuildAllDimensionMembers();
1623 sal_uInt16 nOrientation;
1624 long nDimIndex = pDPObj->GetHeaderDim(rPos, nOrientation);
1625 if (nDimIndex < 0)
1626 // Invalid dimension index. Bail out.
1627 return;
1629 ScDPSaveData* pSaveData = pDPObj->GetSaveData();
1630 if (!pSaveData)
1631 return;
1633 ScDPSaveData aNewSaveData(*pSaveData);
1634 bool bDataLayout;
1635 OUString aDimName = pDPObj->GetDimName(nDimIndex, bDataLayout);
1636 ScDPSaveDimension* pSaveDim = aNewSaveData.GetDimensionByName(aDimName);
1637 if (!pSaveDim)
1638 return;
1640 // manual evaluation of sort order is only needed if a user list id is given
1641 if ( pUserListId )
1643 typedef ScDPSaveDimension::MemberList MemList;
1644 const MemList& rDimMembers = pSaveDim->GetMembers();
1645 list<OUString> aMembers;
1646 std::unordered_set<OUString, OUStringHash> aMemberSet;
1647 size_t nMemberCount = 0;
1648 for (MemList::const_iterator itr = rDimMembers.begin(), itrEnd = rDimMembers.end();
1649 itr != itrEnd; ++itr)
1651 ScDPSaveMember* pMem = *itr;
1652 aMembers.push_back(pMem->GetName());
1653 aMemberSet.insert(pMem->GetName());
1654 ++nMemberCount;
1657 // Sort the member list in ascending order.
1658 ScOUStringCollate aCollate( ScGlobal::GetCollator() );
1659 aMembers.sort(aCollate);
1661 // Collect and rank those custom sort strings that also exist in the member name list.
1663 typedef std::unordered_map<OUString, sal_uInt16, OUStringHash> UserSortMap;
1664 UserSortMap aSubStrs;
1665 sal_uInt16 nSubCount = 0;
1666 if (pUserListId)
1668 ScUserList* pUserList = ScGlobal::GetUserList();
1669 if (!pUserList)
1670 return;
1673 size_t n = pUserList->size();
1674 if (!n || *pUserListId >= static_cast<sal_uInt16>(n))
1675 return;
1678 const ScUserListData& rData = (*pUserList)[*pUserListId];
1679 sal_uInt16 n = rData.GetSubCount();
1680 for (sal_uInt16 i = 0; i < n; ++i)
1682 OUString aSub = rData.GetSubStr(i);
1683 if (!aMemberSet.count(aSub))
1684 // This string doesn't exist in the member name set. Don't add this.
1685 continue;
1687 aSubStrs.insert(UserSortMap::value_type(aSub, nSubCount++));
1691 // Rank all members.
1693 vector<OUString> aRankedNames(nMemberCount);
1694 sal_uInt16 nCurStrId = 0;
1695 for (list<OUString>::const_iterator itr = aMembers.begin(), itrEnd = aMembers.end();
1696 itr != itrEnd; ++itr)
1698 OUString aName = *itr;
1699 sal_uInt16 nRank = 0;
1700 UserSortMap::const_iterator itrSub = aSubStrs.find(aName);
1701 if (itrSub == aSubStrs.end())
1702 nRank = nSubCount + nCurStrId++;
1703 else
1704 nRank = itrSub->second;
1706 if (!bAscending)
1707 nRank = static_cast< sal_uInt16 >( nMemberCount - nRank - 1 );
1709 aRankedNames[nRank] = aName;
1712 // Re-order ScDPSaveMember instances with the new ranks.
1714 for (vector<OUString>::const_iterator itr = aRankedNames.begin(), itrEnd = aRankedNames.end();
1715 itr != itrEnd; ++itr)
1717 const ScDPSaveMember* pOldMem = pSaveDim->GetExistingMemberByName(*itr);
1718 if (!pOldMem)
1719 // All members are supposed to be present.
1720 continue;
1722 ScDPSaveMember* pNewMem = new ScDPSaveMember(*pOldMem);
1723 pSaveDim->AddMember(pNewMem);
1726 // Set the sorting mode to manual for now. We may introduce a new sorting
1727 // mode later on.
1729 sheet::DataPilotFieldSortInfo aSortInfo;
1730 aSortInfo.Mode = sheet::DataPilotFieldSortMode::MANUAL;
1731 pSaveDim->SetSortInfo(&aSortInfo);
1733 else
1735 // without user list id, just apply sorting mode
1737 sheet::DataPilotFieldSortInfo aSortInfo;
1738 aSortInfo.Mode = sheet::DataPilotFieldSortMode::NAME;
1739 aSortInfo.IsAscending = bAscending;
1740 pSaveDim->SetSortInfo(&aSortInfo);
1743 // Update the datapilot with the newly sorted field members.
1745 std::unique_ptr<ScDPObject> pNewObj(new ScDPObject(*pDPObj));
1746 pNewObj->SetSaveData(aNewSaveData);
1747 ScDBDocFunc aFunc(*GetViewData().GetDocShell());
1749 aFunc.DataPilotUpdate(pDPObj, pNewObj.get(), true, false);
1752 bool ScDBFunc::DataPilotMove( const ScRange& rSource, const ScAddress& rDest )
1754 bool bRet = false;
1755 ScDocument* pDoc = GetViewData().GetDocument();
1756 ScDPObject* pDPObj = pDoc->GetDPAtCursor( rSource.aStart.Col(), rSource.aStart.Row(), rSource.aStart.Tab() );
1757 if ( pDPObj && pDPObj == pDoc->GetDPAtCursor( rDest.Col(), rDest.Row(), rDest.Tab() ) )
1759 sheet::DataPilotTableHeaderData aDestData;
1760 pDPObj->GetHeaderPositionData( rDest, aDestData );
1761 bool bValid = ( aDestData.Dimension >= 0 ); // dropping onto a field
1763 // look through the source range
1764 std::unordered_set< OUString, OUStringHash > aMembersSet; // for lookup
1765 std::vector< OUString > aMembersVector; // members in original order, for inserting
1766 aMembersVector.reserve( std::max( static_cast<SCSIZE>( rSource.aEnd.Col() - rSource.aStart.Col() + 1 ),
1767 static_cast<SCSIZE>( rSource.aEnd.Row() - rSource.aStart.Row() + 1 ) ) );
1768 for (SCROW nRow = rSource.aStart.Row(); bValid && nRow <= rSource.aEnd.Row(); ++nRow )
1769 for (SCCOL nCol = rSource.aStart.Col(); bValid && nCol <= rSource.aEnd.Col(); ++nCol )
1771 sheet::DataPilotTableHeaderData aSourceData;
1772 pDPObj->GetHeaderPositionData( ScAddress( nCol, nRow, rSource.aStart.Tab() ), aSourceData );
1773 if ( aSourceData.Dimension == aDestData.Dimension && !aSourceData.MemberName.isEmpty() )
1775 if ( aMembersSet.find( aSourceData.MemberName ) == aMembersSet.end() )
1777 aMembersSet.insert( aSourceData.MemberName );
1778 aMembersVector.push_back( aSourceData.MemberName );
1780 // duplicates are ignored
1782 else
1783 bValid = false; // empty (subtotal) or different field
1786 if ( bValid )
1788 bool bIsDataLayout;
1789 OUString aDimName = pDPObj->GetDimName( aDestData.Dimension, bIsDataLayout );
1790 if ( !bIsDataLayout )
1792 ScDPSaveData aData( *pDPObj->GetSaveData() );
1793 ScDPSaveDimension* pDim = aData.GetDimensionByName( aDimName );
1795 // get all member names in source order
1796 uno::Sequence<OUString> aMemberNames;
1797 pDPObj->GetMemberNames( aDestData.Dimension, aMemberNames );
1799 bool bInserted = false;
1801 sal_Int32 nMemberCount = aMemberNames.getLength();
1802 for (sal_Int32 nMemberPos=0; nMemberPos<nMemberCount; ++nMemberPos)
1804 OUString aMemberStr( aMemberNames[nMemberPos] );
1806 if ( !bInserted && aMemberNames[nMemberPos] == aDestData.MemberName )
1808 // insert dragged items before this item
1809 for ( std::vector<OUString>::const_iterator aIter = aMembersVector.begin();
1810 aIter != aMembersVector.end(); ++aIter )
1811 lcl_MoveToEnd( *pDim, *aIter );
1812 bInserted = true;
1815 if ( aMembersSet.find( aMemberStr ) == aMembersSet.end() ) // skip dragged items
1816 lcl_MoveToEnd( *pDim, aMemberStr );
1818 // insert dragged item at end if dest wasn't found (for example, empty)
1819 if ( !bInserted )
1820 for ( std::vector<OUString>::const_iterator aIter = aMembersVector.begin();
1821 aIter != aMembersVector.end(); ++aIter )
1822 lcl_MoveToEnd( *pDim, *aIter );
1824 // Items that were in SaveData, but not in the source, end up at the start of the list.
1826 // set flag for manual sorting
1827 sheet::DataPilotFieldSortInfo aSortInfo;
1828 aSortInfo.Mode = sheet::DataPilotFieldSortMode::MANUAL;
1829 pDim->SetSortInfo( &aSortInfo );
1831 // apply changes
1832 ScDBDocFunc aFunc( *GetViewData().GetDocShell() );
1833 std::unique_ptr<ScDPObject> pNewObj(new ScDPObject( *pDPObj ));
1834 pNewObj->SetSaveData( aData );
1835 aFunc.DataPilotUpdate( pDPObj, pNewObj.get(), true, false ); //! bApi for drag&drop?
1836 pNewObj.reset();
1838 Unmark(); // entry was moved - no use in leaving the old cell selected
1840 bRet = true;
1845 return bRet;
1848 bool ScDBFunc::HasSelectionForDrillDown( sal_uInt16& rOrientation )
1850 bool bRet = false;
1852 ScDPObject* pDPObj = GetViewData().GetDocument()->GetDPAtCursor( GetViewData().GetCurX(),
1853 GetViewData().GetCurY(), GetViewData().GetTabNo() );
1854 if ( pDPObj )
1856 ScDPUniqueStringSet aEntries;
1857 long nSelectDimension = -1;
1858 GetSelectedMemberList( aEntries, nSelectDimension );
1860 if (!aEntries.empty())
1862 bool bIsDataLayout;
1863 OUString aDimName = pDPObj->GetDimName( nSelectDimension, bIsDataLayout );
1864 if ( !bIsDataLayout )
1866 ScDPSaveData* pSaveData = pDPObj->GetSaveData();
1867 ScDPSaveDimension* pDim = pSaveData->GetExistingDimensionByName( aDimName );
1868 if ( pDim )
1870 sal_uInt16 nDimOrient = pDim->GetOrientation();
1871 ScDPSaveDimension* pInner = pSaveData->GetInnermostDimension( nDimOrient );
1872 if ( pDim == pInner )
1874 rOrientation = nDimOrient;
1875 bRet = true;
1882 return bRet;
1885 void ScDBFunc::SetDataPilotDetails(bool bShow, const OUString* pNewDimensionName)
1887 ScDPObject* pDPObj = GetViewData().GetDocument()->GetDPAtCursor( GetViewData().GetCurX(),
1888 GetViewData().GetCurY(), GetViewData().GetTabNo() );
1889 if ( pDPObj )
1891 ScDPUniqueStringSet aEntries;
1892 long nSelectDimension = -1;
1893 GetSelectedMemberList( aEntries, nSelectDimension );
1895 if (!aEntries.empty())
1897 bool bIsDataLayout;
1898 OUString aDimName = pDPObj->GetDimName( nSelectDimension, bIsDataLayout );
1899 if ( !bIsDataLayout )
1901 ScDPSaveData aData( *pDPObj->GetSaveData() );
1902 ScDPSaveDimension* pDim = aData.GetDimensionByName( aDimName );
1904 if ( bShow && pNewDimensionName )
1906 // add the new dimension with the same orientation, at the end
1908 ScDPSaveDimension* pNewDim = aData.GetDimensionByName( *pNewDimensionName );
1909 ScDPSaveDimension* pDuplicated = nullptr;
1910 if ( pNewDim->GetOrientation() == sheet::DataPilotFieldOrientation_DATA )
1912 // Need to duplicate the dimension, create column/row in addition to data:
1913 // The duplicated dimension inherits the existing settings, pNewDim is modified below.
1914 pDuplicated = aData.DuplicateDimension( *pNewDimensionName );
1917 sal_uInt16 nOrientation = pDim->GetOrientation();
1918 pNewDim->SetOrientation( nOrientation );
1920 long nPosition = LONG_MAX;
1921 aData.SetPosition( pNewDim, nPosition );
1923 ScDPSaveDimension* pDataLayout = aData.GetDataLayoutDimension();
1924 if ( pDataLayout->GetOrientation() == nOrientation &&
1925 aData.GetDataDimensionCount() <= 1 )
1927 // If there is only one data dimension, the data layout dimension
1928 // must still be the last one in its orientation.
1929 aData.SetPosition( pDataLayout, nPosition );
1932 if ( pDuplicated )
1934 // The duplicated (data) dimension needs to be behind the original dimension
1935 aData.SetPosition( pDuplicated, nPosition );
1938 // Hide details for all visible members (selected are changed below).
1939 //! Use all members from source level instead (including non-visible)?
1941 ScDPUniqueStringSet aVisibleEntries;
1942 pDPObj->GetMemberResultNames( aVisibleEntries, nSelectDimension );
1944 ScDPUniqueStringSet::const_iterator it = aVisibleEntries.begin(), itEnd = aVisibleEntries.end();
1945 for (; it != itEnd; ++it)
1947 const OUString& aVisName = *it;
1948 ScDPSaveMember* pMember = pDim->GetMemberByName( aVisName );
1949 pMember->SetShowDetails( false );
1953 ScDPUniqueStringSet::const_iterator it = aEntries.begin(), itEnd = aEntries.end();
1954 for (; it != itEnd; ++it)
1956 ScDPSaveMember* pMember = pDim->GetMemberByName(*it);
1957 pMember->SetShowDetails( bShow );
1960 // apply changes
1961 ScDBDocFunc aFunc( *GetViewData().GetDocShell() );
1962 std::unique_ptr<ScDPObject> pNewObj(new ScDPObject( *pDPObj ));
1963 pNewObj->SetSaveData( aData );
1964 aFunc.DataPilotUpdate( pDPObj, pNewObj.get(), true, false );
1965 pNewObj.reset();
1967 // unmark cell selection
1968 Unmark();
1974 void ScDBFunc::ShowDataPilotSourceData( ScDPObject& rDPObj, const Sequence<sheet::DataPilotFieldFilter>& rFilters )
1976 ScDocument* pDoc = GetViewData().GetDocument();
1977 if (pDoc->GetDocumentShell()->IsReadOnly())
1979 ErrorMessage(STR_READONLYERR);
1980 return;
1983 Reference<sheet::XDimensionsSupplier> xDimSupplier = rDPObj.GetSource();
1984 Reference<container::XNameAccess> xDims = xDimSupplier->getDimensions();
1985 Reference<sheet::XDrillDownDataSupplier> xDDSupplier(xDimSupplier, UNO_QUERY);
1986 if (!xDDSupplier.is())
1987 return;
1989 Sequence< Sequence<Any> > aTabData = xDDSupplier->getDrillDownData(rFilters);
1990 sal_Int32 nRowSize = aTabData.getLength();
1991 if (nRowSize <= 1)
1992 // There is no data to show. Bail out.
1993 return;
1995 SCCOL nColSize = aTabData[0].getLength();
1997 SCTAB nNewTab = GetViewData().GetTabNo();
1999 std::unique_ptr<ScDocument> pInsDoc(new ScDocument(SCDOCMODE_CLIP));
2000 pInsDoc->ResetClip( pDoc, nNewTab );
2001 for (SCROW nRow = 0; nRow < nRowSize; ++nRow)
2003 for (SCCOL nCol = 0; nCol < nColSize; ++nCol)
2005 const Any& rAny = aTabData[nRow][nCol];
2006 OUString aStr;
2007 double fVal;
2008 if (rAny >>= aStr)
2010 ScSetStringParam aParam;
2011 aParam.setTextInput();
2012 pInsDoc->SetString(ScAddress(nCol,nRow,nNewTab), aStr);
2014 else if (rAny >>= fVal)
2015 pInsDoc->SetValue(nCol, nRow, nNewTab, fVal);
2019 // set number format (important for dates)
2020 for (SCCOL nCol = 0; nCol < nColSize; ++nCol)
2022 OUString aStr;
2023 if (!(aTabData[0][nCol] >>= aStr))
2024 continue;
2026 Reference<XPropertySet> xPropSet(xDims->getByName(aStr), UNO_QUERY);
2027 if (!xPropSet.is())
2028 continue;
2030 Any any = xPropSet->getPropertyValue( SC_UNO_DP_NUMBERFO );
2031 sal_Int32 nNumFmt = 0;
2032 if (!(any >>= nNumFmt))
2033 continue;
2035 ScPatternAttr aPattern( pInsDoc->GetPool() );
2036 aPattern.GetItemSet().Put( SfxUInt32Item(ATTR_VALUE_FORMAT, static_cast<sal_uInt32>(nNumFmt)) );
2037 pInsDoc->ApplyPatternAreaTab(nCol, 1, nCol, nRowSize-1, nNewTab, aPattern);
2040 SCCOL nEndCol = 0;
2041 SCROW nEndRow = 0;
2042 pInsDoc->GetCellArea( nNewTab, nEndCol, nEndRow );
2043 pInsDoc->SetClipArea( ScRange( 0, 0, nNewTab, nEndCol, nEndRow, nNewTab ) );
2045 ::svl::IUndoManager* pMgr = GetViewData().GetDocShell()->GetUndoManager();
2046 OUString aUndo = ScGlobal::GetRscString( STR_UNDO_DOOUTLINE );
2047 pMgr->EnterListAction( aUndo, aUndo );
2049 OUString aNewTabName;
2050 pDoc->CreateValidTabName(aNewTabName);
2051 if ( InsertTable(aNewTabName, nNewTab) )
2052 PasteFromClip( InsertDeleteFlags::ALL, pInsDoc.get() );
2054 pMgr->LeaveListAction();
2057 // repeat data base operations (sorting, filtering, subtotals)
2059 void ScDBFunc::RepeatDB( bool bRecord )
2061 SCCOL nCurX = GetViewData().GetCurX();
2062 SCROW nCurY = GetViewData().GetCurY();
2063 SCTAB nTab = GetViewData().GetTabNo();
2064 ScDocument* pDoc = GetViewData().GetDocument();
2065 ScDBData* pDBData = GetDBData();
2066 if (bRecord && !pDoc->IsUndoEnabled())
2067 bRecord = false;
2069 ScQueryParam aQueryParam;
2070 pDBData->GetQueryParam( aQueryParam );
2071 bool bQuery = aQueryParam.GetEntry(0).bDoQuery;
2073 ScSortParam aSortParam;
2074 pDBData->GetSortParam( aSortParam );
2075 bool bSort = aSortParam.maKeyState[0].bDoSort;
2077 ScSubTotalParam aSubTotalParam;
2078 pDBData->GetSubTotalParam( aSubTotalParam );
2079 bool bSubTotal = aSubTotalParam.bGroupActive[0] && !aSubTotalParam.bRemoveOnly;
2081 if ( bQuery || bSort || bSubTotal )
2083 bool bQuerySize = false;
2084 ScRange aOldQuery;
2085 ScRange aNewQuery;
2086 if (bQuery && !aQueryParam.bInplace)
2088 ScDBData* pDest = pDoc->GetDBAtCursor( aQueryParam.nDestCol, aQueryParam.nDestRow,
2089 aQueryParam.nDestTab, ScDBDataPortion::TOP_LEFT );
2090 if (pDest && pDest->IsDoSize())
2092 pDest->GetArea( aOldQuery );
2093 bQuerySize = true;
2097 SCTAB nDummy;
2098 SCCOL nStartCol;
2099 SCROW nStartRow;
2100 SCCOL nEndCol;
2101 SCROW nEndRow;
2102 pDBData->GetArea( nDummy, nStartCol, nStartRow, nEndCol, nEndRow );
2104 //! undo only needed data ?
2106 ScDocument* pUndoDoc = nullptr;
2107 ScOutlineTable* pUndoTab = nullptr;
2108 ScRangeName* pUndoRange = nullptr;
2109 ScDBCollection* pUndoDB = nullptr;
2111 if (bRecord)
2113 SCTAB nTabCount = pDoc->GetTableCount();
2114 pUndoDoc = new ScDocument( SCDOCMODE_UNDO );
2115 ScOutlineTable* pTable = pDoc->GetOutlineTable( nTab );
2116 if (pTable)
2118 pUndoTab = new ScOutlineTable( *pTable );
2120 SCCOLROW nOutStartCol; // row/column status
2121 SCCOLROW nOutStartRow;
2122 SCCOLROW nOutEndCol;
2123 SCCOLROW nOutEndRow;
2124 pTable->GetColArray().GetRange( nOutStartCol, nOutEndCol );
2125 pTable->GetRowArray().GetRange( nOutStartRow, nOutEndRow );
2127 pUndoDoc->InitUndo( pDoc, nTab, nTab, true, true );
2128 pDoc->CopyToDocument( static_cast<SCCOL>(nOutStartCol), 0, nTab, static_cast<SCCOL>(nOutEndCol), MAXROW, nTab, InsertDeleteFlags::NONE, false, pUndoDoc );
2129 pDoc->CopyToDocument( 0, nOutStartRow, nTab, MAXCOL, nOutEndRow, nTab, InsertDeleteFlags::NONE, false, pUndoDoc );
2131 else
2132 pUndoDoc->InitUndo( pDoc, nTab, nTab, false, true );
2134 // Record data range - including filter results
2135 pDoc->CopyToDocument( 0,nStartRow,nTab, MAXCOL,nEndRow,nTab, InsertDeleteFlags::ALL, false, pUndoDoc );
2137 // all formulas for reference
2138 pDoc->CopyToDocument( 0,0,0, MAXCOL,MAXROW,nTabCount-1, InsertDeleteFlags::FORMULA, false, pUndoDoc );
2140 // data base and other ranges
2141 ScRangeName* pDocRange = pDoc->GetRangeName();
2142 if (!pDocRange->empty())
2143 pUndoRange = new ScRangeName( *pDocRange );
2144 ScDBCollection* pDocDB = pDoc->GetDBCollection();
2145 if (!pDocDB->empty())
2146 pUndoDB = new ScDBCollection( *pDocDB );
2149 if (bSort && bSubTotal)
2151 // sort without subtotals
2153 aSubTotalParam.bRemoveOnly = true; // is resetted below
2154 DoSubTotals( aSubTotalParam, false );
2157 if (bSort)
2159 pDBData->GetSortParam( aSortParam ); // range may have chaged
2160 Sort( aSortParam, false, false);
2162 if (bQuery)
2164 pDBData->GetQueryParam( aQueryParam ); // range may have chaged
2165 ScRange aAdvSource;
2166 if (pDBData->GetAdvancedQuerySource(aAdvSource))
2168 pDoc->CreateQueryParam(
2169 aAdvSource.aStart.Col(), aAdvSource.aStart.Row(),
2170 aAdvSource.aEnd.Col(), aAdvSource.aEnd.Row(),
2171 aAdvSource.aStart.Tab(), aQueryParam );
2172 Query( aQueryParam, &aAdvSource, false );
2174 else
2175 Query( aQueryParam, nullptr, false );
2177 // if not inplace the sheet may have changed
2178 if ( !aQueryParam.bInplace && aQueryParam.nDestTab != nTab )
2179 SetTabNo( nTab );
2181 if (bSubTotal)
2183 pDBData->GetSubTotalParam( aSubTotalParam ); // range may have chaged
2184 aSubTotalParam.bRemoveOnly = false;
2185 DoSubTotals( aSubTotalParam, false );
2188 if (bRecord)
2190 SCTAB nDummyTab;
2191 SCCOL nDummyCol;
2192 SCROW nDummyRow, nNewEndRow;
2193 pDBData->GetArea( nDummyTab, nDummyCol,nDummyRow, nDummyCol,nNewEndRow );
2195 const ScRange* pOld = nullptr;
2196 const ScRange* pNew = nullptr;
2197 if (bQuerySize)
2199 ScDBData* pDest = pDoc->GetDBAtCursor( aQueryParam.nDestCol, aQueryParam.nDestRow,
2200 aQueryParam.nDestTab, ScDBDataPortion::TOP_LEFT );
2201 if (pDest)
2203 pDest->GetArea( aNewQuery );
2204 pOld = &aOldQuery;
2205 pNew = &aNewQuery;
2209 GetViewData().GetDocShell()->GetUndoManager()->AddUndoAction(
2210 new ScUndoRepeatDB( GetViewData().GetDocShell(), nTab,
2211 nStartCol, nStartRow, nEndCol, nEndRow,
2212 nNewEndRow,
2213 nCurX, nCurY,
2214 pUndoDoc, pUndoTab,
2215 pUndoRange, pUndoDB,
2216 pOld, pNew ) );
2219 GetViewData().GetDocShell()->PostPaint(
2220 ScRange(0, 0, nTab, MAXCOL, MAXROW, nTab),
2221 PAINT_GRID | PAINT_LEFT | PAINT_TOP | PAINT_SIZE);
2223 else // "no not execute any operations"
2224 ErrorMessage(STR_MSSG_REPEATDB_0);
2227 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */