summaryrefslogtreecommitdiffstats
path: root/chart2/source/controller/main/ChartController.cxx
blob: f81b261182fa350445818dc009ce55178d83c1d4 (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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
/* -*- 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 <memory>
#include <sal/config.h>

#include <set>

#include <ChartController.hxx>
#include <servicenames.hxx>
#include <ResId.hxx>
#include <dlg_DataSource.hxx>
#include <ChartModel.hxx>
#include <ChartModelHelper.hxx>
#include "ControllerCommandDispatch.hxx"
#include <strings.hrc>
#include <chartview/ExplicitValueProvider.hxx>
#include <ChartViewHelper.hxx>

#include <ChartWindow.hxx>
#include <chartview/DrawModelWrapper.hxx>
#include <DrawViewWrapper.hxx>
#include <ObjectIdentifier.hxx>
#include <DiagramHelper.hxx>
#include <ControllerLockGuard.hxx>
#include "UndoGuard.hxx"
#include "ChartDropTargetHelper.hxx"

#include <dlg_ChartType.hxx>
#include <AccessibleChartView.hxx>
#include "DrawCommandDispatch.hxx"
#include "ShapeController.hxx"
#include "UndoActions.hxx"
#include <ViewElementListProvider.hxx>

#include <cppuhelper/supportsservice.hxx>

#include <com/sun/star/chart2/XChartDocument.hpp>
#include <com/sun/star/chart2/data/XDataReceiver.hpp>
#include <com/sun/star/frame/XController2.hpp>
#include <com/sun/star/util/CloseVetoException.hpp>
#include <com/sun/star/util/XModeChangeBroadcaster.hpp>
#include <com/sun/star/util/XModifyBroadcaster.hpp>
#include <com/sun/star/frame/LayoutManagerEvents.hpp>
#include <com/sun/star/frame/XLayoutManagerEventBroadcaster.hpp>
#include <com/sun/star/document/XUndoManagerSupplier.hpp>
#include <com/sun/star/ui/XSidebar.hpp>
#include <com/sun/star/chart2/XChartTypeContainer.hpp>
#include <com/sun/star/chart2/XCoordinateSystemContainer.hpp>
#include <com/sun/star/chart2/XDataProviderAccess.hpp>

#include <sal/log.hxx>
#include <tools/debug.hxx>
#include <svx/sidebar/SelectionChangeHandler.hxx>
#include <toolkit/awt/vclxwindow.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <vcl/svapp.hxx>
#include <vcl/weld.hxx>
#include <osl/mutex.hxx>

#include <sfx2/sidebar/SidebarController.hxx>

#include <com/sun/star/frame/XLayoutManager.hpp>

// this is needed to properly destroy the unique_ptr to the AcceleratorExecute
// object in the DTOR
#include <svtools/acceleratorexecute.hxx>
#include <svx/ActionDescriptionProvider.hxx>
#include <tools/diagnose_ex.h>

// enable the following define to let the controller listen to model changes and
// react on this by rebuilding the view
#define TEST_ENABLE_MODIFY_LISTENER

namespace chart
{

using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;
using namespace ::com::sun::star::chart2;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;

ChartController::ChartController(uno::Reference<uno::XComponentContext> const & xContext) :
    m_aLifeTimeManager( nullptr ),
    m_bSuspended( false ),
    m_xCC(xContext), //@todo is it allowed to hold this context??
    m_aModelMutex(),
    m_aModel( nullptr, m_aModelMutex ),
    m_xViewWindow(),
    m_xChartView(),
    m_pDrawModelWrapper(),
    m_eDragMode(SdrDragMode::Move),
    m_bWaitingForDoubleClick(false),
    m_bWaitingForMouseUp(false),
    m_bFieldButtonDown(false),
    m_bConnectingToView(false),
    m_bDisposed(false),
    m_aDispatchContainer( m_xCC ),
    m_eDrawMode( CHARTDRAW_SELECT ),
    mpSelectionChangeHandler(new svx::sidebar::SelectionChangeHandler(
            [this]() { return this->GetContextName(); },
                this, vcl::EnumContext::Context::Cell))
{
    m_aDoubleClickTimer.SetInvokeHandler( LINK( this, ChartController, DoubleClickWaitingHdl ) );
}

ChartController::~ChartController()
{
    stopDoubleClickWaiting();
}

ChartController::TheModel::TheModel( const uno::Reference< frame::XModel > & xModel ) :
    m_xModel( xModel ),
    m_bOwnership( true )
{
    m_xCloseable =
        uno::Reference< util::XCloseable >( xModel, uno::UNO_QUERY );
}

ChartController::TheModel::~TheModel()
{
}

void ChartController::TheModel::addListener( ChartController* pController )
{
    if(m_xCloseable.is())
    {
        //if you need to be able to veto against the destruction of the model
        // you must add as a close listener

        //otherwise you 'can' add as closelistener or 'must' add as dispose event listener

        m_xCloseable->addCloseListener(
            static_cast<util::XCloseListener*>(pController) );
    }
    else if( m_xModel.is() )
    {
        //we need to add as dispose event listener
        m_xModel->addEventListener(
            static_cast<util::XCloseListener*>(pController) );
    }

}

void ChartController::TheModel::removeListener(  ChartController* pController )
{
    if(m_xCloseable.is())
        m_xCloseable->removeCloseListener(
            static_cast<util::XCloseListener*>(pController) );

    else if( m_xModel.is() )
        m_xModel->removeEventListener(
            static_cast<util::XCloseListener*>(pController) );
}

void ChartController::TheModel::tryTermination()
{
    if(!m_bOwnership)
        return;

    try
    {
        if(m_xCloseable.is())
        {
            try
            {
                //@todo ? are we allowed to use sal_True here if we have the explicit ownership?
                //I think yes, because there might be other CloseListeners later in the list which might be interested still
                //but make sure that we do not throw the CloseVetoException here ourselves
                //so stop listening before trying to terminate or check the source of queryclosing event
                m_xCloseable->close(true);

                m_bOwnership                = false;
            }
            catch( const util::CloseVetoException& )
            {
                //since we have indicated to give up the ownership with parameter true in close call
                //the one who has thrown the CloseVetoException is the new owner

                SAL_WARN_IF( m_bOwnership, "chart2.main", "a well known owner has caught a CloseVetoException after calling close(true)");
                m_bOwnership                = false;
                return;
            }

        }
        else if( m_xModel.is() )
        {
            //@todo correct??
            m_xModel->dispose();
            return;
        }
    }
    catch(const uno::Exception&)
    {
        DBG_UNHANDLED_EXCEPTION( "chart2", "Termination of model failed" );
    }
}

ChartController::TheModelRef::TheModelRef( TheModel* pTheModel, osl::Mutex& rMutex ) :
    m_rModelMutex(rMutex)
{
    osl::Guard< osl::Mutex > aGuard( m_rModelMutex );
    m_xTheModel = pTheModel;
}
ChartController::TheModelRef::TheModelRef( const TheModelRef& rTheModel, ::osl::Mutex& rMutex ) :
    m_rModelMutex(rMutex)
{
    osl::Guard< osl::Mutex > aGuard( m_rModelMutex );
    m_xTheModel = rTheModel.m_xTheModel;
}
ChartController::TheModelRef& ChartController::TheModelRef::operator=(TheModel* pTheModel)
{
    osl::Guard< osl::Mutex > aGuard( m_rModelMutex );
    m_xTheModel = pTheModel;
    return *this;
}
ChartController::TheModelRef& ChartController::TheModelRef::operator=(const TheModelRef& rTheModel)
{
    osl::Guard< osl::Mutex > aGuard( m_rModelMutex );
    m_xTheModel = rTheModel.operator->();
    return *this;
}
ChartController::TheModelRef::~TheModelRef()
{
    osl::Guard< osl::Mutex > aGuard( m_rModelMutex );
    m_xTheModel.clear();
}
bool ChartController::TheModelRef::is() const
{
    return m_xTheModel.is();
}

namespace {

css::uno::Reference<css::chart2::XChartType> getChartType(
        const css::uno::Reference<css::chart2::XChartDocument>& xChartDoc)
{
    Reference <chart2::XDiagram > xDiagram = xChartDoc->getFirstDiagram();
    if (!xDiagram.is()) {
        return css::uno::Reference<css::chart2::XChartType>();
    }

    Reference< chart2::XCoordinateSystemContainer > xCooSysContainer( xDiagram, uno::UNO_QUERY_THROW );

    Sequence< Reference< chart2::XCoordinateSystem > > xCooSysSequence( xCooSysContainer->getCoordinateSystems());
    if (!xCooSysSequence.hasElements()) {
        return css::uno::Reference<css::chart2::XChartType>();
    }

    Reference< chart2::XChartTypeContainer > xChartTypeContainer( xCooSysSequence[0], uno::UNO_QUERY_THROW );

    Sequence< Reference< chart2::XChartType > > xChartTypeSequence( xChartTypeContainer->getChartTypes() );

    return xChartTypeSequence[0];
}

}

OUString ChartController::GetContextName()
{
    if (m_bDisposed)
        return OUString();

    uno::Any aAny = getSelection();
    if (!aAny.hasValue())
        return "Chart";

    OUString aCID;
    aAny >>= aCID;

    if (aCID.isEmpty())
        return "Chart";

    ObjectType eObjectID = ObjectIdentifier::getObjectType(aCID);
    switch (eObjectID)
    {
        case OBJECTTYPE_DATA_SERIES:
            return "Series";
        break;
        case OBJECTTYPE_DATA_ERRORS_X:
        case OBJECTTYPE_DATA_ERRORS_Y:
        case OBJECTTYPE_DATA_ERRORS_Z:
            return "ErrorBar";
        case OBJECTTYPE_AXIS:
            return "Axis";
        case OBJECTTYPE_GRID:
            return "Grid";
        case OBJECTTYPE_DIAGRAM:
            {
                css::uno::Reference<css::chart2::XChartType> xChartType = getChartType(css::uno::Reference<css::chart2::XChartDocument>(getModel(), uno::UNO_QUERY));
                if (xChartType.is() && xChartType->getChartType() == "com.sun.star.chart2.PieChartType")
                    return "ChartElements";
                break;
            }
        case OBJECTTYPE_DATA_CURVE:
        case OBJECTTYPE_DATA_AVERAGE_LINE:
            return "Trendline";
        default:
        break;
    }

    return "Chart";
}

// private methods

bool ChartController::impl_isDisposedOrSuspended() const
{
    if( m_aLifeTimeManager.impl_isDisposed() )
        return true;

    if( m_bSuspended )
    {
        OSL_FAIL( "This Controller is suspended" );
        return true;
    }
    return false;
}

// lang::XServiceInfo

OUString SAL_CALL ChartController::getImplementationName()
{
    return CHART_CONTROLLER_SERVICE_IMPLEMENTATION_NAME;
}

sal_Bool SAL_CALL ChartController::supportsService( const OUString& rServiceName )
{
    return cppu::supportsService(this, rServiceName);
}

css::uno::Sequence< OUString > SAL_CALL ChartController::getSupportedServiceNames()
{
    return {
        CHART_CONTROLLER_SERVICE_NAME,
        "com.sun.star.frame.Controller"
        //// @todo : add additional services if you support any further
    };
}

namespace {

uno::Reference<ui::XSidebar> getSidebarFromModel(const uno::Reference<frame::XModel>& xModel)
{
    uno::Reference<container::XChild> xChild(xModel, uno::UNO_QUERY);
    if (!xChild.is())
        return nullptr;

    uno::Reference<frame::XModel> xParent (xChild->getParent(), uno::UNO_QUERY);
    if (!xParent.is())
        return nullptr;

    uno::Reference<frame::XController2> xController(xParent->getCurrentController(), uno::UNO_QUERY);
    if (!xController.is())
        return nullptr;

    uno::Reference<ui::XSidebarProvider> xSidebarProvider  = xController->getSidebar();
    if (!xSidebarProvider.is())
        return nullptr;

    return xSidebarProvider->getSidebar();
}

}

// XController

void SAL_CALL ChartController::attachFrame(
    const uno::Reference<frame::XFrame>& xFrame )
{
    SolarMutexGuard aGuard;

    if( impl_isDisposedOrSuspended() ) //@todo? allow attaching the frame while suspended?
        return; //behave passive if already disposed or suspended

    mpSelectionChangeHandler->Connect();

    uno::Reference<ui::XSidebar> xSidebar = getSidebarFromModel(getModel());
    if (xSidebar.is())
    {
        auto pSidebar = dynamic_cast<sfx2::sidebar::SidebarController*>(xSidebar.get());
        assert(pSidebar);
        sfx2::sidebar::SidebarController::registerSidebarForFrame(pSidebar, this);
        pSidebar->updateModel(getModel());
        css::lang::EventObject aEvent;
        mpSelectionChangeHandler->selectionChanged(aEvent);
    }

    if(m_xFrame.is()) //what happens, if we do have a Frame already??
    {
        //@todo? throw exception?
        OSL_FAIL( "there is already a frame attached to the controller" );
        return;
    }

    //--attach frame
    m_xFrame = xFrame; //the frameloader is responsible to call xFrame->setComponent

    //add as disposelistener to the frame (due to persistent reference) ??...:

    //the frame is considered to be owner of this controller and will live longer than we do
    //the frame or the disposer of the frame has the duty to call suspend and dispose on this object
    //so we do not need to add as lang::XEventListener for DisposingEvents right?

    //@todo nothing right???

    //create view @todo is this the correct place here??

    vcl::Window* pParent = nullptr;
    //get the window parent from the frame to use as parent for our new window
    if(xFrame.is())
    {
        uno::Reference< awt::XWindow > xContainerWindow = xFrame->getContainerWindow();
        VCLXWindow* pParentComponent = comphelper::getUnoTunnelImplementation<VCLXWindow>(xContainerWindow);
        assert(pParentComponent);
        if (pParentComponent)
            pParentComponent->setVisible(true);

        pParent = VCLUnoHelper::GetWindow( xContainerWindow ).get();
    }

    {
        // calls to VCL
        SolarMutexGuard aSolarGuard;
        auto pChartWindow = VclPtr<ChartWindow>::Create(this,pParent,pParent?pParent->GetStyle():0);
        pChartWindow->SetBackground();//no Background
        m_xViewWindow.set( pChartWindow->GetComponentInterface(), uno::UNO_QUERY );
        pChartWindow->Show();
        m_apDropTargetHelper.reset(
            new ChartDropTargetHelper( pChartWindow->GetDropTarget(),
                                       uno::Reference< chart2::XChartDocument >( getModel(), uno::UNO_QUERY )));

        impl_createDrawViewController();
    }

    //create the menu
    {
        uno::Reference< beans::XPropertySet > xPropSet( xFrame, uno::UNO_QUERY );
        if( xPropSet.is() )
        {
            try
            {
                uno::Reference< css::frame::XLayoutManager > xLayoutManager;
                xPropSet->getPropertyValue( "LayoutManager" ) >>= xLayoutManager;
                if ( xLayoutManager.is() )
                {
                    xLayoutManager->lock();
                    xLayoutManager->requestElement( "private:resource/menubar/menubar" );
                    //@todo: createElement should become unnecessary, remove when #i79198# is fixed
                    xLayoutManager->createElement( "private:resource/toolbar/standardbar" );
                    xLayoutManager->requestElement( "private:resource/toolbar/standardbar" );
                    //@todo: createElement should become unnecessary, remove when #i79198# is fixed
                    xLayoutManager->createElement( "private:resource/toolbar/toolbar" );
                    xLayoutManager->requestElement( "private:resource/toolbar/toolbar" );

                    // #i12587# support for shapes in chart
                    xLayoutManager->createElement( "private:resource/toolbar/drawbar" );
                    xLayoutManager->requestElement( "private:resource/toolbar/drawbar" );

                    xLayoutManager->requestElement( "private:resource/statusbar/statusbar" );
                    xLayoutManager->unlock();

                    // add as listener to get notified when
                    m_xLayoutManagerEventBroadcaster.set( xLayoutManager, uno::UNO_QUERY );
                    if( m_xLayoutManagerEventBroadcaster.is())
                        m_xLayoutManagerEventBroadcaster->addLayoutManagerEventListener( this );
                }
            }
            catch( const uno::Exception & )
            {
                DBG_UNHANDLED_EXCEPTION("chart2");
            }
        }
    }
}

//XModeChangeListener
void SAL_CALL ChartController::modeChanged( const util::ModeChangeEvent& rEvent )
{
    SolarMutexGuard aGuard;
    auto pChartWindow(GetChartWindow());
    //adjust controller to view status changes

    if( rEvent.NewMode == "dirty" )
    {
        //the view has become dirty, we should repaint it if we have a window
        if( pChartWindow )
            pChartWindow->ForceInvalidate();
    }
    else if( rEvent.NewMode == "invalid" )
    {
        //the view is about to become invalid so end all actions on it
        impl_invalidateAccessible();
        if( m_pDrawViewWrapper && m_pDrawViewWrapper->IsTextEdit() )
            this->EndTextEdit();
        if( m_pDrawViewWrapper )
        {
            m_pDrawViewWrapper->UnmarkAll();
            m_pDrawViewWrapper->HideSdrPage();
        }
    }
    else
    {
        //the view was rebuild so we can start some actions on it again
        if( !m_bConnectingToView )
        {
            if(pChartWindow && m_aModel.is() )
            {
                m_bConnectingToView = true;

                GetDrawModelWrapper();
                if(m_pDrawModelWrapper)
                {
                    {
                        if( m_pDrawViewWrapper )
                            m_pDrawViewWrapper->ReInit();
                    }

                    //reselect object
                    if( m_aSelection.hasSelection() )
                        this->impl_selectObjectAndNotiy();
                    else
                        ChartModelHelper::triggerRangeHighlighting( getModel() );

                    impl_initializeAccessible();

                    {
                        if( pChartWindow )
                            pChartWindow->Invalidate();
                    }
                }

                m_bConnectingToView = false;
            }
        }
    }
}

sal_Bool SAL_CALL ChartController::attachModel( const uno::Reference< frame::XModel > & xModel )
{
    impl_invalidateAccessible();

    //is called to attach the controller to a new model.
    //return true if attach was successfully, false otherwise (e.g. if you do not work with a model)

    SolarMutexResettableGuard aGuard;
    if( impl_isDisposedOrSuspended() ) //@todo? allow attaching a new model while suspended?
        return false; //behave passive if already disposed or suspended
    aGuard.clear();

    TheModelRef aNewModelRef( new TheModel( xModel), m_aModelMutex);
    TheModelRef aOldModelRef(m_aModel,m_aModelMutex);
    m_aModel = aNewModelRef;

    //--handle relations to the old model if any
    if( aOldModelRef.is() )
    {
        uno::Reference< util::XModeChangeBroadcaster > xViewBroadcaster( m_xChartView, uno::UNO_QUERY );
        if( xViewBroadcaster.is() )
            xViewBroadcaster->removeModeChangeListener(this);
        m_pDrawModelWrapper.reset();

        aOldModelRef->removeListener( this );
 #ifdef TEST_ENABLE_MODIFY_LISTENER
        uno::Reference< util::XModifyBroadcaster > xMBroadcaster( aOldModelRef->getModel(),uno::UNO_QUERY );
        if( xMBroadcaster.is())
            xMBroadcaster->removeModifyListener( this );
#endif
    }

    //--handle relations to the new model
    aNewModelRef->addListener( this );

    aGuard.reset(); // lock for m_aDispatchContainer access
    // set new model at dispatchers
    m_aDispatchContainer.setModel( aNewModelRef->getModel());
    ControllerCommandDispatch * pDispatch = new ControllerCommandDispatch( m_xCC, this, &m_aDispatchContainer );
    pDispatch->initialize();

    // the dispatch container will return "this" for all commands returned by
    // impl_getAvailableCommands().  That means, for those commands dispatch()
    // is called here at the ChartController.
    m_aDispatchContainer.setChartDispatch( pDispatch, impl_getAvailableCommands() );

    DrawCommandDispatch* pDrawDispatch = new DrawCommandDispatch( m_xCC, this );
    pDrawDispatch->initialize();
    m_aDispatchContainer.setDrawCommandDispatch( pDrawDispatch );

    ShapeController* pShapeController = new ShapeController( m_xCC, this );
    pShapeController->initialize();
    m_aDispatchContainer.setShapeController( pShapeController );
    aGuard.clear();

#ifdef TEST_ENABLE_MODIFY_LISTENER
    uno::Reference< util::XModifyBroadcaster > xMBroadcaster( aNewModelRef->getModel(),uno::UNO_QUERY );
    if( xMBroadcaster.is())
        xMBroadcaster->addModifyListener( this );
#endif

    // #i119999# Do not do this per default to allow the user to deselect the chart OLE with a single press to ESC
    // select chart area per default:
    // select( uno::Any( ObjectIdentifier::createClassifiedIdentifier( OBJECTTYPE_PAGE, OUString() ) ) );

    uno::Reference< lang::XMultiServiceFactory > xFact( getModel(), uno::UNO_QUERY );
    if( xFact.is())
    {
        m_xChartView = xFact->createInstance( CHART_VIEW_SERVICE_NAME );
        GetDrawModelWrapper();
        uno::Reference< util::XModeChangeBroadcaster > xViewBroadcaster( m_xChartView, uno::UNO_QUERY );
        if( xViewBroadcaster.is() )
            xViewBroadcaster->addModeChangeListener(this);
    }

    //the frameloader is responsible to call xModel->connectController
    {
        SolarMutexGuard aGuard2;
        auto pChartWindow(GetChartWindow());
        if( pChartWindow )
            pChartWindow->Invalidate();
    }

    uno::Reference< document::XUndoManagerSupplier > xSuppUndo( getModel(), uno::UNO_QUERY_THROW );
    m_xUndoManager.set( xSuppUndo->getUndoManager(), uno::UNO_SET_THROW );

    return true;
}

uno::Reference< frame::XFrame > SAL_CALL ChartController::getFrame()
{
    //provides access to owner frame of this controller
    //return the frame containing this controller

    return m_xFrame;
}

uno::Reference< frame::XModel > SAL_CALL ChartController::getModel()
{
    //provides access to currently attached model
    //returns the currently attached model

    //return nothing, if you do not have a model
    TheModelRef aModelRef( m_aModel, m_aModelMutex);
    if(aModelRef.is())
        return aModelRef->getModel();

    return uno::Reference< frame::XModel > ();
}

uno::Any SAL_CALL ChartController::getViewData()
{
    //provides access to current view status
    //set of data that can be used to restore the current view status at later time
    //  by using XController::restoreViewData()

    SolarMutexGuard aGuard;
    if( impl_isDisposedOrSuspended() )
        return uno::Any(); //behave passive if already disposed or suspended //@todo? or throw an exception??

    //-- collect current view state
    uno::Any aRet;
    //// @todo integrate specialized implementation

    return aRet;
}

void SAL_CALL ChartController::restoreViewData(
    const uno::Any& /* Value */ )
{
    //restores the view status using the data gotten from a previous call to XController::getViewData()

    SolarMutexGuard aGuard;
    if( impl_isDisposedOrSuspended() )
        return; //behave passive if already disposed or suspended //@todo? or throw an exception??

    //// @todo integrate specialized implementation
}

