summaryrefslogtreecommitdiff
path: root/src/VBox/Frontends/VirtualBox/src/manager/chooser/UIChooserAbstractModel.cpp
blob: c7a3d4d956c25feea8696473a90263bbb740da22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
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
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
/* $Id$ */
/** @file
 * VBox Qt GUI - UIChooserAbstractModel class implementation.
 */

/*
 * Copyright (C) 2012-2022 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

/* Qt includes: */
#include <QRegExp>
#include <QRegularExpression>
#include <QThread>

/* GUI includes: */
#include "UICommon.h"
#include "UIChooser.h"
#include "UIChooserAbstractModel.h"
#include "UIChooserNode.h"
#include "UIChooserNodeGroup.h"
#include "UIChooserNodeGlobal.h"
#include "UIChooserNodeMachine.h"
#include "UICloudNetworkingStuff.h"
#include "UIExtraDataManager.h"
#include "UIMessageCenter.h"
#include "UINotificationCenter.h"
#include "UIProgressTaskReadCloudMachineList.h"
#include "UIVirtualBoxEventHandler.h"
#include "UIVirtualMachineItemCloud.h"

/* COM includes: */
#include "CCloudMachine.h"
#include "CCloudProfile.h"
#include "CCloudProvider.h"
#include "CMachine.h"

/* Type defs: */
typedef QSet<QString> UIStringSet;


/** QThread subclass allowing to save group settings asynchronously. */
class UIThreadGroupSettingsSave : public QThread
{
    Q_OBJECT;

signals:

    /** Notifies about machine with certain @a uMachineId to be reloaded. */
    void sigReload(const QUuid &uMachineId);

    /** Notifies about task is complete. */
    void sigComplete();

public:

    /** Returns group settings saving thread instance. */
    static UIThreadGroupSettingsSave *instance();
    /** Prepares group settings saving thread instance. */
    static void prepare();
    /** Cleanups group settings saving thread instance. */
    static void cleanup();

    /** Configures @a group settings saving thread with corresponding @a pListener.
      * @param  oldLists  Brings the old settings list to be compared.
      * @param  newLists  Brings the new settings list to be saved. */
    void configure(QObject *pParent,
                   const QMap<QString, QStringList> &oldLists,
                   const QMap<QString, QStringList> &newLists);

protected:

    /** Constructs group settings saving thread. */
    UIThreadGroupSettingsSave();
    /** Destructs group settings saving thread. */
    virtual ~UIThreadGroupSettingsSave() RT_OVERRIDE;

    /** Contains a thread task to be executed. */
    virtual void run() RT_OVERRIDE;

    /** Holds the singleton instance. */
    static UIThreadGroupSettingsSave *s_pInstance;

    /** Holds the map of group settings to be compared. */
    QMap<QString, QStringList> m_oldLists;
    /** Holds the map of group settings to be saved. */
    QMap<QString, QStringList> m_newLists;
};


/** QThread subclass allowing to save group definitions asynchronously. */
class UIThreadGroupDefinitionsSave : public QThread
{
    Q_OBJECT;

signals:

    /** Notifies about task is complete. */
    void sigComplete();

public:

    /** Returns group definitions saving thread instance. */
    static UIThreadGroupDefinitionsSave *instance();
    /** Prepares group definitions saving thread instance. */
    static void prepare();
    /** Cleanups group definitions saving thread instance. */
    static void cleanup();

    /** Configures group definitions saving thread with corresponding @a pListener.
      * @param  lists  Brings definitions lists to be saved. */
    void configure(QObject *pListener,
                   const QMap<QString, QStringList> &lists);

protected:

    /** Constructs group definitions saving thread. */
    UIThreadGroupDefinitionsSave();
    /** Destructs group definitions saving thread. */
    virtual ~UIThreadGroupDefinitionsSave() RT_OVERRIDE;

    /** Contains a thread task to be executed. */
    virtual void run() RT_OVERRIDE;

    /** Holds the singleton instance. */
    static UIThreadGroupDefinitionsSave *s_pInstance;

    /** Holds the map of group definitions to be saved. */
    QMap<QString, QStringList>  m_lists;
};


/*********************************************************************************************************************************
*   Class UIThreadGroupSettingsSave implementation.                                                                              *
*********************************************************************************************************************************/

/* static */
UIThreadGroupSettingsSave *UIThreadGroupSettingsSave::s_pInstance = 0;

/* static */
UIThreadGroupSettingsSave *UIThreadGroupSettingsSave::instance()
{
    return s_pInstance;
}

/* static */
void UIThreadGroupSettingsSave::prepare()
{
    /* Make sure instance is not prepared: */
    if (s_pInstance)
        return;

    /* Crate instance: */
    new UIThreadGroupSettingsSave;
}

/* static */
void UIThreadGroupSettingsSave::cleanup()
{
    /* Make sure instance is prepared: */
    if (!s_pInstance)
        return;

    /* Delete instance: */
    delete s_pInstance;
}

void UIThreadGroupSettingsSave::configure(QObject *pParent,
                                          const QMap<QString, QStringList> &oldLists,
                                          const QMap<QString, QStringList> &newLists)
{
    m_oldLists = oldLists;
    m_newLists = newLists;
    UIChooserAbstractModel *pChooserAbstractModel = qobject_cast<UIChooserAbstractModel*>(pParent);
    AssertPtrReturnVoid(pChooserAbstractModel);
    {
        connect(this, &UIThreadGroupSettingsSave::sigComplete,
                pChooserAbstractModel, &UIChooserAbstractModel::sltGroupSettingsSaveComplete);
    }
}

UIThreadGroupSettingsSave::UIThreadGroupSettingsSave()
{
    /* Assign instance: */
    s_pInstance = this;
}

UIThreadGroupSettingsSave::~UIThreadGroupSettingsSave()
{
    /* Make sure thread work is complete: */
    wait();

    /* Erase instance: */
    s_pInstance = 0;
}

void UIThreadGroupSettingsSave::run()
{
    /* COM prepare: */
    COMBase::InitializeCOM(false);

    /* For every particular machine ID: */
    foreach (const QString &strId, m_newLists.keys())
    {
        /* Get new group list/set: */
        const QStringList &newGroupList = m_newLists.value(strId);
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
        const UIStringSet newGroupSet(newGroupList.begin(), newGroupList.end());
#else
        const UIStringSet &newGroupSet = UIStringSet::fromList(newGroupList);
#endif
        /* Get old group list/set: */
        const QStringList &oldGroupList = m_oldLists.value(strId);
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
        const UIStringSet oldGroupSet(oldGroupList.begin(), oldGroupList.end());
#else
        const UIStringSet &oldGroupSet = UIStringSet::fromList(oldGroupList);
#endif
        /* Make sure group set changed: */
        if (newGroupSet == oldGroupSet)
            continue;

        /* The next steps are subsequent.
         * Every of them is mandatory in order to continue
         * with common cleanup in case of failure.
         * We have to simulate a try-catch block. */
        CSession comSession;
        CMachine comMachine;
        do
        {
            /* 1. Open session: */
            comSession = uiCommon().openSession(QUuid(strId));
            if (comSession.isNull())
                break;

            /* 2. Get session machine: */
            comMachine = comSession.GetMachine();
            if (comMachine.isNull())
                break;

            /* 3. Set new groups: */
            comMachine.SetGroups(newGroupList.toVector());
            if (!comMachine.isOk())
            {
                msgCenter().cannotSetGroups(comMachine);
                break;
            }

            /* 4. Save settings: */
            comMachine.SaveSettings();
            if (!comMachine.isOk())
            {
                msgCenter().cannotSaveMachineSettings(comMachine);
                break;
            }
        } while (0);

        /* Cleanup if necessary: */
        if (comMachine.isNull() || !comMachine.isOk())
            emit sigReload(QUuid(strId));
        if (!comSession.isNull())
            comSession.UnlockMachine();
    }

    /* Notify listeners about completeness: */
    emit sigComplete();

    /* COM cleanup: */
    COMBase::CleanupCOM();
}


/*********************************************************************************************************************************
*   Class UIThreadGroupDefinitionsSave implementation.                                                                           *
*********************************************************************************************************************************/

/* static */
UIThreadGroupDefinitionsSave *UIThreadGroupDefinitionsSave::s_pInstance = 0;

/* static */
UIThreadGroupDefinitionsSave *UIThreadGroupDefinitionsSave::instance()
{
    return s_pInstance;
}

/* static */
void UIThreadGroupDefinitionsSave::prepare()
{
    /* Make sure instance is not prepared: */
    if (s_pInstance)
        return;

    /* Crate instance: */
    new UIThreadGroupDefinitionsSave;
}

/* static */
void UIThreadGroupDefinitionsSave::cleanup()
{
    /* Make sure instance is prepared: */
    if (!s_pInstance)
        return;

    /* Delete instance: */
    delete s_pInstance;
}

