summaryrefslogtreecommitdiff
path: root/chart2/source/controller/dialogs/DataBrowserModel.cxx
blob: a61d957b5f72c4502741013b702c6e4116129bcf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "DataBrowserModel.hxx"
#include "DialogModel.hxx"
#include <ChartModelHelper.hxx>
#include <ChartTypeManager.hxx>
#include <DiagramHelper.hxx>
#include <Diagram.hxx>
#include <DataSeriesHelper.hxx>
#include <ControllerLockGuard.hxx>
#include <StatisticsHelper.hxx>
#include <ChartTypeHelper.hxx>
#include <ChartTypeManager.hxx>
#include <ChartTypeTemplate.hxx>
#include <chartview/ExplicitValueProvider.hxx>
#include <ExplicitCategoriesProvider.hxx>
#include <BaseCoordinateSystem.hxx>

#include <ChartModel.hxx>
#include <unonames.hxx>

#include <com/sun/star/container/XIndexReplace.hpp>
#include <com/sun/star/chart2/XDataSeriesContainer.hpp>
#include <com/sun/star/chart2/XInternalDataProvider.hpp>
#include <com/sun/star/chart2/XCoordinateSystemContainer.hpp>
#include <com/sun/star/chart2/XChartTypeContainer.hpp>
#include <com/sun/star/chart2/data/XDataSource.hpp>
#include <com/sun/star/chart2/data/XLabeledDataSequence.hpp>
#include <com/sun/star/chart2/data/XNumericalDataSequence.hpp>
#include <com/sun/star/chart2/data/XTextualDataSequence.hpp>
#include <com/sun/star/util/XModifiable.hpp>
#include <o3tl/safeint.hxx>
#include <tools/diagnose_ex.h>
#include <comphelper/property.hxx>

#include <algorithm>
#include <limits>

using namespace ::com::sun::star;

using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;

namespace chart {

namespace {

OUString lcl_getRole(
    const Reference< chart2::data::XDataSequence > & xSeq )
{
    OUString aResult;
    Reference< beans::XPropertySet > xProp( xSeq, uno::UNO_QUERY );
    if( xProp.is())
    {
        try
        {
            xProp->getPropertyValue( "Role" ) >>= aResult;
        }
        catch( const uno::Exception & )
        {
            DBG_UNHANDLED_EXCEPTION("chart2");
        }
    }
    return aResult;
}

OUString lcl_getUIRoleName(
    const Reference< chart2::data::XLabeledDataSequence > & xLSeq )
{
    OUString aResult = DataSeriesHelper::getRole(xLSeq);
    if( !aResult.isEmpty())
        aResult = DialogModel::ConvertRoleFromInternalToUI(aResult);
    return aResult;
}

void lcl_copyDataSequenceProperties(
    const Reference< chart2::data::XDataSequence > & xOldSequence,
    const Reference< chart2::data::XDataSequence > & xNewSequence )
{
    Reference< beans::XPropertySet > xOldSeqProp( xOldSequence, uno::UNO_QUERY );
    Reference< beans::XPropertySet > xNewSeqProp( xNewSequence, uno::UNO_QUERY );
    comphelper::copyProperties( xOldSeqProp, xNewSeqProp );
}

bool lcl_SequenceOfSeriesIsShared(
    const Reference< chart2::XDataSeries > & xSeries,
    const Reference< chart2::data::XDataSequence > & xValues )
{
    bool bResult = false;
    if( !xValues.is())
        return bResult;
    try
    {
        OUString aValuesRole( lcl_getRole( xValues ));
        OUString aValuesRep( xValues->getSourceRangeRepresentation());
        Reference< chart2::data::XDataSource > xSource( xSeries, uno::UNO_QUERY_THROW );
        const Sequence< Reference< chart2::data::XLabeledDataSequence > > aLSeq( xSource->getDataSequences());
        for( Reference< chart2::data::XLabeledDataSequence > const & labeledDataSeq : aLSeq )
            if (labeledDataSeq.is() && DataSeriesHelper::getRole(labeledDataSeq) == aValuesRole)
            {
                // getValues().is(), because lcl_getRole checked that already
                bResult = (aValuesRep == labeledDataSeq->getValues()->getSourceRangeRepresentation());
                // assumption: a role appears only once in a series
                break;
            }
    }
    catch( const uno::Exception & )
    {
        DBG_UNHANDLED_EXCEPTION("chart2");
    }
    return bResult;
}

typedef std::vector< Reference< chart2::data::XLabeledDataSequence > > lcl_tSharedSeqVec;

lcl_tSharedSeqVec lcl_getSharedSequences( const Sequence< Reference< chart2::XDataSeries > > & rSeries )
{
    // @todo: if only some series share a sequence, those have to be duplicated
    // and made unshared for all series
    lcl_tSharedSeqVec aResult;
    // if we have only one series, we don't want any shared sequences
    if( rSeries.getLength() <= 1 )
        return aResult;

    Reference< chart2::data::XDataSource > xSource( rSeries[0], uno::UNO_QUERY );
    const Sequence< Reference< chart2::data::XLabeledDataSequence > > aLSeq( xSource->getDataSequences());
    for( Reference< chart2::data::XLabeledDataSequence >  const & labeledDataSeq : aLSeq )
    {
        Reference< chart2::data::XDataSequence > xValues( labeledDataSeq->getValues());
        bool bShared = true;
        for( sal_Int32 nSeriesIdx=1; nSeriesIdx<rSeries.getLength(); ++nSeriesIdx )
        {
            bShared = lcl_SequenceOfSeriesIsShared( rSeries[nSeriesIdx], xValues );
            if( !bShared )
                break;
        }
        if( bShared )
            aResult.push_back( labeledDataSeq );
    }

    return aResult;
}

sal_Int32 lcl_getValuesRepresentationIndex(
    const Reference< chart2::data::XLabeledDataSequence > & xLSeq )
{
    sal_Int32 nResult = -1;
    if( xLSeq.is())
    {
        Reference< chart2::data::XDataSequence > xSeq( xLSeq->getValues());
        if( xSeq.is())
        {
            OUString aRep( xSeq->getSourceRangeRepresentation());
            nResult = aRep.toInt32();
        }
    }
    return nResult;
}

struct lcl_RepresentationsOfLSeqMatch
{
    explicit lcl_RepresentationsOfLSeqMatch( const Reference< chart2::data::XLabeledDataSequence > & xLSeq ) :
            m_aValuesRep( xLSeq.is() ?
                          (xLSeq->getValues().is() ? xLSeq->getValues()->getSourceRangeRepresentation() : OUString())
                          : OUString() )
    {}
    bool operator() ( const Reference< chart2::data::XLabeledDataSequence > & xLSeq )
    {
        if (!xLSeq.is() || !xLSeq->getValues().is())
            return false;

        return xLSeq->getValues()->getSourceRangeRepresentation() == m_aValuesRep;
    }
private:
    OUString m_aValuesRep;
};

struct lcl_RolesOfLSeqMatch
{
    explicit lcl_RolesOfLSeqMatch( const Reference< chart2::data::XLabeledDataSequence > & xLSeq ) :
        m_aRole(DataSeriesHelper::getRole(xLSeq)) {}