sal_Bool SAL_CALL ChartController::suspend( sal_Bool bSuspend )
{
    //is called to prepare the controller for closing the view
    //bSuspend==true: force the controller to suspend his work
    //bSuspend==false try to reactivate the controller
    //returns true if request was accepted and of course successfully finished, false otherwise

    //we may show dialogs here to ask the user for saving changes ... @todo?

    SolarMutexGuard aGuard;
    if( m_aLifeTimeManager.impl_isDisposed() )
        return false; //behave passive if already disposed, return false because request was not accepted //@todo? correct

    if(bool(bSuspend) == m_bSuspended)
    {
        OSL_FAIL( "new suspend mode equals old suspend mode" );
        return true;
    }

    //change suspend mode
    m_bSuspended = bSuspend;
    return true;
}

void ChartController::impl_createDrawViewController()
{
    SolarMutexGuard aGuard;
    if(!m_pDrawViewWrapper)
    {
        if( m_pDrawModelWrapper )
        {
            m_pDrawViewWrapper.reset( new DrawViewWrapper(m_pDrawModelWrapper->getSdrModel(),GetChartWindow()) );
            m_pDrawViewWrapper->attachParentReferenceDevice( getModel() );
        }
    }
}

void ChartController::impl_deleteDrawViewController()
{
    if( m_pDrawViewWrapper )
    {
        SolarMutexGuard aGuard;
        if( m_pDrawViewWrapper->IsTextEdit() )
            this->EndTextEdit();
        m_pDrawViewWrapper.reset();
    }
}

// XComponent (base of XController)

void SAL_CALL ChartController::dispose()
{
    m_bDisposed = true;

    if (getModel().is())
    {
        uno::Reference<ui::XSidebar> xSidebar = getSidebarFromModel(getModel());
        if (sfx2::sidebar::SidebarController* pSidebar = dynamic_cast<sfx2::sidebar::SidebarController*>(xSidebar.get()))
        {
            sfx2::sidebar::SidebarController::unregisterSidebarForFrame(pSidebar, this);
        }
    }
    mpSelectionChangeHandler->selectionChanged(css::lang::EventObject());
    mpSelectionChangeHandler->Disconnect();

    try
    {
        //This object should release all resources and references in the
        //easiest possible manner
        //This object must notify all registered listeners using the method
        //<member>XEventListener::disposing</member>

        //hold no mutex
        if( !m_aLifeTimeManager.dispose() )
            return;

//  OSL_ENSURE( m_bSuspended, "dispose was called but controller is not suspended" );

        this->stopDoubleClickWaiting();

        //end range highlighting
        if( m_aModel.is())
        {
            uno::Reference< view::XSelectionChangeListener > xSelectionChangeListener;
            uno::Reference< chart2::data::XDataReceiver > xDataReceiver( getModel(), uno::UNO_QUERY );
            if( xDataReceiver.is() )
                xSelectionChangeListener.set( xDataReceiver->getRangeHighlighter(), uno::UNO_QUERY );
            if( xSelectionChangeListener.is() )
            {
                uno::Reference< frame::XController > xController( this );
                lang::EventObject aEvent( xController );
                xSelectionChangeListener->disposing( aEvent );
            }
        }

        //--release all resources and references
        {
            uno::Reference< util::XModeChangeBroadcaster > xViewBroadcaster( m_xChartView, uno::UNO_QUERY );
            if( xViewBroadcaster.is() )
                xViewBroadcaster->removeModeChangeListener(this);

            impl_invalidateAccessible();
            SolarMutexGuard aSolarGuard;
            impl_deleteDrawViewController();
            m_pDrawModelWrapper.reset();

            m_apDropTargetHelper.reset();

            //the accessible view is disposed within window destructor of m_pChartWindow
            if(m_xViewWindow.is())
                m_xViewWindow->dispose(); //ChartWindow is deleted via UNO due to dispose of m_xViewWindow (triggered by Framework (Controller pretends to be XWindow also))
            m_xChartView.clear();
        }

        // remove as listener to layout manager events
        if( m_xLayoutManagerEventBroadcaster.is())
        {
            m_xLayoutManagerEventBroadcaster->removeLayoutManagerEventListener( this );
            m_xLayoutManagerEventBroadcaster.set( nullptr );
        }

        m_xFrame.clear();
        m_xUndoManager.clear();

        TheModelRef aModelRef( m_aModel, m_aModelMutex);
        m_aModel = nullptr;

        if( aModelRef.is())
        {
            uno::Reference< frame::XModel > xModel( aModelRef->getModel() );
            if(xModel.is())
                xModel->disconnectController( uno::Reference< frame::XController >( this ));

            aModelRef->removeListener( this );
#ifdef TEST_ENABLE_MODIFY_LISTENER
            try
            {
                uno::Reference< util::XModifyBroadcaster > xMBroadcaster( aModelRef->getModel(),uno::UNO_QUERY );
                if( xMBroadcaster.is())
                    xMBroadcaster->removeModifyListener( this );
            }
            catch( const uno::Exception & )
            {
                DBG_UNHANDLED_EXCEPTION("chart2");
            }
#endif
            aModelRef->tryTermination();
        }

        //// @todo integrate specialized implementation
        //e.g. release further resources and references

        SolarMutexGuard g;
        m_aDispatchContainer.DisposeAndClear();
    }
    catch( const uno::Exception & )
    {
        DBG_UNHANDLED_EXCEPTION("chart2");
        assert(!m_xChartView.is());
    }
 }

void SAL_CALL ChartController::addEventListener(
    const uno::Reference<lang::XEventListener>& xListener )
{
    SolarMutexGuard aGuard;
    if( impl_isDisposedOrSuspended() )//@todo? allow adding of listeners in suspend mode?
        return; //behave passive if already disposed or suspended

    //--add listener
    m_aLifeTimeManager.m_aListenerContainer.addInterface( cppu::UnoType<lang::XEventListener>::get(), xListener );
}

void SAL_CALL ChartController::removeEventListener(
    const uno::Reference<lang::XEventListener>& xListener )
{
    SolarMutexGuard aGuard;
    if( m_aLifeTimeManager.impl_isDisposed(false) )
        return; //behave passive if already disposed or suspended

    //--remove listener
    m_aLifeTimeManager.m_aListenerContainer.removeInterface( cppu::UnoType<lang::XEventListener>::get(), xListener );
}

// util::XCloseListener
void SAL_CALL ChartController::queryClosing(
    const lang::EventObject& rSource,
    sal_Bool /*bGetsOwnership*/ )
{
    //do not use the m_aControllerMutex here because this call is not allowed to block

    TheModelRef aModelRef( m_aModel, m_aModelMutex);

    if( !aModelRef.is() )
        return;

    if( aModelRef->getModel() != rSource.Source )
    {
        OSL_FAIL( "queryClosing was called on a controller from an unknown source" );
        return;
    }

    //@ todo prepare to closing model -> don't start any further hindering actions
}

