summaryrefslogtreecommitdiff
path: root/src/VBox/Frontends/VirtualBox/src/snapshots/UISnapshotPane.cpp
blob: 892f96d1b7bd8ce04521ccf0cc7028d091bd6e5f (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
/* $Id$ */
/** @file
 * VBox Qt GUI - UISnapshotPane class implementation.
 */

/*
 * Copyright (C) 2006-2020 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 <QAccessibleWidget>
#include <QApplication>
#include <QDateTime>
#include <QHeaderView>
#include <QIcon>
#include <QMenu>
#include <QPointer>
#include <QReadWriteLock>
#include <QScrollBar>
#include <QTimer>
#include <QVBoxLayout>
#include <QWriteLocker>

/* GUI includes: */
#include "QIMessageBox.h"
#include "QITreeWidget.h"
#include "UIActionPoolManager.h"
#include "UIConverter.h"
#include "UIExtraDataManager.h"
#include "UIIconPool.h"
#include "UIMessageCenter.h"
#include "UIModalWindowManager.h"
#include "UISnapshotDetailsWidget.h"
#include "UISnapshotPane.h"
#include "UITakeSnapshotDialog.h"
#include "UIToolBar.h"
#include "UIVirtualBoxEventHandler.h"
#include "UIWizardCloneVM.h"

/* COM includes: */
#include "CConsole.h"


/** Snapshot tree column tags. */
enum
{
    Column_Name,
    Column_Taken,
    Column_Max,
};


/** QITreeWidgetItem subclass for snapshots items. */
class UISnapshotItem : public QITreeWidgetItem, public UIDataSnapshot
{
    Q_OBJECT;

public:

    /** Casts QTreeWidgetItem* to UISnapshotItem* if possible. */
    static UISnapshotItem *toSnapshotItem(QTreeWidgetItem *pItem);
    /** Casts const QTreeWidgetItem* to const UISnapshotItem* if possible. */
    static const UISnapshotItem *toSnapshotItem(const QTreeWidgetItem *pItem);

    /** Constructs normal snapshot item (child of tree-widget). */
    UISnapshotItem(UISnapshotPane *pSnapshotWidget, QITreeWidget *pTreeWidget, const CSnapshot &comSnapshot);
    /** Constructs normal snapshot item (child of tree-widget-item). */
    UISnapshotItem(UISnapshotPane *pSnapshotWidget, QITreeWidgetItem *pRootItem, const CSnapshot &comSnapshot);

    /** Constructs "current state" item (child of tree-widget). */
    UISnapshotItem(UISnapshotPane *pSnapshotWidget, QITreeWidget *pTreeWidget, const CMachine &comMachine);
    /** Constructs "current state" item (child of tree-widget-item). */
    UISnapshotItem(UISnapshotPane *pSnapshotWidget, QITreeWidgetItem *pRootItem, const CMachine &comMachine);

    /** Returns item machine. */
    CMachine machine() const { return m_comMachine; }
    /** Returns item snapshot. */
    CSnapshot snapshot() const { return m_comSnapshot; }
    /** Returns item snapshot ID. */
    QUuid snapshotID() const { return m_uSnapshotID; }

    /** Returns whether this is the "current state" item. */
    bool isCurrentStateItem() const { return m_fCurrentStateItem; }

    /** Returns whether this is the "current snapshot" item. */
    bool isCurrentSnapshotItem() const { return m_fCurrentSnapshotItem; }
    /** Defines whether this is the @a fCurrent snapshot item. */
    void setCurrentSnapshotItem(bool fCurrent);

    /** Calculates and returns the current item level. */
    int level() const;

    /** Recaches the item's contents. */
    void recache();

    /** Returns current machine state. */
    KMachineState machineState() const;
    /** Defines current machine @a enmState. */
    void setMachineState(KMachineState enmState);

    /** Updates item age. */
    SnapshotAgeFormat updateAge();

protected:

    /** Recaches item tool-tip. */
    void recacheToolTip();

private:

    /** Holds the pointer to the snapshot-widget this item belongs to. */
    QPointer<UISnapshotPane>  m_pSnapshotWidget;

    /** Holds whether this is a "current state" item. */
    bool  m_fCurrentStateItem;
    /** Holds whether this is a "current snapshot" item. */
    bool  m_fCurrentSnapshotItem;

    /** Holds the snapshot COM wrapper. */
    CSnapshot  m_comSnapshot;
    /** Holds the machine COM wrapper. */
    CMachine   m_comMachine;

    /** Holds the "current snapshot" ID. */
    QUuid  m_uSnapshotID;
    /** Holds whether the "current snapshot" is online one. */
    bool   m_fOnline;

    /** Holds the item timestamp. */
    QDateTime  m_timestamp;

    /** Holds whether the current state is modified. */
    bool           m_fCurrentStateModified;
    /** Holds the cached machine state. */
    KMachineState  m_enmMachineState;
};


/** QITreeWidget subclass for snapshots items. */
class UISnapshotTree : public QITreeWidget
{
    Q_OBJECT;

public:

    /** Constructs snapshot tree passing @a pParent to the base-class. */
    UISnapshotTree(QWidget *pParent);
};


/*********************************************************************************************************************************
*   Class UISnapshotItem implementation.                                                                                         *
*********************************************************************************************************************************/

/* static */
UISnapshotItem *UISnapshotItem::toSnapshotItem(QTreeWidgetItem *pItem)
{
    /* Get QITreeWidgetItem item first: */
    QITreeWidgetItem *pIItem = QITreeWidgetItem::toItem(pItem);
    if (!pIItem)
        return 0;

    /* Return casted UISnapshotItem then: */
    return qobject_cast<UISnapshotItem*>(pIItem);
}

/* static */
const UISnapshotItem *UISnapshotItem::toSnapshotItem(const QTreeWidgetItem *pItem)
{
    /* Get QITreeWidgetItem item first: */
    const QITreeWidgetItem *pIItem = QITreeWidgetItem::toItem(pItem);
    if (!pIItem)
        return 0;

    /* Return casted UISnapshotItem then: */
    return qobject_cast<const UISnapshotItem*>(pIItem);
}

UISnapshotItem::UISnapshotItem(UISnapshotPane *pSnapshotWidget, QITreeWidget *pTreeWidget, const CSnapshot &comSnapshot)
    : QITreeWidgetItem(pTreeWidget)
    , m_pSnapshotWidget(pSnapshotWidget)
    , m_fCurrentStateItem(false)
    , m_fCurrentSnapshotItem(false)
    , m_comSnapshot(comSnapshot)
    , m_fOnline(false)
    , m_fCurrentStateModified(false)
    , m_enmMachineState(KMachineState_Null)
{
}

UISnapshotItem::UISnapshotItem(UISnapshotPane *pSnapshotWidget, QITreeWidgetItem *pRootItem, const CSnapshot &comSnapshot)
    : QITreeWidgetItem(pRootItem)
    , m_pSnapshotWidget(pSnapshotWidget)
    , m_fCurrentStateItem(false)
    , m_fCurrentSnapshotItem(false)
    , m_comSnapshot(comSnapshot)
    , m_fOnline(false)
    , m_fCurrentStateModified(false)
    , m_enmMachineState(KMachineState_Null)
{
}

UISnapshotItem::UISnapshotItem(UISnapshotPane *pSnapshotWidget, QITreeWidget *pTreeWidget, const CMachine &comMachine)
    : QITreeWidgetItem(pTreeWidget)
    , m_pSnapshotWidget(pSnapshotWidget)
    , m_fCurrentStateItem(true)
    , m_fCurrentSnapshotItem(false)
    , m_comMachine(comMachine)
    , m_fOnline(false)
    , m_fCurrentStateModified(false)
    , m_enmMachineState(KMachineState_Null)
{
    /* Set the bold font state
     * for "current state" item: */
    QFont myFont = font(Column_Name);
    myFont.setBold(true);
    setFont(Column_Name, myFont);

    /* Fetch current machine state: */
    setMachineState(m_comMachine.GetState());
}

UISnapshotItem::UISnapshotItem(UISnapshotPane *pSnapshotWidget, QITreeWidgetItem *pRootItem, const CMachine &comMachine)
    : QITreeWidgetItem(pRootItem)
    , m_pSnapshotWidget(pSnapshotWidget)
    , m_fCurrentStateItem(true)
    , m_fCurrentSnapshotItem(false)
    , m_comMachine(comMachine)
    , m_fOnline(false)
    , m_fCurrentStateModified(false)
    , m_enmMachineState(KMachineState_Null)
{
    /* Set the bold font state
     * for "current state" item: */
    QFont myFont = font(Column_Name);
    myFont.setBold(true);
    setFont(Column_Name, myFont);

    /* Fetch current machine state: */
    setMachineState(m_comMachine.GetState());
}

int UISnapshotItem::level() const
{
    const QTreeWidgetItem *pItem = this;
    int iResult = 0;
    while (pItem->parent())
    {
        ++iResult;
        pItem = pItem->parent();
    }
    return iResult;
}

void UISnapshotItem::setCurrentSnapshotItem(bool fCurrent)
{
    /* Remember the state: */
    m_fCurrentSnapshotItem = fCurrent;

    /* Set/clear the bold font state
     * for "current snapshot" item: */
    QFont myFont = font(Column_Name);
    myFont.setBold(fCurrent);
    setFont(Column_Name, myFont);

    /* Update tool-tip: */
    recacheToolTip();
}

void UISnapshotItem::recache()
{
    /* For "current state" item: */
    if (m_fCurrentStateItem)
    {
        /* Fetch machine information: */
        AssertReturnVoid(m_comMachine.isNotNull());
        m_fCurrentStateModified = m_comMachine.GetCurrentStateModified();
        m_strName = m_fCurrentStateModified
                  ? tr("Current State (changed)", "Current State (Modified)")
                  : tr("Current State", "Current State (Unmodified)");
        setText(Column_Name, m_strName);
        m_strDescription = m_fCurrentStateModified
                         ? tr("The current state differs from the state stored in the current snapshot")
                         : QTreeWidgetItem::parent() != 0
                         ? tr("The current state is identical to the state stored in the current snapshot")
                         : QString();
    }
    /* For snapshot item: */
    else
    {
        /* Fetch snapshot information: */
        AssertReturnVoid(m_comSnapshot.isNotNull());
        m_uSnapshotID = m_comSnapshot.GetId();
        m_strName = m_comSnapshot.GetName();
        setText(Column_Name, m_strName);
        m_fOnline = m_comSnapshot.GetOnline();
        setIcon(Column_Name, *m_pSnapshotWidget->snapshotItemIcon(m_fOnline));
        m_strDescription = m_comSnapshot.GetDescription();
        m_timestamp.setTime_t(m_comSnapshot.GetTimeStamp() / 1000);
        m_fCurrentStateModified = false;
    }

    /* Update tool-tip: */
    recacheToolTip();
}

KMachineState UISnapshotItem::machineState() const
{
    /* Make sure machine is valid: */
    if (m_comMachine.isNull())
        return KMachineState_Null;

    /* Return cached state: */
    return m_enmMachineState;
}

void UISnapshotItem::setMachineState(KMachineState enmState)
{
    /* Make sure machine is valid: */
    if (m_comMachine.isNull())
        return;

    /* Cache new state: */
    m_enmMachineState = enmState;
    /* Set corresponding icon: */
    setIcon(Column_Name, gpConverter->toIcon(m_enmMachineState));
    /* Update timestamp: */
    m_timestamp.setTime_t(m_comMachine.GetLastStateChange() / 1000);
}

SnapshotAgeFormat UISnapshotItem::updateAge()
{
    /* Prepare age: */
    QString strAge;

    /* Age: [date time|%1d ago|%1h ago|%1min ago|%1sec ago] */
    SnapshotAgeFormat enmAgeFormat;
    const QDateTime now = QDateTime::currentDateTime();
    QDateTime then = m_timestamp;
    if (then > now)
        then = now; /* can happen if the host time is wrong */
    if (then.daysTo(now) > 30)
    {
        strAge = then.toString(Qt::LocalDate);
        enmAgeFormat = SnapshotAgeFormat_Max;
    }
    else if (then.secsTo(now) > 60 * 60 * 24)
    {
        strAge = tr("%1 (%2 ago)", "date time (how long ago)")
                    .arg(then.toString(Qt::LocalDate), UICommon::daysToString(then.secsTo(now) / 60 / 60 / 24));
        enmAgeFormat = SnapshotAgeFormat_InDays;
    }
    else if (then.secsTo(now) > 60 * 60)
    {
        strAge = tr("%1 (%2 ago)", "date time (how long ago)")
                    .arg(then.toString(Qt::LocalDate), UICommon::hoursToString(then.secsTo(now) / 60 / 60));
        enmAgeFormat = SnapshotAgeFormat_InHours;
    }
    else if (then.secsTo(now) > 60)
    {
        strAge = tr("%1 (%2 ago)", "date time (how long ago)")
                    .arg(then.toString(Qt::LocalDate), UICommon::minutesToString(then.secsTo(now) / 60));
        enmAgeFormat = SnapshotAgeFormat_InMinutes;
    }
    else
    {
        strAge = tr("%1 (%2 ago)", "date time (how long ago)")
                    .arg(then.toString(Qt::LocalDate), UICommon::secondsToString(then.secsTo(now)));
        enmAgeFormat = SnapshotAgeFormat_InSeconds;
    }

    /* Update data: */
    if (!m_fCurrentStateItem)
        setText(Column_Taken, strAge);

    /* Return age: */
    return enmAgeFormat;
}

void UISnapshotItem::recacheToolTip()
{
    /* Is the saved date today? */
    const bool fDateTimeToday = m_timestamp.date() == QDate::currentDate();

    /* Compose date time: */
    QString strDateTime = fDateTimeToday
                        ? m_timestamp.time().toString(Qt::LocalDate)
                        : m_timestamp.toString(Qt::LocalDate);

    /* Prepare details: */
    QString strDetails;

    /* For "current state" item: */
    if (m_fCurrentStateItem)
    {
        strDateTime = tr("%1 since %2", "Current State (time or date + time)")
                         .arg(gpConverter->toString(m_enmMachineState)).arg(strDateTime);
    }
    /* For snapshot item: */
    else
    {
        /* Gather details: */
        QStringList details;
        if (isCurrentSnapshotItem())
            details << tr("current", "snapshot");
        details << (m_fOnline ? tr("online", "snapshot")
                              : tr("offline", "snapshot"));
        strDetails = QString(" (%1)").arg(details.join(", "));

        /* Add date/time information: */
        if (fDateTimeToday)
            strDateTime = tr("Taken at %1", "Snapshot (time)").arg(strDateTime);
        else
            strDateTime = tr("Taken on %1", "Snapshot (date + time)").arg(strDateTime);
    }

    /* Prepare tool-tip: */
    QString strToolTip = QString("<nobr><b>%1</b>%2</nobr><br><nobr>%3</nobr>")
                             .arg(text(Column_Name)).arg(strDetails).arg(strDateTime);

    /* Append description if any: */
    if (!m_strDescription.isEmpty())
        strToolTip += "<hr>" + m_strDescription;

    /* Assign tool-tip finally: */
    setToolTip(Column_Name, strToolTip);
}


/*********************************************************************************************************************************
*   Class UISnapshotTree implementation.                                                                                         *
*********************************************************************************************************************************/

UISnapshotTree::UISnapshotTree(QWidget *pParent)
    : QITreeWidget(pParent)
{
    /* Configure snapshot tree: */
    setColumnCount(Column_Max);
    setAllColumnsShowFocus(true);
    setAlternatingRowColors(true);
    setExpandsOnDoubleClick(false);
    setContextMenuPolicy(Qt::CustomContextMenu);
    setEditTriggers(  QAbstractItemView::SelectedClicked
                    | QAbstractItemView::EditKeyPressed);
}


/*********************************************************************************************************************************
*   Class UISnapshotPane implementation.                                                                                         *
*********************************************************************************************************************************/

UISnapshotPane::UISnapshotPane(UIActionPool *pActionPool, bool fShowToolbar /* = true */, QWidget *pParent /* = 0 */)
    : QIWithRetranslateUI<QWidget>(pParent)
    , m_pActionPool(pActionPool)
    , m_fShowToolbar(fShowToolbar)
    , m_enmSessionState(KSessionState_Null)
    , m_fShapshotOperationsAllowed(false)
    , m_pLockReadWrite(0)
    , m_pIconSnapshotOffline(0)
    , m_pIconSnapshotOnline(0)
    , m_pTimerUpdateAge(0)
    , m_pToolBar(0)
    , m_pSnapshotTree(0)
    , m_pCurrentSnapshotItem(0)
    , m_pCurrentStateItem(0)
    , m_pDetailsWidget(0)
{
    /* Prepare: */
    prepare();
}

UISnapshotPane::~UISnapshotPane()
{
    /* Cleanup: */
    cleanup();
}

void UISnapshotPane::setMachine(const CMachine &comMachine)
{
    /* Cache passed machine: */
    m_comMachine = comMachine;

    /* Cache machine details: */
    if (m_comMachine.isNull())
    {
        m_uMachineId = QUuid();
        m_enmSessionState = KSessionState_Null;
        m_fShapshotOperationsAllowed = false;
    }
    else
    {
        m_uMachineId = comMachine.GetId();
        m_enmSessionState = comMachine.GetSessionState();
        m_fShapshotOperationsAllowed = gEDataManager->machineSnapshotOperationsEnabled(m_uMachineId);
    }

    /* Refresh everything: */
    refreshAll();
}

const QIcon *UISnapshotPane::snapshotItemIcon(bool fOnline) const
{
    return !fOnline ? m_pIconSnapshotOffline : m_pIconSnapshotOnline;
}

bool UISnapshotPane::isCurrentStateItemSelected() const
{
    return m_pCurrentStateItem && m_pSnapshotTree->currentItem() == m_pCurrentStateItem;
}

void UISnapshotPane::retranslateUi()
{
    /* Translate snapshot tree: */
    m_pSnapshotTree->setWhatsThis(tr("Contains the snapshot tree of the current virtual machine"));

    /* Translate toolbar: */
#ifdef VBOX_WS_MAC
    // WORKAROUND:
    // There is a bug in Qt Cocoa which result in showing a "more arrow" when
    // the necessary size of the toolbar is increased. Also for some languages
    // the with doesn't match if the text increase. So manually adjust the size
    // after changing the text. */
    if (m_pToolBar)
        m_pToolBar->updateLayout();
#endif

    /* Translate snapshot tree: */
    const QStringList fields = QStringList()
                               << tr("Name", "snapshot")
                               << tr("Taken", "snapshot");
    m_pSnapshotTree->setHeaderLabels(fields);

    /* Refresh whole the tree: */
    refreshAll();
}

void UISnapshotPane::resizeEvent(QResizeEvent *pEvent)
{
    /* Call to base-class: */
    QIWithRetranslateUI<QWidget>::resizeEvent(pEvent);

    /* Adjust snapshot tree: */
    adjustTreeWidget();
}

void UISnapshotPane::showEvent(QShowEvent *pEvent)
{
    /* Call to base-class: */
    QIWithRetranslateUI<QWidget>::showEvent(pEvent);

    /* Adjust snapshot tree: */
    adjustTreeWidget();
}

void UISnapshotPane::sltHandleMachineDataChange(const QUuid &uMachineId)
{
    /* Make sure it's our VM: */
    if (uMachineId != m_uMachineId)
        return;

    /* Prevent snapshot editing in the meantime: */
    QWriteLocker locker(m_pLockReadWrite);

    /* Recache "current state" item data: */
    m_pCurrentStateItem->recache();

    /* Choose current item again (to update details-widget): */
    sltHandleCurrentItemChange();
}

void UISnapshotPane::sltHandleMachineStateChange(const QUuid &uMachineId, const KMachineState enmState)
{
    /* Make sure it's our VM: */
    if (uMachineId != m_uMachineId)
        return;

    /* Prevent snapshot editing in the meantime: */
    QWriteLocker locker(m_pLockReadWrite);

    /* Recache "current state" item data and machine-state: */
    m_pCurrentStateItem->recache();
    m_pCurrentStateItem->setMachineState(enmState);
}

void UISnapshotPane::sltHandleSessionStateChange(const QUuid &uMachineId, const KSessionState enmState)
{
    /* Make sure it's our VM: */
    if (uMachineId != m_uMachineId)
        return;

    /* Prevent snapshot editing in the meantime: */
    QWriteLocker locker(m_pLockReadWrite);

    /* Recache current session-state: */
    m_enmSessionState = enmState;

    /* Update action states: */
    updateActionStates();
}

void UISnapshotPane::sltHandleSnapshotTake(const QUuid &uMachineId, const QUuid &uSnapshotId)
{
    /* Make sure it's our VM: */
    if (uMachineId != m_uMachineId)
        return;

    LogRel(("GUI: Updating snapshot tree after TAKING snapshot with MachineID={%s}, SnapshotID={%s}...\n",
            uMachineId.toString().toUtf8().constData(), uSnapshotId.toString().toUtf8().constData()));

    /* Prepare result: */
    bool fSuccess = true;
    {
        /* Prevent snapshot editing in the meantime: */
        QWriteLocker locker(m_pLockReadWrite);

        /* Search for corresponding snapshot: */
        CSnapshot comSnapshot = m_comMachine.FindSnapshot(uSnapshotId.toString());
        fSuccess = m_comMachine.isOk() && !comSnapshot.isNull();

        /* Show error message if necessary: */
        if (!fSuccess)
            msgCenter().cannotFindSnapshotById(m_comMachine, uSnapshotId, this);
        else
        {
            /* Where will be the newly created item located? */
            UISnapshotItem *pParentItem = 0;

            /* Acquire snapshot parent: */
            CSnapshot comParentSnapshot = comSnapshot.GetParent();
            if (comParentSnapshot.isNotNull())
            {
                /* Acquire parent snapshot id: */
                const QUuid uParentSnapshotId = comParentSnapshot.GetId();
                fSuccess = comParentSnapshot.isOk();

                /* Show error message if necessary: */
                if (!fSuccess)
                    msgCenter().cannotAcquireSnapshotAttributes(comSnapshot, this);
                else
                {
                    /* Search for an existing parent-item with such id: */
                    pParentItem = findItem(uParentSnapshotId);
                    fSuccess = pParentItem;
                }
            }

            /* Make sure this parent-item is a parent of "current state" item as well: */
            if (fSuccess)
                fSuccess = qobject_cast<UISnapshotItem*>(m_pCurrentStateItem->parentItem()) == pParentItem;
            /* Make sure this parent-item is a "current snapshot" item as well: */
            if (fSuccess)
                fSuccess = m_pCurrentSnapshotItem == pParentItem;

            /* Create new item: */
            if (fSuccess)
            {
                /* Delete "current state" item first of all: */
                UISnapshotItem *pCurrentStateItem = m_pCurrentStateItem;
                m_pCurrentStateItem = 0;
                delete pCurrentStateItem;
                pCurrentStateItem = 0;

                /* Create "current snapshot" item for a newly taken snapshot: */
                if (m_pCurrentSnapshotItem)
                    m_pCurrentSnapshotItem->setCurrentSnapshotItem(false);
                m_pCurrentSnapshotItem = pParentItem
                                       ? new UISnapshotItem(this, pParentItem, comSnapshot)
                                       : new UISnapshotItem(this, m_pSnapshotTree, comSnapshot);
                /* Mark it as editable: */
                m_pCurrentSnapshotItem->setFlags(m_pCurrentSnapshotItem->flags() | Qt::ItemIsEditable);
                /* Mark it as current: */
                m_pCurrentSnapshotItem->setCurrentSnapshotItem(true);
                /* And recache it's content: */
                m_pCurrentSnapshotItem->recache();

                /* Create "current state" item as a child of "current snapshot" item: */
                m_pCurrentStateItem = new UISnapshotItem(this, m_pCurrentSnapshotItem, m_comMachine);
                /* Recache it's content: */
                m_pCurrentStateItem->recache();
                /* And choose is as current one: */
                m_pSnapshotTree->setCurrentItem(m_pCurrentStateItem);
                sltHandleCurrentItemChange();

                LogRel(("GUI: Snapshot tree update successful!\n"));
            }
        }
    }

    /* Just refresh everything as fallback: */
    if (!fSuccess)
    {
        LogRel(("GUI: Snapshot tree update failed! Rebuilding from scratch...\n"));
        refreshAll();
    }
}

void UISnapshotPane::sltHandleSnapshotDelete(const QUuid &uMachineId, const QUuid &uSnapshotId)
{
    /* Make sure it's our VM: */
    if (uMachineId != m_uMachineId)
        return;

    LogRel(("GUI: Updating snapshot tree after DELETING snapshot with MachineID={%s}, SnapshotID={%s}...\n",
            uMachineId.toString().toUtf8().constData(), uSnapshotId.toString().toUtf8().constData()));

    /* Prepare result: */
    bool fSuccess = false;
    {
        /* Prevent snapshot editing in the meantime: */
        QWriteLocker locker(m_pLockReadWrite);

        /* Search for an existing item with such id: */
        UISnapshotItem *pItem = findItem(uSnapshotId);
        fSuccess = pItem;

        /* Make sure item has no more than one child: */
        if (fSuccess)
            fSuccess = pItem->childCount() <= 1;

        /* Detach child before deleting item: */
        QTreeWidgetItem *pChild = 0;
        if (fSuccess && pItem->childCount() == 1)
            pChild = pItem->takeChild(0);

        /* Check whether item has parent: */
        QTreeWidgetItem *pParent = 0;
        if (fSuccess)
            pParent = pItem->QTreeWidgetItem::parent();

        /* If item has child: */
        if (pChild)
        {
            /* Determine where the item located: */
            int iIndexOfChild = -1;
            if (fSuccess)
            {
                if (pParent)
                    iIndexOfChild = pParent->indexOfChild(pItem);
                else
                    iIndexOfChild = m_pSnapshotTree->indexOfTopLevelItem(pItem);
                fSuccess = iIndexOfChild != -1;
            }

            /* And move child into this place: */
            if (fSuccess)
            {
                if (pParent)
                    pParent->insertChild(iIndexOfChild, pChild);
                else
                    m_pSnapshotTree->insertTopLevelItem(iIndexOfChild, pChild);
                expandItemChildren(pChild);
            }
        }

        /* Delete item finally: */
        if (fSuccess)
        {
            if (pItem == m_pCurrentSnapshotItem)
            {
                m_pCurrentSnapshotItem = UISnapshotItem::toSnapshotItem(pParent);
                if (m_pCurrentSnapshotItem)
                    m_pCurrentSnapshotItem->setCurrentSnapshotItem(true);
            }
            delete pItem;
            pItem = 0;

            LogRel(("GUI: Snapshot tree update successful!\n"));
        }
    }

    /* Just refresh everything as fallback: */
    if (!fSuccess)
    {
        LogRel(("GUI: Snapshot tree update failed! Rebuilding from scratch...\n"));
        refreshAll();
    }
}

void UISnapshotPane::sltHandleSnapshotChange(const QUuid &uMachineId, const QUuid &uSnapshotId)
{
    /* Make sure it's our VM: */
    if (uMachineId != m_uMachineId)
        return;

    LogRel(("GUI: Updating snapshot tree after CHANGING snapshot with MachineID={%s}, SnapshotID={%s}...\n",
            uMachineId.toString().toUtf8().constData(), uSnapshotId.toString().toUtf8().constData()));

    /* Prepare result: */
    bool fSuccess = true;
    {
        /* Prevent snapshot editing in the meantime: */
        QWriteLocker locker(m_pLockReadWrite);

        /* Search for an existing item with such id: */
        UISnapshotItem *pItem = findItem(uSnapshotId);
        fSuccess = pItem;

        /* Update the item: */
        if (fSuccess)
        {
            /* Recache it: */
            pItem->recache();
            /* And choose it again if it's current one (to update details-widget): */
            if (UISnapshotItem::toSnapshotItem(m_pSnapshotTree->currentItem()) == pItem)
                sltHandleCurrentItemChange();

            LogRel(("GUI: Snapshot tree update successful!\n"));
        }
    }

    /* Just refresh everything as fallback: */
    if (!fSuccess)
    {
        LogRel(("GUI: Snapshot tree update failed! Rebuilding from scratch...\n"));
        refreshAll();
    }
}

void UISnapshotPane::sltHandleSnapshotRestore(const QUuid &uMachineId, const QUuid &uSnapshotId)
{
    /* Make sure it's our VM: */
    if (uMachineId != m_uMachineId)
        return;

    LogRel(("GUI: Updating snapshot tree after RESTORING snapshot with MachineID={%s}, SnapshotID={%s}...\n",
            uMachineId.toString().toUtf8().constData(), uSnapshotId.toString().toUtf8().constData()));

    /* Prepare result: */
    bool fSuccess = true;
    {
        /* Prevent snapshot editing in the meantime: */
        QWriteLocker locker(m_pLockReadWrite);

        /* Search for an existing item with such id: */
        UISnapshotItem *pItem = findItem(uSnapshotId);
        fSuccess = pItem;

        /* Choose this item as new "current snapshot": */
        if (fSuccess)
        {
            /* Delete "current state" item first of all: */
            UISnapshotItem *pCurrentStateItem = m_pCurrentStateItem;
            m_pCurrentStateItem = 0;
            delete pCurrentStateItem;
            pCurrentStateItem = 0;

            /* Move the "current snapshot" token from one to another: */
            AssertPtrReturnVoid(m_pCurrentSnapshotItem);
            m_pCurrentSnapshotItem->setCurrentSnapshotItem(false);
            m_pCurrentSnapshotItem = pItem;
            m_pCurrentSnapshotItem->setCurrentSnapshotItem(true);

            /* Create "current state" item as a child of "current snapshot" item: */
            m_pCurrentStateItem = new UISnapshotItem(this, m_pCurrentSnapshotItem, m_comMachine);
            m_pCurrentStateItem->recache();
            /* And choose is as current one: */
            m_pSnapshotTree->setCurrentItem(m_pCurrentStateItem);
            sltHandleCurrentItemChange();

            LogRel(("GUI: Snapshot tree update successful!\n"));
        }
    }

    /* Just refresh everything as fallback: */
    if (!fSuccess)
    {
        LogRel(("GUI: Snapshot tree update failed! Rebuilding from scratch...\n"));
        refreshAll();
    }
}

void UISnapshotPane::sltUpdateSnapshotsAge()
{
    /* Stop timer if active: */
    if (m_pTimerUpdateAge->isActive())
        m_pTimerUpdateAge->stop();

    /* Search for smallest snapshot age to optimize timer timeout: */
    const SnapshotAgeFormat enmAge = traverseSnapshotAge(m_pSnapshotTree->invisibleRootItem());
    switch (enmAge)
    {
        case SnapshotAgeFormat_InSeconds: m_pTimerUpdateAge->setInterval(5 * 1000); break;
        case SnapshotAgeFormat_InMinutes: m_pTimerUpdateAge->setInterval(60 * 1000); break;
        case SnapshotAgeFormat_InHours:   m_pTimerUpdateAge->setInterval(60 * 60 * 1000); break;
        case SnapshotAgeFormat_InDays:    m_pTimerUpdateAge->setInterval(24 * 60 * 60 * 1000); break;
        default:                          m_pTimerUpdateAge->setInterval(0); break;
    }

    /* Restart timer if necessary: */
    if (m_pTimerUpdateAge->interval() > 0)
        m_pTimerUpdateAge->start();
}

void UISnapshotPane::sltToggleSnapshotDetailsVisibility(bool fVisible)
{
    /* Save the setting: */
    gEDataManager->setSnapshotManagerDetailsExpanded(fVisible);
    /* Show/hide details-widget: */
    m_pDetailsWidget->setVisible(fVisible);
    /* If details-widget is visible: */
    if (m_pDetailsWidget->isVisible())
    {
        /* Acquire selected item: */
        const UISnapshotItem *pSnapshotItem = UISnapshotItem::toSnapshotItem(m_pSnapshotTree->currentItem());
        AssertPtrReturnVoid(pSnapshotItem);
        /* Update details-widget: */
        if (pSnapshotItem->isCurrentStateItem())
            m_pDetailsWidget->setData(m_comMachine);
        else
            m_pDetailsWidget->setData(*pSnapshotItem, pSnapshotItem->snapshot());
    }
}

void UISnapshotPane::sltApplySnapshotDetailsChanges()
{
    /* Acquire selected item: */
    const UISnapshotItem *pSnapshotItem = UISnapshotItem::toSnapshotItem(m_pSnapshotTree->currentItem());
    AssertPtrReturnVoid(pSnapshotItem);

    /* For current state item: */
    if (pSnapshotItem->isCurrentStateItem())
    {
        /* Get item data: */
        UIDataSnapshot newData = m_pDetailsWidget->data();

        /* Open a session (this call will handle all errors): */
        CSession comSession;
        if (m_enmSessionState != KSessionState_Unlocked)
            comSession = uiCommon().openExistingSession(m_uMachineId);
        else
            comSession = uiCommon().openSession(m_uMachineId);
        if (comSession.isNotNull())
        {
            /* Get corresponding machine object: */
            CMachine comMachine = comSession.GetMachine();

            /* Perform separate linked steps: */
            do
            {
                /* Take snapshot: */
                QUuid uSnapshotId;
                CProgress comProgress = comMachine.TakeSnapshot(newData.m_strName,
                                                                newData.m_strDescription,
                                                                true, uSnapshotId);
                if (!comMachine.isOk())
                {
                    msgCenter().cannotTakeSnapshot(comMachine, comMachine.GetName());
                    break;
                }

                /* Show snapshot taking progress: */
                msgCenter().showModalProgressDialog(comProgress, comMachine.GetName(),
                                                    ":/progress_snapshot_create_90px.png");
                if (!comProgress.isOk() || comProgress.GetResultCode() != 0)
                {
                    msgCenter().cannotTakeSnapshot(comProgress, comMachine.GetName());
                    break;
                }
            }
            while (0);

            /* Cleanup session: */
            comSession.UnlockMachine();
        }
    }
    /* For snapshot items: */
    else
    {
        /* Make sure nothing being edited in the meantime: */
        if (!m_pLockReadWrite->tryLockForWrite())
            return;

        /* Make sure that's a snapshot item indeed: */
        CSnapshot comSnapshot = pSnapshotItem->snapshot();
        AssertReturnVoid(comSnapshot.isNotNull());

        /* Get item data: */
        UIDataSnapshot oldData = *pSnapshotItem;
        UIDataSnapshot newData = m_pDetailsWidget->data();
        AssertReturnVoid(newData != oldData);

        /* Open a session (this call will handle all errors): */
        CSession comSession;
        if (m_enmSessionState != KSessionState_Unlocked)
            comSession = uiCommon().openExistingSession(m_uMachineId);
        else
            comSession = uiCommon().openSession(m_uMachineId);
        if (comSession.isNotNull())
        {
            /* Get corresponding machine object: */
            CMachine comMachine = comSession.GetMachine();

            /* Perform separate independent steps: */
            do
            {
                /* Save snapshot name: */
                if (newData.m_strName != oldData.m_strName)
                {
                    comSnapshot.SetName(newData.m_strName);
                    if (!comSnapshot.isOk())
                    {
                        msgCenter().cannotChangeSnapshot(comSnapshot, oldData.m_strName, comMachine.GetName());
                        break;
                    }
                }

                /* Save snapshot description: */
                if (newData.m_strDescription != oldData.m_strDescription)
                {
                    comSnapshot.SetDescription(newData.m_strDescription);
                    if (!comSnapshot.isOk())
                    {
                        msgCenter().cannotChangeSnapshot(comSnapshot, oldData.m_strName, comMachine.GetName());
                        break;
                    }
                }
            }
            while (0);

            /* Cleanup session: */
            comSession.UnlockMachine();
        }

        /* Allows editing again: */
        m_pLockReadWrite->unlock();
    }

    /* Adjust snapshot tree: */
    adjustTreeWidget();
}

void UISnapshotPane::sltHandleCurrentItemChange()
{
    /* Acquire "current snapshot" item: */
    const UISnapshotItem *pSnapshotItem = UISnapshotItem::toSnapshotItem(m_pSnapshotTree->currentItem());

    /* Make the current item visible: */
    if (pSnapshotItem)
    {
        m_pSnapshotTree->horizontalScrollBar()->setValue(0);
        m_pSnapshotTree->scrollToItem(pSnapshotItem);
        m_pSnapshotTree->horizontalScrollBar()->setValue(m_pSnapshotTree->indentation() * pSnapshotItem->level());
    }

    /* Update action states: */
    updateActionStates();

    /* Update details-widget if it's visible: */
    if (pSnapshotItem && !m_pDetailsWidget->isHidden())
    {
        if (pSnapshotItem->isCurrentStateItem())
            m_pDetailsWidget->setData(m_comMachine);
        else
            m_pDetailsWidget->setData(*pSnapshotItem, pSnapshotItem->snapshot());
    }

    /* Notify listeners: */
    emit sigCurrentItemChange();
}

void UISnapshotPane::sltHandleContextMenuRequest(const QPoint &position)
{
    /* Search for corresponding item: */
    const QTreeWidgetItem *pItem = m_pSnapshotTree->itemAt(position);
    if (!pItem)
        return;

    /* Acquire corresponding snapshot item: */
    const UISnapshotItem *pSnapshotItem = UISnapshotItem::toSnapshotItem(pItem);
    AssertReturnVoid(pSnapshotItem);

    /* Prepare menu: */
    QMenu menu;
    /* For snapshot item: */
    if (m_pCurrentSnapshotItem && !pSnapshotItem->isCurrentStateItem())
    {
        menu.addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Delete));
        menu.addSeparator();
        menu.addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Restore));
        menu.addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_T_Properties));
        menu.addSeparator();
        menu.addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Clone));
    }
    /* For "current state" item: */
    else
    {
        menu.addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Take));
        menu.addSeparator();
        menu.addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Clone));
    }

    /* Show menu: */
    menu.exec(m_pSnapshotTree->viewport()->mapToGlobal(position));
}

void UISnapshotPane::sltHandleItemChange(QTreeWidgetItem *pItem)
{
    /* Make sure nothing being edited in the meantime: */
    if (!m_pLockReadWrite->tryLockForWrite())
        return;

    /* Acquire corresponding snapshot item: */
    const UISnapshotItem *pSnapshotItem = UISnapshotItem::toSnapshotItem(pItem);
    AssertPtr(pSnapshotItem);
    if (pSnapshotItem)
    {
        /* Make sure that's a snapshot item indeed: */
        CSnapshot comSnapshot = pSnapshotItem->snapshot();
        if (comSnapshot.isNotNull())
        {
            /* Rename corresponding snapshot if necessary: */
            if (comSnapshot.GetName() != pSnapshotItem->text(Column_Name))
            {
                /* We need to open a session when we manipulate the snapshot data of a machine: */
                CSession comSession = uiCommon().openExistingSession(comSnapshot.GetMachine().GetId());
                if (!comSession.isNull())
                {
                    /// @todo Add settings save validation.

                    /* Save snapshot name: */
                    comSnapshot.SetName(pSnapshotItem->text(Column_Name));

                    /* Close the session again: */
                    comSession.UnlockMachine();
                }
            }
        }
    }

    /* Allows editing again: */
    m_pLockReadWrite->unlock();

    /* Adjust snapshot tree: */
    adjustTreeWidget();
}

void UISnapshotPane::sltHandleItemDoubleClick(QTreeWidgetItem *pItem)
{
    /* Acquire corresponding snapshot item: */
    const UISnapshotItem *pSnapshotItem = UISnapshotItem::toSnapshotItem(pItem);
    AssertReturnVoid(pSnapshotItem);

    /* If this is a snapshot item: */
    if (pSnapshotItem)
    {
        /* Handle Ctrl+DoubleClick: */
        if (QApplication::keyboardModifiers() == Qt::ControlModifier)
        {
            /* As snapshot-restore procedure: */
            if (pSnapshotItem->isCurrentStateItem())
                takeSnapshot(true /* automatically */);
            else
                restoreSnapshot(true /* suppress non-critical warnings */);
        }
        /* Handle Ctrl+Shift+DoubleClick: */
        else if (QApplication::keyboardModifiers() == (Qt::KeyboardModifiers)(Qt::ControlModifier | Qt::ShiftModifier))
        {
            /* As snapshot-delete procedure: */
            if (!pSnapshotItem->isCurrentStateItem())
                deleteSnapshot(true /* automatically */);
        }
        /* Handle other kinds of DoubleClick: */
        else
        {
            /* As show details-widget procedure: */
            m_pActionPool->action(UIActionIndexST_M_Snapshot_T_Properties)->setChecked(true);
        }
    }
}