    bool operator() ( const Reference< chart2::data::XLabeledDataSequence > & xLSeq )
    {
        return DataSeriesHelper::getRole(xLSeq) == m_aRole;
    }
private:
    OUString m_aRole;
};

bool lcl_ShowCategoriesAsDataLabel( const Reference< chart2::XDiagram > & xDiagram )
{
    return !DiagramHelper::isCategoryDiagram(xDiagram);
}

} // anonymous namespace

struct DataBrowserModel::tDataColumn
{
    uno::Reference<chart2::XDataSeries>  m_xDataSeries;
    OUString                             m_aUIRoleName;
    uno::Reference<chart2::data::XLabeledDataSequence> m_xLabeledDataSequence;
    eCellType                                          m_eCellType;
    sal_Int32                                          m_nNumberFormatKey;

    // default CTOR
    tDataColumn() : m_eCellType( TEXT ), m_nNumberFormatKey( 0 ) {}
    // "full" CTOR
    tDataColumn(
        const uno::Reference<chart2::XDataSeries> & xDataSeries,
        const OUString& aUIRoleName,
        const uno::Reference<chart2::data::XLabeledDataSequence>& xLabeledDataSequence,
        eCellType aCellType,
        sal_Int32 nNumberFormatKey ) :
            m_xDataSeries( xDataSeries ),
            m_aUIRoleName( aUIRoleName ),
            m_xLabeledDataSequence( xLabeledDataSequence ),
            m_eCellType( aCellType ),
            m_nNumberFormatKey( nNumberFormatKey )
    {}
};

struct DataBrowserModel::implColumnLess
{
    bool operator() ( const DataBrowserModel::tDataColumn & rLeft, const DataBrowserModel::tDataColumn & rRight )
    {
        if( rLeft.m_xLabeledDataSequence.is() && rRight.m_xLabeledDataSequence.is())
        {
            return DialogModel::GetRoleIndexForSorting(DataSeriesHelper::getRole(rLeft.m_xLabeledDataSequence)) <
                DialogModel::GetRoleIndexForSorting(DataSeriesHelper::getRole(rRight.m_xLabeledDataSequence));
        }
        return true;
    }
};

DataBrowserModel::DataBrowserModel(
    const rtl::Reference<::chart::ChartModel> & xChartDoc,
    const Reference< uno::XComponentContext > & xContext ) :
        m_xChartDocument( xChartDoc ),
        m_apDialogModel( new DialogModel( xChartDoc, xContext ))
{
    updateFromModel();
}

DataBrowserModel::~DataBrowserModel()
{}

namespace
{
struct lcl_DataSeriesOfHeaderMatches
{
    explicit lcl_DataSeriesOfHeaderMatches(
        const Reference< chart2::XDataSeries > & xSeriesToCompareWith ) :
            m_xSeries( xSeriesToCompareWith )
    {}
    bool operator() ( const ::chart::DataBrowserModel::tDataHeader & rHeader )
    {
        return (m_xSeries == rHeader.m_xDataSeries);
    }
private:
    Reference< chart2::XDataSeries  > m_xSeries;
};
}

void DataBrowserModel::insertDataSeries( sal_Int32 nAfterColumnIndex )
{
    OSL_ASSERT(m_apDialogModel);
    Reference< chart2::XInternalDataProvider > xDataProvider(
        m_apDialogModel->getDataProvider(), uno::UNO_QUERY );

    if (!xDataProvider.is())
        return;

    if( isCategoriesColumn(nAfterColumnIndex) )
        // Move to the last category column.
        nAfterColumnIndex = getCategoryColumnCount()-1;

    sal_Int32 nStartCol = 0;
    rtl::Reference< Diagram > xDiagram = ChartModelHelper::findDiagram(m_xChartDocument);
    Reference<chart2::XChartType> xChartType;
    Reference<chart2::XDataSeries> xSeries;
    if (o3tl::make_unsigned(nAfterColumnIndex) < m_aColumns.size())
        // Get the data series at specific column position (if available).
        xSeries.set( m_aColumns[nAfterColumnIndex].m_xDataSeries );

    sal_Int32 nSeriesNumberFormat = 0;
    if( xSeries.is())
    {
        // Use the chart type of the currently selected data series.
        xChartType.set( DiagramHelper::getChartTypeOfSeries( xDiagram, xSeries ));

        // Find the corresponding header and determine the last column of this
        // data series.
        tDataHeaderVector::const_iterator aIt(
            std::find_if( m_aHeaders.begin(), m_aHeaders.end(),
                            lcl_DataSeriesOfHeaderMatches( xSeries )));
        if( aIt != m_aHeaders.end())
            nStartCol = aIt->m_nEndColumn;

        // Get the number format too.
        Reference< beans::XPropertySet > xSeriesProps( xSeries, uno::UNO_QUERY );
        if( xSeriesProps.is() )
            xSeriesProps->getPropertyValue(CHART_UNONAME_NUMFMT) >>= nSeriesNumberFormat;
    }
    else
    {
        // No data series at specified column position. Use the first chart type.
        xChartType.set( DiagramHelper::getChartTypeByIndex( xDiagram, 0 ));
        nStartCol = nAfterColumnIndex;
    }

    if (!xChartType.is())
        return;

    // Get shared sequences of current series.  Normally multiple data series
    // only share "values-x" sequences. (TODO: simplify this logic).
    Reference< chart2::XDataSeriesContainer > xSeriesCnt( xChartType, uno::UNO_QUERY );
    lcl_tSharedSeqVec aSharedSequences;
    if( xSeriesCnt.is())
        aSharedSequences = lcl_getSharedSequences( xSeriesCnt->getDataSeries());

    Reference<chart2::XDataSeries> xNewSeries =
        m_apDialogModel->insertSeriesAfter(xSeries, xChartType, true);

    if (!xNewSeries.is())
        // Failed to insert new data series to the model. Bail out.
        return;

    Reference< chart2::data::XDataSource > xSource( xNewSeries, uno::UNO_QUERY );
    if (xSource.is())
    {
        Sequence<Reference<chart2::data::XLabeledDataSequence> > aLSequences = xSource->getDataSequences();
        sal_Int32 nSeqIdx = 0;
        sal_Int32 nSeqSize = aLSequences.getLength();
        for (sal_Int32 nIndex = nStartCol; nSeqIdx < nSeqSize; ++nSeqIdx)
        {
            lcl_tSharedSeqVec::const_iterator aSharedIt(
                std::find_if( aSharedSequences.begin(), aSharedSequences.end(),
                                lcl_RolesOfLSeqMatch( aLSequences[nSeqIdx] )));

            if( aSharedIt != aSharedSequences.end())
            {
                // Shared sequence. Most likely "values-x" sequence.  Copy it from existing sequence.
                aLSequences[nSeqIdx]->setValues( (*aSharedIt)->getValues());
                aLSequences[nSeqIdx]->setLabel( (*aSharedIt)->getLabel());
            }
            else
            {
                // Insert a new column in the internal data for the new sequence.
                xDataProvider->insertSequence( nIndex - 1 );

                // values
                Reference< chart2::data::XDataSequence > xNewSeq(
                    xDataProvider->createDataSequenceByRangeRepresentation(
                        OUString::number( nIndex )));
                lcl_copyDataSequenceProperties(
                    aLSequences[nSeqIdx]->getValues(), xNewSeq );
                aLSequences[nSeqIdx]->setValues( xNewSeq );

                // labels
                Reference< chart2::data::XDataSequence > xNewLabelSeq(
                    xDataProvider->createDataSequenceByRangeRepresentation(
                        "label " +
                        OUString::number( nIndex )));
                lcl_copyDataSequenceProperties(
                    aLSequences[nSeqIdx]->getLabel(), xNewLabelSeq );
                aLSequences[nSeqIdx]->setLabel( xNewLabelSeq );
                ++nIndex;
            }
        }
    }

    if( nSeriesNumberFormat != 0 )
    {
        //give the new series the same number format as the former series especially for bubble charts thus the bubble size values can be edited with same format immediately
        Reference< beans::XPropertySet > xNewSeriesProps( xNewSeries, uno::UNO_QUERY );
        if( xNewSeriesProps.is() )
            xNewSeriesProps->setPropertyValue(CHART_UNONAME_NUMFMT , uno::Any(nSeriesNumberFormat));
    }

    updateFromModel();
}

void DataBrowserModel::insertComplexCategoryLevel( sal_Int32 nAfterColumnIndex )
{
    //create a new text column for complex categories

    OSL_ASSERT(m_apDialogModel);
    Reference< chart2::XInternalDataProvider > xDataProvider( m_apDialogModel->getDataProvider(), uno::UNO_QUERY );
    if (!xDataProvider.is())
        return;

    if( !isCategoriesColumn(nAfterColumnIndex) )
        nAfterColumnIndex = getCategoryColumnCount()-1;

    if(nAfterColumnIndex<0)
    {
        OSL_FAIL( "wrong index for category level insertion" );
        return;
    }

    m_apDialogModel->startControllerLockTimer();
    ControllerLockGuardUNO aLockedControllers( m_xChartDocument );
    xDataProvider->insertComplexCategoryLevel( nAfterColumnIndex+1 );
    updateFromModel();
}

void DataBrowserModel::removeComplexCategoryLevel( sal_Int32 nAtColumnIndex )
{
    //delete a category column if there is more than one level (in case of a single column we do not get here)
    OSL_ENSURE(nAtColumnIndex>0, "wrong index for categories deletion" );

    Reference< chart2::XInternalDataProvider > xDataProvider( m_apDialogModel->getDataProvider(), uno::UNO_QUERY );
    if (!xDataProvider.is())
        return;

    m_apDialogModel->startControllerLockTimer();
    ControllerLockGuardUNO aLockedControllers( m_xChartDocument );
    xDataProvider->deleteComplexCategoryLevel( nAtColumnIndex );

    updateFromModel();
}

void DataBrowserModel::removeDataSeriesOrComplexCategoryLevel( sal_Int32 nAtColumnIndex )
{
    OSL_ASSERT(m_apDialogModel);
    if (nAtColumnIndex < 0 || o3tl::make_unsigned(nAtColumnIndex) >= m_aColumns.size())
        // Out of bound.
        return;

    if (isCategoriesColumn(nAtColumnIndex))
    {
        removeComplexCategoryLevel(nAtColumnIndex);
        return;
    }

    const Reference<chart2::XDataSeries>& xSeries = m_aColumns[nAtColumnIndex].m_xDataSeries;

    m_apDialogModel->deleteSeries(xSeries, getHeaderForSeries(xSeries).m_xChartType);

    //delete sequences from internal data provider that are not used anymore
    //but do not delete sequences that are still in use by the remaining series

    Reference< chart2::XInternalDataProvider > xDataProvider( m_apDialogModel->getDataProvider(), uno::UNO_QUERY );
    Reference< chart2::data::XDataSource > xSourceOfDeleted( xSeries, uno::UNO_QUERY );
    if (!xDataProvider.is() || !xSourceOfDeleted.is())
    {
        // Something went wrong.  Bail out.
        updateFromModel();
        return;
    }

    Reference<chart2::XDataSeriesContainer> xSeriesCnt(
        getHeaderForSeries(xSeries).m_xChartType, uno::UNO_QUERY);
    if (!xSeriesCnt.is())
    {
        // Unexpected happened.  Bail out.
        updateFromModel();
        return;
    }

    // Collect all the remaining data sequences in the same chart type. The
    // deleted data series is already gone by this point.
    std::vector<Reference<chart2::data::XLabeledDataSequence> > aAllDataSeqs =
        DataSeriesHelper::getAllDataSequences(xSeriesCnt->getDataSeries());

    // Check if the sequences to be deleted are still referenced by any of
    // the other data series.  If not, mark them for deletion.
    std::vector<sal_Int32> aSequenceIndexesToDelete;
    const Sequence<Reference<chart2::data::XLabeledDataSequence> > aSequencesOfDeleted = xSourceOfDeleted->getDataSequences();
    for (auto const & labeledDataSeq : aSequencesOfDeleted)
    {
        // if not used by the remaining series this sequence can be deleted
        if( std::none_of( aAllDataSeqs.begin(), aAllDataSeqs.end(),
                         lcl_RepresentationsOfLSeqMatch( labeledDataSeq )) )
            aSequenceIndexesToDelete.push_back( lcl_getValuesRepresentationIndex( labeledDataSeq ) );
    }

    // delete unnecessary sequences of the internal data
    // iterate using greatest index first, so that deletion does not
    // shift other sequences that will be deleted later
    std::sort( aSequenceIndexesToDelete.begin(), aSequenceIndexesToDelete.end());
    for( std::vector< sal_Int32 >::reverse_iterator aIt(
             aSequenceIndexesToDelete.rbegin()); aIt != aSequenceIndexesToDelete.rend(); ++aIt )
    {
        if( *aIt != -1 )
            xDataProvider->deleteSequence( *aIt );
    }

    updateFromModel();
}

void DataBrowserModel::swapDataSeries( sal_Int32 nFirstColumnIndex )
{
    OSL_ASSERT(m_apDialogModel);
    if( o3tl::make_unsigned( nFirstColumnIndex ) < m_aColumns.size() - 1 )
    {
        Reference< chart2::XDataSeries > xSeries( m_aColumns[nFirstColumnIndex].m_xDataSeries );
        if( xSeries.is())
        {
            m_apDialogModel->moveSeries( xSeries, DialogModel::MoveDirection::Down );
            updateFromModel();
        }
    }
}

void DataBrowserModel::swapDataPointForAllSeries( sal_Int32 nFirstIndex )
{
    OSL_ASSERT(m_apDialogModel);
    Reference< chart2::XInternalDataProvider > xDataProvider(
        m_apDialogModel->getDataProvider(), uno::UNO_QUERY );
    // lockControllers
    ControllerLockGuardUNO aGuard( m_apDialogModel->getChartModel());
    if( xDataProvider.is())
        xDataProvider->swapDataPointWithNextOneForAllSequences( nFirstIndex );
    // unlockControllers
}

void DataBrowserModel::insertDataPointForAllSeries( sal_Int32 nAfterIndex )
{
    Reference< chart2::XInternalDataProvider > xDataProvider(
        m_apDialogModel->getDataProvider(), uno::UNO_QUERY );
    // lockControllers
    ControllerLockGuardUNO aGuard( m_apDialogModel->getChartModel());
    if( xDataProvider.is())
        xDataProvider->insertDataPointForAllSequences( nAfterIndex );
    // unlockControllers
}

void DataBrowserModel::removeDataPointForAllSeries( sal_Int32 nAtIndex )
{
    Reference< chart2::XInternalDataProvider > xDataProvider(
        m_apDialogModel->getDataProvider(), uno::UNO_QUERY );
    // lockControllers
    ControllerLockGuardUNO aGuard( m_apDialogModel->getChartModel());
    if( xDataProvider.is())
        xDataProvider->deleteDataPointForAllSequences( nAtIndex );
    // unlockControllers
}

DataBrowserModel::tDataHeader DataBrowserModel::getHeaderForSeries(
    const Reference< chart2::XDataSeries > & xSeries ) const
{
    for (auto const& elemHeader : m_aHeaders)
    {
        if( elemHeader.m_xDataSeries == xSeries )
            return elemHeader;
    }
    return tDataHeader();
}

Reference< chart2::XDataSeries >
    DataBrowserModel::getDataSeriesByColumn( sal_Int32 nColumn ) const
{
    tDataColumnVector::size_type nIndex( nColumn );
    if( nIndex < m_aColumns.size())
        return m_aColumns[nIndex].m_xDataSeries;
    return nullptr;
}

DataBrowserModel::eCellType DataBrowserModel::getCellType( sal_Int32 nAtColumn ) const
{
    eCellType eResult = TEXT;
    tDataColumnVector::size_type nIndex( nAtColumn );
    if( nIndex < m_aColumns.size())
        eResult = m_aColumns[nIndex].m_eCellType;
    return eResult;
}

double DataBrowserModel::getCellNumber( sal_Int32 nAtColumn, sal_Int32 nAtRow )
{
    tDataColumnVector::size_type nIndex( nAtColumn );
    if( nIndex < m_aColumns.size() &&
        m_aColumns[ nIndex ].m_xLabeledDataSequence.is())
    {
        Reference< chart2::data::XNumericalDataSequence > xData(
            m_aColumns[ nIndex ].m_xLabeledDataSequence->getValues(), uno::UNO_QUERY );
        if( xData.is())
        {
            Sequence< double > aValues( xData->getNumericalData());
            if( nAtRow < aValues.getLength())
                return aValues[nAtRow];
        }
    }
    return std::numeric_limits<double>::quiet_NaN();
}

uno::Any DataBrowserModel::getCellAny( sal_Int32 nAtColumn, sal_Int32 nAtRow )
{
    uno::Any aResult;

    tDataColumnVector::size_type nIndex( nAtColumn );
    if( nIndex < m_aColumns.size() &&
        m_aColumns[ nIndex ].m_xLabeledDataSequence.is())
    {
        Reference< chart2::data::XDataSequence > xData(
            m_aColumns[ nIndex ].m_xLabeledDataSequence->getValues() );
        if( xData.is() )
        {
            Sequence< uno::Any > aValues( xData->getData());
            if( nAtRow < aValues.getLength())
                aResult = aValues[nAtRow];
        }
    }
    return aResult;
}

OUString DataBrowserModel::getCellText( sal_Int32 nAtColumn, sal_Int32 nAtRow )
{
    OUString aResult;

    tDataColumnVector::size_type nIndex( nAtColumn );
    if( nIndex < m_aColumns.size() &&
        m_aColumns[ nIndex ].m_xLabeledDataSequence.is())
    {
        Reference< chart2::data::XTextualDataSequence > xData(
            m_aColumns[ nIndex ].m_xLabeledDataSequence->getValues(), uno::UNO_QUERY );
        if( xData.is())
        {
            Sequence< OUString > aValues( xData->getTextualData());
            if( nAtRow < aValues.getLength())
                aResult = aValues[nAtRow];
        }
    }
    return aResult;
}

sal_uInt32 DataBrowserModel::getNumberFormatKey( sal_Int32 nAtColumn )
{
    tDataColumnVector::size_type nIndex( nAtColumn );
    if( nIndex < m_aColumns.size())
        return m_aColumns[ nIndex ].m_nNumberFormatKey;
    return 0;
}

bool DataBrowserModel::setCellAny( sal_Int32 nAtColumn, sal_Int32 nAtRow, const uno::Any & rValue )
{
    bool bResult = false;
    tDataColumnVector::size_type nIndex( nAtColumn );
    if( nIndex < m_aColumns.size() &&
        m_aColumns[ nIndex ].m_xLabeledDataSequence.is())
    {
        bResult = true;
        try
        {
            ControllerLockGuardUNO aLockedControllers( m_xChartDocument );

            // label
            if( nAtRow == -1 )
            {
                Reference< container::XIndexReplace > xIndexReplace(
                    m_aColumns[ nIndex ].m_xLabeledDataSequence->getLabel(), uno::UNO_QUERY_THROW );
                xIndexReplace->replaceByIndex( 0, rValue );
            }
            else
            {
                Reference< container::XIndexReplace > xIndexReplace(
                    m_aColumns[ nIndex ].m_xLabeledDataSequence->getValues(), uno::UNO_QUERY_THROW );
                xIndexReplace->replaceByIndex( nAtRow, rValue );
            }

            m_apDialogModel->startControllerLockTimer();
            //notify change directly to the model (this is necessary here as sequences for complex categories not known directly to the chart model so they do not notify their changes) (for complex categories see issue #i82971#)
            if( m_xChartDocument.is() )
                m_xChartDocument->setModified(true);
        }
        catch( const uno::Exception & )
        {
            bResult = false;
        }
    }
    return bResult;
}

bool DataBrowserModel::setCellNumber( sal_Int32 nAtColumn, sal_Int32 nAtRow, double fValue )
{
    return (getCellType( nAtColumn ) == NUMBER) &&
        setCellAny( nAtColumn, nAtRow, uno::Any( fValue ));
}

bool DataBrowserModel::setCellText( sal_Int32 nAtColumn, sal_Int32 nAtRow, const OUString & rText )
{
    return (getCellType( nAtColumn ) == TEXT) &&
        setCellAny( nAtColumn, nAtRow, uno::Any( rText ));
}

sal_Int32 DataBrowserModel::getColumnCount() const
{
    return static_cast< sal_Int32 >( m_aColumns.size());
}

sal_Int32 DataBrowserModel::getMaxRowCount() const
{
    sal_Int32 nResult = 0;
    for (auto const& column : m_aColumns)
    {
        if( column.m_xLabeledDataSequence.is())
        {
            Reference< chart2::data::XDataSequence > xSeq(
                column.m_xLabeledDataSequence->getValues());
            if( !xSeq.is())
                continue;
            sal_Int32 nLength( xSeq->getData().getLength());
            if( nLength > nResult )
                nResult = nLength;
        }
    }

    return nResult;
}

OUString DataBrowserModel::getRoleOfColumn( sal_Int32 nColumnIndex ) const
{
    if( nColumnIndex != -1 &&
        o3tl::make_unsigned( nColumnIndex ) < m_aColumns.size())
        return m_aColumns[ nColumnIndex ].m_aUIRoleName;
    return OUString();
}

bool DataBrowserModel::isCategoriesColumn( sal_Int32 nColumnIndex ) const
{
    if (nColumnIndex < 0)
        return false;

    if (o3tl::make_unsigned(nColumnIndex) >= m_aColumns.size())
        return false;

    // A column is a category when it doesn't have an associated data series.
    return !m_aColumns[nColumnIndex].m_xDataSeries.is();
}

sal_Int32 DataBrowserModel::getCategoryColumnCount()
{
    sal_Int32 nLastTextColumnIndex = -1;
    for (auto const& column : m_aColumns)
    {
        if( !column.m_xDataSeries.is() )
            nLastTextColumnIndex++;
        else
            break;
    }
    return nLastTextColumnIndex+1;
}

void DataBrowserModel::updateFromModel()
{
    if( !m_xChartDocument.is())
        return;
    m_aColumns.clear();
    m_aHeaders.clear();

    rtl::Reference< Diagram > xDiagram( ChartModelHelper::findDiagram( m_xChartDocument ));
    if( !xDiagram.is())
        return;

    // set template at DialogModel
    rtl::Reference< ::chart::ChartTypeManager > xChartTypeManager = m_xChartDocument->getTypeManager();
    DiagramHelper::tTemplateWithServiceName aTemplateAndService =
        DiagramHelper::getTemplateForDiagram( xDiagram, xChartTypeManager );
    if( aTemplateAndService.xChartTypeTemplate.is())
        m_apDialogModel->setTemplate( aTemplateAndService.xChartTypeTemplate );

    sal_Int32 nHeaderStart = 0;
    sal_Int32 nHeaderEnd   = 0;
    {
        ExplicitCategoriesProvider aExplicitCategoriesProvider( ChartModelHelper::getFirstCoordinateSystem(m_xChartDocument), *m_xChartDocument );

        const Sequence< Reference< chart2::data::XLabeledDataSequence> >& rSplitCategoriesList( aExplicitCategoriesProvider.getSplitCategoriesList() );
        sal_Int32 nLevelCount = rSplitCategoriesList.getLength();
        for( sal_Int32 nL = 0; nL<nLevelCount; nL++ )
        {
            Reference< chart2::data::XLabeledDataSequence > xCategories( rSplitCategoriesList[nL] );
            if( !xCategories.is() )
                continue;

            tDataColumn aCategories;
            aCategories.m_xLabeledDataSequence.set( xCategories );
            if( lcl_ShowCategoriesAsDataLabel( xDiagram ))
                aCategories.m_aUIRoleName = DialogModel::GetRoleDataLabel();
            else
                aCategories.m_aUIRoleName = lcl_getUIRoleName( xCategories );
            aCategories.m_eCellType = TEXTORDATE;
            m_aColumns.push_back( aCategories );
            ++nHeaderStart;
        }
    }

    if( !xDiagram.is())
        return;
    const Sequence< Reference< chart2::XCoordinateSystem > > aCooSysSeq( xDiagram->getCoordinateSystems());
    for( Reference< chart2::XCoordinateSystem > const & coords : aCooSysSeq )
    {
        Reference< chart2::XChartTypeContainer > xCTCnt( coords, uno::UNO_QUERY_THROW );
        const Sequence< Reference< chart2::XChartType > > aChartTypes( xCTCnt->getChartTypes());
        sal_Int32 nXAxisNumberFormat = DataSeriesHelper::getNumberFormatKeyFromAxis( nullptr, coords, 0, 0 );

        for( sal_Int32 nCTIdx=0; nCTIdx<aChartTypes.getLength(); ++nCTIdx )
        {
            Reference< chart2::XDataSeriesContainer > xSeriesCnt( aChartTypes[nCTIdx], uno::UNO_QUERY );
            if( xSeriesCnt.is())
            {
                OUString aRoleForDataLabelNumberFormat = ChartTypeHelper::getRoleOfSequenceForDataLabelNumberFormatDetection( aChartTypes[nCTIdx] );

                const Sequence< Reference< chart2::XDataSeries > > aSeries( xSeriesCnt->getDataSeries());
                lcl_tSharedSeqVec aSharedSequences( lcl_getSharedSequences( aSeries ));
                for (auto const& sharedSequence : aSharedSequences)
                {
                    tDataColumn aSharedSequence;
                    aSharedSequence.m_xLabeledDataSequence = sharedSequence;
                    aSharedSequence.m_aUIRoleName = lcl_getUIRoleName(sharedSequence);
                    aSharedSequence.m_eCellType = NUMBER;
                    // as the sequences are shared it should be ok to take the first series
                    // @todo: dimension index 0 for x-values used here. This is just a guess.
                    // Also, the axis index is 0, as there is usually only one x-axis
                    aSharedSequence.m_nNumberFormatKey = nXAxisNumberFormat;
                    m_aColumns.push_back( aSharedSequence );
                    ++nHeaderStart;
                }
                for( Reference< chart2::XDataSeries > const & dataSeries : aSeries )
                {
                    tDataColumnVector::size_type nStartColIndex = m_aColumns.size();
                    Reference< chart2::XDataSeries > xSeries( dataSeries );
                    Reference< chart2::data::XDataSource > xSource( xSeries, uno::UNO_QUERY );
                    if( xSource.is())
                    {
                        Sequence< Reference< chart2::data::XLabeledDataSequence > > aLSeqs( xSource->getDataSequences());
                        if( !aLSeqs.hasElements() )
                            continue;
                        nHeaderEnd = nHeaderStart;

                        // @todo: dimension index 1 for y-values used here. This is just a guess
                        sal_Int32 nYAxisNumberFormatKey =
                            DataSeriesHelper::getNumberFormatKeyFromAxis(
                                dataSeries, coords, 1 );

                        sal_Int32 nSeqIdx=0;
                        for( ; nSeqIdx<aLSeqs.getLength(); ++nSeqIdx )
                        {
                            sal_Int32 nSequenceNumberFormatKey = nYAxisNumberFormatKey;
                            OUString aRole = DataSeriesHelper::getRole(aLSeqs[nSeqIdx]);

                            if( aRole == aRoleForDataLabelNumberFormat )
                            {
                                nSequenceNumberFormatKey = ExplicitValueProvider::getExplicitNumberFormatKeyForDataLabel(
                                    Reference< beans::XPropertySet >( xSeries, uno::UNO_QUERY ));
                            }
                            else if( aRole == "values-x" )
                                nSequenceNumberFormatKey = nXAxisNumberFormat;

                            if( std::none_of( aSharedSequences.begin(), aSharedSequences.end(),
                                             lcl_RepresentationsOfLSeqMatch( aLSeqs[nSeqIdx] )) )
                            {
                                // no shared sequence
                                m_aColumns.emplace_back(
                                        dataSeries,
                                        lcl_getUIRoleName( aLSeqs[nSeqIdx] ),
                                        aLSeqs[nSeqIdx],
                                        NUMBER,
                                        nSequenceNumberFormatKey );
                                ++nHeaderEnd;
                            }
                            // else skip
                        }
                        bool bSwapXAndYAxis = false;
                        try
                        {
                            Reference< beans::XPropertySet > xProp( coords, uno::UNO_QUERY );
                            xProp->getPropertyValue( "SwapXAndYAxis" ) >>= bSwapXAndYAxis;
                        }
                        catch( const beans::UnknownPropertyException & ) {}

                        // add ranges for error bars if present for a series
                        if( StatisticsHelper::usesErrorBarRanges( dataSeries ))
                            addErrorBarRanges( dataSeries, nYAxisNumberFormatKey, nSeqIdx, nHeaderEnd, true );

                        if( StatisticsHelper::usesErrorBarRanges( dataSeries, /* bYError = */ false ))
                            addErrorBarRanges( dataSeries, nYAxisNumberFormatKey, nSeqIdx, nHeaderEnd, false );

                        m_aHeaders.emplace_back(
                                dataSeries,
                                aChartTypes[nCTIdx],
                                bSwapXAndYAxis,
                                nHeaderStart,
                                nHeaderEnd - 1 );

                        nHeaderStart = nHeaderEnd;

                        std::sort( m_aColumns.begin() + nStartColIndex, m_aColumns.end(), implColumnLess() );
                    }
                }
            }
        }
    }
}

void DataBrowserModel::addErrorBarRanges(
    const Reference< chart2::XDataSeries > & xDataSeries,
    sal_Int32 nNumberFormatKey,
    sal_Int32 & rInOutSequenceIndex,
    sal_Int32 & rInOutHeaderEnd, bool bYError )
{
    try
    {
        std::vector< Reference< chart2::data::XLabeledDataSequence > > aSequences;

        Reference< chart2::data::XDataSource > xErrorSource(
            StatisticsHelper::getErrorBars( xDataSeries, bYError ), uno::UNO_QUERY );

        Reference< chart2::data::XLabeledDataSequence > xErrorLSequence(
            StatisticsHelper::getErrorLabeledDataSequenceFromDataSource(
                xErrorSource,
                /* bPositiveValue = */ true,
                bYError ));
        if( xErrorLSequence.is())
            aSequences.push_back( xErrorLSequence );

        xErrorLSequence.set(
            StatisticsHelper::getErrorLabeledDataSequenceFromDataSource(
                xErrorSource,
                /* bPositiveValue = */ false,
                bYError ));
        if( xErrorLSequence.is())
            aSequences.push_back( xErrorLSequence );

        for (Reference<chart2::data::XLabeledDataSequence> const & rDataSequence : aSequences)
        {
            m_aColumns.emplace_back(xDataSeries, lcl_getUIRoleName(rDataSequence),
                                             rDataSequence, NUMBER, nNumberFormatKey);
            ++rInOutSequenceIndex;
            ++rInOutHeaderEnd;
        }
    }
    catch( const uno::Exception & )
    {
        DBG_UNHANDLED_EXCEPTION("chart2");
    }
}

} //  namespace chart

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */