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
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
/* -*- 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 <config_features.h>

#include <osl/file.hxx>
#include <osl/thread.hxx>
#include <osl/module.hxx>
#include <rtl/ustrbuf.hxx>

#include <sal/log.hxx>

#include <tools/debug.hxx>
#include <tools/time.hxx>
#include <tools/stream.hxx>

#include <unotools/configmgr.hxx>
#include <unotools/syslocaleoptions.hxx>

#include <vcl/toolkit/dialog.hxx>
#include <vcl/dialoghelper.hxx>
#include <vcl/lok.hxx>
#include <vcl/floatwin.hxx>
#include <vcl/settings.hxx>
#include <vcl/keycod.hxx>
#include <vcl/event.hxx>
#include <vcl/vclevent.hxx>
#include <vcl/virdev.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/svapp.hxx>
#include <vcl/cvtgrf.hxx>
#include <vcl/toolkit/unowrap.hxx>
#include <vcl/timer.hxx>
#include <vcl/scheduler.hxx>
#if HAVE_FEATURE_OPENGL
#include <vcl/opengl/OpenGLWrapper.hxx>
#endif
#include <vcl/skia/SkiaHelper.hxx>

#include <salinst.hxx>
#include <salframe.hxx>
#include <salsys.hxx>
#include <svdata.hxx>
#include <displayconnectiondispatch.hxx>
#include <window.h>
#include <accmgr.hxx>
#include <strings.hrc>
#include <strings.hxx>
#if OSL_DEBUG_LEVEL > 0
#include <schedulerimpl.hxx>
#endif

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/awt/XToolkit.hpp>
#include <comphelper/lok.hxx>
#include <comphelper/solarmutex.hxx>
#include <osl/process.h>

#include <cassert>
#include <utility>
#include <thread>

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

namespace {
void InitSettings(ImplSVData* pSVData);
}

// keycodes handled internally by VCL
static vcl::KeyCode const ReservedKeys[]
{
                vcl::KeyCode(KEY_F1,0)                  ,
                vcl::KeyCode(KEY_F1,KEY_SHIFT)          ,
                vcl::KeyCode(KEY_F1,KEY_MOD1)           ,
                vcl::KeyCode(KEY_F2,KEY_SHIFT)          ,
                vcl::KeyCode(KEY_F4,KEY_MOD1)           ,
                vcl::KeyCode(KEY_F4,KEY_MOD2)           ,
                vcl::KeyCode(KEY_F4,KEY_MOD1|KEY_MOD2)  ,
                vcl::KeyCode(KEY_F6,0)                  ,
                vcl::KeyCode(KEY_F6,KEY_MOD1)           ,
                vcl::KeyCode(KEY_F6,KEY_SHIFT)          ,
                vcl::KeyCode(KEY_F6,KEY_MOD1|KEY_SHIFT) ,
                vcl::KeyCode(KEY_F10,0)
#ifdef UNX
                ,
                vcl::KeyCode(KEY_1,KEY_SHIFT|KEY_MOD1),
                vcl::KeyCode(KEY_2,KEY_SHIFT|KEY_MOD1),
                vcl::KeyCode(KEY_3,KEY_SHIFT|KEY_MOD1),
                vcl::KeyCode(KEY_4,KEY_SHIFT|KEY_MOD1),
                vcl::KeyCode(KEY_5,KEY_SHIFT|KEY_MOD1),
                vcl::KeyCode(KEY_6,KEY_SHIFT|KEY_MOD1),
                vcl::KeyCode(KEY_7,KEY_SHIFT|KEY_MOD1),
                vcl::KeyCode(KEY_8,KEY_SHIFT|KEY_MOD1),
                vcl::KeyCode(KEY_9,KEY_SHIFT|KEY_MOD1),
                vcl::KeyCode(KEY_0,KEY_SHIFT|KEY_MOD1),
                vcl::KeyCode(KEY_ADD,KEY_SHIFT|KEY_MOD1)
#endif
};

extern "C" {
    typedef UnoWrapperBase* (*FN_TkCreateUnoWrapper)();
}

struct ImplPostEventData
{
    VclEventId      mnEvent;
    VclPtr<vcl::Window> mpWin;
    ImplSVEvent *   mnEventId;
    KeyEvent        maKeyEvent;
    MouseEvent      maMouseEvent;
    GestureEvent    maGestureEvent;

    ImplPostEventData(VclEventId nEvent, vcl::Window* pWin, const KeyEvent& rKeyEvent)
        : mnEvent(nEvent)
        , mpWin(pWin)
        , mnEventId(nullptr)
        , maKeyEvent(rKeyEvent)
    {}
    ImplPostEventData(VclEventId nEvent, vcl::Window* pWin, const MouseEvent& rMouseEvent)
        : mnEvent(nEvent)
        , mpWin(pWin)
        , mnEventId(nullptr)
        , maMouseEvent(rMouseEvent)
    {}
    ImplPostEventData(VclEventId nEvent, vcl::Window* pWin, const GestureEvent& rGestureEvent)
        : mnEvent(nEvent)
        , mpWin(pWin)
        , mnEventId(nullptr)
        , maGestureEvent(rGestureEvent)
    {}
};

Application* GetpApp()
{
    ImplSVData* pSVData = ImplGetSVData();
    if ( !pSVData )
        return nullptr;
    return pSVData->mpApp;
}

Application::Application()
{
    // useful for themes at least, perhaps extensions too
    OUString aVar("LIBO_VERSION"), aValue(LIBO_VERSION_DOTTED);
    osl_setEnvironment(aVar.pData, aValue.pData);

    ImplGetSVData()->mpApp = this;
}

Application::~Application()
{
    ImplDeInitSVData();
    ImplGetSVData()->mpApp = nullptr;
}

int Application::Main()
{
    SAL_WARN("vcl", "Application is a base class and should be overridden.");
    return EXIT_SUCCESS;
}

bool Application::QueryExit()
{
    WorkWindow* pAppWin = ImplGetSVData()->maFrameData.mpAppWin;

    // call the close handler of the application window
    if ( pAppWin )
        return pAppWin->Close();
    else
        return true;
}

void Application::Shutdown()
{
}

void Application::Init()
{
}

void Application::InitFinished()
{
}

void Application::DeInit()
{
}

sal_uInt16 Application::GetCommandLineParamCount()
{
    return static_cast<sal_uInt16>(osl_getCommandArgCount());
}

OUString Application::GetCommandLineParam( sal_uInt16 nParam )
{
    OUString aParam;
    osl_getCommandArg( nParam, &aParam.pData );
    return aParam;
}

OUString Application::GetAppFileName()
{
    ImplSVData* pSVData = ImplGetSVData();
    SAL_WARN_IF( !pSVData->maAppData.mxAppFileName, "vcl", "AppFileName should be set to something after SVMain!" );
    if ( pSVData->maAppData.mxAppFileName )
        return *pSVData->maAppData.mxAppFileName;

    /*
     *  provide a fallback for people without initialized vcl here (like setup
     *  in responsefile mode)
     */
    OUString aAppFileName;
    OUString aExeFileName;
    osl_getExecutableFile(&aExeFileName.pData);

    // convert path to native file format
    osl::FileBase::getSystemPathFromFileURL(aExeFileName, aAppFileName);

    return aAppFileName;
}

