File: Application.cpp

package info (click to toggle)
camitk 6.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 389,496 kB
  • sloc: cpp: 103,476; sh: 2,448; python: 1,618; xml: 984; makefile: 128; perl: 84; sed: 20
file content (1775 lines) | stat: -rw-r--r-- 70,162 bytes parent folder | download
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
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

// -- Core stuff
#include "Application.h"
#include "Core.h"
#include "MainWindow.h"
#include "ExtensionManager.h"
#include "Action.h"
#include "Viewer.h"
#include "HistoryComponent.h"
#include "ImageComponent.h"
#include "Property.h"
#include "PropertyObject.h"
#include "TransformationManager.h"
#include "PersistenceManager.h"
#include "SplashScreen.h"
#include "AbortException.h"
#ifdef PYTHON_BINDING
#include "PythonManager.h"
#endif

#include "Log.h"

// -- QT stuff
#include <QSettings>
#include <QMessageBox>
#include <QInputDialog>
#include <QFileDialog>
#include <QDomDocument>
#include <QTextStream>
#include <QDateTime>
#include <QProcess>

// -- VTK stuff (only for updating progress bar via vtk filters)
#include <vtkAlgorithm.h>

#include<array>

// see http://doc.qt.nokia.com/latest/resources.html (bottom)
inline void initIcons() {
    Q_INIT_RESOURCE(CamiTKIcons);
}