void UIThreadGroupDefinitionsSave::configure(QObject *pParent,
                                             const QMap<QString, QStringList> &groups)
{
    m_lists = groups;
    UIChooserAbstractModel *pChooserAbstractModel = qobject_cast<UIChooserAbstractModel*>(pParent);
    AssertPtrReturnVoid(pChooserAbstractModel);
    {
        connect(this, &UIThreadGroupDefinitionsSave::sigComplete,
                pChooserAbstractModel, &UIChooserAbstractModel::sltGroupDefinitionsSaveComplete);
    }
}

UIThreadGroupDefinitionsSave::UIThreadGroupDefinitionsSave()
{
    /* Assign instance: */
    s_pInstance = this;
}

UIThreadGroupDefinitionsSave::~UIThreadGroupDefinitionsSave()
{
    /* Make sure thread work is complete: */
    wait();

    /* Erase instance: */
    s_pInstance = 0;
}

void UIThreadGroupDefinitionsSave::run()
{
    /* COM prepare: */
    COMBase::InitializeCOM(false);

    /* Acquire a list of known group definition keys: */
    QStringList knownKeys = gEDataManager->knownMachineGroupDefinitionKeys();
    /* For every group definition to be saved: */
    foreach (const QString &strId, m_lists.keys())
    {
        /* Save definition only if there is a change: */
        if (gEDataManager->machineGroupDefinitions(strId) != m_lists.value(strId))
            gEDataManager->setMachineGroupDefinitions(strId, m_lists.value(strId));
        /* Remove it from known keys: */
        knownKeys.removeAll(strId);
    }
    /* Wipe out rest of known group definitions: */
    foreach (const QString strId, knownKeys)
        gEDataManager->setMachineGroupDefinitions(strId, QStringList());

    /* Notify listeners about completeness: */
    emit sigComplete();

    /* COM cleanup: */
    COMBase::CleanupCOM();
}


/*********************************************************************************************************************************
*   Class UIChooserAbstractModel implementation.                                                                                 *
*********************************************************************************************************************************/

UIChooserAbstractModel::UIChooserAbstractModel(UIChooser *pParent)
    : QObject(pParent)
    , m_pParent(pParent)
    , m_pInvisibleRootNode(0)
{
    prepare();
}

UIChooserAbstractModel::~UIChooserAbstractModel()
{
    cleanup();
}

void UIChooserAbstractModel::init()
{
    /* Create invisible root group node: */
    m_pInvisibleRootNode = new UIChooserNodeGroup(0 /* parent */,
                                                  0 /* position */,
                                                  QUuid() /* id */,
                                                  QString() /* name */,
                                                  UIChooserNodeGroupType_Local,
                                                  true /* opened */);
    if (invisibleRoot())
    {
        /* Link root to this model: */
        invisibleRoot()->setModel(this);

        /* Create global node: */
        new UIChooserNodeGlobal(invisibleRoot() /* parent */,
                                0 /* position */,
                                shouldGlobalNodeBeFavorite(invisibleRoot()),
                                QString() /* tip */);

        /* Reload local tree: */
        reloadLocalTree();
        /* Reload cloud tree: */
        reloadCloudTree();
    }
}

void UIChooserAbstractModel::deinit()
{
    /* Make sure all saving steps complete: */
    makeSureGroupSettingsSaveIsFinished();
    makeSureGroupDefinitionsSaveIsFinished();
}

void UIChooserAbstractModel::wipeOutEmptyGroups()
{
    wipeOutEmptyGroupsStartingFrom(invisibleRoot());
}

QStringList UIChooserAbstractModel::possibleGroupNodeNamesForMachineNodeToMove(const QUuid &uId)
{
    /* Search for all the machine nodes with passed ID: */
    QList<UIChooserNode*> machineNodes;
    invisibleRoot()->searchForNodes(uId.toString(),
                                    UIChooserItemSearchFlag_Machine | UIChooserItemSearchFlag_ExactId,
                                    machineNodes);

    /* Return group nodes starting from root one: */
    return gatherPossibleGroupNodeNames(invisibleRoot(), machineNodes);
}

QStringList UIChooserAbstractModel::possibleGroupNodeNamesForGroupNodeToMove(const QString &strFullName)
{
    /* Search for all the group nodes with passed full-name: */
    QList<UIChooserNode*> groupNodes;
    invisibleRoot()->searchForNodes(strFullName,
                                    UIChooserItemSearchFlag_LocalGroup | UIChooserItemSearchFlag_FullName,
                                    groupNodes);

    /* Return group nodes starting from root one: */
    return gatherPossibleGroupNodeNames(invisibleRoot(), groupNodes);
}

/* static */
QString UIChooserAbstractModel::uniqueGroupName(UIChooserNode *pRoot)
{
    /* Enumerate all the group names: */
    QStringList groupNames;
    foreach (UIChooserNode *pNode, pRoot->nodes(UIChooserNodeType_Group))
        groupNames << pNode->name();

    /* Prepare reg-exp: */
    const QString strMinimumName = tr("New group");
    const QString strShortTemplate = strMinimumName;
    const QString strFullTemplate = strShortTemplate + QString(" (\\d+)");
    const QRegExp shortRegExp(strShortTemplate);
    const QRegExp fullRegExp(strFullTemplate);

    /* Search for the maximum index: */
    int iMinimumPossibleNumber = 0;
    foreach (const QString &strName, groupNames)
    {
        if (shortRegExp.exactMatch(strName))
            iMinimumPossibleNumber = qMax(iMinimumPossibleNumber, 2);
        else if (fullRegExp.exactMatch(strName))
            iMinimumPossibleNumber = qMax(iMinimumPossibleNumber, fullRegExp.cap(1).toInt() + 1);
    }

    /* Prepare/return result: */
    QString strResult = strMinimumName;
    if (iMinimumPossibleNumber)
        strResult += " " + QString::number(iMinimumPossibleNumber);
    return strResult;
}

void UIChooserAbstractModel::performSearch(const QString &strSearchTerm, int iSearchFlags)
{
    /* Make sure invisible root exists: */
    AssertPtrReturnVoid(invisibleRoot());

    /* Currently we perform the search only for machines, when this to be changed make
     * sure the disabled flags of the other item types are also managed correctly. */

    /* Reset the search first to erase the disabled flag,
     * this also returns a full list of all machine nodes: */
    const QList<UIChooserNode*> nodes = resetSearch();

    /* Stop here if no search conditions specified: */
    if (strSearchTerm.isEmpty())
        return;

    /* Search for all the nodes matching required condition: */
    invisibleRoot()->searchForNodes(strSearchTerm, iSearchFlags, m_searchResults);

    /* Assign/reset the disabled flag for required nodes: */
    foreach (UIChooserNode *pNode, nodes)
    {
        AssertPtrReturnVoid(pNode);
        pNode->setDisabled(!m_searchResults.contains(pNode));
    }
}

QList<UIChooserNode*> UIChooserAbstractModel::resetSearch()
{
    /* Prepare resulting nodes: */
    QList<UIChooserNode*> nodes;

    /* Make sure invisible root exists: */
    AssertPtrReturn(invisibleRoot(), nodes);

    /* Calling UIChooserNode::searchForNodes with an empty search term
     * returns a list all nodes (of the whole tree) of the required type: */
    invisibleRoot()->searchForNodes(QString(), UIChooserItemSearchFlag_Machine, nodes);

    /* Reset the disabled flag of the nodes first: */
    foreach (UIChooserNode *pNode, nodes)
    {
        AssertPtrReturn(pNode, nodes);
        pNode->setDisabled(false);
    }

    /* Reset the search result related data: */
    m_searchResults.clear();

    /* Return nodes: */
    return nodes;
}

QList<UIChooserNode*> UIChooserAbstractModel::searchResult() const
{
    return m_searchResults;
}

void UIChooserAbstractModel::saveGroups()
{
    emit sigSaveSettings();
}

bool UIChooserAbstractModel::isGroupSavingInProgress() const
{
    return    UIThreadGroupSettingsSave::instance()
           || UIThreadGroupDefinitionsSave::instance();
}

/* static */
QString UIChooserAbstractModel::toOldStyleUuid(const QUuid &uId)
{
    return uId.toString().remove(QRegularExpression("[{}]"));
}

/* static */
QString UIChooserAbstractModel::prefixToString(UIChooserNodeDataPrefixType enmType)
{
    switch (enmType)
    {
        /* Global nodes: */
        case UIChooserNodeDataPrefixType_Global:   return "n";
        /* Machine nodes: */
        case UIChooserNodeDataPrefixType_Machine:  return "m";
        /* Group nodes: */
        case UIChooserNodeDataPrefixType_Local:    return "g";
        case UIChooserNodeDataPrefixType_Provider: return "p";
        case UIChooserNodeDataPrefixType_Profile:  return "a";
    }
    return QString();
}

/* static */
QString UIChooserAbstractModel::optionToString(UIChooserNodeDataOptionType enmType)
{
    switch (enmType)
    {
        /* Global nodes: */
        case UIChooserNodeDataOptionType_GlobalFavorite: return "f";
        /* Group nodes: */
        case UIChooserNodeDataOptionType_GroupOpened:    return "o";
    }
    return QString();
}

/* static */
QString UIChooserAbstractModel::valueToString(UIChooserNodeDataValueType enmType)
{
    switch (enmType)
    {
        /* Global nodes: */
        case UIChooserNodeDataValueType_GlobalDefault: return "GLOBAL";
    }
    return QString();
}

void UIChooserAbstractModel::insertCloudEntityKey(const UICloudEntityKey &key)
{
//    printf("Cloud entity with key %s being updated..\n", key.toString().toUtf8().constData());
    m_cloudEntityKeysBeingUpdated.insert(key);
    emit sigCloudUpdateStateChanged();
}

void UIChooserAbstractModel::removeCloudEntityKey(const UICloudEntityKey &key)
{
//    printf("Cloud entity with key %s is updated!\n", key.toString().toUtf8().constData());
    m_cloudEntityKeysBeingUpdated.remove(key);
    emit sigCloudUpdateStateChanged();
}

bool UIChooserAbstractModel::containsCloudEntityKey(const UICloudEntityKey &key) const
{
    return m_cloudEntityKeysBeingUpdated.contains(key);
}

bool UIChooserAbstractModel::isCloudProfileUpdateInProgress() const
{
    /* Compose RE for profile: */
    QRegExp re("^/[^/]+/[^/]+$");
    /* Check whether keys match profile RE: */
    foreach (const UICloudEntityKey &key, m_cloudEntityKeysBeingUpdated)
    {
        const int iIndex = re.indexIn(key.toString());
        if (iIndex != -1)
            return true;
    }
    /* False by default: */
    return false;
}

void UIChooserAbstractModel::sltHandleCloudMachineRefreshStarted()
{
    /* Acquire sender: */
    UIVirtualMachineItem *pCache = qobject_cast<UIVirtualMachineItem*>(sender());
    AssertPtrReturnVoid(pCache);

    /* Acquire sender's ID: */
    const QUuid uId = pCache->id();

    /* Search for a first machine node with passed ID: */
    UIChooserNode *pMachineNode = searchMachineNode(invisibleRoot(), uId);

    /* Insert cloud machine key into a list of keys currently being updated: */
    const UICloudEntityKey guiCloudMachineKey = UICloudEntityKey(pMachineNode->parentNode()->parentNode()->name(),
                                                                 pMachineNode->parentNode()->name(),
                                                                 pMachineNode->toMachineNode()->id());
    insertCloudEntityKey(guiCloudMachineKey);
}

void UIChooserAbstractModel::sltHandleCloudMachineRefreshFinished()
{
    /* Acquire sender: */
    UIVirtualMachineItem *pCache = qobject_cast<UIVirtualMachineItem*>(sender());
    AssertPtrReturnVoid(pCache);

    /* Acquire sender's ID: */
    const QUuid uId = pCache->id();

    /* Search for a first machine node with passed ID: */
    UIChooserNode *pMachineNode = searchMachineNode(invisibleRoot(), uId);

    /* Remove cloud machine key from the list of keys currently being updated: */
    const UICloudEntityKey guiCloudMachineKey = UICloudEntityKey(pMachineNode->parentNode()->parentNode()->name(),
                                                                 pMachineNode->parentNode()->name(),
                                                                 pMachineNode->toMachineNode()->id());
    removeCloudEntityKey(guiCloudMachineKey);

    /* Notify listeners: */
    emit sigCloudMachineStateChange(uId);
}

void UIChooserAbstractModel::sltGroupSettingsSaveComplete()
{
    makeSureGroupSettingsSaveIsFinished();
    emit sigGroupSavingStateChanged();
}

void UIChooserAbstractModel::sltGroupDefinitionsSaveComplete()
{
    makeSureGroupDefinitionsSaveIsFinished();
    emit sigGroupSavingStateChanged();
}

void UIChooserAbstractModel::sltLocalMachineStateChanged(const QUuid &uMachineId, const KMachineState)
{
    /* Update machine-nodes with passed id: */
    invisibleRoot()->updateAllNodes(uMachineId);
}

void UIChooserAbstractModel::sltLocalMachineDataChanged(const QUuid &uMachineId)
{
    /* Update machine-nodes with passed id: */
    invisibleRoot()->updateAllNodes(uMachineId);
}

void UIChooserAbstractModel::sltLocalMachineRegistrationChanged(const QUuid &uMachineId, const bool fRegistered)
{
    /* Existing VM unregistered? */
    if (!fRegistered)
    {
        /* Remove machine-items with passed id: */
        invisibleRoot()->removeAllNodes(uMachineId);
        /* Wipe out empty groups: */
        wipeOutEmptyGroups();
    }
    /* New VM registered? */
    else
    {
        /* Should we show this VM? */
        if (gEDataManager->showMachineInVirtualBoxManagerChooser(uMachineId))
        {
            /* Add new machine-item: */
            const CMachine comMachine = uiCommon().virtualBox().FindMachine(uMachineId.toString());
            if (comMachine.isNotNull())
                addLocalMachineIntoTheTree(comMachine, true /* make it visible */);
        }
    }
}

void UIChooserAbstractModel::sltSessionStateChanged(const QUuid &uMachineId, const KSessionState)
{
    /* Update machine-nodes with passed id: */
    invisibleRoot()->updateAllNodes(uMachineId);
}

void UIChooserAbstractModel::sltSnapshotChanged(const QUuid &uMachineId, const QUuid &)
{
    /* Update machine-nodes with passed id: */
    invisibleRoot()->updateAllNodes(uMachineId);
}

void UIChooserAbstractModel::sltHandleCloudProviderUninstall(const QUuid &uProviderId)
{
    /* First of all, stop all cloud updates: */
    stopCloudUpdates();

    /* Search and delete corresponding cloud provider node if present: */
    delete searchProviderNode(uProviderId);
}

void UIChooserAbstractModel::sltReloadMachine(const QUuid &uMachineId)
{
    /* Remove machine-items with passed id: */
    invisibleRoot()->removeAllNodes(uMachineId);
    /* Wipe out empty groups: */
    wipeOutEmptyGroups();

    /* Should we show this VM? */
    if (gEDataManager->showMachineInVirtualBoxManagerChooser(uMachineId))
    {
        /* Add new machine-item: */
        const CMachine comMachine = uiCommon().virtualBox().FindMachine(uMachineId.toString());
        addLocalMachineIntoTheTree(comMachine, true /* make it visible */);
    }
}

void UIChooserAbstractModel::sltCommitData()
{
    /* Finally, stop all cloud updates: */
    stopCloudUpdates(true /* forced? */);
}

void UIChooserAbstractModel::sltDetachCOM()
{
    /* Delete tree: */
    delete m_pInvisibleRootNode;
    m_pInvisibleRootNode = 0;
}

void UIChooserAbstractModel::sltCloudMachineUnregistered(const QString &strProviderShortName,
                                                         const QString &strProfileName,
                                                         const QUuid &uId)
{
    /* Search for profile node: */
    UIChooserNode *pProfileNode = searchProfileNode(strProviderShortName, strProfileName);
    if (!pProfileNode)
        return;

    /* Remove machine-item with passed uId: */
    pProfileNode->removeAllNodes(uId);

    /* If there are no items left => add fake cloud VM node: */
    if (pProfileNode->nodes(UIChooserNodeType_Machine).isEmpty())
        createCloudMachineNode(pProfileNode, UIFakeCloudVirtualMachineItemState_Done);
}

void UIChooserAbstractModel::sltCloudMachinesUnregistered(const QString &strProviderShortName,
                                                          const QString &strProfileName,
                                                          const QList<QUuid> &ids)
{
    /* Search for profile node: */
    UIChooserNode *pProfileNode = searchProfileNode(strProviderShortName, strProfileName);
    if (!pProfileNode)
        return;

    /* Remove machine-items with passed id: */
    foreach (const QUuid &uId, ids)
        pProfileNode->removeAllNodes(uId);

    /* If there are no items left => add fake cloud VM node: */
    if (pProfileNode->nodes(UIChooserNodeType_Machine).isEmpty())
        createCloudMachineNode(pProfileNode, UIFakeCloudVirtualMachineItemState_Done);
}

void UIChooserAbstractModel::sltCloudMachineRegistered(const QString &strProviderShortName,
                                                       const QString &strProfileName,
                                                       const CCloudMachine &comMachine)
{
    /* Search for profile node: */
    UIChooserNode *pProfileNode = searchProfileNode(strProviderShortName, strProfileName);
    if (!pProfileNode)
        return;

    /* Compose corresponding group path: */
    const QString strGroup = QString("/%1/%2").arg(strProviderShortName, strProfileName);
    /* Make sure there is no VM with such ID already: */
    QUuid uId;
    if (!cloudMachineId(comMachine, uId))
        return;
    if (checkIfNodeContainChildWithId(pProfileNode, uId))
        return;
    /* Add new machine-item: */
    addCloudMachineIntoTheTree(strGroup, comMachine, true /* make it visible? */);

    /* Delete fake node if present: */
    delete searchFakeNode(pProfileNode);
}

void UIChooserAbstractModel::sltCloudMachinesRegistered(const QString &strProviderShortName,
                                                        const QString &strProfileName,
                                                        const QVector<CCloudMachine> &machines)
{
    /* Search for profile node: */
    UIChooserNode *pProfileNode = searchProfileNode(strProviderShortName, strProfileName);
    if (!pProfileNode)
        return;

    /* Compose corresponding group path: */
    const QString strGroup = QString("/%1/%2").arg(strProviderShortName, strProfileName);
    foreach (const CCloudMachine &comMachine, machines)
    {
        /* Make sure there is no VM with such ID already: */
        QUuid uId;
        if (!cloudMachineId(comMachine, uId))
            continue;
        if (checkIfNodeContainChildWithId(pProfileNode, uId))
            continue;
        /* Add new machine-item: */
        addCloudMachineIntoTheTree(strGroup, comMachine, false /* make it visible? */);
    }

    /* Delete fake node if present: */
    delete searchFakeNode(pProfileNode);
}

void UIChooserAbstractModel::sltHandleReadCloudMachineListTaskComplete()
{
    /* Parse task result: */
    UIProgressTaskReadCloudMachineList *pSender = qobject_cast<UIProgressTaskReadCloudMachineList*>(sender());
    AssertPtrReturnVoid(pSender);
    const UICloudEntityKey guiCloudProfileKey = pSender->cloudProfileKey();
    const QVector<CCloudMachine> machines = pSender->machines();
    const QString strErrorMessage = pSender->errorMessage();

    /* Delete task: */
    delete pSender;

    /* Check whether this task was expected: */
    if (!containsCloudEntityKey(guiCloudProfileKey))
        return;

    /* Search for provider node separately, it can be removed already: */
    UIChooserNode *pProviderNode = searchProviderNode(guiCloudProfileKey.m_strProviderShortName);
    if (pProviderNode)
    {
        /* Search for profile node separately, it can be hidden at all: */
        UIChooserNode *pProfileNode = searchProfileNode(pProviderNode, guiCloudProfileKey.m_strProfileName);
        if (pProfileNode)
        {
            /* Compose old set of machine IDs: */
            QSet<QUuid> oldIDs;
            foreach (UIChooserNode *pNode, pProfileNode->nodes(UIChooserNodeType_Machine))
            {
                AssertPtrReturnVoid(pNode);
                UIChooserNodeMachine *pNodeMachine = pNode->toMachineNode();
                AssertPtrReturnVoid(pNodeMachine);
                if (pNodeMachine->cacheType() != UIVirtualMachineItemType_CloudReal)
                    continue;
                oldIDs << pNodeMachine->id();
            }
            /* Compose new set of machine IDs and map of machines: */
            QSet<QUuid> newIDs;
            QMap<QUuid, CCloudMachine> newMachines;
            foreach (const CCloudMachine &comMachine, machines)
            {
                QUuid uId;
                AssertReturnVoid(cloudMachineId(comMachine, uId));
                newMachines[uId] = comMachine;
                newIDs << uId;
            }

            /* Calculate set of unregistered/registered IDs: */
            const QSet<QUuid> unregisteredIDs = oldIDs - newIDs;
            const QSet<QUuid> registeredIDs = newIDs - oldIDs;
            QVector<CCloudMachine> registeredMachines;
            foreach (const QUuid &uId, registeredIDs)
                registeredMachines << newMachines.value(uId);

            /* Remove unregistered cloud VM nodes: */
            if (!unregisteredIDs.isEmpty())
            {
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
                QList<QUuid> listUnregisteredIDs(unregisteredIDs.begin(), unregisteredIDs.end());
#else
                QList<QUuid> listUnregisteredIDs = unregisteredIDs.toList();
#endif
                sltCloudMachinesUnregistered(guiCloudProfileKey.m_strProviderShortName,
                                             guiCloudProfileKey.m_strProfileName,
                                             listUnregisteredIDs);
            }
            /* Add registered cloud VM nodes: */
            if (!registeredMachines.isEmpty())
                sltCloudMachinesRegistered(guiCloudProfileKey.m_strProviderShortName,
                                           guiCloudProfileKey.m_strProfileName,
                                           registeredMachines);
            /* If we changed nothing and have nothing currently: */
            if (unregisteredIDs.isEmpty() && newIDs.isEmpty())
            {
                /* We should update at least fake cloud machine node: */
                UIChooserNode *pFakeNode = searchFakeNode(pProfileNode);
                AssertPtrReturnVoid(pFakeNode);
                UIVirtualMachineItemCloud *pFakeMachineItem = pFakeNode->toMachineNode()->cache()->toCloud();
                AssertPtrReturnVoid(pFakeMachineItem);
                pFakeMachineItem->setFakeCloudItemState(UIFakeCloudVirtualMachineItemState_Done);
                pFakeMachineItem->setFakeCloudItemErrorMessage(strErrorMessage);
                if (pFakeNode->item())
                    pFakeNode->item()->updateItem();
            }
        }
    }

    /* Remove cloud entity key from the list of keys currently being updated: */
    removeCloudEntityKey(guiCloudProfileKey);
}

void UIChooserAbstractModel::sltHandleCloudProfileManagerCumulativeChange()
{
    /* Reload cloud tree: */
    reloadCloudTree();
}

void UIChooserAbstractModel::createReadCloudMachineListTask(const UICloudEntityKey &guiCloudProfileKey, bool fWithRefresh)
{
    /* Do not create task if already registered: */
    if (containsCloudEntityKey(guiCloudProfileKey))
        return;

    /* Create task: */
    UIProgressTaskReadCloudMachineList *pTask = new UIProgressTaskReadCloudMachineList(this,
                                                                                       guiCloudProfileKey,
                                                                                       fWithRefresh);
    if (pTask)
    {
        /* It's easy to find child by name later: */
        pTask->setObjectName(guiCloudProfileKey.toString());

        /* Insert cloud profile key into a list of keys currently being updated: */
        insertCloudEntityKey(guiCloudProfileKey);

        /* Connect and start it finally: */
        connect(pTask, &UIProgressTaskReadCloudMachineList::sigProgressFinished,
                this, &UIChooserAbstractModel::sltHandleReadCloudMachineListTaskComplete);
        pTask->start();
    }
}

void UIChooserAbstractModel::sltSaveSettings()
{
    saveGroupSettings();
    saveGroupDefinitions();
}

void UIChooserAbstractModel::prepare()
{
    prepareConnections();
}

void UIChooserAbstractModel::prepareConnections()
{
    /* UICommon connections: */
    connect(&uiCommon(), &UICommon::sigAskToCommitData,
            this, &UIChooserAbstractModel::sltCommitData);
    connect(&uiCommon(), &UICommon::sigAskToDetachCOM,
            this, &UIChooserAbstractModel::sltDetachCOM);
    connect(&uiCommon(), &UICommon::sigCloudMachineUnregistered,
            this, &UIChooserAbstractModel::sltCloudMachineUnregistered);
    connect(&uiCommon(), &UICommon::sigCloudMachineRegistered,
            this, &UIChooserAbstractModel::sltCloudMachineRegistered);

    /* Global connections: */
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigMachineStateChange,
            this, &UIChooserAbstractModel::sltLocalMachineStateChanged);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigMachineDataChange,
            this, &UIChooserAbstractModel::sltLocalMachineDataChanged);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigMachineRegistered,
            this, &UIChooserAbstractModel::sltLocalMachineRegistrationChanged);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigSessionStateChange,
            this, &UIChooserAbstractModel::sltSessionStateChanged);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigSnapshotTake,
            this, &UIChooserAbstractModel::sltSnapshotChanged);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigSnapshotDelete,
            this, &UIChooserAbstractModel::sltSnapshotChanged);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigSnapshotChange,
            this, &UIChooserAbstractModel::sltSnapshotChanged);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigSnapshotRestore,
            this, &UIChooserAbstractModel::sltSnapshotChanged);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigCloudProviderListChanged,
            this, &UIChooserAbstractModel::sltHandleCloudProfileManagerCumulativeChange);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigCloudProfileRegistered,
            this, &UIChooserAbstractModel::sltHandleCloudProfileManagerCumulativeChange);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigCloudProfileChanged,
            this, &UIChooserAbstractModel::sltHandleCloudProfileManagerCumulativeChange);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigCloudProviderUninstall,
            this, &UIChooserAbstractModel::sltHandleCloudProviderUninstall);

    /* Settings saving connections: */
    connect(this, &UIChooserAbstractModel::sigSaveSettings,
            this, &UIChooserAbstractModel::sltSaveSettings,
            Qt::QueuedConnection);

    /* Extra-data connections: */
    connect(gEDataManager, &UIExtraDataManager::sigCloudProfileManagerRestrictionChange,
            this, &UIChooserAbstractModel::sltHandleCloudProfileManagerCumulativeChange);
}

void UIChooserAbstractModel::cleanupConnections()
{
    /* Group saving connections: */
    disconnect(this, &UIChooserAbstractModel::sigSaveSettings,
               this, &UIChooserAbstractModel::sltSaveSettings);
}

void UIChooserAbstractModel::cleanup()
{
    cleanupConnections();
}

void UIChooserAbstractModel::reloadLocalTree()
{
    LogRelFlow(("UIChooserAbstractModel: Loading local VMs...\n"));

    /* Acquire VBox: */
    const CVirtualBox comVBox = uiCommon().virtualBox();

    /* Acquire existing local machines: */
    const QVector<CMachine> machines = comVBox.GetMachines();
    /* Show error message if necessary: */
    if (!comVBox.isOk())
        UINotificationMessage::cannotAcquireVirtualBoxParameter(comVBox);
    else
    {
        /* Iterate through existing machines: */
        foreach (const CMachine &comMachine, machines)
        {
            /* Skip if we have nothing to populate (wtf happened?): */
            if (comMachine.isNull())
                continue;

            /* Get machine ID: */
            const QUuid uMachineID = comMachine.GetId();
            /* Show error message if necessary: */
            if (!comMachine.isOk())
            {
                UINotificationMessage::cannotAcquireMachineParameter(comMachine);
                continue;
            }

            /* Skip if we have nothing to show (wtf happened?): */
            if (uMachineID.isNull())
                continue;

            /* Skip if machine is restricted from being shown: */
            if (!gEDataManager->showMachineInVirtualBoxManagerChooser(uMachineID))
                continue;

            /* Add machine into tree: */
            addLocalMachineIntoTheTree(comMachine);
        }
    }

    LogRelFlow(("UIChooserAbstractModel: Local VMs loaded.\n"));
}

void UIChooserAbstractModel::reloadCloudTree()
{
    LogRelFlow(("UIChooserAbstractModel: Loading cloud providers/profiles...\n"));

    /* Wipe out existing cloud providers first.
     * This is quite rude, in future we need to reimplement it more wise.. */
    foreach (UIChooserNode *pNode, invisibleRoot()->nodes(UIChooserNodeType_Group))
    {
        AssertPtrReturnVoid(pNode);
        UIChooserNodeGroup *pGroupNode = pNode->toGroupNode();
        AssertPtrReturnVoid(pGroupNode);
        if (pGroupNode->groupType() == UIChooserNodeGroupType_Provider)
            delete pNode;
    }

    /* Acquire Cloud Profile Manager restrictions: */
    const QStringList restrictions = gEDataManager->cloudProfileManagerRestrictions();

    /* Iterate through existing providers: */
    foreach (CCloudProvider comCloudProvider, listCloudProviders())
    {
        /* Skip if we have nothing to populate: */
        if (comCloudProvider.isNull())
            continue;

        /* Acquire provider id: */
        QUuid uProviderId;
        if (!cloudProviderId(comCloudProvider, uProviderId))
            continue;

        /* Acquire provider short name: */
        QString strProviderShortName;
        if (!cloudProviderShortName(comCloudProvider, strProviderShortName))
            continue;

        /* Make sure this provider isn't restricted: */
        const QString strProviderPath = QString("/%1").arg(strProviderShortName);
        if (restrictions.contains(strProviderPath))
            continue;

        /* Acquire list of profiles: */
        const QVector<CCloudProfile> profiles = listCloudProfiles(comCloudProvider);
        if (profiles.isEmpty())
            continue;

        /* Add provider group node: */
        UIChooserNodeGroup *pProviderNode =
            new UIChooserNodeGroup(invisibleRoot() /* parent */,
                                   getDesiredNodePosition(invisibleRoot(),
                                                          UIChooserNodeDataPrefixType_Provider,
                                                          strProviderShortName),
                                   uProviderId,
                                   strProviderShortName,
                                   UIChooserNodeGroupType_Provider,
                                   shouldGroupNodeBeOpened(invisibleRoot(),
                                                           UIChooserNodeDataPrefixType_Provider,
                                                           strProviderShortName));

        /* Iterate through provider's profiles: */
        foreach (CCloudProfile comCloudProfile, profiles)
        {
            /* Skip if we have nothing to populate: */
            if (comCloudProfile.isNull())
                continue;

            /* Acquire profile name: */
            QString strProfileName;
            if (!cloudProfileName(comCloudProfile, strProfileName))
                continue;

            /* Make sure this profile isn't restricted: */
            const QString strProfilePath = QString("/%1/%2").arg(strProviderShortName, strProfileName);
            if (restrictions.contains(strProfilePath))
                continue;

            /* Add profile sub-group node: */
            UIChooserNodeGroup *pProfileNode =
                new UIChooserNodeGroup(pProviderNode /* parent */,
                                       getDesiredNodePosition(pProviderNode,
                                                              UIChooserNodeDataPrefixType_Profile,
                                                              strProfileName),
                                       QUuid() /* id */,
                                       strProfileName,
                                       UIChooserNodeGroupType_Profile,
                                       shouldGroupNodeBeOpened(pProviderNode,
                                                               UIChooserNodeDataPrefixType_Profile,
                                                               strProfileName));

            /* Add fake cloud VM item: */
            createCloudMachineNode(pProfileNode, UIFakeCloudVirtualMachineItemState_Loading);

            /* Create read cloud machine list task: */
            const UICloudEntityKey guiCloudProfileKey = UICloudEntityKey(strProviderShortName, strProfileName);
            createReadCloudMachineListTask(guiCloudProfileKey, true /* with refresh? */);
        }
    }

    LogRelFlow(("UIChooserAbstractModel: Cloud providers/profiles loaded.\n"));
}

void UIChooserAbstractModel::addLocalMachineIntoTheTree(const CMachine &comMachine,
                                                        bool fMakeItVisible /* = false */)
{
    /* Make sure passed VM is not NULL: */
    if (comMachine.isNull())
        LogRelFlow(("UIChooserModel: ERROR: Passed local VM is NULL!\n"));
    AssertReturnVoid(!comMachine.isNull());

    /* Which VM we are loading: */
    const QUuid uId = comMachine.GetId();
    LogRelFlow(("UIChooserModel: Loading local VM with ID={%s}...\n",
                toOldStyleUuid(uId).toUtf8().constData()));

    /* Is that machine accessible? */
    if (comMachine.GetAccessible())
    {
        /* Acquire VM name: */
        const QString strName = comMachine.GetName();
        LogRelFlow(("UIChooserModel:  Local VM {%s} is accessible.\n", strName.toUtf8().constData()));
        /* Which groups passed machine attached to? */
        const QVector<QString> groups = comMachine.GetGroups();
        const QStringList groupList = groups.toList();
        const QString strGroups = groupList.join(", ");
        LogRelFlow(("UIChooserModel:  Local VM {%s} has groups: {%s}.\n",
                    strName.toUtf8().constData(), strGroups.toUtf8().constData()));
        foreach (QString strGroup, groups)
        {
            /* Remove last '/' if any: */
            if (strGroup.right(1) == "/")
                strGroup.truncate(strGroup.size() - 1);
            /* Create machine-item with found group-item as parent: */
            LogRelFlow(("UIChooserModel:   Creating node for local VM {%s} in group {%s}.\n",
                        strName.toUtf8().constData(), strGroup.toUtf8().constData()));
            createLocalMachineNode(getLocalGroupNode(strGroup, invisibleRoot(), fMakeItVisible), comMachine);
        }
        /* Update group settings: */
        m_groups[toOldStyleUuid(uId)] = groupList;
    }
    /* Inaccessible machine: */
    else
    {
        /* VM is accessible: */
        LogRelFlow(("UIChooserModel:  Local VM {%s} is inaccessible.\n",
                    toOldStyleUuid(uId).toUtf8().constData()));
        /* Create machine-item with main-root group-item as parent: */
        createLocalMachineNode(invisibleRoot(), comMachine);
    }
}

void UIChooserAbstractModel::addCloudMachineIntoTheTree(const QString &strGroup,
                                                        const CCloudMachine &comMachine,
                                                        bool fMakeItVisible /* = false */)
{
    /* Make sure passed VM is not NULL: */
    if (comMachine.isNull())
        LogRelFlow(("UIChooserModel: ERROR: Passed cloud VM is NULL!\n"));
    AssertReturnVoid(!comMachine.isNull());

    /* Which VM we are loading: */
    const QUuid uId = comMachine.GetId();
    LogRelFlow(("UIChooserModel: Loading cloud VM with ID={%s}...\n",
                toOldStyleUuid(uId).toUtf8().constData()));

    /* Acquire VM name: */
    QString strName = comMachine.GetName();
    if (strName.isEmpty())
        strName = uId.toString();
    LogRelFlow(("UIChooserModel:  Creating node for cloud VM {%s} in group {%s}.\n",
                strName.toUtf8().constData(), strGroup.toUtf8().constData()));
    /* Create machine-item with found group-item as parent: */
    createCloudMachineNode(getCloudGroupNode(strGroup, invisibleRoot(), fMakeItVisible), comMachine);
    /* Update group settings: */
    const QStringList groupList(strGroup);
    m_groups[toOldStyleUuid(uId)] = groupList;
}

UIChooserNode *UIChooserAbstractModel::getLocalGroupNode(const QString &strName, UIChooserNode *pParentNode, bool fAllGroupsOpened)
{
    /* Check passed stuff: */
    if (pParentNode->name() == strName)
        return pParentNode;

    /* Prepare variables: */
    const QString strFirstSubName = strName.section('/', 0, 0);
    const QString strFirstSuffix = strName.section('/', 1, -1);
    const QString strSecondSubName = strFirstSuffix.section('/', 0, 0);
    const QString strSecondSuffix = strFirstSuffix.section('/', 1, -1);

    /* Passed group name equal to first sub-name: */
    if (pParentNode->name() == strFirstSubName)
    {
        /* Make sure first-suffix is NOT empty: */
        AssertMsg(!strFirstSuffix.isEmpty(), ("Invalid group name!"));
        /* Trying to get group node among our children: */
        foreach (UIChooserNode *pNode, pParentNode->nodes(UIChooserNodeType_Group))
        {
            AssertPtrReturn(pNode, 0);
            UIChooserNodeGroup *pGroupNode = pNode->toGroupNode();
            AssertPtrReturn(pGroupNode, 0);
            if (   pGroupNode->groupType() == UIChooserNodeGroupType_Local
                && pNode->name() == strSecondSubName)
            {
                UIChooserNode *pFoundNode = getLocalGroupNode(strFirstSuffix, pNode, fAllGroupsOpened);
                if (UIChooserNodeGroup *pFoundGroupNode = pFoundNode->toGroupNode())
                    if (fAllGroupsOpened && pFoundGroupNode->isClosed())
                        pFoundGroupNode->open();
                return pFoundNode;
            }
        }
    }

    /* Found nothing? Creating: */
    UIChooserNodeGroup *pNewGroupNode =
        new UIChooserNodeGroup(pParentNode,
                               getDesiredNodePosition(pParentNode,
                                                      UIChooserNodeDataPrefixType_Local,
                                                      strSecondSubName),
                               QUuid() /* id */,
                               strSecondSubName,
                               UIChooserNodeGroupType_Local,
                               fAllGroupsOpened || shouldGroupNodeBeOpened(pParentNode,
                                                                           UIChooserNodeDataPrefixType_Local,
                                                                           strSecondSubName));
    return strSecondSuffix.isEmpty() ? pNewGroupNode : getLocalGroupNode(strFirstSuffix, pNewGroupNode, fAllGroupsOpened);
}

UIChooserNode *UIChooserAbstractModel::getCloudGroupNode(const QString &strName, UIChooserNode *pParentNode, bool fAllGroupsOpened)
{
    /* Check passed stuff: */
    if (pParentNode->name() == strName)
        return pParentNode;

    /* Prepare variables: */
    const QString strFirstSubName = strName.section('/', 0, 0);
    const QString strFirstSuffix = strName.section('/', 1, -1);
    const QString strSecondSubName = strFirstSuffix.section('/', 0, 0);

    /* Passed group name equal to first sub-name: */
    if (pParentNode->name() == strFirstSubName)
    {
        /* Make sure first-suffix is NOT empty: */
        AssertMsg(!strFirstSuffix.isEmpty(), ("Invalid group name!"));
        /* Trying to get group node among our children: */
        foreach (UIChooserNode *pNode, pParentNode->nodes(UIChooserNodeType_Group))
        {
            AssertPtrReturn(pNode, 0);
            UIChooserNodeGroup *pGroupNode = pNode->toGroupNode();
            AssertPtrReturn(pGroupNode, 0);
            if (   (   pGroupNode->groupType() == UIChooserNodeGroupType_Provider
                    || pGroupNode->groupType() == UIChooserNodeGroupType_Profile)
                && pNode->name() == strSecondSubName)
            {
                UIChooserNode *pFoundNode = getCloudGroupNode(strFirstSuffix, pNode, fAllGroupsOpened);
                if (UIChooserNodeGroup *pFoundGroupNode = pFoundNode->toGroupNode())
                    if (fAllGroupsOpened && pFoundGroupNode->isClosed())
                        pFoundGroupNode->open();
                return pFoundNode;
            }
        }
    }

    /* Found nothing? Returning parent: */
    AssertFailedReturn(pParentNode);
}

bool UIChooserAbstractModel::shouldGroupNodeBeOpened(UIChooserNode *pParentNode,
                                                     UIChooserNodeDataPrefixType enmDataType,
                                                     const QString &strName) const
{
    /* Read group definitions: */
    const QStringList definitions = gEDataManager->machineGroupDefinitions(pParentNode->fullName());
    /* Return 'false' if no definitions found: */
    if (definitions.isEmpty())
        return false;

    /* Prepare required group definition reg-exp: */
    const QString strNodePrefix = prefixToString(enmDataType);
    const QString strNodeOptionOpened = optionToString(UIChooserNodeDataOptionType_GroupOpened);
    const QString strDefinitionTemplate = QString("%1(\\S)*=%2").arg(strNodePrefix, strName);
    const QRegExp definitionRegExp(strDefinitionTemplate);
    /* For each the group definition: */
    foreach (const QString &strDefinition, definitions)
    {
        /* Check if this is required definition: */
        if (definitionRegExp.indexIn(strDefinition) == 0)
        {
            /* Get group descriptor: */
            const QString strDescriptor(definitionRegExp.cap(1));
            if (strDescriptor.contains(strNodeOptionOpened))
                return true;
        }
    }

    /* Return 'false' by default: */
    return false;
}

bool UIChooserAbstractModel::shouldGlobalNodeBeFavorite(UIChooserNode *pParentNode) const
{
    /* Read group definitions: */
    const QStringList definitions = gEDataManager->machineGroupDefinitions(pParentNode->fullName());
    /* Return 'false' if no definitions found: */
    if (definitions.isEmpty())
        return false;

    /* Prepare required group definition reg-exp: */
    const QString strNodePrefix = prefixToString(UIChooserNodeDataPrefixType_Global);
    const QString strNodeOptionFavorite = optionToString(UIChooserNodeDataOptionType_GlobalFavorite);
    const QString strNodeValueDefault = valueToString(UIChooserNodeDataValueType_GlobalDefault);
    const QString strDefinitionTemplate = QString("%1(\\S)*=%2").arg(strNodePrefix, strNodeValueDefault);
    const QRegExp definitionRegExp(strDefinitionTemplate);
    /* For each the group definition: */
    foreach (const QString &strDefinition, definitions)
    {
        /* Check if this is required definition: */
        if (definitionRegExp.indexIn(strDefinition) == 0)
        {
            /* Get group descriptor: */
            const QString strDescriptor(definitionRegExp.cap(1));
            if (strDescriptor.contains(strNodeOptionFavorite))
                return true;
        }
    }

    /* Return 'false' by default: */
    return false;
}

void UIChooserAbstractModel::wipeOutEmptyGroupsStartingFrom(UIChooserNode *pParent)
{
    /* Cleanup all the group children recursively first: */
    foreach (UIChooserNode *pNode, pParent->nodes(UIChooserNodeType_Group))
        wipeOutEmptyGroupsStartingFrom(pNode);
    /* If parent isn't root and has no nodes: */
    if (!pParent->isRoot() && !pParent->hasNodes())
    {
        /* Delete parent node and item: */
        delete pParent;
    }
}

int UIChooserAbstractModel::getDesiredNodePosition(UIChooserNode *pParentNode,
                                                   UIChooserNodeDataPrefixType enmDataType,
                                                   const QString &strName)
{
    /* End of list (by default)? */
    int iNewNodeDesiredPosition = -1;
    /* Which position should be new node placed by definitions: */
    const int iNewNodeDefinitionPosition = getDefinedNodePosition(pParentNode, enmDataType, strName);

    /* If some position defined: */
    if (iNewNodeDefinitionPosition != -1)
    {
        /* Start of list if some definition present: */
        iNewNodeDesiredPosition = 0;
        /* We have to check all the existing node positions: */
        UIChooserNodeType enmType = UIChooserNodeType_Any;
        switch (enmDataType)
        {
            case UIChooserNodeDataPrefixType_Global:   enmType = UIChooserNodeType_Global; break;
            case UIChooserNodeDataPrefixType_Machine:  enmType = UIChooserNodeType_Machine; break;
            case UIChooserNodeDataPrefixType_Local:
            case UIChooserNodeDataPrefixType_Provider:
            case UIChooserNodeDataPrefixType_Profile:  enmType = UIChooserNodeType_Group; break;
        }
        const QList<UIChooserNode*> nodes = pParentNode->nodes(enmType);
        for (int i = nodes.size() - 1; i >= 0; --i)
        {
            /* Get current node: */
            UIChooserNode *pNode = nodes.at(i);
            AssertPtrReturn(pNode, iNewNodeDesiredPosition);
            /* Which position should be current node placed by definitions? */
            UIChooserNodeDataPrefixType enmNodeDataType = UIChooserNodeDataPrefixType_Global;
            QString strDefinitionName;
            switch (pNode->type())
            {
                case UIChooserNodeType_Machine:
                {
                    enmNodeDataType = UIChooserNodeDataPrefixType_Machine;
                    strDefinitionName = toOldStyleUuid(pNode->toMachineNode()->id());
                    break;
                }
                case UIChooserNodeType_Group:
                {
                    /* Cast to group node: */
                    UIChooserNodeGroup *pGroupNode = pNode->toGroupNode();
                    AssertPtrReturn(pGroupNode, iNewNodeDesiredPosition);
                    switch (pGroupNode->groupType())
                    {
                        case UIChooserNodeGroupType_Local:    enmNodeDataType = UIChooserNodeDataPrefixType_Local; break;
                        case UIChooserNodeGroupType_Provider: enmNodeDataType = UIChooserNodeDataPrefixType_Provider; break;
                        case UIChooserNodeGroupType_Profile:  enmNodeDataType = UIChooserNodeDataPrefixType_Profile; break;
                        default: break;
                    }
                    strDefinitionName = pNode->name();
                    break;
                }
                default:
                    break;
            }
            /* If some position defined: */
            const int iNodeDefinitionPosition = getDefinedNodePosition(pParentNode, enmNodeDataType, strDefinitionName);
            if (iNodeDefinitionPosition != -1)
            {
                AssertReturn(iNodeDefinitionPosition != iNewNodeDefinitionPosition, iNewNodeDesiredPosition);
                if (iNodeDefinitionPosition < iNewNodeDefinitionPosition)
                {
                    iNewNodeDesiredPosition = i + 1;
                    break;
                }
            }
        }
    }

    /* Return desired node position: */
    return iNewNodeDesiredPosition;
}

int UIChooserAbstractModel::getDefinedNodePosition(UIChooserNode *pParentNode, UIChooserNodeDataPrefixType enmDataType, const QString &strName)
{
    /* Read group definitions: */
    const QStringList definitions = gEDataManager->machineGroupDefinitions(pParentNode->fullName());
    /* Return 'false' if no definitions found: */
    if (definitions.isEmpty())
        return -1;

    /* Prepare definition reg-exp: */
    QString strDefinitionTemplateShort;
    QString strDefinitionTemplateFull;
    const QString strNodePrefixLocal = prefixToString(UIChooserNodeDataPrefixType_Local);
    const QString strNodePrefixProvider = prefixToString(UIChooserNodeDataPrefixType_Provider);
    const QString strNodePrefixProfile = prefixToString(UIChooserNodeDataPrefixType_Profile);
    const QString strNodePrefixMachine = prefixToString(UIChooserNodeDataPrefixType_Machine);
    switch (enmDataType)
    {
        case UIChooserNodeDataPrefixType_Local:
        {
            strDefinitionTemplateShort = QString("^[%1%2%3](\\S)*=").arg(strNodePrefixLocal, strNodePrefixProvider, strNodePrefixProfile);
            strDefinitionTemplateFull = QString("^%1(\\S)*=%2$").arg(strNodePrefixLocal, strName);
            break;
        }
        case UIChooserNodeDataPrefixType_Provider:
        {
            strDefinitionTemplateShort = QString("^[%1%2%3](\\S)*=").arg(strNodePrefixLocal, strNodePrefixProvider, strNodePrefixProfile);
            strDefinitionTemplateFull = QString("^%1(\\S)*=%2$").arg(strNodePrefixProvider, strName);
            break;
        }
        case UIChooserNodeDataPrefixType_Profile:
        {
            strDefinitionTemplateShort = QString("^[%1%2%3](\\S)*=").arg(strNodePrefixLocal, strNodePrefixProvider, strNodePrefixProfile);
            strDefinitionTemplateFull = QString("^%1(\\S)*=%2$").arg(strNodePrefixProfile, strName);
            break;
        }
        case UIChooserNodeDataPrefixType_Machine:
        {
            strDefinitionTemplateShort = QString("^%1=").arg(strNodePrefixMachine);
            strDefinitionTemplateFull = QString("^%1=%2$").arg(strNodePrefixMachine, strName);
            break;
        }
        default:
            return -1;
    }
    QRegExp definitionRegExpShort(strDefinitionTemplateShort);
    QRegExp definitionRegExpFull(strDefinitionTemplateFull);

    /* For each the definition: */
    int iDefinitionIndex = -1;
    foreach (const QString &strDefinition, definitions)
    {
        /* Check if this definition is of required type: */
        if (definitionRegExpShort.indexIn(strDefinition) == 0)
        {
            ++iDefinitionIndex;
            /* Check if this definition is exactly what we need: */
            if (definitionRegExpFull.indexIn(strDefinition) == 0)
                return iDefinitionIndex;
        }
    }

    /* Return result: */
    return -1;
}

void UIChooserAbstractModel::createLocalMachineNode(UIChooserNode *pParentNode, const CMachine &comMachine)
{
    new UIChooserNodeMachine(pParentNode,
                             getDesiredNodePosition(pParentNode,
                                                    UIChooserNodeDataPrefixType_Machine,
                                                    toOldStyleUuid(comMachine.GetId())),
                             comMachine);
}

void UIChooserAbstractModel::createCloudMachineNode(UIChooserNode *pParentNode, UIFakeCloudVirtualMachineItemState enmState)
{
    new UIChooserNodeMachine(pParentNode,
                             0 /* position */,
                             enmState);
}

void UIChooserAbstractModel::createCloudMachineNode(UIChooserNode *pParentNode, const CCloudMachine &comMachine)
{
    UIChooserNodeMachine *pNode = new UIChooserNodeMachine(pParentNode,
                                                           getDesiredNodePosition(pParentNode,
                                                                                  UIChooserNodeDataPrefixType_Machine,
                                                                                  toOldStyleUuid(comMachine.GetId())),
                                                           comMachine);
    /* Request for async node update if necessary: */
    if (!comMachine.GetAccessible())
    {
        AssertReturnVoid(pNode && pNode->cacheType() == UIVirtualMachineItemType_CloudReal);
        pNode->cache()->toCloud()->updateInfoAsync(false /* delayed? */);
    }
}

QStringList UIChooserAbstractModel::gatherPossibleGroupNodeNames(UIChooserNode *pCurrentNode, QList<UIChooserNode*> exceptions) const
{
    /* Prepare result: */
    QStringList result;

    /* Walk through all the children and make sure there are no exceptions: */
    bool fAddCurrent = true;
    foreach (UIChooserNode *pChild, pCurrentNode->nodes(UIChooserNodeType_Any))
    {
        AssertPtrReturn(pChild, result);
        if (exceptions.contains(pChild))
            fAddCurrent = false;
        else
        {
            if (pChild->type() == UIChooserNodeType_Group)
            {
                UIChooserNodeGroup *pChildGroup = pChild->toGroupNode();
                AssertPtrReturn(pChildGroup, result);
                if (pChildGroup->groupType() == UIChooserNodeGroupType_Local)
                    result << gatherPossibleGroupNodeNames(pChild, exceptions);
            }
        }
    }

    /* Add current item if not overridden: */
    if (fAddCurrent)
        result.prepend(pCurrentNode->fullName());

    /* Return result: */
    return result;
}

bool UIChooserAbstractModel::checkIfNodeContainChildWithId(UIChooserNode *pParentNode, const QUuid &uId) const
{
    /* Check parent-node type: */
    AssertPtrReturn(pParentNode, false);
    switch (pParentNode->type())
    {
        case UIChooserNodeType_Machine:
        {
            /* Check if pParentNode has the passed uId itself: */
            UIChooserNodeMachine *pMachineNode = pParentNode->toMachineNode();
            AssertPtrReturn(pMachineNode, false);
            if (pMachineNode->id() == uId)
                return true;
            break;
        }
        case UIChooserNodeType_Group:
        {
            /* Recursively iterate through children: */
            foreach (UIChooserNode *pChildNode, pParentNode->nodes())
                if (checkIfNodeContainChildWithId(pChildNode, uId))
                    return true;
            break;
        }
        default:
            break;
    }

    /* False by default: */
    return false;
}