void UISnapshotPane::prepare()
{
    /* Create read-write locker: */
    m_pLockReadWrite = new QReadWriteLock;

    /* Create pixmaps: */
    m_pIconSnapshotOffline = new QIcon(UIIconPool::iconSet(":/snapshot_offline_16px.png"));
    m_pIconSnapshotOnline = new QIcon(UIIconPool::iconSet(":/snapshot_online_16px.png"));

    /* Create timer: */
    m_pTimerUpdateAge = new QTimer;
    AssertPtrReturnVoid(m_pTimerUpdateAge);
    {
        /* Configure timer: */
        m_pTimerUpdateAge->setSingleShot(true);
        connect(m_pTimerUpdateAge, &QTimer::timeout, this, &UISnapshotPane::sltUpdateSnapshotsAge);
    }

    /* Prepare connections: */
    prepareConnections();
    /* Prepare actions: */
    prepareActions();
    /* Prepare widgets: */
    prepareWidgets();

    /* Load settings: */
    loadSettings();

    /* Apply language settings: */
    retranslateUi();
}

void UISnapshotPane::prepareConnections()
{
    /* Configure Main event connections: */
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigMachineDataChange,
            this, &UISnapshotPane::sltHandleMachineDataChange);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigMachineStateChange,
            this, &UISnapshotPane::sltHandleMachineStateChange);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigSessionStateChange,
            this, &UISnapshotPane::sltHandleSessionStateChange);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigSnapshotTake,
            this, &UISnapshotPane::sltHandleSnapshotTake);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigSnapshotDelete,
            this, &UISnapshotPane::sltHandleSnapshotDelete);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigSnapshotChange,
            this, &UISnapshotPane::sltHandleSnapshotChange);
    connect(gVBoxEvents, &UIVirtualBoxEventHandler::sigSnapshotRestore,
            this, &UISnapshotPane::sltHandleSnapshotRestore);
}