void SAL_CALL ChartController::notifyClosing(
    const lang::EventObject& rSource )
{
    //Listener should deregister himself and release all references to the closing object.

    TheModelRef aModelRef( m_aModel, m_aModelMutex);
    if( !impl_releaseThisModel( rSource.Source ) )
        return;

    //--stop listening to the closing model
    aModelRef->removeListener( this );

    // #i79087# If the model using this controller is closed, the frame is
    // expected to be closed as well
    Reference< util::XCloseable > xFrameCloseable( m_xFrame, uno::UNO_QUERY );
    if( xFrameCloseable.is())
    {
        try
        {
            xFrameCloseable->close( false /* DeliverOwnership */ );
            m_xFrame.clear();
        }
        catch( const util::CloseVetoException & )
        {
            // closing was vetoed
        }
    }
}

bool ChartController::impl_releaseThisModel(
    const uno::Reference< uno::XInterface > & xModel )
{
    bool bReleaseModel = false;
    {
        ::osl::Guard< ::osl::Mutex > aGuard( m_aModelMutex );
        if( m_aModel.is() && m_aModel->getModel() == xModel )
        {
            m_aModel = nullptr;
            m_xUndoManager.clear();
            bReleaseModel = true;
        }
    }
    if( bReleaseModel )
    {
        SolarMutexGuard g;
        m_aDispatchContainer.setModel( nullptr );
    }
    return bReleaseModel;
}

// util::XEventListener (base of XCloseListener)
void SAL_CALL ChartController::disposing(
    const lang::EventObject& rSource )
{
    if( !impl_releaseThisModel( rSource.Source ))
    {
        if( rSource.Source == m_xLayoutManagerEventBroadcaster )
            m_xLayoutManagerEventBroadcaster.set( nullptr );
    }
}

void SAL_CALL ChartController::layoutEvent(
    const lang::EventObject& aSource,
    sal_Int16 eLayoutEvent,
    const uno::Any& /* aInfo */ )
{
    if( eLayoutEvent == frame::LayoutManagerEvents::MERGEDMENUBAR )
    {
        Reference< frame::XLayoutManager > xLM( aSource.Source, uno::UNO_QUERY );
        if( xLM.is())
        {
            xLM->createElement(  "private:resource/statusbar/statusbar" );
            xLM->requestElement( "private:resource/statusbar/statusbar" );
        }
    }
}

// XDispatchProvider (required interface)

namespace
{

bool lcl_isFormatObjectCommand( const OUString& aCommand )
{
    return aCommand == "MainTitle"
        || aCommand == "SubTitle"
        || aCommand == "XTitle"
        || aCommand == "YTitle"
        || aCommand == "ZTitle"
        || aCommand == "SecondaryXTitle"
        || aCommand == "SecondaryYTitle"
        || aCommand == "AllTitles"
        || aCommand == "DiagramAxisX"
        || aCommand == "DiagramAxisY"
        || aCommand == "DiagramAxisZ"
        || aCommand == "DiagramAxisA"
        || aCommand == "DiagramAxisB"
        || aCommand == "DiagramAxisAll"
        || aCommand == "DiagramGridXMain"
        || aCommand == "DiagramGridYMain"
        || aCommand == "DiagramGridZMain"
        || aCommand == "DiagramGridXHelp"
        || aCommand == "DiagramGridYHelp"
        || aCommand == "DiagramGridZHelp"
        || aCommand == "DiagramGridAll"

        || aCommand == "DiagramWall"
        || aCommand == "DiagramFloor"
        || aCommand == "DiagramArea"
        || aCommand == "Legend"

        || aCommand == "FormatWall"
        || aCommand == "FormatFloor"
        || aCommand == "FormatChartArea"
        || aCommand == "FormatLegend"

        || aCommand == "FormatTitle"
        || aCommand == "FormatAxis"
        || aCommand == "FormatDataSeries"
        || aCommand == "FormatDataPoint"
        || aCommand == "FormatDataLabels"
        || aCommand == "FormatDataLabel"
        || aCommand == "FormatXErrorBars"
        || aCommand == "FormatYErrorBars"
        || aCommand == "FormatMeanValue"
        || aCommand == "FormatTrendline"
        || aCommand == "FormatTrendlineEquation"
        || aCommand == "FormatStockLoss"
        || aCommand == "FormatStockGain"
        || aCommand == "FormatMajorGrid"
        || aCommand == "FormatMinorGrid";
}

} // anonymous namespace

uno::Reference<frame::XDispatch> SAL_CALL
    ChartController::queryDispatch(
        const util::URL& rURL,
        const OUString& rTargetFrameName,
        sal_Int32 /* nSearchFlags */)
{
    SolarMutexGuard aGuard;

    if ( !m_aLifeTimeManager.impl_isDisposed() && getModel().is() )
    {
        if( !rTargetFrameName.isEmpty() && rTargetFrameName == "_self" )
            return m_aDispatchContainer.getDispatchForURL( rURL );
    }
    return uno::Reference< frame::XDispatch > ();
}

uno::Sequence<uno::Reference<frame::XDispatch > >
    ChartController::queryDispatches(
        const uno::Sequence<frame::DispatchDescriptor>& xDescripts )
{
    SolarMutexGuard g;

    if ( !m_aLifeTimeManager.impl_isDisposed() )
    {
        return m_aDispatchContainer.getDispatchesForURLs( xDescripts );
    }
    return uno::Sequence<uno::Reference<frame::XDispatch > > ();
}

// frame::XDispatch