void Application::Exception( ExceptionCategory nCategory )
{
    switch ( nCategory )
    {
        // System has precedence (so do nothing)
        case ExceptionCategory::System:
        case ExceptionCategory::UserInterface:
            break;

#ifdef DBG_UTIL
        case ExceptionCategory::ResourceNotLoaded:
            Abort("Resource not loaded");
            break;
        default:
            Abort("Unknown Error");
            break;
#else
        default:
            Abort(OUString());
            break;
#endif
    }
}

void Application::Abort( const OUString& rErrorText )
{
    //HACK: Dump core iff --norestore command line argument is given (assuming
    // this process is run by developers who are interested in cores, vs. end
    // users who are not):
#if OSL_DEBUG_LEVEL > 0
    bool dumpCore = true;
#else
    bool dumpCore = false;
    sal_uInt16 n = GetCommandLineParamCount();
    for (sal_uInt16 i = 0; i != n; ++i) {
        if (GetCommandLineParam(i) == "--norestore") {
            dumpCore = true;
            break;
        }
    }
#endif

    SalAbort( rErrorText, dumpCore );
}

size_t Application::GetReservedKeyCodeCount()
{
    return SAL_N_ELEMENTS(ReservedKeys);
}

const vcl::KeyCode* Application::GetReservedKeyCode( size_t i )
{
    if( i >= GetReservedKeyCodeCount() )
        return nullptr;
    else
        return &ReservedKeys[i];
}

IMPL_STATIC_LINK_NOARG( ImplSVAppData, ImplEndAllPopupsMsg, void*, void )
{
    ImplSVData* pSVData = ImplGetSVData();
    while (pSVData->mpWinData->mpFirstFloat)
        pSVData->mpWinData->mpFirstFloat->EndPopupMode(FloatWinPopupEndFlags::Cancel);
}

IMPL_STATIC_LINK_NOARG( ImplSVAppData, ImplEndAllDialogsMsg, void*, void )
{
    vcl::Window* pAppWindow = Application::GetFirstTopLevelWindow();
    while (pAppWindow)
    {
        vcl::EndAllDialogs(pAppWindow);
        pAppWindow = Application::GetNextTopLevelWindow(pAppWindow);
    }
}

void Application::EndAllDialogs()
{
    Application::PostUserEvent( LINK( nullptr, ImplSVAppData, ImplEndAllDialogsMsg ) );
}

void Application::EndAllPopups()
{
    Application::PostUserEvent( LINK( nullptr, ImplSVAppData, ImplEndAllPopupsMsg ) );
}


namespace
{
    VclPtr<vcl::Window> GetEventWindow()
    {
        VclPtr<vcl::Window> xWin(Application::GetFirstTopLevelWindow());
        while (xWin)
        {
            if (xWin->IsVisible())
                break;
            xWin.reset(Application::GetNextTopLevelWindow(xWin));
        }
        return xWin;
    }

    bool InjectKeyEvent(SvStream& rStream)
    {
        VclPtr<vcl::Window> xWin(GetEventWindow());
        if (!xWin)
            return false;

        // skip the first available cycle and insert on the next one when we
        // are trying the initial event, flagged by a triggered but undeleted
        // mpEventTestingIdle
        ImplSVData* pSVData = ImplGetSVData();
        if (pSVData->maAppData.mpEventTestingIdle)
        {
            delete pSVData->maAppData.mpEventTestingIdle;
            pSVData->maAppData.mpEventTestingIdle = nullptr;
            return false;
        }

        sal_uInt16 nCode, nCharCode;
        rStream.ReadUInt16(nCode);
        rStream.ReadUInt16(nCharCode);
        if (!rStream.good())
            return false;

        KeyEvent aVCLKeyEvt(nCharCode, nCode);
        Application::PostKeyEvent(VclEventId::WindowKeyInput, xWin.get(), &aVCLKeyEvt);
        Application::PostKeyEvent(VclEventId::WindowKeyUp, xWin.get(), &aVCLKeyEvt);
        return true;
    }

    void CloseDialogsAndQuit()
    {
        Application::EndAllPopups();
        Application::EndAllDialogs();
        Application::PostUserEvent( LINK( nullptr, ImplSVAppData, ImplPrepareExitMsg ) );
    }
}

IMPL_LINK_NOARG(ImplSVAppData, VclEventTestingHdl, Timer *, void)
{
    if (Application::AnyInput())
    {
        mpEventTestingIdle->Start();
    }
    else
    {
        Application::PostUserEvent( LINK( nullptr, ImplSVAppData, ImplVclEventTestingHdl ) );
    }
}

IMPL_STATIC_LINK_NOARG( ImplSVAppData, ImplVclEventTestingHdl, void*, void )
{
    ImplSVData* pSVData = ImplGetSVData();
    SAL_INFO("vcl.eventtesting", "EventTestLimit is " << pSVData->maAppData.mnEventTestLimit);
    if (pSVData->maAppData.mnEventTestLimit == 0)
    {
        delete pSVData->maAppData.mpEventTestInput;
        SAL_INFO("vcl.eventtesting", "Event Limit reached, exiting" << pSVData->maAppData.mnEventTestLimit);
        CloseDialogsAndQuit();
    }
    else
    {
        if (InjectKeyEvent(*pSVData->maAppData.mpEventTestInput))
            --pSVData->maAppData.mnEventTestLimit;
        if (!pSVData->maAppData.mpEventTestInput->good())
        {
            SAL_INFO("vcl.eventtesting", "Event Input exhausted, exit next cycle");
            pSVData->maAppData.mnEventTestLimit = 0;
        }
        Application::PostUserEvent( LINK( nullptr, ImplSVAppData, ImplVclEventTestingHdl ) );
    }
}

IMPL_STATIC_LINK_NOARG( ImplSVAppData, ImplPrepareExitMsg, void*, void )
{
    //now close top level frames
    (void)GetpApp()->QueryExit();
}

void Application::Execute()
{
    ImplSVData* pSVData = ImplGetSVData();
    pSVData->maAppData.mbInAppExecute = true;
    pSVData->maAppData.mbAppQuit = false;

    if (Application::IsEventTestingModeEnabled())
    {
        pSVData->maAppData.mnEventTestLimit = 50;
        pSVData->maAppData.mpEventTestingIdle = new Idle("eventtesting");
        pSVData->maAppData.mpEventTestingIdle->SetInvokeHandler(LINK(&(pSVData->maAppData), ImplSVAppData, VclEventTestingHdl));
        pSVData->maAppData.mpEventTestingIdle->SetPriority(TaskPriority::HIGH_IDLE);
        pSVData->maAppData.mpEventTestInput = new SvFileStream("eventtesting", StreamMode::READ);
        pSVData->maAppData.mpEventTestingIdle->Start();
    }

    while ( !pSVData->maAppData.mbAppQuit )
        Application::Yield();

    pSVData->maAppData.mbInAppExecute = false;

    GetpApp()->Shutdown();
}

static bool ImplYield(bool i_bWait, bool i_bAllEvents)
{
    ImplSVData* pSVData = ImplGetSVData();

    SAL_INFO("vcl.schedule", "Enter ImplYield: " << (i_bWait ? "wait" : "no wait") <<
             ": " << (i_bAllEvents ? "all events" : "one event"));

    // there's a data race here on WNT only because ImplYield may be
    // called without SolarMutex; but the only remaining use of mnDispatchLevel
    // is in OSX specific code
    pSVData->maAppData.mnDispatchLevel++;

    // do not wait for events if application was already quit; in that
    // case only dispatch events already available
    bool bProcessedEvent = pSVData->mpDefInst->DoYield(
            i_bWait && !pSVData->maAppData.mbAppQuit, i_bAllEvents );

    pSVData->maAppData.mnDispatchLevel--;

    DBG_TESTSOLARMUTEX(); // must be locked on return from Yield

    SAL_INFO("vcl.schedule", "Leave ImplYield with return " << bProcessedEvent );
    return bProcessedEvent;
}

bool Application::Reschedule( bool i_bAllEvents )
{
    return ImplYield(false, i_bAllEvents);
}

void Scheduler::ProcessEventsToIdle()
{
    int nSanity = 1;
    while( Application::Reschedule( true ) )
    {
        if (0 == ++nSanity % 1000)
        {
            SAL_WARN("vcl.schedule", "ProcessEventsToIdle: " << nSanity);
        }
    }
#if OSL_DEBUG_LEVEL > 0
    // If we yield from a non-main thread we just can guarantee that all idle
    // events were processed at some point, but our check can't prevent further
    // processing in the main thread, which may add new events, so skip it.
    const ImplSVData* pSVData = ImplGetSVData();
    if ( !pSVData->mpDefInst->IsMainThread() )
        return;
    for (int nTaskPriority = 0; nTaskPriority < PRIO_COUNT; ++nTaskPriority)
    {
        const ImplSchedulerData* pSchedulerData = pSVData->maSchedCtx.mpFirstSchedulerData[nTaskPriority];
        while (pSchedulerData)
        {
            if (pSchedulerData->mpTask && !pSchedulerData->mbInScheduler)
            {
                Idle *pIdle = dynamic_cast<Idle*>(pSchedulerData->mpTask);
                if (pIdle && pIdle->IsActive())
                {
                    SAL_WARN("vcl.schedule", "Unprocessed Idle: "
                             << pIdle << " " << pIdle->GetDebugName());
                }
            }
            pSchedulerData = pSchedulerData->mpNext;
        }
    }
#endif
}

extern "C" {
/// used by unit tests that test only via the LOK API
SAL_DLLPUBLIC_EXPORT void unit_lok_process_events_to_idle()<--- The function 'unit_lok_process_events_to_idle' is never used.
{
    const SolarMutexGuard aGuard;
    Scheduler::ProcessEventsToIdle();
}
}

void Application::Yield()
{
    ImplYield(true, false);
}

IMPL_STATIC_LINK_NOARG( ImplSVAppData, ImplQuitMsg, void*, void )
{
    assert(ImplGetSVData()->maAppData.mbAppQuit);
}

void Application::Quit()
{
    ImplGetSVData()->maAppData.mbAppQuit = true;
    Application::PostUserEvent( LINK( nullptr, ImplSVAppData, ImplQuitMsg ) );
}

comphelper::SolarMutex& Application::GetSolarMutex()
{
    ImplSVData* pSVData = ImplGetSVData();
    return *(pSVData->mpDefInst->GetYieldMutex());
}

bool Application::IsMainThread()
{
    return ImplGetSVData()->mnMainThreadId == osl::Thread::getCurrentIdentifier();
}

sal_uInt32 Application::ReleaseSolarMutex()
{
    ImplSVData* pSVData = ImplGetSVData();
    return pSVData->mpDefInst->ReleaseYieldMutexAll();
}

void Application::AcquireSolarMutex( sal_uInt32 nCount )
{
    ImplSVData* pSVData = ImplGetSVData();
    pSVData->mpDefInst->AcquireYieldMutex( nCount );
}

bool Application::IsInMain()
{
    ImplSVData* pSVData = ImplGetSVData();
    return pSVData && pSVData->maAppData.mbInAppMain;
}

bool Application::IsInExecute()
{
    return ImplGetSVData()->maAppData.mbInAppExecute;
}

bool Application::IsInModalMode()
{
    return (ImplGetSVData()->maAppData.mnModalMode != 0);
}

sal_uInt16 Application::GetDispatchLevel()
{
    return ImplGetSVData()->maAppData.mnDispatchLevel;
}

bool Application::AnyInput( VclInputFlags nType )
{
    return ImplGetSVData()->mpDefInst->AnyInput( nType );
}

sal_uInt64 Application::GetLastInputInterval()
{
    return (tools::Time::GetSystemTicks()-ImplGetSVData()->maAppData.mnLastInputTime);
}

bool Application::IsUICaptured()
{
    ImplSVData* pSVData = ImplGetSVData();

    // If mouse was captured, or if in tracking- or in select-mode of a floatingwindow (e.g. menus
    // or pulldown toolboxes) another window should be created
    // D&D active !!!
    return pSVData->mpWinData->mpCaptureWin || pSVData->mpWinData->mpTrackWin
           || pSVData->mpWinData->mpFirstFloat || nImplSysDialog;
}

void Application::OverrideSystemSettings( AllSettings& /*rSettings*/ )
{
}

void Application::MergeSystemSettings( AllSettings& rSettings )
{
    vcl::Window* pWindow = ImplGetSVData()->maFrameData.mpFirstFrame;
    if( ! pWindow )
        pWindow = ImplGetDefaultWindow();
    if( pWindow )
    {
        ImplSVData* pSVData = ImplGetSVData();
        if ( !pSVData->maAppData.mbSettingsInit )
        {
            // side effect: ImplUpdateGlobalSettings does an ImplGetFrame()->UpdateSettings
            pWindow->ImplUpdateGlobalSettings( *pSVData->maAppData.mpSettings );
            pSVData->maAppData.mbSettingsInit = true;
        }
        // side effect: ImplUpdateGlobalSettings does an ImplGetFrame()->UpdateSettings
        pWindow->ImplUpdateGlobalSettings( rSettings, false );
    }
}

void Application::SetSettings( const AllSettings& rSettings )
{
    const SolarMutexGuard aGuard;

    ImplSVData* pSVData = ImplGetSVData();
    if ( !pSVData->maAppData.mpSettings )
    {
        InitSettings(pSVData);
        *pSVData->maAppData.mpSettings = rSettings;
    }
    else
    {
        AllSettings aOldSettings = *pSVData->maAppData.mpSettings;
        if (aOldSettings.GetUILanguageTag().getLanguageType() != rSettings.GetUILanguageTag().getLanguageType() &&
                pSVData->mbResLocaleSet)
        {
            pSVData->mbResLocaleSet = false;
        }
        *pSVData->maAppData.mpSettings = rSettings;
        AllSettingsFlags nChangeFlags = aOldSettings.GetChangeFlags( *pSVData->maAppData.mpSettings );
        if ( bool(nChangeFlags) )
        {
            DataChangedEvent aDCEvt( DataChangedEventType::SETTINGS, &aOldSettings, nChangeFlags );

            // notify data change handler
            ImplCallEventListenersApplicationDataChanged( &aDCEvt);

            // Update all windows
            vcl::Window* pFirstFrame = pSVData->maFrameData.mpFirstFrame;
            // Reset data that needs to be re-calculated
            long nOldDPIX = 0;
            long nOldDPIY = 0;
            if ( pFirstFrame )
            {
                nOldDPIX = pFirstFrame->GetDPIX();
                nOldDPIY = pFirstFrame->GetDPIY();
                vcl::Window::ImplInitAppFontData(pFirstFrame);
            }
            vcl::Window* pFrame = pFirstFrame;
            while ( pFrame )
            {
                // call UpdateSettings from ClientWindow in order to prevent updating data twice
                vcl::Window* pClientWin = pFrame;
                while ( pClientWin->ImplGetClientWindow() )
                    pClientWin = pClientWin->ImplGetClientWindow();
                pClientWin->UpdateSettings( rSettings, true );

                vcl::Window* pTempWin = pFrame->mpWindowImpl->mpFrameData->mpFirstOverlap;
                while ( pTempWin )
                {
                    // call UpdateSettings from ClientWindow in order to prevent updating data twice
                    pClientWin = pTempWin;
                    while ( pClientWin->ImplGetClientWindow() )
                        pClientWin = pClientWin->ImplGetClientWindow();
                    pClientWin->UpdateSettings( rSettings, true );
                    pTempWin = pTempWin->mpWindowImpl->mpNextOverlap;
                }

                pFrame = pFrame->mpWindowImpl->mpFrameData->mpNextFrame;
            }

            // if DPI resolution for screen output was changed set the new resolution for all
            // screen compatible VirDev's
            pFirstFrame = pSVData->maFrameData.mpFirstFrame;
            if ( pFirstFrame )
            {
                if ( (pFirstFrame->GetDPIX() != nOldDPIX) ||
                     (pFirstFrame->GetDPIY() != nOldDPIY) )
                {
                    VirtualDevice* pVirDev = pSVData->maGDIData.mpFirstVirDev;
                    while ( pVirDev )
                    {
                        if ( pVirDev->mbScreenComp &&
                             (pVirDev->GetDPIX() == nOldDPIX) &&
                             (pVirDev->GetDPIY() == nOldDPIY) )
                        {
                            pVirDev->SetDPIX( pFirstFrame->GetDPIX() );
                            pVirDev->SetDPIY( pFirstFrame->GetDPIY() );
                            if ( pVirDev->IsMapModeEnabled() )
                            {
                                MapMode aMapMode = pVirDev->GetMapMode();
                                pVirDev->SetMapMode();
                                pVirDev->SetMapMode( aMapMode );
                            }
                        }

                        pVirDev = pVirDev->mpNext;
                    }
                }
            }
        }
    }
}

const AllSettings& Application::GetSettings()
{
    ImplSVData* pSVData = ImplGetSVData();
    if ( !pSVData->maAppData.mpSettings )
    {
        InitSettings(pSVData);
    }

    return *(pSVData->maAppData.mpSettings);
}

namespace {

void InitSettings(ImplSVData* pSVData)
{
    assert(!pSVData->maAppData.mpSettings && "initialization should not happen twice!");

    pSVData->maAppData.mpSettings.reset(new AllSettings());
    if (!utl::ConfigManager::IsFuzzing())
    {
        pSVData->maAppData.mpCfgListener = new LocaleConfigurationListener;
        pSVData->maAppData.mpSettings->GetSysLocale().GetOptions().AddListener( pSVData->maAppData.mpCfgListener );
    }
}

}

void Application::NotifyAllWindows( DataChangedEvent& rDCEvt )
{
    ImplSVData* pSVData = ImplGetSVData();
    vcl::Window* pFrame = pSVData->maFrameData.mpFirstFrame;
    while ( pFrame )
    {
        pFrame->NotifyAllChildren( rDCEvt );

        vcl::Window* pSysWin = pFrame->mpWindowImpl->mpFrameData->mpFirstOverlap;
        while ( pSysWin )
        {
            pSysWin->NotifyAllChildren( rDCEvt );
            pSysWin = pSysWin->mpWindowImpl->mpNextOverlap;
        }

        pFrame = pFrame->mpWindowImpl->mpFrameData->mpNextFrame;
    }
}

void Application::ImplCallEventListenersApplicationDataChanged( void* pData )
{
    ImplSVData* pSVData = ImplGetSVData();
    VclWindowEvent aEvent( nullptr, VclEventId::ApplicationDataChanged, pData );

    pSVData->maAppData.maEventListeners.Call( aEvent );
}

void Application::ImplCallEventListeners( VclSimpleEvent& rEvent )
{
    ImplSVData* pSVData = ImplGetSVData();
    pSVData->maAppData.maEventListeners.Call( rEvent );
}

void Application::AddEventListener( const Link<VclSimpleEvent&,void>& rEventListener )
{
    ImplSVData* pSVData = ImplGetSVData();
    pSVData->maAppData.maEventListeners.addListener( rEventListener );
}

void Application::RemoveEventListener( const Link<VclSimpleEvent&,void>& rEventListener )
{
    ImplSVData* pSVData = ImplGetSVData();
    pSVData->maAppData.maEventListeners.removeListener( rEventListener );
}

void Application::AddKeyListener( const Link<VclWindowEvent&,bool>& rKeyListener )
{
    ImplSVData* pSVData = ImplGetSVData();
    pSVData->maAppData.maKeyListeners.push_back( rKeyListener );
}

void Application::RemoveKeyListener( const Link<VclWindowEvent&,bool>& rKeyListener )
{
    ImplSVData* pSVData = ImplGetSVData();
    auto & rVec = pSVData->maAppData.maKeyListeners;
    rVec.erase( std::remove(rVec.begin(), rVec.end(), rKeyListener ), rVec.end() );
}

bool Application::HandleKey( VclEventId nEvent, vcl::Window *pWin, KeyEvent* pKeyEvent )
{
    // let listeners process the key event
    VclWindowEvent aEvent( pWin, nEvent, static_cast<void *>(pKeyEvent) );

    ImplSVData* pSVData = ImplGetSVData();

    if ( pSVData->maAppData.maKeyListeners.empty() )
        return false;

    bool bProcessed = false;
    // Copy the list, because this can be destroyed when calling a Link...
    std::vector<Link<VclWindowEvent&,bool>> aCopy( pSVData->maAppData.maKeyListeners );
    for ( const Link<VclWindowEvent&,bool>& rLink : aCopy )
    {
        if( rLink.Call( aEvent ) )
        {<--- Consider using std::any_of algorithm instead of a raw loop.
            bProcessed = true;
            break;
        }
    }
    return bProcessed;
}

ImplSVEvent * Application::PostKeyEvent( VclEventId nEvent, vcl::Window *pWin, KeyEvent const * pKeyEvent )
{
    const SolarMutexGuard aGuard;
    ImplSVEvent * nEventId = nullptr;

    if( pWin && pKeyEvent )
    {
        std::unique_ptr<ImplPostEventData> pPostEventData(new ImplPostEventData( nEvent, pWin, *pKeyEvent ));

        nEventId = PostUserEvent(
                       LINK( nullptr, Application, PostEventHandler ),
                       pPostEventData.get() );

        if( nEventId )
        {
            pPostEventData->mnEventId = nEventId;
            ImplGetSVData()->maAppData.maPostedEventList.emplace_back( pWin, pPostEventData.release() );
        }
    }

    return nEventId;
}

ImplSVEvent* Application::PostGestureEvent(VclEventId nEvent, vcl::Window* pWin, GestureEvent const * pGestureEvent)
{
    const SolarMutexGuard aGuard;
    ImplSVEvent * nEventId = nullptr;

    if (pWin && pGestureEvent)
    {
        Point aTransformedPosition(pGestureEvent->mnX, pGestureEvent->mnY);

        aTransformedPosition.AdjustX(pWin->GetOutOffXPixel());
        aTransformedPosition.AdjustY(pWin->GetOutOffYPixel());

        const GestureEvent aGestureEvent(
            sal_Int32(aTransformedPosition.X()),
            sal_Int32(aTransformedPosition.Y()),
            pGestureEvent->meEventType,
            pGestureEvent->mnOffset,
            pGestureEvent->meOrientation
        );

        std::unique_ptr<ImplPostEventData> pPostEventData(new ImplPostEventData(nEvent, pWin, aGestureEvent));

        nEventId = PostUserEvent(
                       LINK( nullptr, Application, PostEventHandler ),
                       pPostEventData.get());

        if (nEventId)
        {
            pPostEventData->mnEventId = nEventId;
            ImplGetSVData()->maAppData.maPostedEventList.emplace_back(pWin, pPostEventData.release());
        }
    }

    return nEventId;
}

ImplSVEvent* Application::PostMouseEvent( VclEventId nEvent, vcl::Window *pWin, MouseEvent const * pMouseEvent )
{
    const SolarMutexGuard aGuard;
    ImplSVEvent * nEventId = nullptr;

    if( pWin && pMouseEvent )
    {
        Point aTransformedPos( pMouseEvent->GetPosPixel() );

        // LOK uses (0, 0) as the origin of all windows; don't offset.
        if (!comphelper::LibreOfficeKit::isActive())
        {
            aTransformedPos.AdjustX(pWin->GetOutOffXPixel());
            aTransformedPos.AdjustY(pWin->GetOutOffYPixel());
        }

        const MouseEvent aTransformedEvent( aTransformedPos, pMouseEvent->GetClicks(), pMouseEvent->GetMode(),
                                            pMouseEvent->GetButtons(), pMouseEvent->GetModifier() );

        std::unique_ptr<ImplPostEventData> pPostEventData(new ImplPostEventData( nEvent, pWin, aTransformedEvent ));

        nEventId = PostUserEvent(
                       LINK( nullptr, Application, PostEventHandler ),
                       pPostEventData.get() );

        if( nEventId )
        {
            pPostEventData->mnEventId = nEventId;
            ImplGetSVData()->maAppData.maPostedEventList.emplace_back( pWin, pPostEventData.release() );
        }
    }

    return nEventId;
}


IMPL_STATIC_LINK( Application, PostEventHandler, void*, pCallData, void )
{
    const SolarMutexGuard aGuard;
    ImplPostEventData*  pData = static_cast< ImplPostEventData * >( pCallData );
    const void*         pEventData;
    SalEvent            nEvent;
    ImplSVEvent * const nEventId = pData->mnEventId;

    switch( pData->mnEvent )
    {
        case VclEventId::WindowMouseMove:
            nEvent = SalEvent::ExternalMouseMove;
            pEventData = &pData->maMouseEvent;
        break;

        case VclEventId::WindowMouseButtonDown:
            nEvent = SalEvent::ExternalMouseButtonDown;
            pEventData = &pData->maMouseEvent;
        break;

        case VclEventId::WindowMouseButtonUp:
            nEvent = SalEvent::ExternalMouseButtonUp;
            pEventData = &pData->maMouseEvent;
        break;

        case VclEventId::WindowKeyInput:
            nEvent = SalEvent::ExternalKeyInput;
            pEventData = &pData->maKeyEvent;
        break;

        case VclEventId::WindowKeyUp:
            nEvent = SalEvent::ExternalKeyUp;
            pEventData = &pData->maKeyEvent;
        break;

        case VclEventId::WindowGestureEvent:
            nEvent = SalEvent::ExternalGesture;
            pEventData = &pData->maGestureEvent;
        break;

        default:
            nEvent = SalEvent::NONE;
            pEventData = nullptr;
        break;
    }

    if( pData->mpWin && pData->mpWin->mpWindowImpl->mpFrameWindow && pEventData )
        ImplWindowFrameProc( pData->mpWin->mpWindowImpl->mpFrameWindow.get(), nEvent, pEventData );

    // remove this event from list of posted events, watch for destruction of internal data
    auto svdata = ImplGetSVData();
    ::std::vector< ImplPostEventPair >::iterator aIter( svdata->maAppData.maPostedEventList.begin() );

    while( aIter != svdata->maAppData.maPostedEventList.end() )
    {
        if( nEventId == (*aIter).second->mnEventId )
        {
            delete (*aIter).second;
            aIter = svdata->maAppData.maPostedEventList.erase( aIter );
        }
        else
            ++aIter;
    }
}

void Application::RemoveMouseAndKeyEvents( vcl::Window* pWin )
{
    const SolarMutexGuard aGuard;

    // remove all events for specific window, watch for destruction of internal data
    auto svdata = ImplGetSVData();
    ::std::vector< ImplPostEventPair >::iterator aIter( svdata->maAppData.maPostedEventList.begin() );

    while( aIter != svdata->maAppData.maPostedEventList.end() )
    {
        if( pWin == (*aIter).first )
        {
            if( (*aIter).second->mnEventId )
                RemoveUserEvent( (*aIter).second->mnEventId );

            delete (*aIter).second;
            aIter = svdata->maAppData.maPostedEventList.erase( aIter );
        }
        else
            ++aIter;
    }
}

ImplSVEvent * Application::PostUserEvent( const Link<void*,void>& rLink, void* pCaller,
                                          bool bReferenceLink )
{
    vcl::Window* pDefWindow = ImplGetDefaultWindow();
    if ( pDefWindow == nullptr )
        return nullptr;

    std::unique_ptr<ImplSVEvent> pSVEvent(new ImplSVEvent);
    pSVEvent->mpData    = pCaller;
    pSVEvent->maLink    = rLink;
    pSVEvent->mpWindow  = nullptr;
    pSVEvent->mbCall    = true;
    if (bReferenceLink)
    {
        SolarMutexGuard aGuard;
        // Double check that this is indeed a vcl::Window instance.
        assert(dynamic_cast<vcl::Window *>(
                        static_cast<OutputDevice *>(rLink.GetInstance())) ==
               static_cast<vcl::Window *>(rLink.GetInstance()));
        pSVEvent->mpInstanceRef = static_cast<vcl::Window *>(rLink.GetInstance());
    }

    auto pTmpEvent = pSVEvent.get();
    if (!pDefWindow->ImplGetFrame()->PostEvent( std::move(pSVEvent) ))
        return nullptr;
    return pTmpEvent;
}

void Application::RemoveUserEvent( ImplSVEvent * nUserEvent )
{
    if(nUserEvent)
    {
        SAL_WARN_IF( nUserEvent->mpWindow, "vcl",
                    "Application::RemoveUserEvent(): Event is send to a window" );
        SAL_WARN_IF( !nUserEvent->mbCall, "vcl",
                    "Application::RemoveUserEvent(): Event is already removed" );

        nUserEvent->mpWindow.clear();
        nUserEvent->mpInstanceRef.clear();
        nUserEvent->mbCall = false;
    }
}

void Application::LockFontUpdates(bool bLock)
{
    OutputDevice::LockFontUpdates(bLock);
}

vcl::Window* Application::GetFocusWindow()
{
    return ImplGetSVData()->mpWinData->mpFocusWin;
}

OutputDevice* Application::GetDefaultDevice()
{
    return ImplGetDefaultWindow();
}

vcl::Window* Application::GetFirstTopLevelWindow()
{
    ImplSVData* pSVData = ImplGetSVData();
    return pSVData->maFrameData.mpFirstFrame;
}

vcl::Window* Application::GetNextTopLevelWindow( vcl::Window const * pWindow )
{
    return pWindow->mpWindowImpl->mpFrameData->mpNextFrame;
}

long    Application::GetTopWindowCount()
{
    long nRet = 0;
    ImplSVData* pSVData = ImplGetSVData();
    vcl::Window *pWin = pSVData ? pSVData->maFrameData.mpFirstFrame.get() : nullptr;
    while( pWin )
    {
        if( pWin->ImplGetWindow()->IsTopWindow() )
            nRet++;
        pWin = pWin->mpWindowImpl->mpFrameData->mpNextFrame;
    }
    return nRet;
}

vcl::Window* Application::GetTopWindow( long nIndex )
{
    long nIdx = 0;
    ImplSVData* pSVData = ImplGetSVData();
    vcl::Window *pWin = pSVData ? pSVData->maFrameData.mpFirstFrame.get() : nullptr;
    while( pWin )
    {
        if( pWin->ImplGetWindow()->IsTopWindow() )
        {
            if( nIdx == nIndex )
                return pWin->ImplGetWindow();
            else
                nIdx++;
        }
        pWin = pWin->mpWindowImpl->mpFrameData->mpNextFrame;
    }
    return nullptr;
}

vcl::Window* Application::GetActiveTopWindow()
{
    vcl::Window *pWin = ImplGetSVData()->mpWinData->mpFocusWin;
    while( pWin )
    {
        if( pWin->IsTopWindow() )
            return pWin;
        pWin = pWin->mpWindowImpl->mpParent;
    }
    return nullptr;
}

void Application::SetAppName( const OUString& rUniqueName )
{
    ImplSVData* pSVData = ImplGetSVData();
    pSVData->maAppData.mxAppName = rUniqueName;
}

OUString Application::GetAppName()
{
    ImplSVData* pSVData = ImplGetSVData();
    if ( pSVData->maAppData.mxAppName )
        return *(pSVData->maAppData.mxAppName);
    else
        return OUString();
}

enum {hwAll=0, hwEnv=1, hwUI=2};

OUString Application::GetHWOSConfInfo(const int bSelection)
{
    ImplSVData* pSVData = ImplGetSVData();
    OUStringBuffer aDetails;

    const auto appendDetails = [&aDetails](const OUStringLiteral& sep, auto&& val) {
        if (!aDetails.isEmpty() && sep.getLength())
            aDetails.append(sep);
        aDetails.append(std::move(val));
    };

    if (bSelection != hwUI) {
        appendDetails("; ", VclResId(SV_APP_CPUTHREADS)
                                + OUString::number(std::thread::hardware_concurrency()));

        OUString aVersion;
        if ( pSVData && pSVData->mpDefInst )
            aVersion = pSVData->mpDefInst->getOSVersion();
        else
            aVersion = "-";

        appendDetails("; ", VclResId(SV_APP_OSVERSION) + aVersion);
    }

    if (bSelection != hwEnv) {
        appendDetails("; ", VclResId(SV_APP_UIRENDER));
#if HAVE_FEATURE_SKIA
        if ( SkiaHelper::isVCLSkiaEnabled() )
        {
            switch(SkiaHelper::renderMethodToUse())
            {
                case SkiaHelper::RenderVulkan:
                    appendDetails("", VclResId(SV_APP_SKIA_VULKAN));
                    break;
                case SkiaHelper::RenderRaster:
                    appendDetails("", VclResId(SV_APP_SKIA_RASTER));
                    break;
            }
        }
        else
#endif
#if HAVE_FEATURE_OPENGL
        if ( OpenGLWrapper::isVCLOpenGLEnabled() )
            appendDetails("", VclResId(SV_APP_GL));
        else
#endif
            appendDetails("", VclResId(SV_APP_DEFAULT));

#if (defined LINUX || defined _WIN32 || defined MACOSX)
        appendDetails("; ", SV_APP_VCLBACKEND + GetToolkitName());
#endif
    }

    return aDetails.makeStringAndClear();
}

void Application::SetDisplayName( const OUString& rName )
{
    ImplSVData* pSVData = ImplGetSVData();
    pSVData->maAppData.mxDisplayName = rName;
}

OUString Application::GetDisplayName()
{
    ImplSVData* pSVData = ImplGetSVData();
    if ( pSVData->maAppData.mxDisplayName )
        return *(pSVData->maAppData.mxDisplayName);
    else if (pSVData->maFrameData.mpAppWin)
        return pSVData->maFrameData.mpAppWin->GetText();
    else
        return OUString();
}

unsigned int Application::GetScreenCount()
{
    SalSystem* pSys = ImplGetSalSystem();
    return pSys ? pSys->GetDisplayScreenCount() : 0;
}

bool Application::IsUnifiedDisplay()
{
    SalSystem* pSys = ImplGetSalSystem();
    return pSys == nullptr || pSys->IsUnifiedDisplay();
}

unsigned int Application::GetDisplayBuiltInScreen()
{
    SalSystem* pSys = ImplGetSalSystem();
    return pSys ? pSys->GetDisplayBuiltInScreen() : 0;
}

unsigned int Application::GetDisplayExternalScreen()
{
    // This is really unpleasant, in theory we could have multiple
    // external displays etc.
    int nExternal(0);
    switch (GetDisplayBuiltInScreen())
    {
    case 0:
        nExternal = 1;
        break;
    case 1:
        nExternal = 0;
        break;
    default:
        // When the built-in display is neither 0 nor 1
        // then place the full-screen presentation on the
        // first available screen.
        nExternal = 0;
        break;
    }
    return nExternal;
}

tools::Rectangle Application::GetScreenPosSizePixel( unsigned int nScreen )
{
    SalSystem* pSys = ImplGetSalSystem();
    if (!pSys)
    {
        SAL_WARN("vcl", "Requesting screen size/pos for screen #" << nScreen << " failed");
        assert(false);
        return tools::Rectangle();
    }
    tools::Rectangle aRect = pSys->GetDisplayScreenPosSizePixel(nScreen);
    if (aRect.getHeight() == 0)
        SAL_WARN("vcl", "Requesting screen size/pos for screen #" << nScreen << " returned 0 height.");
    return aRect;
}

namespace {
unsigned long calcDistSquare( const Point& i_rPoint, const tools::Rectangle& i_rRect )
{
    const Point aRectCenter( (i_rRect.Left() + i_rRect.Right())/2,
                       (i_rRect.Top() + i_rRect.Bottom())/ 2 );
    const long nDX = aRectCenter.X() - i_rPoint.X();
    const long nDY = aRectCenter.Y() - i_rPoint.Y();
    return nDX*nDX + nDY*nDY;
}
}

unsigned int Application::GetBestScreen( const tools::Rectangle& i_rRect )
{
    if( !IsUnifiedDisplay() )
        return GetDisplayBuiltInScreen();

    const unsigned int nScreens = GetScreenCount();
    unsigned int nBestMatchScreen = 0;
    unsigned long nOverlap = 0;
    for( unsigned int i = 0; i < nScreens; i++ )
    {
        const tools::Rectangle aCurScreenRect( GetScreenPosSizePixel( i ) );
        // if a screen contains the rectangle completely it is obviously the best screen
        if( aCurScreenRect.IsInside( i_rRect ) )
            return i;
        // next the screen which contains most of the area of the rect is the best
        tools::Rectangle aIntersection( aCurScreenRect.GetIntersection( i_rRect ) );
        if( ! aIntersection.IsEmpty() )
        {
            const unsigned long nCurOverlap( aIntersection.GetWidth() * aIntersection.GetHeight() );
            if( nCurOverlap > nOverlap )
            {
                nOverlap = nCurOverlap;
                nBestMatchScreen = i;
            }
        }
    }
    if( nOverlap > 0 )
        return nBestMatchScreen;

    // finally the screen which center is nearest to the rect is the best
    const Point aCenter( (i_rRect.Left() + i_rRect.Right())/2,
                         (i_rRect.Top() + i_rRect.Bottom())/2 );
    unsigned long nDist = ULONG_MAX;
    for( unsigned int i = 0; i < nScreens; i++ )
    {
        const tools::Rectangle aCurScreenRect( GetScreenPosSizePixel( i ) );
        const unsigned long nCurDist( calcDistSquare( aCenter, aCurScreenRect ) );
        if( nCurDist < nDist )
        {
            nBestMatchScreen = i;
            nDist = nCurDist;
        }
    }
    return nBestMatchScreen;
}

bool Application::InsertAccel( Accelerator* pAccel )
{
    ImplSVData* pSVData = ImplGetSVData();

    if ( !pSVData->maAppData.mpAccelMgr )
        pSVData->maAppData.mpAccelMgr = new ImplAccelManager();
    return pSVData->maAppData.mpAccelMgr->InsertAccel( pAccel );
}

void Application::RemoveAccel( Accelerator const * pAccel )
{
    ImplSVData* pSVData = ImplGetSVData();

    if ( pSVData->maAppData.mpAccelMgr )
        pSVData->maAppData.mpAccelMgr->RemoveAccel( pAccel );
}

void Application::SetHelp( Help* pHelp )
{
    ImplGetSVData()->maAppData.mpHelp = pHelp;
}

void Application::UpdateMainThread()
{
    ImplSVData* pSVData = ImplGetSVData();
    if (pSVData && pSVData->mpDefInst)
        pSVData->mpDefInst->updateMainThread();
}

Help* Application::GetHelp()
{
    return ImplGetSVData()->maAppData.mpHelp;
}

OUString Application::GetToolkitName()
{
    ImplSVData* pSVData = ImplGetSVData();
    if ( pSVData->maAppData.mxToolkitName )
        return *(pSVData->maAppData.mxToolkitName);
    else
        return OUString();
}

vcl::Window* Application::GetDefDialogParent()
{
    ImplSVData* pSVData = ImplGetSVData();
    // find some useful dialog parent

    // always use the topmost parent of the candidate
    // window to avoid using dialogs or floaters
    // as DefDialogParent

    // current focus frame
    vcl::Window *pWin = pSVData->mpWinData->mpFocusWin;
    if (pWin && !pWin->IsMenuFloatingWindow())
    {
        while (pWin->mpWindowImpl && pWin->mpWindowImpl->mpParent)
            pWin = pWin->mpWindowImpl->mpParent;

        // check for corrupted window hierarchy, #122232#, may be we now crash somewhere else
        if (!pWin->mpWindowImpl)
        {
            OSL_FAIL( "Window hierarchy corrupted!" );
            pSVData->mpWinData->mpFocusWin = nullptr;   // avoid further access
            return nullptr;
        }

        if ((pWin->mpWindowImpl->mnStyle & WB_INTROWIN) == 0)
        {
            return pWin->mpWindowImpl->mpFrameWindow->ImplGetWindow();
        }
    }

    // last active application frame
    pWin = pSVData->maFrameData.mpActiveApplicationFrame;
    if (pWin)
    {
        return pWin->mpWindowImpl->mpFrameWindow->ImplGetWindow();
    }

    // first visible top window (may be totally wrong...)
    pWin = pSVData->maFrameData.mpFirstFrame;
    while (pWin)
    {
        if( pWin->ImplGetWindow()->IsTopWindow() &&
            pWin->mpWindowImpl->mbReallyVisible &&
            (pWin->mpWindowImpl->mnStyle & WB_INTROWIN) == 0
        )
        {
            while( pWin->mpWindowImpl->mpParent )
                pWin = pWin->mpWindowImpl->mpParent;
            return pWin->mpWindowImpl->mpFrameWindow->ImplGetWindow();
        }
        pWin = pWin->mpWindowImpl->mpFrameData->mpNextFrame;
    }

    // use the desktop
    return nullptr;
}

DialogCancelMode Application::GetDialogCancelMode()
{
    return ImplGetSVData()->maAppData.meDialogCancel;
}

void Application::SetDialogCancelMode( DialogCancelMode mode )
{
    ImplGetSVData()->maAppData.meDialogCancel = mode;
}

bool Application::IsDialogCancelEnabled()
{
    return ImplGetSVData()->maAppData.meDialogCancel != DialogCancelMode::Off;
}

void Application::SetSystemWindowMode( SystemWindowFlags nMode )
{
    ImplGetSVData()->maAppData.mnSysWinMode = nMode;
}

SystemWindowFlags Application::GetSystemWindowMode()
{
    return ImplGetSVData()->maAppData.mnSysWinMode;
}

css::uno::Reference< css::awt::XToolkit > Application::GetVCLToolkit()
{
    css::uno::Reference< css::awt::XToolkit > xT;
    UnoWrapperBase* pWrapper = UnoWrapperBase::GetUnoWrapper();
    if ( pWrapper )
        xT = pWrapper->GetVCLToolkit();
    return xT;
}

#ifdef DISABLE_DYNLOADING

extern "C" { UnoWrapperBase* CreateUnoWrapper(); }

#else

extern "C" { static void thisModule() {} }

#endif