void UIChooserAbstractModel::saveGroupSettings()
{
    /* Make sure there is no group settings saving activity: */
    if (UIThreadGroupSettingsSave::instance())
        return;

    /* Prepare full group map: */
    QMap<QString, QStringList> groups;
    gatherGroupSettings(groups, invisibleRoot());

    /* Save information in other thread: */
    UIThreadGroupSettingsSave::prepare();
    emit sigGroupSavingStateChanged();
    connect(UIThreadGroupSettingsSave::instance(), &UIThreadGroupSettingsSave::sigReload,
            this, &UIChooserAbstractModel::sltReloadMachine);
    UIThreadGroupSettingsSave::instance()->configure(this, m_groups, groups);
    UIThreadGroupSettingsSave::instance()->start();
    m_groups = groups;
}

void UIChooserAbstractModel::saveGroupDefinitions()
{
    /* Make sure there is no group definitions save activity: */
    if (UIThreadGroupDefinitionsSave::instance())
        return;

    /* Prepare full group map: */
    QMap<QString, QStringList> groups;
    gatherGroupDefinitions(groups, invisibleRoot());

    /* Save information in other thread: */
    UIThreadGroupDefinitionsSave::prepare();
    emit sigGroupSavingStateChanged();
    UIThreadGroupDefinitionsSave::instance()->configure(this, groups);
    UIThreadGroupDefinitionsSave::instance()->start();
}

void UIChooserAbstractModel::gatherGroupSettings(QMap<QString, QStringList> &settings,
                                                 UIChooserNode *pParentGroup)
{
    /* Iterate over all the machine-nodes: */
    foreach (UIChooserNode *pNode, pParentGroup->nodes(UIChooserNodeType_Machine))
    {
        /* Make sure it's really machine node: */
        AssertPtrReturnVoid(pNode);
        UIChooserNodeMachine *pMachineNode = pNode->toMachineNode();
        AssertPtrReturnVoid(pMachineNode);
        /* Make sure it's local machine node exactly and it's accessible: */
        if (   pMachineNode->cacheType() == UIVirtualMachineItemType_Local
            && pMachineNode->accessible())
            settings[toOldStyleUuid(pMachineNode->id())] << pParentGroup->fullName();
    }
    /* Iterate over all the group-nodes: */
    foreach (UIChooserNode *pNode, pParentGroup->nodes(UIChooserNodeType_Group))
        gatherGroupSettings(settings, pNode);
}

void UIChooserAbstractModel::gatherGroupDefinitions(QMap<QString, QStringList> &definitions,
                                                    UIChooserNode *pParentGroup)
{
    /* Prepare extra-data key for current group: */
    const QString strExtraDataKey = pParentGroup->fullName();
    /* Iterate over all the global-nodes: */
    foreach (UIChooserNode *pNode, pParentGroup->nodes(UIChooserNodeType_Global))
    {
        /* Append node definition: */
        AssertPtrReturnVoid(pNode);
        definitions[strExtraDataKey] << pNode->definition(true /* full */);
    }
    /* Iterate over all the group-nodes: */
    foreach (UIChooserNode *pNode, pParentGroup->nodes(UIChooserNodeType_Group))
    {
        /* Append node definition: */
        AssertPtrReturnVoid(pNode);
        definitions[strExtraDataKey] << pNode->definition(true /* full */);
        /* Go recursively through children: */
        gatherGroupDefinitions(definitions, pNode);
    }
    /* Iterate over all the machine-nodes: */
    foreach (UIChooserNode *pNode, pParentGroup->nodes(UIChooserNodeType_Machine))
    {
        /* Make sure it's really machine node: */
        AssertPtrReturnVoid(pNode);
        UIChooserNodeMachine *pMachineNode = pNode->toMachineNode();
        AssertPtrReturnVoid(pMachineNode);
        /* Append node definition, make sure it's local or real cloud machine node only: */
        if (   pMachineNode->cacheType() == UIVirtualMachineItemType_Local
            || pMachineNode->cacheType() == UIVirtualMachineItemType_CloudReal)
            definitions[strExtraDataKey] << pNode->definition(true /* full */);
    }
}

void UIChooserAbstractModel::makeSureGroupSettingsSaveIsFinished()
{
    /* Cleanup if necessary: */
    if (UIThreadGroupSettingsSave::instance())
        UIThreadGroupSettingsSave::cleanup();
}

void UIChooserAbstractModel::makeSureGroupDefinitionsSaveIsFinished()
{
    /* Cleanup if necessary: */
    if (UIThreadGroupDefinitionsSave::instance())
        UIThreadGroupDefinitionsSave::cleanup();
}

UIChooserNode *UIChooserAbstractModel::searchProviderNode(const QUuid &uProviderId)
{
    /* Search for a list of nodes matching passed name: */
    QList<UIChooserNode*> providerNodes;
    invisibleRoot()->searchForNodes(uProviderId.toString(),
                                    UIChooserItemSearchFlag_CloudProvider | UIChooserItemSearchFlag_ExactId,
                                    providerNodes);

    /* Return 1st node if any: */
    return providerNodes.value(0);
}

UIChooserNode *UIChooserAbstractModel::searchProviderNode(const QString &strProviderShortName)
{
    /* Search for a list of nodes matching passed name: */
    QList<UIChooserNode*> providerNodes;
    invisibleRoot()->searchForNodes(strProviderShortName,
                                    UIChooserItemSearchFlag_CloudProvider | UIChooserItemSearchFlag_ExactName,
                                    providerNodes);

    /* Return 1st node if any: */
    return providerNodes.value(0);
}

UIChooserNode *UIChooserAbstractModel::searchProfileNode(UIChooserNode *pProviderNode, const QString &strProfileName)
{
    AssertPtrReturn(pProviderNode, 0);

    /* Search for a list of nodes matching passed name: */
    QList<UIChooserNode*> profileNodes;
    pProviderNode->searchForNodes(strProfileName,
                                  UIChooserItemSearchFlag_CloudProfile | UIChooserItemSearchFlag_ExactName,
                                  profileNodes);

    /* Return 1st node if any: */
    return profileNodes.value(0);
}

UIChooserNode *UIChooserAbstractModel::searchProfileNode(const QString &strProviderShortName, const QString &strProfileName)
{
    /* Wrap method above: */
    return searchProfileNode(searchProviderNode(strProviderShortName), strProfileName);
}

UIChooserNode *UIChooserAbstractModel::searchMachineNode(UIChooserNode *pProfileNode, const QUuid &uMachineId)
{
    AssertPtrReturn(pProfileNode, 0);

    /* Search for a list of nodes matching passed ID: */
    QList<UIChooserNode*> machineNodes;
    pProfileNode->searchForNodes(uMachineId.toString(),
                                 UIChooserItemSearchFlag_Machine | UIChooserItemSearchFlag_ExactId,
                                 machineNodes);

    /* Return 1st node if any: */
    return machineNodes.value(0);
}

UIChooserNode *UIChooserAbstractModel::searchMachineNode(const QString &strProviderShortName, const QString &strProfileName, const QUuid &uMachineId)
{
    /* Wrap method above: */
    return searchMachineNode(searchProfileNode(strProviderShortName, strProfileName), uMachineId);
}

UIChooserNode *UIChooserAbstractModel::searchFakeNode(UIChooserNode *pProfileNode)
{
    /* Wrap method above: */
    return searchMachineNode(pProfileNode, QUuid());
}

UIChooserNode *UIChooserAbstractModel::searchFakeNode(const QString &strProviderShortName, const QString &strProfileName)
{
    /* Wrap method above: */
    return searchMachineNode(strProviderShortName, strProfileName, QUuid());
}

void UIChooserAbstractModel::stopCloudUpdates(bool fForced /* = false */)
{
    /* Stop all cloud entity updates currently being performed: */
    foreach (const UICloudEntityKey &key, m_cloudEntityKeysBeingUpdated)
    {
        /* For profiles: */
        if (key.m_uMachineId.isNull())
        {
            /* Search task child by key: */
            UIProgressTaskReadCloudMachineList *pTask = findChild<UIProgressTaskReadCloudMachineList*>(key.toString());
            AssertPtrReturnVoid(pTask);

            /* Wait for cloud profile refresh task to complete,
             * then delete the task itself manually: */
            if (!fForced)
                pTask->cancel();
            delete pTask;
        }
        /* For machines: */
        else
        {
            /* Search machine node: */
            UIChooserNode *pNode = searchMachineNode(key.m_strProviderShortName, key.m_strProfileName, key.m_uMachineId);
            AssertPtrReturnVoid(pNode);
            /* Acquire cloud machine item: */
            UIVirtualMachineItemCloud *pCloudMachineItem = pNode->toMachineNode()->cache()->toCloud();
            AssertPtrReturnVoid(pCloudMachineItem);

            /* Wait for cloud machine refresh task to complete,
             * task itself will be deleted with the machine-node: */
            pCloudMachineItem->waitForAsyncInfoUpdateFinished();
        }
    }

    /* We haven't let tasks to unregister themselves
     * so we have to cleanup task set ourselves: */
    m_cloudEntityKeysBeingUpdated.clear();
}


#include "UIChooserAbstractModel.moc"