void SAL_CALL ChartController::dispatch(
    const util::URL& rURL,
    const uno::Sequence< beans::PropertyValue >& rArgs )
{
    OUString aCommand = rURL.Path;

    if(aCommand == "LOKSetTextSelection")
    {
        if (rArgs.getLength() == 3)
        {
            sal_Int32 nType = -1;
            rArgs[0].Value >>= nType;
            sal_Int32 nX = 0;
            rArgs[1].Value >>= nX;
            sal_Int32 nY = 0;
            rArgs[2].Value >>= nY;
            executeDispatch_LOKSetTextSelection(nType, nX, nY);
        }
    }
    else if (aCommand == "LOKTransform")
    {
        if (rArgs[0].Name == "Action")
        {
            OUString sAction;
            if ((rArgs[0].Value >>= sAction) && sAction == "PieSegmentDragging")
            {
                if (rArgs[1].Name == "Offset")
                {
                    sal_Int32 nOffset;
                    if (rArgs[1].Value >>= nOffset)
                    {
                        this->executeDispatch_LOKPieSegmentDragging(nOffset);
                    }
                }
            }
        }
        else
        {
            this->executeDispatch_PositionAndSize(&rArgs);
        }
    }
    else if(aCommand == "Paste")
        this->executeDispatch_Paste();
    else if(aCommand == "Copy" )
        this->executeDispatch_Copy();
    else if(aCommand == "Cut" )
        this->executeDispatch_Cut();
    else if(aCommand == "DataRanges" )
        this->executeDispatch_SourceData();
    else if(aCommand == "Update" ) //Update Chart
    {
        ChartViewHelper::setViewToDirtyState( getModel() );
        SolarMutexGuard aGuard;
        auto pChartWindow(GetChartWindow());
        if( pChartWindow )
            pChartWindow->Invalidate();
    }
    else if(aCommand == "DiagramData" )
        this->executeDispatch_EditData();
    //insert objects
    else if( aCommand == "InsertTitles"
        || aCommand == "InsertMenuTitles")
        this->executeDispatch_InsertTitles();
    else if( aCommand == "InsertMenuLegend" )
        this->executeDispatch_OpenLegendDialog();
    else if( aCommand == "InsertLegend" )
        this->executeDispatch_InsertLegend();
    else if( aCommand == "DeleteLegend" )
        this->executeDispatch_DeleteLegend();
    else if( aCommand == "InsertMenuDataLabels" )
        this->executeDispatch_InsertMenu_DataLabels();
    else if( aCommand == "InsertMenuAxes"
        || aCommand == "InsertRemoveAxes" )
        this->executeDispatch_InsertAxes();
    else if( aCommand == "InsertMenuGrids" )
        this->executeDispatch_InsertGrid();
    else if( aCommand == "InsertMenuTrendlines" )
        this->executeDispatch_InsertMenu_Trendlines();
    else if( aCommand == "InsertMenuMeanValues" )
        this->executeDispatch_InsertMenu_MeanValues();
    else if( aCommand == "InsertMenuXErrorBars" )
        this->executeDispatch_InsertErrorBars(false);
    else if( aCommand == "InsertMenuYErrorBars" )
        this->executeDispatch_InsertErrorBars(true);
    else if( aCommand == "InsertSymbol" )
         this->executeDispatch_InsertSpecialCharacter();
    else if( aCommand == "InsertTrendline" )
         this->executeDispatch_InsertTrendline();
    else if( aCommand == "DeleteTrendline" )
         this->executeDispatch_DeleteTrendline();
    else if( aCommand == "InsertMeanValue" )
        this->executeDispatch_InsertMeanValue();
    else if( aCommand == "DeleteMeanValue" )
        this->executeDispatch_DeleteMeanValue();
    else if( aCommand == "InsertXErrorBars" )
        this->executeDispatch_InsertErrorBars(false);
    else if( aCommand == "InsertYErrorBars" )
        this->executeDispatch_InsertErrorBars(true);
    else if( aCommand == "DeleteXErrorBars" )
        this->executeDispatch_DeleteErrorBars(false);
    else if( aCommand == "DeleteYErrorBars" )
        this->executeDispatch_DeleteErrorBars(true);
    else if( aCommand == "InsertTrendlineEquation" )
         this->executeDispatch_InsertTrendlineEquation();
    else if( aCommand == "DeleteTrendlineEquation" )
         this->executeDispatch_DeleteTrendlineEquation();
    else if( aCommand == "InsertTrendlineEquationAndR2" )
         this->executeDispatch_InsertTrendlineEquation( true );
    else if( aCommand == "InsertR2Value" )
         this->executeDispatch_InsertR2Value();
    else if( aCommand == "DeleteR2Value")
         this->executeDispatch_DeleteR2Value();
    else if( aCommand == "InsertDataLabels" )
        this->executeDispatch_InsertDataLabels();
    else if( aCommand == "InsertDataLabel" )
        this->executeDispatch_InsertDataLabel();
    else if( aCommand == "DeleteDataLabels")
        this->executeDispatch_DeleteDataLabels();
    else if( aCommand == "DeleteDataLabel" )
        this->executeDispatch_DeleteDataLabel();
    else if( aCommand == "ResetAllDataPoints" )
        this->executeDispatch_ResetAllDataPoints();
    else if( aCommand == "ResetDataPoint" )
        this->executeDispatch_ResetDataPoint();
    else if( aCommand == "InsertAxis" )
        this->executeDispatch_InsertAxis();
    else if( aCommand == "InsertMajorGrid" )
        this->executeDispatch_InsertMajorGrid();
    else if( aCommand == "InsertMinorGrid" )
        this->executeDispatch_InsertMinorGrid();
    else if( aCommand == "InsertAxisTitle" )
        this->executeDispatch_InsertAxisTitle();
    else if( aCommand == "DeleteAxis" )
        this->executeDispatch_DeleteAxis();
    else if( aCommand == "DeleteMajorGrid")
        this->executeDispatch_DeleteMajorGrid();
    else if( aCommand == "DeleteMinorGrid" )
        this->executeDispatch_DeleteMinorGrid();
    //format objects
    else if( aCommand == "FormatSelection" )
        this->executeDispatch_ObjectProperties();
    else if( aCommand == "TransformDialog" )
    {
        if ( isShapeContext() )
        {
            this->impl_ShapeControllerDispatch( rURL, rArgs );
        }
        else
        {
            this->executeDispatch_PositionAndSize();
        }
    }
    else if( lcl_isFormatObjectCommand(aCommand) )
        this->executeDispatch_FormatObject(rURL.Path);
    //more format
    else if( aCommand == "DiagramType" )
        this->executeDispatch_ChartType();
    else if( aCommand == "View3D" )
        this->executeDispatch_View3D();
    else if ( aCommand == "Forward" )
    {
        if ( isShapeContext() )
        {
            this->impl_ShapeControllerDispatch( rURL, rArgs );
        }
        else
        {
            this->executeDispatch_MoveSeries( true );
        }
    }
    else if ( aCommand == "Backward" )
    {
        if ( isShapeContext() )
        {
            this->impl_ShapeControllerDispatch( rURL, rArgs );
        }
        else
        {
            this->executeDispatch_MoveSeries( false );
        }
    }
    else if( aCommand == "NewArrangement")
        this->executeDispatch_NewArrangement();
    else if( aCommand == "ToggleLegend" )
        this->executeDispatch_ToggleLegend();
    else if( aCommand == "ToggleGridHorizontal" )
        this->executeDispatch_ToggleGridHorizontal();
    else if( aCommand == "ToggleGridVertical" )
        this->executeDispatch_ToggleGridVertical();
    else if( aCommand == "ScaleText" )
        this->executeDispatch_ScaleText();
    else if( aCommand == "StatusBarVisible" )
    {
        // workaround: this should not be necessary.
        uno::Reference< beans::XPropertySet > xPropSet( m_xFrame, uno::UNO_QUERY );
        if( xPropSet.is() )
        {
            uno::Reference< css::frame::XLayoutManager > xLayoutManager;
            xPropSet->getPropertyValue( "LayoutManager" ) >>= xLayoutManager;
            if ( xLayoutManager.is() )
            {
                bool bIsVisible( xLayoutManager->isElementVisible( "private:resource/statusbar/statusbar" ));
                if( bIsVisible )
                {
                    xLayoutManager->hideElement( "private:resource/statusbar/statusbar" );
                    xLayoutManager->destroyElement( "private:resource/statusbar/statusbar" );
                }
                else
                {
                    xLayoutManager->createElement( "private:resource/statusbar/statusbar" );
                    xLayoutManager->showElement( "private:resource/statusbar/statusbar" );
                }
                // @todo: update menu state (checkmark next to "Statusbar").
            }
        }
    }
}