void UISnapshotPane::prepareActions()
{
    /* First of all, add actions which has smaller shortcut scope: */
    addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Take));
    addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Delete));
    addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Restore));
    addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_T_Properties));
    addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Clone));

    /* Connect actions: */
    connect(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Take), &UIAction::triggered,
            this, &UISnapshotPane::sltTakeSnapshot);
    connect(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Delete), &UIAction::triggered,
            this, &UISnapshotPane::sltDeleteSnapshot);
    connect(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Restore), &UIAction::triggered,
            this, &UISnapshotPane::sltRestoreSnapshot);
    connect(m_pActionPool->action(UIActionIndexST_M_Snapshot_T_Properties), &UIAction::toggled,
            this, &UISnapshotPane::sltToggleSnapshotDetailsVisibility);
    connect(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Clone), &UIAction::triggered,
            this, &UISnapshotPane::sltCloneSnapshot);
}

void UISnapshotPane::prepareWidgets()
{
    /* Create layout: */
    new QVBoxLayout(this);
    AssertPtrReturnVoid(layout());
    {
        /* Configure layout: */
        layout()->setContentsMargins(0, 0, 0, 0);
#ifdef VBOX_WS_MAC
        layout()->setSpacing(10);
#else
        layout()->setSpacing(qApp->style()->pixelMetric(QStyle::PM_LayoutVerticalSpacing) / 2);
#endif

        /* Prepare toolbar, if requested: */
        if (m_fShowToolbar)
            prepareToolbar();
        /* Prepare snapshot tree: */
        prepareTreeWidget();
        /* Prepare details-widget: */
        prepareDetailsWidget();
    }
}