namespace camitk {

// the main window (static, unique instance, verifies singleton)
MainWindow* Application::mainWindow = nullptr;
SplashScreen* Application::splashScreen = nullptr;
QSettings Application::settings(QSettings::IniFormat, QSettings::UserScope, "CamiTK", QString(Core::version()).remove(QChar(' ')));
QList<QFileInfo> Application::recentDocuments;
QDir Application::lastUsedDirectory;
int Application::maxRecentDocuments = 0;
QString Application::name = Core::version();
int Application::argc = 0;
char** Application::argv = nullptr;
QTranslator* Application::translator = nullptr;
PropertyObject* Application::propertyObject = nullptr;
Action* Application::currentAction = nullptr;

// ----------------- constructor --------------------
Application::Application(QString name, int& theArgc, char** theArgv, bool autoloadExtensions, bool registerFileExtension, bool useSplashScreen) : QApplication(theArgc, theArgv) {

    //-- generic init
    this->name = name;
    QApplication::setApplicationName(name);    // associate the QProperty to the Qt meta-object

    argc = theArgc;
    argv = theArgv;
    mainWindow = nullptr;
    translator = nullptr;

    //-- sometimes needed to get the icon when compiled in static mode
    initIcons();

    //-- Load the resources of the application (mainly its translation file)
    initResources();

    //-- Add application properties
    createProperties();

    //-- load all property values from the settings and apply them a first time
    propertyObject->loadFromSettings(Application::getName() + ".Application");
    applyPropertyValues();

    CAMITK_INFO(tr("Starting application..."))

    // recommended (see exec() comment in QApplication)
    connect(this, SIGNAL(aboutToQuit()), SLOT(quitting()));
    connect(this, SIGNAL(lastWindowClosed()), SLOT(quitting()));

    //-- create splash screen if required
    if (useSplashScreen) {
        splashScreen = new SplashScreen();
        splashScreen->show();
        showStatusBarMessage(QString("Initializing %1...").arg(name));
        setProgressBarValue(0);
    }

#ifdef PYTHON_BINDING
    // Init the python interpreter.
    //
    // This is done automatically in the Application constructor to take
    // the following scenarios into account (see also PythonManager::python):
    // - CamiTK CE was built without PYTHON_BINDING: no effect, python extensions are not available
    // - CamiTK CE was built with PYTHON_BINDING but python is not installed
    //   or the camitk python module is not installed: python extensions are not available
    // - CamiTK CE was built with PYTHON_BINDING and python AND camitk module are installed:
    //   python extensions are available.
    //
    // The second scenario requires that PythonManager::initPython() must be called
    // systematically when an application starts and should not produce an error, just disable
    // python if not available.
    //
    // Use PythonManager::pythonEnabled() to check the python interpreter status at any time
    PythonManager::initPython();
#endif

    //-- Load extensions
    // once the log is setup, only now one can try to load the extensions
    if (autoloadExtensions) {
        ExtensionManager::autoload();
    }

    //-- initialize recent/lastUsedDirectory documents from the settings
    settings.beginGroup(name + ".Application");

    // max memorized recent documents
    maxRecentDocuments = settings.value("maxRecentDocuments", 10).toInt();

    // the recent documents
    QStringList recentDoc = settings.value("recentDocuments").toStringList();
    recentDocuments.clear();

    for (QString fileName : recentDoc) {
        recentDocuments.append(QFileInfo(fileName));
    }

    // the last used directory
    QDir defaultDir(Core::getTestDataDir());
    lastUsedDirectory.setPath(settings.value("lastUsedDirectory", defaultDir.absolutePath()).toString());
    settings.endGroup();

    //-- register file association with this application for opening
    if (registerFileExtension) {
        // TODO : remove ifdef WIN32 as soon as we handle file association for other platform than Windows
        // see ExtensionManager::registerFileExtension method.
#ifdef WIN32
        // TODO : uses a better way to ask the user so that each component can be selected individually
        // File types association with the application for opening
        QStringList newFileExtensions;
        QStringList fileExtensionsAlreadyRegistered = settings.value("fileExtensionsRegistered").toStringList();
        // Forbidden list, to avoid user to have common image file type associated with the application
        QStringList fileExtensionForbidden;
        fileExtensionForbidden.append("jpg");
        fileExtensionForbidden.append("png");
        fileExtensionForbidden.append("bmp");
        fileExtensionForbidden.append("tif");
        fileExtensionForbidden.append("tiff");

        for (QString extensionFile : ExtensionManager::getFileExtensions()) {
            // check the application can handle new file type
            if (!fileExtensionsAlreadyRegistered.contains(extensionFile) && !fileExtensionForbidden.contains(extensionFile)) {
                newFileExtensions.append(extensionFile);
            }
        }

        // check if the application handles new file types
        if (!newFileExtensions.isEmpty()) {
            // new component extension(s) allow(s) the application to handle new file types
            // Prompt the user if he wishes those file extension to be associated with this application for default file opening.
            // CCC Exception: Use a QMessageBox as the user interaction is required
            QMessageBox msgBox;
            msgBox.setWindowTitle(tr("Associate new file extensions for opening."));
            msgBox.setText(tr("New component extension(s) allow(s) this application to handle new file type(s)\n\n")
                           + newFileExtensions.join(", ") + "\n\n"
                           + tr("Do you want this/these file type(s) to be opened by default with this application")
                           + " (" + QApplication::applicationName() + ") ?\n");
            msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
            msgBox.setDefaultButton(QMessageBox::Yes);
            msgBox.setWindowFlags(Qt::WindowStaysOnTopHint); // to stay on top of the splash screen

            if (msgBox.exec() == QMessageBox::Yes) {
                // user agrees : register each new file type
                for (QString fileExtensionToRegister : newFileExtensions) {
                    ExtensionManager::registerFileExtension(fileExtensionToRegister);
                }
            }

            // save the file types in the application's settings in order not to be prompt again
            fileExtensionsAlreadyRegistered.append(newFileExtensions);
            settings.setValue("fileExtensionsRegistered", fileExtensionsAlreadyRegistered);
        }

#endif
    }

    //-- Get notified (in evenFilter method) every time one of the property is modified
    // All event filter on the property object are delegated to the Application class
    // @see eventFilter()
    propertyObject->installEventFilter(this);

    // trigger change for all the values
    Application::eventFilter(this, new QEvent(QEvent::DynamicPropertyChange));
}

// ----------------- destructor --------------------
Application::~Application() {
    // do not use the destructor to clean or free resources, but quitting()

    // delete property object and all its properties !
    if (propertyObject) {
        delete propertyObject;
    }

    // finish all logging properly
    CAMITK_INFO(tr("Exiting application..."))
}

// ----------------- destructor --------------------
QString Application::getName() {
    return name;
}

// ----------------- quitting --------------------
void Application::quitting() {
    // this is connected to the aboutToQuit signal from QApplication
    // it should contain all the code that frees the resources

    // delete all actions (they are instantiated when the extension is loaded)
    ExtensionManager::unloadAllActionExtensions();
    ExtensionManager::unloadAllViewerExtensions();

    if (translator != nullptr) {
        // delete instance of internationalization support
        delete translator;
    }
}

// ----------------- notify --------------------
bool Application::notify(QObject* receiver, QEvent* event) {
    bool done = true;
    std::exception_ptr otherException;

    try {
        done = QApplication::notify(receiver, event);
    }
    catch (const std::bad_alloc& e) {
        CAMITK_WARNING_ALT(QString("Caught a bad alloc exception, the application has run out of memory:\n%1").arg(e.what()))
    }
    catch (const std::exception& e) {
        CAMITK_ERROR(tr("Caught a std exception:\n%1").arg(e.what()))
    }
    catch (...) {
        CAMITK_ERROR(tr("Caught an unknown exception"))
        otherException = std::current_exception();

        try {
            if (otherException) {
                std::rethrow_exception(otherException);
            }
        }
        catch (const std::exception& e) {
            CAMITK_ERROR(tr("Exception: %1").arg(e.what()))
        }
    }

    return done;
}

// ----------------- setMainWindow --------------------
void Application::setMainWindow(MainWindow* mw, bool redirect) {
    if (mw == nullptr) {
        mainWindow = new MainWindow(name);
    }
    else {
        mainWindow = mw;
    }

    // by default redirect to console
    mainWindow->redirectToConsole(redirect);

    // apply properties that modify the main window (e.g. stylesheet for splitter/separator)
    applyMainWindowPropertyValues();

    // Set the locale to C for using dot as decimal point despite locale
    // Set utf8 for output to enforce using utf8 strings.
    //
    // see http://doc.qt.io/qt-5/qcoreapplication.html#locale-settings
    // and various threads or forum discussions such as http://stackoverflow.com/questions/25661295/why-does-qcoreapplication-call-setlocalelc-all-by-default-on-unix-linux
    char* statusOk = setlocale(LC_CTYPE, "C.UTF-8");

    if (statusOk != nullptr) {
        statusOk = setlocale(LC_NUMERIC, "C.UTF-8");
    }

    if (statusOk != nullptr) {
        statusOk = setlocale(LC_TIME, "C.UTF-8");
    }

    // try without UTF-8
    if (!statusOk) {
        statusOk = setlocale(LC_CTYPE, "C");

        if (statusOk != nullptr) {
            statusOk = setlocale(LC_NUMERIC, "C");
        }

        if (statusOk != nullptr) {
            statusOk = setlocale(LC_TIME, "C");
        }

        if (statusOk == nullptr) {
            CAMITK_ERROR(tr("Could not set the locale to C. This is mandatory to enforce dot as the decimal separator and ensure platform independency of numerics.\nThis can cause a lot of trouble for numerics I/O... Beware of decimal dots...\n"))
        }
    }

    // hand over everything to main window
    if (splashScreen) {
        splashScreen->close();
    }
}


// ----------------- getMainWindow --------------------
MainWindow* Application::getMainWindow() {
    if (mainWindow == nullptr && dynamic_cast<Application*>(qApp) != nullptr) {
        // this is the first time getMainWindow() is called and no MainWindow were created
        // In this case, force the creation of a default MainWindow by sending nullptr
        dynamic_cast<Application*>(qApp)->setMainWindow(nullptr);
        // and then returns it
    }

    return mainWindow;
}

// ----------------- getSettings --------------------
QSettings& Application::getSettings() {
    return settings;
}

// ----------------- exec --------------------
int Application::exec() {
    if (mainWindow == nullptr && dynamic_cast<Application*>(qApp) != nullptr) {
        dynamic_cast<Application*>(qApp)->setMainWindow(nullptr);
    }

    // if mainWindow was nullptr when entering this method, it should have
    // been created by the call to setMainWindow(nullptr) above
    if (mainWindow != nullptr) {
        mainWindow->aboutToShow();
        mainWindow->show();
    }
    else {
        CAMITK_ERROR_ALT(tr("Cannot create MainWindow instance"));
    }

    return QApplication::exec();
}

// ------------- restart -----------------
void Application::restart(QString reason) {
    // ask for reload when extension dynamic library/shared object changes on the disk
    QStringList options;
    options << "Restart & Reload" << "Restart Only";
    bool ok;
    QString restartOption = QInputDialog::getItem(nullptr, "Restart", reason, options, 0, false, &ok);

    if (ok && !restartOption.isEmpty()) {
        QStringList arguments;
        // save workspace
        if (restartOption == options[0]) {
            // Create "unique" temporary camitk file
            QString temporaryFile = QDir::temp().absoluteFilePath(name + "-" + QString::number(QDateTime::currentMSecsSinceEpoch()) + ".camitk");
            bool saveStatus = Application::saveWorkspace(temporaryFile);
            if (!saveStatus) {
                QMessageBox::StandardButton reply = QMessageBox::question(nullptr, "Error Saving Workspace",
                                                    "An error occurred when attempting to save the workspace: it will not be possible to reload the currently opened components.<br/>Do you still want to restart?",
                                                    QMessageBox::Yes | QMessageBox::No);
                if (reply == QMessageBox::No) {
                    mainWindow->statusBar()->showMessage(tr("Restart cancelled..."));
                    return;
                }
            }
            else {
                arguments.append(temporaryFile);
            }
        }
        QString executable = QCoreApplication::applicationFilePath();

        QProcess::startDetached(executable, arguments);
        QCoreApplication::quit();
    }
    else {
        // User chose not to reload the extension
        if (mainWindow) {
            mainWindow->statusBar()->showMessage(tr("Restart cancelled..."));
        }
    }
}

// ----------------- refresh --------------------
void Application::refresh() {
    if (mainWindow != nullptr) {
        mainWindow->refresh();
    }

    // now that every viewer was refresh, clear the interface node modification flag
    for (Component* c : Application::getAllComponents()) {
        c->setNodeModified(false);
    }
}

// ----------------- showStatusBarMessage --------------------
void Application::showStatusBarMessage(QString msg, int timeout) {
    // if this application has no main window (no GUI)
    // there is no status bar, check if the splashscreen is available
    if (mainWindow && mainWindow->statusBar()) {
        mainWindow->statusBar()->showMessage(msg, timeout);
        QApplication::processEvents();
    }
    else {
        if (splashScreen && splashScreen->isVisible()) {
            splashScreen->showMessage(msg);
        }
        else {
            CAMITK_INFO_ALT(msg);
        }
    }
}

// ----------------- resetProgressBar --------------------
void Application::resetProgressBar() {
    // if this application has no main window (no GUI)
    // there is no status bar, therefore nothing to do
    if (mainWindow) {
        QProgressBar* progress = mainWindow->getProgressBar();

        if (progress) {
            progress->setValue(0);
        }
    }
}

// ----------------- setProgressBarValue --------------------
void Application::setProgressBarValue(int value) {
    // if this application has no main window (no GUI)
    // there is no status bar, check for a splash screen
    if (mainWindow && mainWindow->getProgressBar()) {
        mainWindow->getProgressBar()->setValue(value);
    }
    else {
        if (splashScreen && splashScreen->isVisible()) {
            splashScreen->setProgress(value);
        }
    }
}

// ----------------- vtkProgressFunction --------------------
void Application::vtkProgressFunction(vtkObject* caller, long unsigned int, void*, void*) {
    // if this application has no main window (no GUI)
    // there is no status bar, therefore nothing to do
    if (mainWindow) {
        QProgressBar* progress = mainWindow->getProgressBar();
        auto* filter = static_cast<vtkAlgorithm*>(caller);
        int progressVal = filter->GetProgress() * 100;

        if (progress) {
            progress->setValue(progressVal);
        }
    }
}

// ----------------- addRecentDocument --------------------
void Application::addRecentDocument(QString filename) {
    QFileInfo fileInfo(filename);
    recentDocuments.removeOne(fileInfo);
    recentDocuments.append(fileInfo);

    // update the last used dir
    lastUsedDirectory = recentDocuments.last().absoluteDir();

    // save settings (the last 10 recent files by default)
    settings.beginGroup(name + ".Application");

    // max memorized recent documents
    settings.setValue("maxRecentDocuments", maxRecentDocuments);

    // save all up to maxRecentDocuments
    int firstOpened = recentDocuments.size() - maxRecentDocuments;

    if (firstOpened < 0) {
        firstOpened = 0;
    }

    QStringList recentDoc;

    for (int i = firstOpened; i < recentDocuments.size(); i++) {
        recentDoc.append(recentDocuments[i].absoluteFilePath());
    }

    settings.setValue("recentDocuments", recentDoc);

    // last used directory
    settings.setValue("lastUsedDirectory", lastUsedDirectory.absolutePath());
    settings.endGroup();
}

// ----------------- getLastUsedDirectory --------------------
const QDir Application::getLastUsedDirectory() {
    return lastUsedDirectory;
}

// ----------------- setLastUsedDirectory --------------------
void Application::setLastUsedDirectory(QDir last) {
    lastUsedDirectory = last;
}

// ----------------- getRecentDocuments --------------------
const QList< QFileInfo > Application::getRecentDocuments() {
    return recentDocuments;
}

// ----------------- getMaxRecentDocuments --------------------
const int Application::getMaxRecentDocuments() {
    return maxRecentDocuments;
}

// -------------------- open --------------------
Component* Application::open(const QString& fileName, bool blockRefresh) {
    // set waiting cursor
    setOverrideCursor(QCursor(Qt::WaitCursor));

    Component* comp = nullptr;

    // -- Get the corresponding extension... (compatible format)
    QFileInfo fileInfo(fileName);

    // -- ask the plugin instance to create the Component instance using the
    // suffix (i.e. = check "bar" extension for fileName equals to "/path/to/file.foo.bar")
    ComponentExtension* componentExtension = ExtensionManager::getComponentExtension(fileInfo.suffix());

    // -- try harder: file may be compressed (as in ".foo.gz") so we check the complete extension
    if (componentExtension == nullptr) {
        // here check check "foo.bar" extension for fileName equals to "/path/to/file.foo.bar"
        componentExtension = ExtensionManager::getComponentExtension(fileInfo.completeSuffix());
    }

    // -- check the validity of the plugin
    if (!componentExtension) {
        // restore the normal cursor/progress bar
        restoreOverrideCursor();
        resetProgressBar();

        CAMITK_ERROR_ALT(tr("ComponentExtension Opening Error: cannot find the appropriate component plugin for opening:\n\"%1\" (extension \"%2\" or \"%3\")\nTo solve this problem, make sure that:\n - A corresponding valid plugin is present in one of the following directories: \"%4\"\n - Your application loaded the the appropriate extension before trying to open a file")
                         .arg(fileName,
                              fileInfo.suffix(),
                              fileInfo.completeSuffix(),
                              Core::getComponentDirectories().join(", ")))
    }
    else {
        std::exception_ptr otherException;

        // -- ask the plugin to create the top level component
        try {
            // open using transformed path so that anything looking like C:\\Dir1\\Dir2\\foo.zzz is unified to a C:/Dir1/Dir2/foo.zz
            comp = componentExtension->open(QFileInfo(fileName).absoluteFilePath());

            if (comp != nullptr) {
                // if a component is created, add the document to the recent list
                addRecentDocument(fileName);
                showStatusBarMessage(tr(QString("File " + fileName + " successfully loaded").toStdString().c_str()));

                CAMITK_WARNING_IF_ALT((!comp->isTopLevel()), tr("Instantiating a NON top level component."))

                if (!blockRefresh) {
                    // Cleanup unused frames and transformations, after opening component some may be unused now
                    TransformationManager::cleanupFramesAndTransformations();

                    // now refresh
                    refresh();
                }
            }
        }
        catch (AbortException& e) {
            // restore the normal cursor/progress bar
            restoreOverrideCursor();
            resetProgressBar();
            CAMITK_ERROR_ALT(tr("Opening aborted: extension: \"%1\"\nError: cannot open file \"%2\"\nReason:\n%3").arg(componentExtension->getName(), fileName, e.what()))
            comp = nullptr;
        }
        catch (std::exception& e) {
            // restore the normal cursor/progress bar
            restoreOverrideCursor();
            resetProgressBar();
            CAMITK_ERROR_ALT(tr("Opening aborted: extension: \"%1\"\nError: cannot open file \"%2\"\nExternal exception:\nThis exception was not generated directly by the extension,\nbut by one of its dependency.\nReason:\n%3").arg(componentExtension->getName(), fileName, e.what()))
            comp = nullptr;
        }
        catch (...) {
            // restore the normal cursor/progress bar
            restoreOverrideCursor();
            resetProgressBar();
            comp = nullptr;

            CAMITK_ERROR_ALT(tr("Opening aborted: extension: \"%1\"\nError: cannot open file \"%2\"\nUnknown Reason:\nThis unknown exception was not generated directly by the extension,\nbut by one of its dependency.").arg(componentExtension->getName(), fileName))

            // try harder
            otherException = std::current_exception();

            try {
                if (otherException) {
                    std::rethrow_exception(otherException);
                }
            }
            catch (const std::exception& e) {
                CAMITK_ERROR_ALT(tr("Reason:\n%1").arg(e.what()))
            }
        }
    }

    // restore the normal cursor/progress bar
    restoreOverrideCursor();
    resetProgressBar();

    return comp;
}

// -------------------- openDirectory --------------------
Component* Application::openDirectory(const QString& dirName, const QString& pluginName) {
    // set waiting cursor
    setOverrideCursor(QCursor(Qt::WaitCursor));

    Component* comp = nullptr;

    ComponentExtension* cp = ExtensionManager::getDataDirectoryComponentExtension(pluginName);

    if (cp != nullptr) {
        std::exception_ptr otherException;

        // Ask the plugin instance to create the Component instance
        try {
            comp = cp->open(QDir(dirName).absolutePath());

            // -- notify the application
            if (comp == nullptr) {
                CAMITK_ERROR_ALT(tr("Error loading directory: extension: \"%1\" error: cannot open directory: \"%2\"").arg(cp->getName(), dirName))
                showStatusBarMessage(tr("Error loading directory:") + dirName);
            }
            else {
                showStatusBarMessage(tr("Directory %1 successfully loaded").arg(dirName).toStdString().c_str());

                // In the process of loading Components and Viewers, Frames and Transformations might have
                // been created and replaced : we should remove the unused ones
                TransformationManager::cleanupFramesAndTransformations();

                // refresh all viewers
                refresh();
            }
        }
        catch (AbortException& e) {
            // restore the normal cursor/progress bar
            restoreOverrideCursor();
            resetProgressBar();
            CAMITK_ERROR_ALT(tr("Opening aborted: extension: \"%1\" error: cannot open directory: \"%2\"\nReason:\n%3").arg(cp->getName(), dirName, e.what()))
            comp = nullptr;
        }
        catch (...) {
            // restore the normal cursor/progress bar
            restoreOverrideCursor();
            resetProgressBar();
            comp = nullptr;

            CAMITK_ERROR_ALT(tr("Opening aborted: extension \"%1\" error: cannot open directory: \"%2\"\nThis exception was not generated directly by the extension,\nbut by one of its dependency.").arg(cp->getName(), dirName))

            // try harder
            otherException = std::current_exception();

            try {
                if (otherException) {
                    std::rethrow_exception(otherException);
                }
            }
            catch (const std::exception& e) {
                CAMITK_ERROR_ALT(tr("Reason:\n%1").arg(e.what()))
            }
        }
    }
    else {
        // restore the normal cursor/progress bar
        restoreOverrideCursor();
        resetProgressBar();
        CAMITK_ERROR_ALT(tr("Opening Error: Cannot find the appropriate component plugin for opening directory:\n%1\n"
                            "To solve this problem, make sure that:\n"
                            " - A corresponding valid plugin is present in one of the component directories: \"%2\"\n"
                            " - And either your application is initialized with the autoloadExtensions option\n"
                            " - Or your correctly registered your component in the CamiTK settings").arg(dirName, Core::getComponentDirectories().join(", ")))
    }

    // restore the normal cursor/progress bar
    restoreOverrideCursor();
    resetProgressBar();


    return comp;
}

// -------------------- loadWorkspace --------------------
bool Application::loadWorkspace(const QString& filepath) {
    if (PersistenceManager::loadWorkspace(filepath)) {
        // Update MainWindow settings
        MainWindow* window = getMainWindow();
        if (window) {
            window->initSettings();
        }

        // add the document to the recent list
        addRecentDocument(filepath);
        showStatusBarMessage(tr("Workspace %1 successfully loaded").arg(filepath));

        // In the process of loading Components and Viewers, Frames and Transformations might have
        // been created and replaced : We should remove the unused ones
        TransformationManager::cleanupFramesAndTransformations();

        // now refresh
        refresh();

        return true;
    }
    else {
        return false;
    }
}

// -------------------------- close ------------------------------
bool Application::close(Component* comp, bool blockRefresh) {
    int keyPressed = QMessageBox::Discard;
    bool saveOk = true;
    QString compName = comp->getName();

    // check if the top-level component needs to be saved
    if (comp->getModified()) {
        // Component was modified, propose to save it
        // CCC Exception: Use a QMessageBox::warning instead of CAMITK_WARNING as the user interaction is required
        keyPressed = QMessageBox::warning(nullptr, "Closing...", tr("Component \"") + compName + tr("\" has been modified.\nDo you want to save your change before closing?"), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Save);

        // Do we have to save or not?
        if (keyPressed == QMessageBox::Save) {
            saveOk = save(comp);
        }
    }

    // Do we have to close or not?
    if (saveOk && keyPressed != QMessageBox::Cancel) {
        // delete the data
        // The Component destructor will unregister it from Application
        // And remove its children with it
        delete comp;
        comp = nullptr;

        if (!blockRefresh) {
            // refresh all viewers (that may change their Frame)
            refresh();

            // Cleanup unused frames and transformations
            // Closing components and refreshing viewers, some may now be useless
            TransformationManager::cleanupFramesAndTransformations();

            // Refresh again so that the TransformationExplorer displays up-to-date data
            refresh();
        }

        showStatusBarMessage(compName + tr(" successfully closed..."));
        return true;
    }
    else {
        // return that the close was cancelled
        showStatusBarMessage(tr("Close cancelled..."));
        return false;
    }

}

// -------------------- save --------------------
bool Application::save(Component* component) {

    // no name -> save as
    if (component->getFileName().isEmpty()) {
        getAction("Save As")->setInputComponent(component);
        return (getAction("Save As")->apply() == Action::SUCCESS);
    }

    // -- Get the corresponding extension... (compatible format)
    QFileInfo fileInfo(component->getFileName());

    // -- ask the plugin instance to create the Component instance using the
    // suffix (i.e. = check "bar" extension for fileName equals to "/path/to/file.foo.bar")
    ComponentExtension* componentExtension = ExtensionManager::getComponentExtension(fileInfo.suffix());

    // -- try harder: file may be compressed (as in ".foo.gz") so we check the complete extension
    if (componentExtension == nullptr) {
        // here check check "foo.bar" extension for fileName equals to "/path/to/file.foo.bar"
        componentExtension = ExtensionManager::getComponentExtension(fileInfo.completeSuffix());
    }

    // -- check the validity of the plugin
    if (!componentExtension) {
        QString extensionFileSuffix = "\"" + fileInfo.suffix() + "\"";
        if (fileInfo.completeSuffix() != fileInfo.suffix()) {
            extensionFileSuffix += "(or \"" + fileInfo.completeSuffix() + "\")";
        }
        CAMITK_ERROR_ALT(tr("Saving Error: cannot find the appropriate component extension for saving component: \"%1\"\n"
                            "Of type: \"%2\"\n"
                            "In file: \"%3\"\n"
                            "Using suffix: %4\n"
                            "To solve this problem, make sure that:\n"
                            " - A component extension that manages %4 suffix is present in one of the component extension directories: [%5]\n"
                            " - And either your application is initialized with the autoloadExtensions option\n"
                            "   or you correctly registered your component in the CamiTK settings")
                         .arg(component->getName(),
                              component->metaObject()->className(),
                              fileInfo.filePath(),
                              extensionFileSuffix,
                              Core::getComponentDirectories().join(", ")))
        return false;
    }
    else {
        // ready to save
        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

        if (componentExtension->save(component)) {

            // update the last used dir
            setLastUsedDirectory(QFileInfo(component->getFileName()).absoluteDir());
            showStatusBarMessage(tr("%1 successfully saved...").arg(component->getName()));
            component->setModified(false);

            QApplication::restoreOverrideCursor();
            return true;
        }
        else {
            QApplication::restoreOverrideCursor();
            return false;
        }
    }
}

bool Application::saveWorkspace(const QString& filepath) {
    // Check whether all components are saved
    QStringList unsavedComps;
    for (auto* c : Application::getTopLevelComponents()) {
        if (c->getModified()) {
            unsavedComps.push_back(c->getName());
        }
    }
    if (!unsavedComps.isEmpty()) {
        CAMITK_WARNING_ALT(tr("Some components are not saved, saving the workspace will not save them!\nList of unsaved components:\n- %1").arg(unsavedComps.join("\n- ")));
    }
    // Make sure the mainwindow has saved its settings
    MainWindow* window = getMainWindow();
    if (window) {
        window->saveSettings();
    }
    return PersistenceManager::saveWorkspace(filepath);
}

// -------------------- getActionMap --------------------
QMap<QString, Action*>& Application::getActionMap() {
    static QMap<QString, Action*> actionMap;

    return actionMap;
}

// -------------------- getActions --------------------
const ActionList Application::getActions() {
    return getActionMap().values();
}

// -------------------- registerAllActions --------------------
int Application::registerAllActions(ActionExtension* ext) {
    int registered = 0;

    for (Action* action : ext->getActions()) {
        // check if an action with same name was not already registered
        if (getActionMap().contains(action->getName())) {
            CAMITK_ERROR_ALT(tr("Cannot register action: %1 (extension: %2, family: %3, description: \"%4\")\n"
                                "extension of same name already registered by extension \"%5\"")
                             .arg(action->getName(),
                                  action->getExtensionName(),
                                  action->getFamily(),
                                  action->getDescription(),
                                  getAction(action->getName())->getExtensionName()))
        }
        else {
            getActionMap().insert(action->getName(), action);
            registered++;
        }
    }

    return registered;
}

// -------------------- unregisterAllActions --------------------
int Application::unregisterAllActions(ActionExtension* ext) {
    int registered = 0;

    for (Action* action : ext->getActions()) {
        getActionMap().remove(action->getName());
        registered++;
    }

    return registered;
}

// ---------------- actionLessThan ----------------
bool actionLessThan(const camitk::Action* a1, const camitk::Action* a2) {
    // This method is needed by qsort in the sort method to sort action by name
    return a1->getName() < a2->getName();
}

// ---------------- viewerLessThan ----------------
bool viewerLessThan(const camitk::Viewer* v1, const camitk::Viewer* v2) {
    // This method is needed by qsort in the sort method to sort viewer by name
    return v1->getName() < v2->getName();
}


// ---------------- sort ----------------
ActionList Application::sort(ActionSet actionSet) {
    // sort actions by name
    ActionList actionList = actionSet.values();
    std::sort(actionList.begin(), actionList.end(), actionLessThan);

    return actionList;
}

ViewerList Application::sort(ViewerSet viewerSet) {
    // sort actions by name
    ViewerList viewerList = viewerSet.values();
    std::sort(viewerList.begin(), viewerList.end(), viewerLessThan);

    return viewerList;
}


// ---------------- getAction ----------------
Action* Application::getAction(QString name) {
    return getActionMap().value(name);
}

// ---------------- getActions ----------------
ActionList Application::getActions(Component* component) {
    ActionSet actions;

    if (component) {
        QStringList componentHierarchy = component->getHierarchy();

        for (Action* currentAct : Application::getActions()) {
            if (componentHierarchy.contains(currentAct->getComponentClassName())) {
                actions.insert(currentAct);
            }
        }
    }
    else {
        for (Action* currentAct : Application::getActions()) {
            if (currentAct->getComponentClassName().isEmpty()) {
                actions.insert(currentAct);
            }
        }
    }

    return sort(actions);
}

// ---------------- getActions ----------------
ActionList Application::getActions(ComponentList cList) {
    // if this is an empty list, return all actions not using any component
    if (cList.size() == 0) {
        return getActions(nullptr);
    }
    else {
        ActionSet actions;

        for (Component* currentComp : cList) {
            ActionList listOfCompatibleActions = getActions(currentComp);
            actions += ActionSet(listOfCompatibleActions.begin(), listOfCompatibleActions.end());
        }

        return sort(actions);
    }
}

// ---------------- getActions ----------------
ActionList Application::getActions(ComponentList selComp, QString tag) {
    // first build the list of possible actions for cList
    ActionList possibleActions = getActions(selComp);

    // now check possibleActions considering the tag value
    ActionList actions;

    for (Action* action : possibleActions) {
        if (action->getTag().contains(tag)) {
            actions.append(action);
        }
    }

    // sort and return
    std::sort(actions.begin(), actions.end(), actionLessThan);
    return actions;

}

// -------------------- getViewerMap --------------------
QMap<QString, Viewer*>& Application::getViewerMap() {
    static QMap<QString, Viewer*> viewerMap;

    return viewerMap;
}

// -------------------- getViewer --------------------
Viewer* Application::getViewer(QString name) {
    return getViewerMap().value(name);
}

// -------------------- registerViewer --------------------
bool Application::registerViewer(Viewer* viewer) {
    // first check if a viewer with the same name is not already registered
    if (getViewerMap().contains(viewer->getName())) {
        // if it is already registered, find out more information about the viewer extension
        // that manages the already registered viewer
        QString extensionName = "";
        ViewerExtension* extension = getViewerExtension(viewer);

        if (extension != nullptr) {
            extensionName = extension->getName();
            CAMITK_ERROR_ALT(tr("Cannot register viewer: %1 (description: \"%2\")\n"
                                "viewer of same name already registered in extension %3")
                             .arg(viewer->getName(), viewer->getDescription(), extensionName))
        }
        else {
            // should never happen
            CAMITK_ERROR_ALT(tr("Cannot register viewer: %1 (description: \"%2\")\n"
                                "viewer of same name already registered in an unknown extension...")
                             .arg(viewer->getName(), viewer->getDescription()))
        }

        return false;
    }
    else {
        // everything is alright register the viewer
        getViewerMap().insert(viewer->getName(), viewer);
        return true;
    }
}

// -------------------- registerAllViewers --------------------
int Application::registerAllViewers(ViewerExtension* ext) {
    int registered = 0;

    // register all the viewer instances in this extension
    for (Viewer* viewer : ext->getViewers()) {
        if (registerViewer(viewer)) {
            registered++;
        }
    }

    return registered;
}

// -------------------- getViewers --------------------
const ViewerList Application::getViewers(Component* component) {
    ViewerSet viewers;

    if (component) {
        QStringList componentHierarchy = component->getHierarchy();

        for (Viewer* currentViewer : Application::getViewers()) {
            for (QString compType : currentViewer->getComponentClassNames()) {
                if (componentHierarchy.contains(compType)) {
                    viewers.insert(currentViewer);
                }
            }
        }
    }
    else {
        for (Viewer* currentViewer : Application::getViewers()) {
            for (QString compType : currentViewer->getComponentClassNames()) {
                if (compType.isEmpty()) {
                    viewers.insert(currentViewer);
                }
            }
        }
    }

    return sort(viewers);
}

// -------------------- getNewViewer --------------------
Viewer* Application::getNewViewer(QString name, QString className) {

    int i = 0;
    QList<ViewerExtension*> vl = ExtensionManager::getViewerExtensionsList();

    while (i < vl.size() && vl.at(i)->getViewerClassName() != className) {
        i++;
    }

    if (i < vl.size()) {
        ViewerExtension* ve = vl.at(i);
        return ve->getNewInstance(name);
    }
    else {
        CAMITK_ERROR_ALT(tr("Cannot find a viewer extension that manage viewers of type \"%1\"\n").arg(className))
        return nullptr;
    }
}

// -------------------- getViewers --------------------
const ViewerList Application::getViewers() {
    return getViewerMap().values();
}

// -------------------- unregisterAllViewers --------------------
int Application::unregisterAllViewers(ViewerExtension* ext) {
    int unregistered = 0;

    for (Viewer* viewer : ext->getViewers()) {
        getViewerMap().remove(viewer->getName());
        unregistered++;
    }

    return unregistered;
}

// -------------------- getViewerExtension --------------------
ViewerExtension* Application::getViewerExtension(Viewer* viewer) {

    int i = 0;
    bool found = false;
    ViewerExtension* extension = nullptr;

    while (i < ExtensionManager::getViewerExtensionsList().size() && !found) {
        int j = 0;

        while (j < ExtensionManager::getViewerExtensionsList().at(i)->getViewers().size() && !found) {
            found = (ExtensionManager::getViewerExtensionsList().at(i)->getViewers().at(j)->getName() == viewer->getName());
            j++;
        }

        i++;
    }

    if (found) {
        extension = ExtensionManager::getViewerExtensionsList().at(i - 1);
    }

    return extension;
}

// ---------- isAlive ----------
bool Application::isAlive(Component* comp) {
    return getAllComponents().contains(comp);
}

bool Application::isAlive(Action* action) {
    return getActions().contains(action);
}

// -------------------- hasModified --------------------
bool Application::hasModified() {
    // look for a top level component that has been modified
    int i = 0;

    while (i < getTopLevelComponents().size() && !getTopLevelComponents() [i]->getModified()) {
        i++;
    }

    return (i < getTopLevelComponents().size());
}

// -------------------- getUniqueComponentName --------------------
QString Application::getUniqueComponentName(QString name, const ComponentList& components) {
    auto nameEquals = [&name](const Component * existingComp) {
        return existingComp->getName() == name;
    };

    // look for (number) in name
    QRegularExpression numSearch(R"regex((^.*)\((\d+)\)$)regex");

    // If the same name is already present, add "(index)" to it (same for the label)
    while (std::ranges::any_of(components, nameEquals)) {
        // Does name have "(number)
        QRegularExpressionMatch match = numSearch.match(name);
        if (match.hasMatch()) {
            int nextIndex = match.capturedTexts()[2].toInt() + 1;
            name = match.capturedTexts()[1] + QString("(%1)").arg(nextIndex);
        }
        else {
            name = name + " (2)";
        }
    }
    return name;
}

// -------------------- addComponent --------------------
void Application::addComponent(Component* comp) {
    getAllComponentList().append(comp);

    if (comp->getParentComponent() == nullptr) {
        // this a top level component, make sure it has a unique name
        QString newName = getUniqueComponentName(comp->getName(), getTopLevelComponentList());
        if (newName != comp->getName()) {
            comp->setName(newName);
        }
        getTopLevelComponentList().append(comp);
    }
}

// -------------------- removeComponent --------------------
void Application::removeComponent(Component* comp) {
    getAllComponentList().removeAll(comp);
    getTopLevelComponentList().removeAll(comp);
    getSelectedComponentList().removeAll(comp);
}

// -------------------- getTopLevelComponentList --------------------
ComponentList& Application::getTopLevelComponentList() {
    static ComponentList topLevelComponents;

    return topLevelComponents;
}

// -------------------- getAllComponentList --------------------
ComponentList& Application::getAllComponentList() {
    static ComponentList allComponents;

    return allComponents;
}

// -------------------- getSelectedComponentList --------------------
ComponentList& Application::getSelectedComponentList() {
    static ComponentList selectedComponents;

    return selectedComponents;
}

// -------------------- getTopLevelComponents --------------------
const ComponentList& Application::getTopLevelComponents() {
    return getTopLevelComponentList();
}

// -------------------- getAllComponents --------------------
const ComponentList& Application::getAllComponents() {
    return getAllComponentList();
}

// -------------------- getSelectedComponents --------------------
const ComponentList& Application::getSelectedComponents() {
    return getSelectedComponentList();
}

// -------------------- setSelected --------------------
void Application::setSelected(Component* component, bool isSelected) {
    // in case the component is selected again, put it in the end
    // therefore the correct processing is :
    // 1. remove component from the list
    // 2. if isSelected is true, append
    getSelectedComponentList().removeAll(component);

    if (isSelected) {
        getSelectedComponentList().append(component);
    }
}

// -------------------- clearSelectedComponents --------------------
void Application::clearSelectedComponents() {
    for (Component* comp : getSelectedComponentList()) {
        comp->setSelected(false);
    }

    getSelectedComponentList().clear();
}

// -------------------- setSelectedAction --------------------
void Application::setTriggeredAction(Action* action) {
    currentAction = action;
}

// -------------------- getSelectedAction --------------------
Action* Application::getTriggeredAction() {
    return currentAction;
}

// -------------------- getHistory --------------------
QStack<HistoryItem>& Application::getHistory() {
    // static singleton declaration
    static QStack<HistoryItem> history;
    return history;
}

// -------------------- addHistory ------------------------------
void Application::addHistoryItem(HistoryItem item) {
    getHistory().push(item);
}

// -------------------- removeLastHistoryItem --------------------
HistoryItem Application::removeLastHistoryItem() {
    return getHistory().pop();
}

// -------------------- saveHistoryAsSCXML --------------------
void Application::saveHistoryAsSCXML() {
    // Empty history => do nothing
    if (Application::getHistory().isEmpty()) {
        CAMITK_WARNING_ALT(tr("History is empty: there is no history to save."))
        return;
    }

    // Create the XML document
    QDomDocument doc;
    QDomNode xmlProlog = doc.createProcessingInstruction("xml", R"(version="1.0" encoding="UTF-8")");
    doc.appendChild(xmlProlog);

    // root element
    QDomElement root = doc.createElement("scxml");
    root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    root.setAttribute("xmlns", "http://camitk.imag.fr/3/smallScxml");
    root.setAttribute("xmlns:camitk", "http://camitk.imag.fr/3/asm");
    root.setAttribute("xsi:schemaLocation", "http://camitk.imag.fr/3/smallScxml/../resources/smallScxml.xsd");
    root.setAttribute("initial", "Initialize");
    doc.appendChild(root);

    // SXML always contains an Initialize element which describe the pipeline
    QDomElement initializeElt = doc.createElement("state");
    root.appendChild(initializeElt);
    initializeElt.setAttribute("id", "Initialize");
    QDomElement initializeElt_onEntry = doc.createElement("onentry");
    initializeElt.appendChild(initializeElt_onEntry);
    QDomElement initializeElt_onState = doc.createElement("camitk:onState");
    initializeElt_onEntry.appendChild(initializeElt_onState);
    // Description of the pipeline
    QDomElement initializeElt_desc = doc.createElement("camitk:description");
    initializeElt_onState.appendChild(initializeElt_desc);
    // create the pipeline description that will be filled while processing the history items.
    QString pipelineDescription = "This pipeline will process several actions on the input component(s): <br /> <ul>";
    // Transition
    QDomElement initializeElt_transition = doc.createElement("transition");
    initializeElt_transition.setAttribute("event", "Next");
    initializeElt_transition.setAttribute("target", "Action 1");
    initializeElt.appendChild(initializeElt_transition);
    QDomElement initializeElt_transition2 = doc.createElement("transition");

    // Create a list of all components created during the pipeline, to know which ones to delete once pipeline is reset
    // by the action state machine
    QList<HistoryComponent> allCreatedComponents;

    // Main loop across the different actions in the history
    for (int i = 0; i < Application::getHistory().size(); i++) {
        // Get the current history element, i.e. the action of the pipeline with its parameters
        HistoryItem historyItem = Application::getHistory().at(i);
        Action* action = Application::getAction(historyItem.getName());
        // state
        QDomElement stateElement = doc.createElement("state");
        root.appendChild(stateElement);
        stateElement.setAttribute("id", "Action " + QString::number(i + 1));
        // onEntry
        QDomElement onentryElement = doc.createElement("onentry");
        stateElement.appendChild(onentryElement);
        QDomElement onStateElement = doc.createElement("camitk:onState");
        onentryElement.appendChild(onStateElement);

        // action description
        QDomElement descriptionElement = doc.createElement("camitk:description");
        QDomText descriptionText = doc.createTextNode(action->getDescription());
        descriptionElement.appendChild(descriptionText);
        onStateElement.appendChild(descriptionElement);

        // action name & parameters
        QDomElement actionElement = doc.createElement("camitk:action");
        onStateElement.appendChild(actionElement);
        // action name
        QDomElement actionElementName = doc.createElement("camitk:name");
        actionElement.appendChild(actionElementName);
        pipelineDescription.append("<li>" + action->getName() + "</li>");
        QDomText actionElementNameText = doc.createTextNode(action->getName());
        actionElementName.appendChild(actionElementNameText);

        // action parameters
        QDomElement parametersElement = doc.createElement("camitk:parameters");
        actionElement.appendChild(parametersElement);

        if (!action->dynamicPropertyNames().isEmpty()) {
            for (QByteArray actionParameter : action->dynamicPropertyNames()) {
                QDomElement parameterElement = doc.createElement("camitk:parameter");
                parameterElement.setAttribute("name", QString(actionParameter));
                parameterElement.setAttribute("type", QVariant::typeToName(action->property(actionParameter).type()));
                parameterElement.setAttribute("value", action->property(actionParameter.data()).toString());
                parametersElement.appendChild(parameterElement);
            }
        }

        // action input components
        if (!historyItem.getInputHistoryComponents().isEmpty()) {
            QDomElement actionElementInputComp = doc.createElement("camitk:inputs");
            actionElement.appendChild(actionElementInputComp);

            for (int j = 0; j < historyItem.getInputHistoryComponents().size(); j++) {
                QDomElement componentElement = doc.createElement("camitk:component");
                // determine the type of each input component (image, meshes or other)
                HistoryComponent inputHistoryComponents = historyItem.getInputHistoryComponents().at(j);

                switch (inputHistoryComponents.getType()) {
                    case HistoryComponent::IMAGE_COMPONENT:
                        componentElement.setAttribute("type", "ImageComponent");
                        break;

                    case HistoryComponent::MESH_COMPONENT:
                        componentElement.setAttribute("type", "MeshComponent");
                        break;

                    case HistoryComponent::OTHER:
                    default:
                        componentElement.setAttribute("type", "Other");
                        break;
                }

                // save its name
                componentElement.setAttribute("name", inputHistoryComponents.getName());

                // save the current DOM element in the XML structure
                actionElementInputComp.appendChild(componentElement);
            }
        }

        // action output components
        if (!historyItem.getOutputHistoryComponents().isEmpty()) {
            QDomElement outputsElement = doc.createElement("camitk:outputs");
            actionElement.appendChild(outputsElement);

            for (int j = 0; j < historyItem.getOutputHistoryComponents().size(); j++) {
                QDomElement componentElement = doc.createElement("camitk:component");
                // determine the type of each input component (image, meshes or other)
                HistoryComponent outputHistoryComponents = historyItem.getOutputHistoryComponents().at(j);
                allCreatedComponents.append(outputHistoryComponents);    // note the component created

                switch (outputHistoryComponents.getType()) {
                    case HistoryComponent::IMAGE_COMPONENT:
                        componentElement.setAttribute("type", "ImageComponent");
                        break;

                    case HistoryComponent::MESH_COMPONENT:
                        componentElement.setAttribute("type", "MeshComponent");
                        break;

                    case HistoryComponent::OTHER:
                    default:
                        componentElement.setAttribute("type", "Other");
                        break;
                }

                // save its name
                componentElement.setAttribute("name", outputHistoryComponents.getName());

                // save the current DOM element in the XML structure
                outputsElement.appendChild(componentElement);
            }
        }

        // Transitions
        if (Application::getHistory().size() >= 1) {   // else, no transition at all
            // Next transition
            QDomElement nextTransitionElement = doc.createElement("transition");

            if (i == Application::getHistory().size() - 1) {   // Last action element => next element = Bye element.
                nextTransitionElement.setAttribute("target", "Bye");
            }
            else {   // Next generic action state
                nextTransitionElement.setAttribute("target", "Action " + QString::number(i + 2));
            }

            nextTransitionElement.setAttribute("event", "Next");

            // Back transition
            QDomElement backTransitionElement = doc.createElement("transition");
            backTransitionElement.setAttribute("event", "Back");

            if (i == 0) {   // Back to Initialize state
                backTransitionElement.setAttribute("target", "Initialize");
            }
            else {   // Back to previous state and delete optional created component in memory
                backTransitionElement.setAttribute("target", "Action " + QString::number(i));
                // Verify that previous element has not created components in memory
                HistoryItem previousItem = Application::getHistory().at(i - 1);

                if (!previousItem.getOutputHistoryComponents().isEmpty()) {
                    // Ask for deletion of each component created at the previous element
                    QDomElement onTransitionElement =  doc.createElement("onTransition");
                    backTransitionElement.appendChild(onTransitionElement);
                    QDomElement closeElement = doc.createElement("camitk:close");
                    onTransitionElement.appendChild(closeElement);

                    for (HistoryComponent outputHistoryComponent : previousItem.getOutputHistoryComponents()) {
                        QDomElement backTransitionComponentElement = doc.createElement("camitk:component");
                        closeElement.appendChild(backTransitionComponentElement);

                        switch (outputHistoryComponent.getType()) {
                            case HistoryComponent::IMAGE_COMPONENT:
                                backTransitionComponentElement.setAttribute("type", "ImageComponent");
                                break;

                            case HistoryComponent::MESH_COMPONENT:
                                backTransitionComponentElement.setAttribute("type", "MeshComponent");
                                break;

                            case HistoryComponent::OTHER:
                            default:
                                backTransitionComponentElement.setAttribute("type", "Other");
                                break;
                        }

                        backTransitionComponentElement.setAttribute("name", outputHistoryComponent.getName());
                    }
                }
            }

            // add back first so that the "Back" button appears on the left
            stateElement.appendChild(backTransitionElement);
            // and "Next" appears on the right
            stateElement.appendChild(nextTransitionElement);

        } // End transitions
    }

    // Update description of the pipeline, now that we have filled the it!
    initializeElt_desc.appendChild(doc.createCDATASection(pipelineDescription));

    // Last element : Bye
    QDomElement finalElt = doc.createElement("state");
    root.appendChild(finalElt);
    finalElt.setAttribute("id", "Bye");
    finalElt.setAttribute("final", "true");
    QDomElement finalElt_onEntry = doc.createElement("onentry");
    finalElt.appendChild(finalElt_onEntry);
    QDomElement finalElt_onState = doc.createElement("camitk:onState");
    finalElt_onEntry.appendChild(finalElt_onState);
    // Thanks !
    QDomElement finalElt_desc = doc.createElement("camitk:description");
    finalElt_onState.appendChild(finalElt_desc);
    QDomCDATASection finalEltDesc;
    finalElt_desc.appendChild(doc.createCDATASection("Thanks you for using the CamiTK Action State Machine !"));
    // Transition
    QDomElement finalElt_transition = doc.createElement("transition");
    finalElt_transition.setAttribute("event", "Back to the beginning");
    finalElt_transition.setAttribute("target", "Initialize");
    finalElt.appendChild(finalElt_transition);

    // Ask for deletion of all components created in the pipeline
    if (!allCreatedComponents.isEmpty()) {
        QDomElement finalEltTransition_onTransition =  doc.createElement("onTransition");
        finalElt_transition.appendChild(finalEltTransition_onTransition);
        QDomElement finalEltTransition_close = doc.createElement("camitk:close");
        finalEltTransition_onTransition.appendChild(finalEltTransition_close);

        for (HistoryComponent createdComponent : allCreatedComponents) {
            QDomElement finalEltTransition_comp = doc.createElement("camitk:component");
            finalEltTransition_close.appendChild(finalEltTransition_comp);

            switch (createdComponent.getType()) {
                case HistoryComponent::IMAGE_COMPONENT:
                    finalEltTransition_comp.setAttribute("type", "ImageComponent");
                    break;

                case HistoryComponent::MESH_COMPONENT:
                    finalEltTransition_comp.setAttribute("type", "MeshComponent");
                    break;

                case HistoryComponent::OTHER:
                default:
                    finalEltTransition_comp.setAttribute("type", "Other");
                    break;
            }

            finalEltTransition_comp.setAttribute("name", createdComponent.getName());
        }
    }

    // note: final element will automatically have a "Quit" transition, added by the action state machine.

    // Write the xml to a file
    QString outputFileName = QFileDialog::getSaveFileName(nullptr, tr("Save history of actions ..."), Core::getCurrentWorkingDir() + "/camitk-history-" + QDateTime::currentDateTime().toString("yyyyMMdd-HHmmss") + ".scxml", tr("SCXML Files (*.scxml)"));

    QFile outputFile(outputFileName);

    if (outputFile.open(QFile::WriteOnly | QFile::Text)) {
        QTextStream out(&outputFile);
        // automatically indent XML output
        doc.save(out, 4);
    }
    else {
        CAMITK_ERROR_ALT(tr("Cannot open file \"%1\" for writing. No history saved.").arg(outputFileName))
    }
}


// -------------------- getSelectedLanguage --------------------
QString Application::getSelectedLanguage() {
    // Get the path of the Language File in the setting file
    QSettings& settings(Application::getSettings());
    settings.beginGroup(Application::getName() + ".Application");
    // Get the language an d flag for the current Application instance
    //QString language = settings.value("language").toString();
    QString languageAbreviation = settings.value("languageAbreviation").toString();
    //QString flagFile = settings.value("flagFilename").toString();
    settings.endGroup();

    return languageAbreviation;
}

// -------------------- initResources --------------------
void Application::initResources() {

    // Get the selected language
    QString selectedLanguage = Application::getSelectedLanguage();

    // if a language is defined, then try to load the translation file
    if (!selectedLanguage.isEmpty()) {
        // Load the application translation
        translator = new QTranslator();
        QString languageFile = ":/translate_" + getName().remove("camitk-") + "/translate/translate_" + selectedLanguage + ".qm";

        if (translator->load(languageFile)) {
            QCoreApplication::installTranslator(translator);
        }
        else {
            CAMITK_WARNING_ALT(tr("Cannot load file: %1").arg(languageFile))
        }
    }
}

// -------------------- createProperties --------------------
void Application::createProperties() {
    // instantiate the application property object
    propertyObject = new PropertyObject(getName());

    Property* property;

    //-- Auto Load Last Opened Component
    property = new Property("Auto Load Last Opened Component", false, "If true the last opened components from the previous run is opened when the application starts", "");
    propertyObject->addProperty(property);

    //-- Logger Level
    property = new Property("Logger Level", Log::getLogger()->getLogLevel(), "Logger level. Set the verbosity level of the application logger.", "");
    // Set the enum typeLogger Level"
    property->setEnumTypeName("LogLevel");
    // Set a custom list of GUI names
    QStringList enumGuiText;

    for (const InterfaceLogger::LogLevel l : {
                InterfaceLogger::NONE, InterfaceLogger::ERROR, InterfaceLogger::WARNING, InterfaceLogger::INFO, InterfaceLogger::TRACE
            }) {
        enumGuiText << Log::getLevelAsString(l);
    }
    property->setAttribute("enumNames", enumGuiText);
    propertyObject->addProperty(property);

    //-- Message Box Level
    property = new Property("Message Box Level", Log::getLogger()->getMessageBoxLevel(), "Message box level. Set the lowest log level that will open modal message box for messages instead of unintrusive log.", "");
    // Set the enum type
    property->setEnumTypeName("LogLevel");
    property->setAttribute("enumNames", enumGuiText);
    propertyObject->addProperty(property);

    //-- Log messages to standard output
    property = new Property("Log to Standard Output", Log::getLogger()->getLogToStandardOutput(), "If true all log messages above the current logger level are printed on the standard output.", "");
    propertyObject->addProperty(property);

    //-- Log messages to file
    property = new Property("Log to File", Log::getLogger()->getLogToFile(), "If true all the log messages above the current logger level are printed in the log file. To change the log file use the application preference dialog or do it programmatically (see InterfaceLogger API), as the \"Logger Parameters\" action will only change the value for the current session.", "");
    propertyObject->addProperty(property);

    //-- Display Debug Information
    property = new Property("Display Debug Information to Log Message", Log::getLogger()->getDebugInformation(), "If true display some debug information in the log message header (generally includes method name, file and line number from where the log message was issued. This is very useful for debugging extension projects.", "");
    propertyObject->addProperty(property);

    //-- Display Time stamp Information
    property = new Property("Display Time Stamp Information to Log Message", Log::getLogger()->getTimeStampInformation(), "If true display the time stamp for every log message in the \"yyyy-MM-dd HH:mm:ss.zzz\" format.", "");
    propertyObject->addProperty(property);

    // -- Window Separator Size
    property = new Property("Window Separator Size", 2, "The size in pixels of the separator between dock widgets and the central widget. Change the value if you prefer a larger splitter. If value is 1, no highlight is visible.", "pixels");
    property->setAttribute("minimum", 1);
    propertyObject->addProperty(property);
}

// ---------------------- getPropertyObject ------------------
PropertyObject* Application::getPropertyObject() {
    return propertyObject;
}

// ---------------- eventFilter ----------------
bool Application::eventFilter(QObject* object, QEvent* event) {
    // watch propertyObject instance for dynamic property changes
    if (event->type() == QEvent::DynamicPropertyChange) {

        //-- first perform the proper action
        applyPropertyValues();

        //-- then save the new values in the settings
        propertyObject->saveToSettings(Application::getName() + ".Application");

        return true;
    }
    else {
        // otherwise pass the event on to the parent class
        return QApplication::eventFilter(object, event);
    }

}

// ---------------------- applyPropertyValues ------------------
void Application::applyPropertyValues() {
    //-- List of settings that does not require any actions when the value is changed
    // - "Auto Load Last Opened Component";

    //-- All other property values to apply
    std::array<InterfaceLogger::LogLevel, 5> logLevelNames { {InterfaceLogger::NONE, InterfaceLogger::ERROR, InterfaceLogger::WARNING, InterfaceLogger::INFO, InterfaceLogger::TRACE} };

    Log::getLogger()->setLogLevel(logLevelNames[propertyObject->property("Logger Level").toInt()]);
    Log::getLogger()->setMessageBoxLevel(logLevelNames[propertyObject->property("Message Box Level").toInt()]);
    Log::getLogger()->setDebugInformation(propertyObject->property("Display Debug Information to Log Message").toBool());
    Log::getLogger()->setTimeStampInformation(propertyObject->property("Display Time Stamp Information to Log Message").toBool());
    Log::getLogger()->setLogToStandardOutput(propertyObject->property("Log to Standard Output").toBool());
    Log::getLogger()->setLogToFile(propertyObject->property("Log to File").toBool());

    applyMainWindowPropertyValues();
}


// ---------------------- applyMainWindowPropertyValues ------------------
void Application::applyMainWindowPropertyValues() {
    // increase the size and highlight the separator between dock widgets and central widget
    // by setting the stylesheet
    if (mainWindow != nullptr) {
        mainWindow->setStyleSheet(QString("QMainWindow::separator { \
          width: %1px; \
          height: %1px; \
        } \
        QMainWindow::separator:hover { \
          background: palette(highlight); \
        }").arg(propertyObject->property("Window Separator Size").toInt()));
    }
}
}