void SAL_CALL ChartController::addStatusListener(
    const uno::Reference<frame::XStatusListener >& /* xControl */,
    const util::URL& /* aURL */ )
{
    //@todo
}

void SAL_CALL ChartController::removeStatusListener(
    const uno::Reference<frame::XStatusListener >& /* xControl */,
    const util::URL& /* aURL */ )
{
    //@todo
}

// XContextMenuInterception (optional interface)
void SAL_CALL ChartController::registerContextMenuInterceptor(
    const uno::Reference< ui::XContextMenuInterceptor >& /* xInterceptor */)
{
    //@todo
}

void SAL_CALL ChartController::releaseContextMenuInterceptor(
    const uno::Reference< ui::XContextMenuInterceptor > & /* xInterceptor */)
{
    //@todo
}

// ____ XEmbeddedClient ____
// implementation see: ChartController_EditData.cxx

void ChartController::executeDispatch_ChartType()
{
    UndoLiveUpdateGuard aUndoGuard(
        SchResId( STR_ACTION_EDIT_CHARTTYPE ), m_xUndoManager );

    SolarMutexGuard aSolarGuard;
    //prepare and open dialog
    ChartTypeDialog aDlg(GetChartFrame(), getModel());
    if (aDlg.run() == RET_OK)
    {
        impl_adaptDataSeriesAutoResize();
        aUndoGuard.commit();
    }
}

void ChartController::executeDispatch_SourceData()
{
    //convert properties to ItemSet
    uno::Reference< XChartDocument >   xChartDoc( getModel(), uno::UNO_QUERY );
    OSL_ENSURE( xChartDoc.is(), "Invalid XChartDocument" );
    if( !xChartDoc.is() )
        return;

    // If there is a data table we should ask user if we really want to destroy it
    // and switch to data ranges.
    ChartModel& rModel = dynamic_cast<ChartModel&>(*xChartDoc);
    if ( rModel.hasInternalDataProvider() )
    {
        // Check if we will able to create data provider later
        css::uno::Reference< com::sun::star::chart2::XDataProviderAccess > xCreatorDoc(
            rModel.getParent(), uno::UNO_QUERY);
        if (!xCreatorDoc.is())
            return;

        SolarMutexGuard aSolarGuard;

        std::unique_ptr<weld::MessageDialog> xQueryBox(Application::CreateMessageDialog(GetChartFrame(),
                                                       VclMessageType::Question, VclButtonsType::YesNo, SchResId(STR_DLG_REMOVE_DATA_TABLE)));
        // If "No" then just return
        if (xQueryBox->run() == RET_NO)
            return;

        // Remove data table
        rModel.removeDataProviders();

        // Ask parent document to create new data provider

        uno::Reference< data::XDataProvider > xDataProvider = xCreatorDoc->createDataProvider();
        SAL_WARN_IF( !xDataProvider.is(), "chart2.main", "Data provider was not created" );
        if (xDataProvider.is())
        {
            rModel.attachDataProvider(xDataProvider);
        }
    }

    UndoLiveUpdateGuard aUndoGuard(
        SchResId(STR_ACTION_EDIT_DATA_RANGES), m_xUndoManager);

    SolarMutexGuard aSolarGuard;
    ::chart::DataSourceDialog aDlg(GetChartFrame(), xChartDoc, m_xCC);
    if (aDlg.run() == RET_OK)
    {
        impl_adaptDataSeriesAutoResize();
        aUndoGuard.commit();
    }
}

void ChartController::executeDispatch_MoveSeries( bool bForward )
{
    ControllerLockGuardUNO aCLGuard( getModel() );

    //get selected series
    OUString aObjectCID(m_aSelection.getSelectedCID());
    uno::Reference< XDataSeries > xGivenDataSeries( ObjectIdentifier::getDataSeriesForCID( //yyy todo also legend entries and labels?
            aObjectCID, getModel() ) );

    UndoGuardWithSelection aUndoGuard(
        ActionDescriptionProvider::createDescription(
            (bForward ? ActionDescriptionProvider::ActionType::MoveToTop : ActionDescriptionProvider::ActionType::MoveToBottom),
            SchResId(STR_OBJECT_DATASERIES)),
        m_xUndoManager );

    bool bChanged = DiagramHelper::moveSeries( ChartModelHelper::findDiagram( getModel() ), xGivenDataSeries, bForward );
    if( bChanged )
    {
        m_aSelection.setSelection( ObjectIdentifier::getMovedSeriesCID( aObjectCID, bForward ) );
        aUndoGuard.commit();
    }
}

// ____ XMultiServiceFactory ____
uno::Reference< uno::XInterface > SAL_CALL
    ChartController::createInstance( const OUString& aServiceSpecifier )
{
    uno::Reference< uno::XInterface > xResult;

    if( aServiceSpecifier == CHART_ACCESSIBLE_TEXT_SERVICE_NAME )
        xResult.set( impl_createAccessibleTextContext());
    return xResult;
}

uno::Reference< uno::XInterface > SAL_CALL
    ChartController::createInstanceWithArguments(
        const OUString& ServiceSpecifier,
        const uno::Sequence< uno::Any >& /* Arguments */ )
{
    // ignore Arguments
    return createInstance( ServiceSpecifier );
}

uno::Sequence< OUString > SAL_CALL
    ChartController::getAvailableServiceNames()
{
    uno::Sequence< OUString > aServiceNames { CHART_ACCESSIBLE_TEXT_SERVICE_NAME };
    return aServiceNames;
}

// ____ XModifyListener ____
void SAL_CALL ChartController::modified(
    const lang::EventObject& /* aEvent */ )
{
    // the source can also be a subobject of the ChartModel
    // @todo: change the source in ChartModel to always be the model itself ?
    //todo? update menu states ?
}

void ChartController::NotifyUndoActionHdl( std::unique_ptr<SdrUndoAction> pUndoAction )
{
    ENSURE_OR_RETURN_VOID( pUndoAction, "invalid Undo action" );

    OUString aObjectCID = m_aSelection.getSelectedCID();
    if ( !aObjectCID.isEmpty() )
        return;

    try
    {
        const Reference< document::XUndoManagerSupplier > xSuppUndo( getModel(), uno::UNO_QUERY_THROW );
        const Reference< document::XUndoManager > xUndoManager( xSuppUndo->getUndoManager(), uno::UNO_SET_THROW );
        const Reference< document::XUndoAction > xAction( new impl::ShapeUndoElement( std::move(pUndoAction) ) );
        xUndoManager->addUndoAction( xAction );
    }
    catch( const uno::Exception& )
    {
        DBG_UNHANDLED_EXCEPTION("chart2");
    }
}

DrawModelWrapper* ChartController::GetDrawModelWrapper()
{
    if( !m_pDrawModelWrapper )
    {
        ExplicitValueProvider* pProvider = comphelper::getUnoTunnelImplementation<ExplicitValueProvider>( m_xChartView );
        if( pProvider )
            m_pDrawModelWrapper = pProvider->getDrawModelWrapper();
        if ( m_pDrawModelWrapper )
        {
            m_pDrawModelWrapper->getSdrModel().SetNotifyUndoActionHdl(
                std::bind(&ChartController::NotifyUndoActionHdl, this, std::placeholders::_1) );
        }
    }
    return m_pDrawModelWrapper.get();
}