void UISnapshotPane::prepareToolbar()
{
    /* Create snapshot toolbar: */
    m_pToolBar = new UIToolBar(this);
    if (m_pToolBar)
    {
        /* Configure toolbar: */
        const int iIconMetric = (int)(QApplication::style()->pixelMetric(QStyle::PM_LargeIconSize));
        m_pToolBar->setIconSize(QSize(iIconMetric, iIconMetric));
        m_pToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);

        /* Add toolbar actions: */
        m_pToolBar->addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Take));
        m_pToolBar->addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Delete));
        m_pToolBar->addSeparator();
        m_pToolBar->addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Restore));
        m_pToolBar->addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_T_Properties));
        m_pToolBar->addSeparator();
        m_pToolBar->addAction(m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Clone));

        /* Add into layout: */
        layout()->addWidget(m_pToolBar);
    }
}

void UISnapshotPane::prepareTreeWidget()
{
    /* Create snapshot tree: */
    m_pSnapshotTree = new UISnapshotTree(this);
    AssertPtrReturnVoid(m_pSnapshotTree);
    {
        /* Configure tree: */
        connect(m_pSnapshotTree, &UISnapshotTree::currentItemChanged,
                this, &UISnapshotPane::sltHandleCurrentItemChange);
        connect(m_pSnapshotTree, &UISnapshotTree::customContextMenuRequested,
                this, &UISnapshotPane::sltHandleContextMenuRequest);
        connect(m_pSnapshotTree, &UISnapshotTree::itemChanged,
                this, &UISnapshotPane::sltHandleItemChange);
        connect(m_pSnapshotTree, &UISnapshotTree::itemDoubleClicked,
                this, &UISnapshotPane::sltHandleItemDoubleClick);

        /* Add into layout: */
        layout()->addWidget(m_pSnapshotTree);
    }
}

void UISnapshotPane::prepareDetailsWidget()
{
    /* Create details-widget: */
    m_pDetailsWidget = new UISnapshotDetailsWidget;
    AssertPtrReturnVoid(m_pDetailsWidget);
    {
        /* Configure details-widget: */
        m_pDetailsWidget->setVisible(false);
        connect(m_pDetailsWidget, &UISnapshotDetailsWidget::sigDataChangeAccepted,
                this, &UISnapshotPane::sltApplySnapshotDetailsChanges);

        /* Add into layout: */
        layout()->addWidget(m_pDetailsWidget);
    }
}

void UISnapshotPane::loadSettings()
{
    /* Details action/widget: */
    m_pActionPool->action(UIActionIndexST_M_Snapshot_T_Properties)->
        setChecked(gEDataManager->snapshotManagerDetailsExpanded());
}

void UISnapshotPane::refreshAll()
{
    /* Prevent snapshot editing in the meantime: */
    QWriteLocker locker(m_pLockReadWrite);

    /* If VM is null, just updated the current item: */
    if (m_comMachine.isNull())
    {
        sltHandleCurrentItemChange();
        return;
    }

    /* Remember the selected item and it's first child: */
    QUuid uSelectedItem, uFirstChildOfSelectedItem;
    const UISnapshotItem *pSnapshotItem = UISnapshotItem::toSnapshotItem(m_pSnapshotTree->currentItem());
    if (pSnapshotItem)
    {
        uSelectedItem = pSnapshotItem->snapshotID();
        if (pSnapshotItem->child(0))
            uFirstChildOfSelectedItem = UISnapshotItem::toSnapshotItem(pSnapshotItem->child(0))->snapshotID();
    }

    /* Clear the tree: */
    m_pSnapshotTree->clear();

    /* If machine has snapshots: */
    if (m_comMachine.GetSnapshotCount() > 0)
    {
        /* Get the first snapshot: */
        const CSnapshot comSnapshot = m_comMachine.FindSnapshot(QString());

        /* Populate snapshot tree: */
        populateSnapshots(comSnapshot, 0);
        /* And make sure it has "current snapshot" item: */
        Assert(m_pCurrentSnapshotItem);

        /* Add the "current state" item as a child to "current snapshot" item: */
        m_pCurrentStateItem = new UISnapshotItem(this, m_pCurrentSnapshotItem, m_comMachine);
        m_pCurrentStateItem->recache();

        /* Search for a previously selected item: */
        UISnapshotItem *pCurrentItem = findItem(uSelectedItem);
        if (pCurrentItem == 0)
            pCurrentItem = findItem(uFirstChildOfSelectedItem);
        if (pCurrentItem == 0)
            pCurrentItem = m_pCurrentStateItem;

        /* Choose current item: */
        m_pSnapshotTree->scrollToItem(pCurrentItem);
        m_pSnapshotTree->setCurrentItem(pCurrentItem);
        sltHandleCurrentItemChange();
    }
    /* If machine has no snapshots: */
    else
    {
        /* There is no "current snapshot" item: */
        m_pCurrentSnapshotItem = 0;

        /* Add the "current state" item as a child of snapshot tree: */
        m_pCurrentStateItem = new UISnapshotItem(this, m_pSnapshotTree, m_comMachine);
        m_pCurrentStateItem->recache();

        /* Choose current item: */
        m_pSnapshotTree->setCurrentItem(m_pCurrentStateItem);
        sltHandleCurrentItemChange();
    }

    /* Update age: */
    sltUpdateSnapshotsAge();

    /* Adjust snapshot tree: */
    adjustTreeWidget();
}