UnoWrapperBase* UnoWrapperBase::GetUnoWrapper( bool bCreateIfNotExist )
{
    ImplSVData* pSVData = ImplGetSVData();
    static bool bAlreadyTriedToCreate = false;
    if ( !pSVData->mpUnoWrapper && bCreateIfNotExist && !bAlreadyTriedToCreate )
    {
#ifndef DISABLE_DYNLOADING
        osl::Module aTkLib;
        aTkLib.loadRelative(&thisModule, TK_DLL_NAME);
        if (aTkLib.is())
        {
            FN_TkCreateUnoWrapper fnCreateWrapper = reinterpret_cast<FN_TkCreateUnoWrapper>(aTkLib.getFunctionSymbol("CreateUnoWrapper"));
            if ( fnCreateWrapper )
            {
                pSVData->mpUnoWrapper = fnCreateWrapper();
            }
            aTkLib.release();
        }
        SAL_WARN_IF( !pSVData->mpUnoWrapper, "vcl", "UnoWrapper could not be created!" );
#else
        pSVData->mpUnoWrapper = CreateUnoWrapper();
#endif
        bAlreadyTriedToCreate = true;
    }
    return pSVData->mpUnoWrapper;
}

void UnoWrapperBase::SetUnoWrapper( UnoWrapperBase* pWrapper )
{
    ImplSVData* pSVData = ImplGetSVData();
    SAL_WARN_IF( pSVData->mpUnoWrapper, "vcl", "SetUnoWrapper: Wrapper already exists" );
    pSVData->mpUnoWrapper = pWrapper;
}

css::uno::Reference< css::awt::XDisplayConnection > Application::GetDisplayConnection()
{
    ImplSVData* pSVData = ImplGetSVData();

    if( !pSVData->mxDisplayConnection.is() )
    {
        pSVData->mxDisplayConnection.set( new vcl::DisplayConnectionDispatch );
        pSVData->mxDisplayConnection->start();
    }

    return pSVData->mxDisplayConnection.get();
}

void Application::SetFilterHdl( const Link<ConvertData&,bool>& rLink )
{
    ImplGetSVData()->maGDIData.mpGrfConverter->SetFilterHdl( rLink );
}

const LocaleDataWrapper& Application::GetAppLocaleDataWrapper()
{
    return GetSettings().GetLocaleDataWrapper();
}

void Application::EnableHeadlessMode( bool dialogsAreFatal )
{
    DialogCancelMode eNewMode = dialogsAreFatal ? DialogCancelMode::Fatal : DialogCancelMode::Silent;
    DialogCancelMode eOldMode = GetDialogCancelMode();
    assert(eOldMode == DialogCancelMode::Off || GetDialogCancelMode() == eNewMode);
    if (eOldMode != eNewMode)
        SetDialogCancelMode( eNewMode );
}

bool Application::IsHeadlessModeEnabled()
{
    return IsDialogCancelEnabled() || comphelper::LibreOfficeKit::isActive();
}

void Application::EnableBitmapRendering()
{
    ImplGetSVData()->maAppData.mbRenderToBitmaps = true;
}

bool Application::IsBitmapRendering()
{
    return ImplGetSVData()->maAppData.mbRenderToBitmaps;
}

void Application::EnableConsoleOnly()
{
    EnableHeadlessMode(true);
    EnableBitmapRendering();
}

static bool bEventTestingMode = false;

bool Application::IsEventTestingModeEnabled()
{
    return bEventTestingMode;
}

void Application::EnableEventTestingMode()
{
    bEventTestingMode = true;
}

static bool bSafeMode = false;

bool Application::IsSafeModeEnabled()
{
    return bSafeMode;
}

void Application::EnableSafeMode()
{
    bSafeMode = true;
}

void Application::ShowNativeErrorBox(const OUString& sTitle  ,
                                     const OUString& sMessage)
{
    int btn = ImplGetSalSystem()->ShowNativeMessageBox(
            sTitle,
            sMessage);
    if (btn != SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK) {
        SAL_WARN( "vcl", "ShowNativeMessageBox returned " << btn);
    }
}

const OUString& Application::GetDesktopEnvironment()
{
    if (IsHeadlessModeEnabled())
    {
        static const OUString aNone("none");
        return aNone;
    }
    else
        return SalGetDesktopEnvironment();
}

void Application::AddToRecentDocumentList(const OUString& rFileUrl, const OUString& rMimeType, const OUString& rDocumentService)
{
    ImplSVData* pSVData = ImplGetSVData();
    pSVData->mpDefInst->AddToRecentDocumentList(rFileUrl, rMimeType, rDocumentService);
}

bool InitAccessBridge()
{
// Disable MSAA bridge on UNIX
#if defined UNX
    return true;
#else
    bool bRet = ImplInitAccessBridge();

    if( !bRet )
    {
        // disable accessibility if the user chooses to continue
        AllSettings aSettings = Application::GetSettings();
        MiscSettings aMisc = aSettings.GetMiscSettings();
        aMisc.SetEnableATToolSupport( false );
        aSettings.SetMiscSettings( aMisc );
        Application::SetSettings( aSettings );
    }
    return bRet;
#endif // !UNX
}

// MT: AppEvent was in oldsv.cxx, but is still needed...
void Application::AppEvent( const ApplicationEvent& /*rAppEvent*/ )
{
}

bool Application::hasNativeFileSelection()
{
    ImplSVData* pSVData = ImplGetSVData();
    return pSVData->mpDefInst->hasNativeFileSelection();
}

Reference< ui::dialogs::XFilePicker2 >
Application::createFilePicker( const Reference< uno::XComponentContext >& xSM )
{
    ImplSVData* pSVData = ImplGetSVData();
    return pSVData->mpDefInst->createFilePicker( xSM );
}

Reference< ui::dialogs::XFolderPicker2 >
Application::createFolderPicker( const Reference< uno::XComponentContext >& xSM )
{
    ImplSVData* pSVData = ImplGetSVData();
    return pSVData->mpDefInst->createFolderPicker( xSM );
}

void Application::setDeInitHook(Link<LinkParamNone*,void> const & hook) {
    ImplSVData * pSVData = ImplGetSVData();
    assert(!pSVData->maDeInitHook.IsSet());
    pSVData->maDeInitHook = hook;
    // Fake this for VCLXToolkit ctor instantiated from
    // postprocess/CppunitTest_services.mk:
    pSVData->maAppData.mbInAppMain = true;
}

namespace vcl::lok {

void registerPollCallbacks(
    LibreOfficeKitPollCallback pPollCallback,
    LibreOfficeKitWakeCallback pWakeCallback,
    void *pData) {

    ImplSVData * pSVData = ImplGetSVData();
    if (pSVData)
    {
        pSVData->mpPollCallback = pPollCallback;
        pSVData->mpWakeCallback = pWakeCallback;
        pSVData->mpPollClosure = pData;
    }
}

void unregisterPollCallbacks()
{
    ImplSVData * pSVData = ImplGetSVData();
    if (pSVData)
    {
        // Not hyper-elegant - but in the case of Android & unipoll we need to detach
        // this thread from the JVM's clutches to avoid a crash closing document
        if (pSVData->mpPollClosure && pSVData->mpDefInst)
            pSVData->mpDefInst->releaseMainThread();

        // Just set mpPollClosure to null as that is what calling this means, that the callback data
        // points to an object that no longer exists. In particular, don't set
        // pSVData->mpPollCallback to nullptr as that is used to detect whether Unipoll is in use in
        // isUnipoll().
        pSVData->mpPollClosure = nullptr;
    }
}

bool isUnipoll()
{
    ImplSVData * pSVData = ImplGetSVData();
    return pSVData && pSVData->mpPollCallback != nullptr;
}

} // namespace lok, namespace vcl

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