DrawViewWrapper* ChartController::GetDrawViewWrapper()
{
    if ( !m_pDrawViewWrapper )
    {
        impl_createDrawViewController();
    }
    return m_pDrawViewWrapper.get();
}


VclPtr<ChartWindow> ChartController::GetChartWindow() const
{
    // clients getting the naked VCL Window from UNO should always have the
    // solar mutex (and keep it over the lifetime of this ptr), as VCL might
    // might deinit otherwise
    DBG_TESTSOLARMUTEX();
    if(!m_xViewWindow.is())
        return nullptr;
    return dynamic_cast<ChartWindow*>(VCLUnoHelper::GetWindow(m_xViewWindow).get());
}

weld::Window* ChartController::GetChartFrame()
{
    // clients getting the naked VCL Window from UNO should always have the
    // solar mutex (and keep it over the lifetime of this ptr), as VCL might
    // might deinit otherwise
    DBG_TESTSOLARMUTEX();
    return Application::GetFrameWeld(m_xViewWindow);
}

bool ChartController::isAdditionalShapeSelected() const
{
    return m_aSelection.isAdditionalShapeSelected();
}

void ChartController::SetAndApplySelection(const Reference<drawing::XShape>& rxShape)
{
    if(rxShape.is())
    {
        m_aSelection.setSelection(rxShape);
        m_aSelection.applySelection(GetDrawViewWrapper());
    }
}



uno::Reference< XAccessible > ChartController::CreateAccessible()
{
    uno::Reference< XAccessible > xResult = new AccessibleChartView( GetDrawViewWrapper() );
    impl_initializeAccessible( uno::Reference< lang::XInitialization >( xResult, uno::UNO_QUERY ) );
    return xResult;
}

void ChartController::impl_invalidateAccessible()
{
    SolarMutexGuard aGuard;
    auto pChartWindow(GetChartWindow());
    if( pChartWindow )
    {
        Reference< lang::XInitialization > xInit( pChartWindow->GetAccessible(false), uno::UNO_QUERY );
        if(xInit.is())
        {
            uno::Sequence< uno::Any > aArguments(3);//empty arguments -> invalid accessible
            xInit->initialize(aArguments);
        }
    }
}
void ChartController::impl_initializeAccessible()
{
    SolarMutexGuard aGuard;
    auto pChartWindow(GetChartWindow());
    if( pChartWindow )
        this->impl_initializeAccessible( Reference< lang::XInitialization >( pChartWindow->GetAccessible(false), uno::UNO_QUERY ) );
}
void ChartController::impl_initializeAccessible( const uno::Reference< lang::XInitialization >& xInit )
{
    if(!xInit.is())
        return;

    uno::Sequence< uno::Any > aArguments(5);
    aArguments[0] <<= uno::Reference<view::XSelectionSupplier>(this);
    aArguments[1] <<= getModel();
    aArguments[2] <<= m_xChartView;
    uno::Reference< XAccessible > xParent;
    {
        SolarMutexGuard aGuard;
        auto pChartWindow(GetChartWindow());
        if( pChartWindow )
        {
            vcl::Window* pParentWin( pChartWindow->GetAccessibleParentWindow());
            if( pParentWin )
                xParent.set( pParentWin->GetAccessible());
        }
    }
    aArguments[3] <<= xParent;
    aArguments[4] <<= m_xViewWindow;

    xInit->initialize(aArguments);
}

const o3tl::sorted_vector< OUString >& ChartController::impl_getAvailableCommands()
{
    static const o3tl::sorted_vector< OUString > s_AvailableCommands {
        // commands for container forward
        "AddDirect",           "NewDoc",                "Open",
        "Save",                "SaveAs",                "SendMail",
        "EditDoc",             "ExportDirectToPDF",     "PrintDefault",

        // own commands
        "Cut",                "Copy",                 "Paste",
        "DataRanges",         "DiagramData",
        // insert objects
        "InsertMenuTitles",   "InsertTitles",
        "InsertMenuLegend",   "InsertLegend",         "DeleteLegend",
        "InsertMenuDataLabels",
        "InsertMenuAxes",     "InsertRemoveAxes",         "InsertMenuGrids",
        "InsertSymbol",
        "InsertTrendlineEquation",  "InsertTrendlineEquationAndR2",
        "InsertR2Value",      "DeleteR2Value",
        "InsertMenuTrendlines",  "InsertTrendline",
        "InsertMenuMeanValues", "InsertMeanValue",
        "InsertMenuXErrorBars",  "InsertXErrorBars",
        "InsertMenuYErrorBars",   "InsertYErrorBars",
        "InsertDataLabels",   "InsertDataLabel",
        "DeleteTrendline",    "DeleteMeanValue",      "DeleteTrendlineEquation",
        "DeleteXErrorBars",   "DeleteYErrorBars",
        "DeleteDataLabels",   "DeleteDataLabel",
        //format objects
        "FormatSelection",     "TransformDialog",
        "DiagramType",        "View3D",
        "Forward",            "Backward",
        "MainTitle",          "SubTitle",
        "XTitle",             "YTitle",               "ZTitle",
        "SecondaryXTitle",    "SecondaryYTitle",
        "AllTitles",          "Legend",
        "DiagramAxisX",       "DiagramAxisY",         "DiagramAxisZ",
        "DiagramAxisA",       "DiagramAxisB",         "DiagramAxisAll",
        "DiagramGridXMain",   "DiagramGridYMain",     "DiagramGridZMain",
        "DiagramGridXHelp",   "DiagramGridYHelp",     "DiagramGridZHelp",
        "DiagramGridAll",
        "DiagramWall",        "DiagramFloor",         "DiagramArea",

        //context menu - format objects entries
        "FormatWall",        "FormatFloor",         "FormatChartArea",
        "FormatLegend",

        "FormatAxis",           "FormatTitle",
        "FormatDataSeries",     "FormatDataPoint",
        "ResetAllDataPoints",   "ResetDataPoint",
        "FormatDataLabels",     "FormatDataLabel",
        "FormatMeanValue",      "FormatTrendline",      "FormatTrendlineEquation",
        "FormatXErrorBars",     "FormatYErrorBars",
        "FormatStockLoss",      "FormatStockGain",

        "FormatMajorGrid",      "InsertMajorGrid",      "DeleteMajorGrid",
        "FormatMinorGrid",      "InsertMinorGrid",      "DeleteMinorGrid",
        "InsertAxis",           "DeleteAxis",           "InsertAxisTitle",

        // toolbar commands
        "ToggleGridHorizontal", "ToggleGridVertical", "ToggleLegend",         "ScaleText",
        "NewArrangement",     "Update",
        "DefaultColors",      "BarWidth",             "NumberOfLines",
        "ArrangeRow",
        "StatusBarVisible",
        "ChartElementSelector"};
    return s_AvailableCommands;
}

ViewElementListProvider ChartController::getViewElementListProvider()
{
    return ViewElementListProvider(m_pDrawModelWrapper.get());
}

} //namespace chart

extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface *
com_sun_star_comp_chart2_ChartController_get_implementation(css::uno::XComponentContext *context,
                                                            css::uno::Sequence<css::uno::Any> const &)
{
    return cppu::acquire(new chart::ChartController(context));
}

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