void UISnapshotPane::populateSnapshots(const CSnapshot &comSnapshot, QITreeWidgetItem *pItem)
{
    /* Create a child of passed item: */
    UISnapshotItem *pSnapshotItem = pItem ? new UISnapshotItem(this, pItem, comSnapshot) :
                                            new UISnapshotItem(this, m_pSnapshotTree, comSnapshot);
    /* And recache it's content: */
    pSnapshotItem->recache();

    /* Mark snapshot item as "current" and remember it: */
    CSnapshot comCurrentSnapshot = m_comMachine.GetCurrentSnapshot();
    if (!comCurrentSnapshot.isNull() && comCurrentSnapshot.GetId() == comSnapshot.GetId())
    {
        pSnapshotItem->setCurrentSnapshotItem(true);
        m_pCurrentSnapshotItem = pSnapshotItem;
    }

    /* Walk through the children recursively: */
    foreach (const CSnapshot &comIteratedSnapshot, comSnapshot.GetChildren())
        populateSnapshots(comIteratedSnapshot, pSnapshotItem);

    /* Expand the newly created item: */
    pSnapshotItem->setExpanded(true);
    /* And mark it as editable: */
    pSnapshotItem->setFlags(pSnapshotItem->flags() | Qt::ItemIsEditable);
}

void UISnapshotPane::cleanup()
{
    /* Stop timer if active: */
    if (m_pTimerUpdateAge->isActive())
        m_pTimerUpdateAge->stop();
    /* Destroy timer: */
    delete m_pTimerUpdateAge;
    m_pTimerUpdateAge = 0;

    /* Destroy icons: */
    delete m_pIconSnapshotOffline;
    delete m_pIconSnapshotOnline;
    m_pIconSnapshotOffline = 0;
    m_pIconSnapshotOnline = 0;

    /* Destroy read-write locker: */
    delete m_pLockReadWrite;
    m_pLockReadWrite = 0;
}

void UISnapshotPane::updateActionStates()
{
    /* Acquire "current snapshot" item: */
    const UISnapshotItem *pSnapshotItem = UISnapshotItem::toSnapshotItem(m_pSnapshotTree->currentItem());

    /* Check whether another direct session is opened: */
    const bool fBusy = m_enmSessionState != KSessionState_Unlocked;

    /* Acquire machine-state of the "current state" item: */
    KMachineState enmState = KMachineState_Null;
    if (m_pCurrentStateItem)
        enmState = m_pCurrentStateItem->machineState();

    /* Determine whether taking or deleting snapshots is possible: */
    const bool fCanTakeDeleteSnapshot =    !fBusy
                                        || enmState == KMachineState_PoweredOff
                                        || enmState == KMachineState_Saved
                                        || enmState == KMachineState_Aborted
                                        || enmState == KMachineState_Running
                                        || enmState == KMachineState_Paused;

    /* Update 'Take' action: */
    m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Take)->setEnabled(
           m_fShapshotOperationsAllowed
        && (   (   fCanTakeDeleteSnapshot
                && m_pCurrentSnapshotItem
                && pSnapshotItem
                && pSnapshotItem->isCurrentStateItem())
            || (   pSnapshotItem
                && !m_pCurrentSnapshotItem))
    );

    /* Update 'Delete' action: */
    m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Delete)->setEnabled(
           m_fShapshotOperationsAllowed
        && fCanTakeDeleteSnapshot
        && m_pCurrentSnapshotItem
        && pSnapshotItem
        && !pSnapshotItem->isCurrentStateItem()
    );

    /* Update 'Restore' action: */
    m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Restore)->setEnabled(
           !fBusy
        && m_pCurrentSnapshotItem
        && pSnapshotItem
        && !pSnapshotItem->isCurrentStateItem()
    );

    /* Update 'Show Details' action: */
    m_pActionPool->action(UIActionIndexST_M_Snapshot_T_Properties)->setEnabled(
        pSnapshotItem
    );

    /* Update 'Clone' action: */
    m_pActionPool->action(UIActionIndexST_M_Snapshot_S_Clone)->setEnabled(
           pSnapshotItem
        && (   !pSnapshotItem->isCurrentStateItem()
            || !fBusy)
    );
}

bool UISnapshotPane::takeSnapshot(bool fAutomatically /* = false */)
{
    /* Simulate try-catch block: */
    bool fSuccess = false;
    do
    {
        /* Open a session (this call will handle all errors): */
        CSession comSession;
        if (m_enmSessionState != KSessionState_Unlocked)
            comSession = uiCommon().openExistingSession(m_uMachineId);
        else
            comSession = uiCommon().openSession(m_uMachineId);
        if (comSession.isNull())
            break;

        /* Simulate try-catch block: */
        do
        {
            /* Get corresponding machine object: */
            CMachine comMachine = comSession.GetMachine();

            /* Search for a maximum available snapshot index: */
            int iMaximumIndex = 0;
            const QString strNameTemplate = tr("Snapshot %1");
            const QRegExp reName(QString("^") + strNameTemplate.arg("([0-9]+)") + QString("$"));
            QTreeWidgetItemIterator iterator(m_pSnapshotTree);
            while (*iterator)
            {
                const QString strName = static_cast<UISnapshotItem*>(*iterator)->text(Column_Name);
                const int iPosition = reName.indexIn(strName);
                if (iPosition != -1)
                    iMaximumIndex = reName.cap(1).toInt() > iMaximumIndex
                                  ? reName.cap(1).toInt()
                                  : iMaximumIndex;
                ++iterator;
            }

            /* Prepare final snapshot name/description: */
            QString strFinalName = strNameTemplate.arg(iMaximumIndex + 1);
            QString strFinalDescription;

            /* In manual mode we should show take snapshot dialog: */
            if (!fAutomatically)
            {
                /* Create take-snapshot dialog: */
                QWidget *pDlgParent = windowManager().realParentWindow(this);
                QPointer<UITakeSnapshotDialog> pDlg = new UITakeSnapshotDialog(pDlgParent, comMachine);
                windowManager().registerNewParent(pDlg, pDlgParent);

                /* Assign corresponding icon: */
                QIcon icon = uiCommon().vmUserIcon(comMachine);
                if (icon.isNull())
                    icon = uiCommon().vmGuestOSTypeIcon(comMachine.GetOSTypeId());
                pDlg->setIcon(icon);

                /* Assign corresponding snapshot name: */
                pDlg->setName(strFinalName);

                /* Show Take Snapshot dialog: */
                if (pDlg->exec() != QDialog::Accepted)
                {
                    /* Cleanup dialog if it wasn't destroyed in own loop: */
                    if (pDlg)
                        delete pDlg;
                    break;
                }

                /* Acquire final snapshot name/description: */
                strFinalName = pDlg->name().trimmed();
                strFinalDescription = pDlg->description();

                /* Cleanup dialog: */
                delete pDlg;
            }

            /* Take snapshot: */
            QUuid uSnapshotId;
            CProgress comProgress = comMachine.TakeSnapshot(strFinalName, strFinalDescription, true, uSnapshotId);
            if (!comMachine.isOk())
            {
                msgCenter().cannotTakeSnapshot(comMachine, comMachine.GetName());
                break;
            }

            /* Show snapshot taking progress: */
            msgCenter().showModalProgressDialog(comProgress, comMachine.GetName(), ":/progress_snapshot_create_90px.png");
            if (!comProgress.isOk() || comProgress.GetResultCode() != 0)
            {
                msgCenter().cannotTakeSnapshot(comProgress, comMachine.GetName());
                break;
            }

            /* Mark snapshot restoring successful: */
            fSuccess = true;
        }
        while (0);

        /* Cleanup try-catch block: */
        comSession.UnlockMachine();
    }
    while (0);

    /* Adjust snapshot tree: */
    adjustTreeWidget();

    /* Return result: */
    return fSuccess;
}

bool UISnapshotPane::deleteSnapshot(bool fAutomatically /* = false */)
{
    /* Simulate try-catch block: */
    bool fSuccess = false;
    do
    {
        /* Acquire "current snapshot" item: */
        const UISnapshotItem *pSnapshotItem = UISnapshotItem::toSnapshotItem(m_pSnapshotTree->currentItem());
        AssertPtr(pSnapshotItem);
        if (!pSnapshotItem)
            break;

        /* Get corresponding snapshot: */
        const CSnapshot comSnapshot = pSnapshotItem->snapshot();
        Assert(!comSnapshot.isNull());
        if (comSnapshot.isNull())
            break;

        /* In manual mode we should ask if user really wants to remove the selected snapshot: */
        if (!fAutomatically && !msgCenter().confirmSnapshotRemoval(comSnapshot.GetName()))
            break;

        /** @todo check available space on the target filesystem etc etc. */
#if 0
        if (!msgCenter().warnAboutSnapshotRemovalFreeSpace(comSnapshot.GetName(),
                                                           "/home/juser/.VirtualBox/Machines/SampleVM/Snapshots/{01020304-0102-0102-0102-010203040506}.vdi",
                                                           "59 GiB",
                                                           "15 GiB"))
            break;
#endif

        /* Open a session (this call will handle all errors): */
        CSession comSession;
        if (m_enmSessionState != KSessionState_Unlocked)
            comSession = uiCommon().openExistingSession(m_uMachineId);
        else
            comSession = uiCommon().openSession(m_uMachineId);
        if (comSession.isNull())
            break;

        /* Simulate try-catch block: */
        do
        {
            /* Remove chosen snapshot: */
            CMachine comMachine = comSession.GetMachine();
            CProgress comProgress = comMachine.DeleteSnapshot(pSnapshotItem->snapshotID());
            if (!comMachine.isOk())
            {
                msgCenter().cannotRemoveSnapshot(comMachine,  comSnapshot.GetName(), m_comMachine.GetName());
                break;
            }

            /* Show snapshot removing progress: */
            msgCenter().showModalProgressDialog(comProgress, m_comMachine.GetName(), ":/progress_snapshot_discard_90px.png");
            if (!comProgress.isOk() || comProgress.GetResultCode() != 0)
            {
                msgCenter().cannotRemoveSnapshot(comProgress,  comSnapshot.GetName(), m_comMachine.GetName());
                break;
            }

            /* Mark snapshot removing successful: */
            fSuccess = true;
        }
        while (0);

        /* Cleanup try-catch block: */
        comSession.UnlockMachine();
    }
    while (0);

    /* Adjust snapshot tree: */
    adjustTreeWidget();

    /* Return result: */
    return fSuccess;
}

bool UISnapshotPane::restoreSnapshot(bool fAutomatically /* = false */)
{
    /* Simulate try-catch block: */
    bool fSuccess = false;
    do
    {
        /* Acquire "current snapshot" item: */
        const UISnapshotItem *pSnapshotItem = UISnapshotItem::toSnapshotItem(m_pSnapshotTree->currentItem());
        AssertPtr(pSnapshotItem);
        if (!pSnapshotItem)
            break;

        /* Get corresponding snapshot: */
        const CSnapshot comSnapshot = pSnapshotItem->snapshot();
        Assert(!comSnapshot.isNull());
        if (comSnapshot.isNull())
            break;

        /* In manual mode we should check whether current state is changed: */
        if (!fAutomatically && m_comMachine.GetCurrentStateModified())
        {
            /* Ask if user really wants to restore the selected snapshot: */
            int iResultCode = msgCenter().confirmSnapshotRestoring(comSnapshot.GetName(), m_comMachine.GetCurrentStateModified());
            if (iResultCode & AlertButton_Cancel)
                break;

            /* Ask if user also wants to create new snapshot of current state which is changed: */
            if (iResultCode & AlertOption_CheckBox)
            {
                /* Take snapshot of changed current state: */
                m_pSnapshotTree->setCurrentItem(m_pCurrentStateItem);
                if (!takeSnapshot())
                    break;
            }
        }

        /* Open a direct session (this call will handle all errors): */
        CSession comSession = uiCommon().openSession(m_uMachineId);
        if (comSession.isNull())
            break;

        /* Simulate try-catch block: */
        do
        {
            /* Restore chosen snapshot: */
            CMachine comMachine = comSession.GetMachine();
            CProgress comProgress = comMachine.RestoreSnapshot(comSnapshot);
            if (!comMachine.isOk())
            {
                msgCenter().cannotRestoreSnapshot(comMachine, comSnapshot.GetName(), m_comMachine.GetName());
                break;
            }

            /* Show snapshot restoring progress: */
            msgCenter().showModalProgressDialog(comProgress, m_comMachine.GetName(), ":/progress_snapshot_restore_90px.png");
            if (!comProgress.isOk() || comProgress.GetResultCode() != 0)
            {
                msgCenter().cannotRestoreSnapshot(comProgress, comSnapshot.GetName(), m_comMachine.GetName());
                break;
            }

            /* Mark snapshot restoring successful: */
            fSuccess = true;
        }
        while (0);

        /* Cleanup try-catch block: */
        comSession.UnlockMachine();
    }
    while (0);

    /* Adjust snapshot tree: */
    adjustTreeWidget();

    /* Return result: */
    return fSuccess;
}

void UISnapshotPane::cloneSnapshot()
{
    /* Acquire "current snapshot" item: */
    const UISnapshotItem *pSnapshotItem = UISnapshotItem::toSnapshotItem(m_pSnapshotTree->currentItem());
    AssertReturnVoid(pSnapshotItem);

    /* Get desired machine/snapshot: */
    CMachine comMachine;
    CSnapshot comSnapshot;
    if (pSnapshotItem->isCurrentStateItem())
        comMachine = pSnapshotItem->machine();
    else
    {
        comSnapshot = pSnapshotItem->snapshot();
        AssertReturnVoid(!comSnapshot.isNull());
        comMachine = comSnapshot.GetMachine();
    }
    AssertReturnVoid(!comMachine.isNull());

    /* Show Clone VM wizard: */
    UISafePointerWizard pWizard = new UIWizardCloneVM(this, comMachine, QString(), comSnapshot);
    pWizard->prepare();
    pWizard->exec();
    if (pWizard)
        delete pWizard;
}

void UISnapshotPane::adjustTreeWidget()
{
    /* Get the snapshot tree abstract interface: */
    QAbstractItemView *pItemView = m_pSnapshotTree;
    /* Get the snapshot tree header-view: */
    QHeaderView *pItemHeader = m_pSnapshotTree->header();

    /* Calculate the total snapshot tree width: */
    const int iTotal = m_pSnapshotTree->viewport()->width();
    /* Look for a minimum width hints for non-important columns: */
    const int iMinWidth1 = qMax(pItemView->sizeHintForColumn(Column_Taken), pItemHeader->sectionSizeHint(Column_Taken));
    /* Propose suitable width hints for non-important columns: */
    const int iWidth1 = iMinWidth1 < iTotal / Column_Max ? iMinWidth1 : iTotal / Column_Max;
    /* Apply the proposal: */
    m_pSnapshotTree->setColumnWidth(Column_Taken, iWidth1);
    m_pSnapshotTree->setColumnWidth(Column_Name, iTotal - iWidth1);
}

UISnapshotItem *UISnapshotPane::findItem(const QUuid &uSnapshotID) const
{
    /* Search for the first item with required ID: */
    QTreeWidgetItemIterator it(m_pSnapshotTree);
    while (*it)
    {
        UISnapshotItem *pSnapshotItem = UISnapshotItem::toSnapshotItem(*it);
        if (pSnapshotItem->snapshotID() == uSnapshotID)
            return pSnapshotItem;
        ++it;
    }

    /* Null by default: */
    return 0;
}

SnapshotAgeFormat UISnapshotPane::traverseSnapshotAge(QTreeWidgetItem *pItem) const
{
    /* Acquire corresponding snapshot item: */
    UISnapshotItem *pSnapshotItem = UISnapshotItem::toSnapshotItem(pItem);

    /* Fetch the snapshot age of the root if it's valid: */
    SnapshotAgeFormat age = pSnapshotItem ? pSnapshotItem->updateAge() : SnapshotAgeFormat_Max;

    /* Walk through the children recursively: */
    for (int i = 0; i < pItem->childCount(); ++i)
    {
        /* Fetch the smallest snapshot age of the children: */
        const SnapshotAgeFormat newAge = traverseSnapshotAge(pItem->child(i));
        /* Remember the smallest snapshot age among existing: */
        age = newAge < age ? newAge : age;
    }

    /* Return result: */
    return age;
}

void UISnapshotPane::expandItemChildren(QTreeWidgetItem *pItem)
{
    pItem ->setExpanded(true);
    for (int i = 0; i < pItem->childCount(); ++i)
        expandItemChildren(pItem->child(i));
}

#include "UISnapshotPane.moc"