Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: f8ad8d1d4a207b82181e636aad72fed95b6151c0 (plain) (blame)
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
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
/*******************************************************************************
 * Copyright (c) 2003, 2013 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.ui.internal.themes;

import com.ibm.icu.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.resource.StringConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IFontProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FontDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.dialogs.PatternFilter;
import org.eclipse.ui.internal.IWorkbenchGraphicConstants;
import org.eclipse.ui.internal.IWorkbenchHelpContextIds;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.internal.WorkbenchMessages;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.ui.internal.misc.StatusUtil;
import org.eclipse.ui.internal.util.PrefUtil;
import org.eclipse.ui.internal.util.Util;
import org.eclipse.ui.themes.ITheme;
import org.eclipse.ui.themes.IThemeManager;
import org.eclipse.ui.themes.IThemePreview;


/**
 * Preference page for management of system colors, gradients and fonts.
 * 
 * @since 3.0
 */
public final class ColorsAndFontsPreferencePage extends PreferencePage
        implements IWorkbenchPreferencePage {
	
	private static final String SELECTED_ELEMENT_PREF = "ColorsAndFontsPreferencePage.selectedElement"; //$NON-NLS-1$
	/**
	 * The preference that stores the expanded state.
	 */
	private static final String EXPANDED_ELEMENTS_PREF = "ColorsAndFontsPreferencePage.expandedCategories"; //$NON-NLS-1$
	/**
	 * The token that separates expanded elements in EXPANDED_ELEMENTS_PREF.
	 */
	private static final String EXPANDED_ELEMENTS_TOKEN = "\t"; //$NON-NLS-1$
	
	/**
     * Marks category tokens in EXPANDED_ELEMENTS_PREF and SELECTED_ELEMENT_PREF.
     */
	private static final char MARKER_CATEGORY = 'T';
	
	/**
	 * Marks color tokens in EXPANDED_ELEMENTS_PREF and SELECTED_ELEMENT_PREF.
	 */
	private static final char MARKER_COLOR = 'C';
	
	/**
	 * Marks font tokens in EXPANDED_ELEMENTS_PREF and SELECTED_ELEMENT_PREF.
	 */
	private static final char MARKER_FONT = 'F';
			
    private class ThemeContentProvider implements ITreeContentProvider {

        private IThemeRegistry registry;

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
         */
        public Object[] getChildren(Object parentElement) {
            if (parentElement instanceof ThemeElementCategory) {
                String categoryId = ((ThemeElementCategory) parentElement)
                        .getId();
                Object[] defintions = (Object[]) categoryMap.get(categoryId);
                if (defintions == null) {
                    defintions = getCategoryChildren(categoryId);
                    categoryMap.put(categoryId, defintions);
                }
                return defintions;
            }

			ArrayList list = new ArrayList();
			IHierarchalThemeElementDefinition def = (IHierarchalThemeElementDefinition) parentElement;
			String id = def.getId();
			IHierarchalThemeElementDefinition[] defs;
			if (def instanceof ColorDefinition) {
				defs = registry.getColors();
			} else {
				defs = registry.getFonts();
			}

			for (int i = 0; i < defs.length; i++) {
				if (id.equals(defs[i].getDefaultsTo())
						&& ColorsAndFontsPreferencePage.equals(
								((ICategorizedThemeElementDefinition) def)
										.getCategoryId(),
								((ICategorizedThemeElementDefinition) defs[i])
										.getCategoryId())) {
					list.add(defs[i]);
				}
			}
			return list.toArray();
        }

        private Object[] getCategoryChildren(String categoryId) {
            ArrayList list = new ArrayList();

            if (categoryId != null) {
                ThemeElementCategory[] categories = registry.getCategories();
                for (int i = 0; i < categories.length; i++) {
                    if (categoryId.equals(categories[i].getParentId())) {
                        Set bindings = themeRegistry
                                .getPresentationsBindingsFor(categories[i]);
                        if (bindings == null
                                || bindings.contains(workbench
                                        .getPresentationId())) {
							list.add(categories[i]);
						}
                    }
                }
            }
            {
                ColorDefinition[] colorDefinitions = themeRegistry
                        .getColorsFor(currentTheme.getId());
                for (int i = 0; i < colorDefinitions.length; i++) {
                    if (!colorDefinitions[i].isEditable()) {
						continue;
					}
                    String catId = colorDefinitions[i].getCategoryId();
                    if ((catId == null && categoryId == null)
                            || (catId != null && categoryId != null && categoryId
                                    .equals(catId))) {
                        if (colorDefinitions[i].getDefaultsTo() != null
                                && parentIsInSameCategory(colorDefinitions[i])) {
							continue;
						}
                        list.add(colorDefinitions[i]);
                    }
                }
            }
            {
                FontDefinition[] fontDefinitions = themeRegistry
                        .getFontsFor(currentTheme.getId());
                for (int i = 0; i < fontDefinitions.length; i++) {
                    if (!fontDefinitions[i].isEditable()) {
						continue;
					}
                    String catId = fontDefinitions[i].getCategoryId();
                    if ((catId == null && categoryId == null)
                            || (catId != null && categoryId != null && categoryId
                                    .equals(catId))) {
                        if (fontDefinitions[i].getDefaultsTo() != null
                                && parentIsInSameCategory(fontDefinitions[i])) {
							continue;
						}
                        list.add(fontDefinitions[i]);
                    }
                }
            }
            return list.toArray(new Object[list.size()]);
        }

        private boolean parentIsInSameCategory(ColorDefinition definition) {
            String defaultsTo = definition.getDefaultsTo();
            ColorDefinition[] defs = registry.getColors();
            for (int i = 0; i < defs.length; i++) {
                if (defs[i].getId().equals(defaultsTo)
                        && ColorsAndFontsPreferencePage.equals(defs[i]
                                .getCategoryId(), definition.getCategoryId())) {
					return true;
				}
            }
            return false;
        }

        private boolean parentIsInSameCategory(FontDefinition definition) {
            String defaultsTo = definition.getDefaultsTo();
            FontDefinition[] defs = registry.getFonts();
            for (int i = 0; i < defs.length; i++) {
                if (defs[i].getId().equals(defaultsTo)
                        && ColorsAndFontsPreferencePage.equals(defs[i]
                                .getCategoryId(), definition.getCategoryId())) {
					return true;
				}
            }
            return false;
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
         */
        public Object getParent(Object element) {
			if (element instanceof ThemeElementCategory)
				return registry;

			if (element instanceof ColorDefinition) {
				String defaultId = ((IHierarchalThemeElementDefinition) element).getDefaultsTo();
				if (defaultId != null) {
					ColorDefinition defaultElement = registry.findColor(defaultId);
					if (parentIsInSameCategory(defaultElement))
						return defaultElement;
				}
				String categoryId = ((ColorDefinition) element).getCategoryId();
				return registry.findCategory(categoryId);
			}

			if (element instanceof FontDefinition) {
				String defaultId = ((FontDefinition) element).getDefaultsTo();
				if (defaultId != null) {
					FontDefinition defaultElement = registry.findFont(defaultId);
					if (parentIsInSameCategory(defaultElement))
						return defaultElement;
				}
				String categoryId = ((FontDefinition) element).getCategoryId();
				return registry.findCategory(categoryId);
			}

			return null;
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
         */
        public boolean hasChildren(Object element) {
            if (element instanceof ThemeElementCategory) {
				return true;
			}

			IHierarchalThemeElementDefinition def = (IHierarchalThemeElementDefinition) element;
			String id = def.getId();
			IHierarchalThemeElementDefinition[] defs;
			if (def instanceof ColorDefinition) {
				defs = registry.getColors();
			} else {
				defs = registry.getFonts();
			}

			for (int i = 0; i < defs.length; i++) {
				if (id.equals(defs[i].getDefaultsTo())
						&& ColorsAndFontsPreferencePage.equals(
								((ICategorizedThemeElementDefinition) def)
										.getCategoryId(),
								((ICategorizedThemeElementDefinition) defs[i])
										.getCategoryId())) {
					return true;
				}
			}

            return false;
        }

        /*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
		 */
        public Object[] getElements(Object inputElement) {
            ArrayList list = new ArrayList();
            Object[] uncatChildren = getCategoryChildren(null);
            list.addAll(Arrays.asList(uncatChildren));
            ThemeElementCategory[] categories = ((IThemeRegistry) inputElement)
                    .getCategories();
            for (int i = 0; i < categories.length; i++) {
                if (categories[i].getParentId() == null) {
                    Set bindings = themeRegistry
                            .getPresentationsBindingsFor(categories[i]);
                    if (bindings == null
                            || bindings.contains(workbench.getPresentationId())) {
						list.add(categories[i]);
					}
                }
            }
            return list.toArray(new Object[list.size()]);
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.IContentProvider#dispose()
         */
        public void dispose() {
            categoryMap.clear();
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
         */
        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
            categoryMap.clear();
            registry = (IThemeRegistry) newInput;
        }

    }

    private class PresentationLabelProvider extends LabelProvider implements
            IFontProvider {

        private HashMap fonts = new HashMap();

        private HashMap images = new HashMap();

        private int imageSize = -1;

        private int usableImageSize = -1;

        private IPropertyChangeListener listener = new IPropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent event) {
                fireLabelProviderChanged(new LabelProviderChangedEvent(
                        PresentationLabelProvider.this));
            }
        };

        private Image emptyImage;

        public PresentationLabelProvider() {
            hookListeners();
        }

        /**
         * Hook the listeners onto the various registries.
         */
        public void hookListeners() {
            colorRegistry.addListener(listener);
            fontRegistry.addListener(listener);
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
         */
        public void dispose() {
            super.dispose();
            colorRegistry.removeListener(listener);
            fontRegistry.removeListener(listener);
            for (Iterator i = images.values().iterator(); i.hasNext();) {
                ((Image) i.next()).dispose();
            }
            images.clear();

            if (emptyImage != null) {
                emptyImage.dispose();
                emptyImage = null;
            }

            //clear the fonts.
            clearFontCache();
        }

        /**
         * Clears and disposes all fonts.
         */
        public void clearFontCache() {
            for (Iterator i = fonts.values().iterator(); i.hasNext();) {
                ((Font) i.next()).dispose();
            }
            fonts.clear();
        }
        
        /**
         * Clears and disposes all fonts and fires a label update.
         */
        public void clearFontCacheAndUpdate() {
        	clearFontCache();
        	fireLabelProviderChanged(new LabelProviderChangedEvent(
                    PresentationLabelProvider.this));
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
         */
        public Font getFont(Object element) {
            Display display = tree.getDisplay();
            if (element instanceof FontDefinition) {
                int parentHeight = tree.getViewer().getControl().getFont()
                        .getFontData()[0].getHeight();
                Font baseFont = fontRegistry.get(((FontDefinition) element)
                        .getId());
                Font font = (Font) fonts.get(baseFont);
                if (font == null) {
                    FontData[] data = baseFont.getFontData();
                    for (int i = 0; i < data.length; i++) {
                        data[i].setHeight(parentHeight);
                    }
                    font = new Font(display, data);

                    fonts.put(baseFont, font);
                }
                return font;
            }

            return JFaceResources.getDialogFont();
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
         */
        public Image getImage(Object element) {
            if (element instanceof ColorDefinition) {
                Color c = colorRegistry
                        .get(((ColorDefinition) element).getId());
                Image image = (Image) images.get(c);
                if (image == null) {
                    Display display = tree.getDisplay();
                    ensureImageSize();
                    image = new Image(display, imageSize, imageSize);

                    GC gc = new GC(image);
                    gc.setBackground(tree.getViewer().getControl()
                            .getBackground());
                    gc.setForeground(tree.getViewer().getControl()
                            .getBackground());
                    gc.drawRectangle(0, 0, imageSize - 1, imageSize - 1);

                    gc.setForeground(tree.getViewer().getControl()
                            .getForeground());
                    gc.setBackground(c);

                    int offset = (imageSize - usableImageSize) / 2;
                    gc.drawRectangle(offset, offset, usableImageSize - offset,
                            usableImageSize - offset);
                    gc.fillRectangle(offset + 1, offset + 1, usableImageSize
                            - offset - 1, usableImageSize - offset - 1);
                    gc.dispose();

                    images.put(c, image);
                }
                return image;

            } else if (element instanceof FontDefinition) {
                return workbench.getSharedImages().getImage(
                        IWorkbenchGraphicConstants.IMG_OBJ_FONT);
            } else {
                return workbench.getSharedImages().getImage(
                        IWorkbenchGraphicConstants.IMG_OBJ_THEME_CATEGORY);
            }
        }

        private void ensureImageSize() {
            if (imageSize == -1) {
                imageSize = tree.getViewer().getTree().getItemHeight();
                usableImageSize = Math.max(1, imageSize - 4);
            }
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
         */
        public String getText(Object element) {
            if (element instanceof IHierarchalThemeElementDefinition) {
                IHierarchalThemeElementDefinition themeElement = (IHierarchalThemeElementDefinition) element;
				if (themeElement.getDefaultsTo() != null) {
                    String myCategory = ((ICategorizedThemeElementDefinition) themeElement).getCategoryId();
                    ICategorizedThemeElementDefinition def;
                    if (element instanceof ColorDefinition)
						def = themeRegistry.findColor(themeElement.getDefaultsTo());
					else
						def = themeRegistry.findFont(themeElement.getDefaultsTo());

                    if (!ColorsAndFontsPreferencePage.equals(def.getCategoryId(), myCategory)) {
                    	if (isDefault(themeElement))
							return MessageFormat.format(RESOURCE_BUNDLE.getString("defaultFormat_default"), new Object[] { themeElement.getName(), def.getName() }); //$NON-NLS-1$
               			return MessageFormat.format(RESOURCE_BUNDLE.getString("defaultFormat_override"), new Object[] { themeElement.getName(), def.getName() }); //$NON-NLS-1$
                    }
                }
            }
            return ((IThemeElementDefinition) element).getName();
        }

        /**
         * Return whether the element is set to default.
         * 
         * @param def the definition
         * @return whether the element is set to default
         * @since 3.2
         */
		private boolean isDefault(IThemeElementDefinition def) {
			if (def instanceof FontDefinition) {
				FontDefinition fontDef = (FontDefinition) def;
				String defaultFontID = fontDef.getDefaultsTo();
				return defaultFontID != null
						&& Arrays.equals(fontRegistry.getFontData(def.getId()),
								fontRegistry.getFontData(defaultFontID));
			}
			if (def instanceof ColorDefinition) {
				ColorDefinition colorDef = (ColorDefinition) def;
				String defaultColorID = colorDef.getDefaultsTo();
				if (defaultColorID == null)
					return false;
				RGB defaultRGB = colorRegistry.getRGB(defaultColorID);
				return defaultRGB != null
						&& defaultRGB.equals(colorRegistry.getRGB(colorDef.getId()));
			}
			return false;
		}
    }

    /**
     * The translation bundle in which to look up internationalized text.
     */
    private final static ResourceBundle RESOURCE_BUNDLE = ResourceBundle
            .getBundle(ColorsAndFontsPreferencePage.class.getName());

    /**
     * Map to precalculate category color lists.
     */
    private Map categoryMap = new HashMap(7);

    private Font appliedDialogFont;

    /**
	 * Map of definition id->RGB capturing the explicit changes made by the
	 * user. These changes need to be stored into the preference store.
	 */
    private Map colorPreferencesToSet = new HashMap(7);

    private CascadingColorRegistry colorRegistry;

    /**
	 * Map of definition id->RGB capturing the temporary changes caused by a
	 * 'defaultsTo' color change.
	 */
    private Map colorValuesToSet = new HashMap(7);

    /**
     * The default color preview composite.
     */
    private Composite defaultColorPreview;
    
    /**
     * The default font preview composite.
     */
    private Composite defaultFontPreview;
    
    /**
     * The composite to use when no preview is available.
     */
    private Composite defaultNoPreview;
    
	/**
	 * Currently selected font for preview; might be null.
	 */
	private Font currentFont;
	
	/**
	 * Currently selected color for preview; might be null. 
	 */
	private Color currentColor;
	
	/**
	 * Canvas used to draw default color preview 
	 */
	private Canvas colorSampler;

	/**
	 * Canvas used to draw default font preview
	 */
	private Canvas fontSampler;

	private String fontSampleText;

    private List dialogFontWidgets = new ArrayList();

    private Button fontChangeButton;

	/**
	 * The button to edit the default of the selected element.
	 * 
	 * @since 3.7
	 */
	private Button editDefaultButton;

	/**
	 * The button to go to the default of the selected element.
	 * 
	 * @since 3.7
	 */
	private Button goToDefaultButton;

	/**
	 * Map of definition id->FontData[] capturing the changes explicitly made by
	 * the user. These changes need to be stored into the preference store.
	 */
    private Map fontPreferencesToSet = new HashMap(7);

    private CascadingFontRegistry fontRegistry;

    private Button fontResetButton;

    private Button fontSystemButton;

	/**
	 * Map of definition id->FontData[] capturing the temporary changes caused
	 * by a 'defaultsTo' font change.
	 */
    private Map fontValuesToSet = new HashMap(7);

    /**
     * The composite that is parent to all previews.
     */
    private Composite previewComposite;

    /**
     * A mapping from PresentationCategory->Composite for the created previews.
     */
    private Map previewMap = new HashMap(7);

    /**
     * Set containing all IPresentationPreviews created.
     */
    private Set previewSet = new HashSet(7);

    /**
     * The layout for the previewComposite.
     */
    private StackLayout stackLayout;

    private final IThemeRegistry themeRegistry;

    private ITheme currentTheme;

    private PresentationLabelProvider labelProvider;

    private CascadingTheme cascadingTheme;

    private IPropertyChangeListener themeChangeListener;

    private Workbench workbench;

    private FilteredTree tree;
    
	private Text descriptionText;

    /**
     * Create a new instance of the receiver.
     */
    public ColorsAndFontsPreferencePage() {
        themeRegistry = WorkbenchPlugin.getDefault().getThemeRegistry();
        //no-op
    }

	/**
	 * {@inheritDoc}
	 * <p>
	 * Everything else except the following string patterns is ignored:
	 * <ul>
	 * <li><strong>selectCategory:</strong>ID - selects and expands the category
	 * with the given ID</li>
	 * <li><strong>selectFont:</strong>ID - selects the font with the given ID</li>
	 * <li><strong>selectColor:</strong>ID - selects the color with the given ID
	 * </li>
	 * </p>
	 * 
	 * @param data
	 *            the data to be applied
	 */
	public void applyData(Object data) {
		if (tree == null || !(data instanceof String))
			return;

		ThemeRegistry themeRegistry = (ThemeRegistry) tree.getViewer().getInput();
		String command = (String) data;
		if (command.startsWith("selectCategory:")) { //$NON-NLS-1$
			String categoryId = command.substring(15);
			ThemeElementCategory category = themeRegistry.findCategory(categoryId);
			if (category != null) {
				selectAndReveal(category);
				tree.getViewer().expandToLevel(category, 1);
			}
		} else if (command.startsWith("selectFont:")) { //$NON-NLS-1$
			String id = command.substring(11);
			FontDefinition fontDef = themeRegistry.findFont(id);
			if (fontDef != null) {
				selectAndReveal(fontDef);
			}
		} else if (command.startsWith("selectColor:")) { //$NON-NLS-1$
			String id = command.substring(12);
			ColorDefinition colorDef = themeRegistry.findColor(id);
			if (colorDef != null) {
				selectAndReveal(colorDef);
			}
		}
	}

	/**
	 * Selects and reveals the given element.
	 * 
	 * @param selection
	 *            the object to select and reveal
	 * @since 3.7
	 */
	private void selectAndReveal(Object selection) {
		TreeViewer viewer = tree.getViewer();
		viewer.setSelection(new StructuredSelection(selection), false);
		viewer.reveal(selection);
		viewer.getTree().setFocus();
	}

    private static boolean equals(String string, String string2) {
        if ((string == null && string2 == null))
			return true;
        if (string == null || string2 == null)
			return false;
        if (string.equals(string2))
			return true;
        return false;
    }

    /**
     * Create a button for the preference page.
     * @param parent
     * @param label
     */
    private Button createButton(Composite parent, String label) {
        Button button = new Button(parent, SWT.PUSH | SWT.CENTER);
        button.setText(label);
        myApplyDialogFont(button);
        setButtonLayoutData(button);
        button.setEnabled(false);
        return button;
    }

	private Label createSeparator(Composite parent) {
		Label separator = new Label(parent, SWT.NONE);
		separator.setFont(parent.getFont());
		separator.setVisible(false);
		GridData gd = new GridData();
		gd.horizontalAlignment = GridData.FILL;
		gd.verticalAlignment = GridData.BEGINNING;
		gd.heightHint = 4;
		separator.setLayoutData(gd);
		return separator;
	}

    /* (non-Javadoc)
     * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
     */
    protected Control createContents(Composite parent) {
    	PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IWorkbenchHelpContextIds.FONTS_PREFERENCE_PAGE);
    	
        parent.addDisposeListener(new DisposeListener() {
            public void widgetDisposed(DisposeEvent e) {
                if (appliedDialogFont != null)
					appliedDialogFont.dispose();
            }
        });
        
		final SashForm advancedComposite = new SashForm(parent, SWT.VERTICAL);
		GridData sashData = new GridData(SWT.FILL, SWT.FILL, true, true);
		advancedComposite.setLayoutData(sashData);
        
        Composite mainColumn = new Composite(advancedComposite, SWT.NONE);
        GridLayout layout = new GridLayout();
        layout.numColumns = 2;
        layout.marginWidth = 0;
        layout.marginHeight = 0;
        mainColumn.setFont(parent.getFont());
        mainColumn.setLayout(layout);

        GridData data = new GridData(GridData.BEGINNING);
        data.horizontalSpan = 2;
        Label label = new Label(mainColumn, SWT.LEFT);
        label.setText(RESOURCE_BUNDLE.getString("colorsAndFonts")); //$NON-NLS-1$
        myApplyDialogFont(label);
        label.setLayoutData(data);

        createTree(mainColumn);
        
        // --- buttons
        Composite controlColumn = new Composite(mainColumn, SWT.NONE);
        data = new GridData(GridData.FILL_VERTICAL);
        controlColumn.setLayoutData(data);
        layout = new GridLayout();
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        controlColumn.setLayout(layout);
        
        // we need placeholder to offset the filter control of the table
        Label placeholder = new Label(controlColumn, SWT.NONE);
        GridData placeholderData = new GridData(SWT.TOP);
        placeholderData.heightHint = convertVerticalDLUsToPixels(12);
        placeholder.setLayoutData(placeholderData);

		fontChangeButton = createButton(controlColumn, RESOURCE_BUNDLE.getString("openChange")); //$NON-NLS-1$
        fontSystemButton = createButton(controlColumn, WorkbenchMessages.FontsPreference_useSystemFont);
        fontResetButton = createButton(controlColumn, RESOURCE_BUNDLE.getString("reset")); //$NON-NLS-1$
		createSeparator(controlColumn);
		editDefaultButton = createButton(controlColumn, RESOURCE_BUNDLE.getString("editDefault")); //$NON-NLS-1$
		goToDefaultButton = createButton(controlColumn, RESOURCE_BUNDLE.getString("goToDefault")); //$NON-NLS-1$
        // --- end of buttons

		createDescriptionControl(mainColumn);

		Composite previewColumn = new Composite(advancedComposite, SWT.NONE);
        GridLayout previewLayout = new GridLayout();
		previewLayout.marginTop = 7;
		previewLayout.marginWidth = 0;
		previewLayout.marginHeight = 0;
        previewColumn.setFont(parent.getFont());
        previewColumn.setLayout(previewLayout);
        
        // --- create preview control
		Composite composite = new Composite(previewColumn, SWT.NONE);

        GridData data2 = new GridData(GridData.FILL_BOTH);
        composite.setLayoutData(data2);
        GridLayout layout2 = new GridLayout(1, true);
		layout2.marginHeight = 0;
		layout2.marginWidth = 0;
		composite.setLayout(layout2);
        
		Label label2 = new Label(composite, SWT.LEFT);
		label2.setText(RESOURCE_BUNDLE.getString("preview")); //$NON-NLS-1$
		myApplyDialogFont(label2);
        
        previewComposite = new Composite(composite, SWT.NONE);
        previewComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
        stackLayout = new StackLayout();
        stackLayout.marginHeight = 0;
        stackLayout.marginWidth = 0;
        previewComposite.setLayout(stackLayout);
        // -- end of preview control
         
        
		defaultFontPreview = createFontPreviewControl();
		defaultColorPreview = createColorPreviewControl();
		defaultNoPreview = createNoPreviewControl();
        
        hookListeners();
        
        updateTreeSelection(tree.getViewer().getSelection());

		advancedComposite.setWeights(new int[] { 75, 25 });
        return advancedComposite;
    }

	/**
	 * Create the <code>ListViewer</code> that will contain all color
	 * definitions as defined in the extension point.
	 * 
	 * @param parent
	 *            the parent <code>Composite</code>.
	 */
	private void createTree(Composite parent) {
		labelProvider = new PresentationLabelProvider();

		// Create a custom pattern matcher that will allow
		// non-category elements to be returned in the event that their children
		// do not and also search the descriptions.
		PatternFilter filter = new PatternFilter() {
			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * org.eclipse.ui.dialogs.PatternFilter#isLeafMatch(org.eclipse.
			 * jface.viewers.Viewer, java.lang.Object)
			 * 
			 * @since 3.7
			 */
			protected boolean isLeafMatch(Viewer viewer, Object element) {
				if (super.isLeafMatch(viewer, element))
					return true;

				String text = null;
				if (element instanceof ICategorizedThemeElementDefinition)
					text = ((ICategorizedThemeElementDefinition) element).getDescription();

				return text != null ? wordMatches(text) : false;
			}
		};
		filter.setIncludeLeadingWildcard(true);

		tree = new FilteredTree(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER,
				filter, true);
		tree.setQuickSelectionMode(true);
		GridData data = new GridData(GridData.FILL_BOTH | GridData.VERTICAL_ALIGN_FILL);
		data.widthHint = Math.max(285, convertWidthInCharsToPixels(30));
		data.heightHint = Math.max(175, convertHeightInCharsToPixels(10));
		tree.setLayoutData(data);
		myApplyDialogFont(tree.getViewer().getControl());
		Text filterText = tree.getFilterControl();
		if (filterText != null)
			myApplyDialogFont(filterText);

		tree.getViewer().setLabelProvider(labelProvider);
		tree.getViewer().setContentProvider(new ThemeContentProvider());
		tree.getViewer().setComparator(new ViewerComparator() {
			public int category(Object element) {
				if (element instanceof ThemeElementCategory)
					return 0;
				return 1;
			}
		});
		tree.getViewer().setInput(WorkbenchPlugin.getDefault().getThemeRegistry());
		tree.getViewer().addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				IStructuredSelection s = (IStructuredSelection) event.getSelection();
				Object element = s.getFirstElement();
				if (tree.getViewer().isExpandable(element))
					tree.getViewer().setExpandedState(element,
							!tree.getViewer().getExpandedState(element));

				if (element instanceof FontDefinition)
					editFont(tree.getDisplay());
				else if (element instanceof ColorDefinition)
					editColor(tree.getDisplay());
				updateControls();
			}
		});

		restoreTreeExpansion();
		restoreTreeSelection();
	}

    /* (non-Javadoc)
     * @see org.eclipse.jface.dialogs.IDialogPage#dispose()
     */
    public void dispose() {
        super.dispose();
        
        workbench.getThemeManager().removePropertyChangeListener(themeChangeListener);
        clearPreviews();
        colorRegistry.dispose();
        fontRegistry.dispose();
    }

    /**
     * Clear all previews.
     */
    private void clearPreviews() {
        if (cascadingTheme != null)
			cascadingTheme.dispose();

        for (Iterator i = previewSet.iterator(); i.hasNext();) {
            IThemePreview preview = (IThemePreview) i.next();
            try {
                preview.dispose();
            } catch (RuntimeException e) {
                WorkbenchPlugin.log(RESOURCE_BUNDLE.getString("errorDisposePreviewLog"), //$NON-NLS-1$ 
                		StatusUtil.newStatus(IStatus.ERROR, e.getMessage(), e));
            }
        }
        previewSet.clear();
    }

    /**
     * Get the ancestor of the given color, if any.
     * 
     * @param definition the descendant <code>ColorDefinition</code>.
     * @return the ancestor <code>ColorDefinition</code>, or <code>null</code>
     * 		if none.
     */
    private ColorDefinition getColorAncestor(ColorDefinition definition) {
        String defaultsTo = definition.getDefaultsTo();
        if (defaultsTo == null)
			return null;
        return themeRegistry.findColor(defaultsTo);
    }

    /**
     * Get the RGB value of the given colors ancestor, if any.
     * 
     * @param definition the descendant <code>ColorDefinition</code>.
     * @return the ancestor <code>RGB</code>, or <code>null</code> if none.
     */
    private RGB getColorAncestorValue(ColorDefinition definition) {
        ColorDefinition ancestor = getColorAncestor(definition);
        if (ancestor == null)
			return null;
        return getColorValue(ancestor);
    }

    /**
     * Get the RGB value for the specified definition.  Cascades through
     * preferenceToSet, valuesToSet and finally the registry.
     * 
     * @param definition the <code>ColorDefinition</code>.
     * @return the <code>RGB</code> value.
     */
    private RGB getColorValue(ColorDefinition definition) {
        String id = definition.getId();
        RGB updatedRGB = (RGB) colorPreferencesToSet.get(id);
        if (updatedRGB == null) {
            updatedRGB = (RGB) colorValuesToSet.get(id);
            if (updatedRGB == null)
				updatedRGB = currentTheme.getColorRegistry().getRGB(id);
        }
        return updatedRGB;
    }

    /**
     * Get colors that descend from the provided color.
     * 
     * @param definition the ancestor <code>ColorDefinition</code>.
     * @return the ColorDefinitions that have the provided definition as their
     * 		defaultsTo attribute.
     */
    private ColorDefinition[] getDescendantColors(ColorDefinition definition) {
        List list = new ArrayList(5);
        String id = definition.getId();

        ColorDefinition[] colors = themeRegistry.getColors();
        ColorDefinition[] sorted = new ColorDefinition[colors.length];
        System.arraycopy(colors, 0, sorted, 0, sorted.length);

        Arrays.sort(sorted, new IThemeRegistry.HierarchyComparator(colors));

        for (int i = 0; i < sorted.length; i++) {
            if (id.equals(sorted[i].getDefaultsTo()))
				list.add(sorted[i]);
        }
        return (ColorDefinition[]) list.toArray(new ColorDefinition[list.size()]);
    }

    private FontDefinition[] getDescendantFonts(FontDefinition definition) {
        List list = new ArrayList(5);
        String id = definition.getId();

        FontDefinition[] fonts = themeRegistry.getFonts();
        FontDefinition[] sorted = new FontDefinition[fonts.length];
        System.arraycopy(fonts, 0, sorted, 0, sorted.length);

        Arrays.sort(sorted, new IThemeRegistry.HierarchyComparator(fonts));

        for (int i = 0; i < sorted.length; i++) {
            if (id.equals(sorted[i].getDefaultsTo()))
				list.add(sorted[i]);
        }
        return (FontDefinition[]) list.toArray(new FontDefinition[list.size()]);
    }

    private FontDefinition getFontAncestor(FontDefinition definition) {
        String defaultsTo = definition.getDefaultsTo();
        if (defaultsTo == null)
			return null;
        return themeRegistry.findFont(defaultsTo);
    }

    private FontData[] getFontAncestorValue(FontDefinition definition) {
        FontDefinition ancestor = getFontAncestor(definition);
        if (ancestor == null) {
			return PreferenceConverter.getDefaultFontDataArray(
					getPreferenceStore(), ThemeElementHelper.createPreferenceKey(currentTheme, definition.getId()));
		}
        return getFontValue(ancestor);
    }

    protected FontData[] getFontValue(FontDefinition definition) {
        String id = definition.getId();
        FontData[] updatedFD = (FontData[]) fontPreferencesToSet.get(id);
        if (updatedFD == null) {
            updatedFD = (FontData[]) fontValuesToSet.get(id);
            if (updatedFD == null)
				updatedFD = currentTheme.getFontRegistry().getFontData(id);
        }
        return updatedFD;
    }

    protected ColorDefinition getSelectedColorDefinition() {
        Object o = ((IStructuredSelection) tree.getViewer().getSelection()).getFirstElement();
        if (o instanceof ColorDefinition)
			return (ColorDefinition) o;
        return null;
    }

    protected FontDefinition getSelectedFontDefinition() {
        Object o = ((IStructuredSelection) tree.getViewer().getSelection()).getFirstElement();
        if (o instanceof FontDefinition)
			return (FontDefinition) o;
        return null;
    }
    
    protected boolean isFontSelected() {
    	Object o = ((IStructuredSelection) tree.getViewer().getSelection()).getFirstElement();
    	return (o instanceof FontDefinition);
    }

    protected boolean isColorSelected() {
    	Object o = ((IStructuredSelection) tree.getViewer().getSelection()).getFirstElement();
    	return (o instanceof ColorDefinition);
    }
    
    /**
     * Hook all control listeners.
     */
    private void hookListeners() {
        TreeViewer viewer = tree.getViewer();
		viewer.addSelectionChangedListener(new ISelectionChangedListener() {
                public void selectionChanged(SelectionChangedEvent event) {
                    updateTreeSelection(event.getSelection());
                }
		});
		
        fontChangeButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent event) {
            	Display display = event.display;
            	if (isFontSelected())
            		editFont(display);
            	else if (isColorSelected())
            		editColor(display);
            	updateControls();
            }
        });

        fontResetButton.addSelectionListener(new SelectionAdapter() {

            public void widgetSelected(SelectionEvent e) {
            	if (isFontSelected())
					resetFont(getSelectedFontDefinition(), false);
            	else if (isColorSelected())
					resetColor(getSelectedColorDefinition(), false);
            	updateControls();
            }
        });

        fontSystemButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent event) {
                FontDefinition definition = getSelectedFontDefinition();
                if (definition == null)
                	return;
                FontData[] defaultFontData = JFaceResources.getDefaultFont().getFontData();
                setFontPreferenceValue(definition, defaultFontData);
                updateControls();
            }
        });

		editDefaultButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				Display display = event.display;
				FontDefinition fontDefinition = getSelectedFontDefinition();
				if (fontDefinition != null) {
					String defaultFontId = fontDefinition.getDefaultsTo();
					FontDefinition defaultFontDefinition = themeRegistry.findFont(defaultFontId);
					editFont(defaultFontDefinition, display);
				} else {
					ColorDefinition colorDefinition = getSelectedColorDefinition();
					if (colorDefinition != null) {
						String defaultColorId = colorDefinition.getDefaultsTo();
						ColorDefinition defaultColorDefinition = themeRegistry
								.findColor(defaultColorId);
						editColor(defaultColorDefinition, display);
					}
				}
				updateControls();
			}
		});

		goToDefaultButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				FontDefinition fontDefinition = getSelectedFontDefinition();
				if (fontDefinition != null) {
					String defaultFontId = fontDefinition.getDefaultsTo();
					FontDefinition defaultFontDefinition = themeRegistry.findFont(defaultFontId);
					selectAndReveal(defaultFontDefinition);
				} else {
					ColorDefinition colorDefinition = getSelectedColorDefinition();
					if (colorDefinition != null) {
						String defaultColorId = colorDefinition.getDefaultsTo();
						ColorDefinition defaultColorDefinition = themeRegistry
								.findColor(defaultColorId);
						selectAndReveal(defaultColorDefinition);
					}
				}
				updateControls();
			}
		});

    }

    /* (non-Javadoc)
     * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
     */
    public void init(IWorkbench aWorkbench) {
        this.workbench = (Workbench) aWorkbench;
        setPreferenceStore(PrefUtil.getInternalPreferenceStore());

        final IThemeManager themeManager = aWorkbench.getThemeManager();
        themeChangeListener = new IPropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent event) {
                if (event.getProperty().equals(
                        IThemeManager.CHANGE_CURRENT_THEME)) {
                    updateThemeInfo(themeManager);
                    refreshCategory();
                    tree.getViewer().refresh(); // refresh all the labels in the tree
                }
            }
        };
        themeManager.addPropertyChangeListener(themeChangeListener);

        updateThemeInfo(themeManager);
    }

    private void updateThemeInfo(IThemeManager manager) {
        clearPreviews();
        categoryMap.clear();

        if (labelProvider != null)
			labelProvider.dispose(); // nuke the old cache

        if (colorRegistry != null)
			colorRegistry.dispose();
        if (fontRegistry != null)
			fontRegistry.dispose();

        currentTheme = manager.getCurrentTheme();

        colorRegistry = new CascadingColorRegistry(currentTheme.getColorRegistry());
        fontRegistry = new CascadingFontRegistry(currentTheme.getFontRegistry());

        fontPreferencesToSet.clear();
        fontValuesToSet.clear();

        colorPreferencesToSet.clear();
        colorValuesToSet.clear();

        if (labelProvider != null)
			labelProvider.hookListeners(); // rehook the listeners
    }

    /**
     * Answers whether the definition is currently set to the default value.
     * 
     * @param definition the <code>ColorDefinition</code> to check.
     * @return Return whether the definition is currently mapped to the default
     * 		value, either in the preference store or in the local change record
     * 		of this preference page.
     */
    private boolean isDefault(ColorDefinition definition) {
        String id = definition.getId();

        if (colorPreferencesToSet.containsKey(id)) {
            if (definition.getValue() != null) { // value-based color
                if (colorPreferencesToSet.get(id).equals(definition.getValue()))
					return true;
            } else {
                if (colorPreferencesToSet.get(id).equals(getColorAncestorValue(definition)))
					return true;
            }
		} else if (colorValuesToSet.containsKey(id)) {
			if (definition.getValue() != null) { // value-based color
				if (colorValuesToSet.get(id).equals(definition.getValue()))
					return true;
			} else {
				if (colorValuesToSet.get(id).equals(getColorAncestorValue(definition)))
					return true;
			}
        } else {
            if (definition.getValue() != null) { // value-based color
                if (getPreferenceStore().isDefault(ThemeElementHelper.createPreferenceKey(currentTheme, id)))
					return true;
            } else {
                // a descendant is default if it's the same value as its ancestor
                if (getColorValue(definition).equals(getColorAncestorValue(definition)))
					return true;
            }
        }
        return false;
    }

    private boolean isDefault(FontDefinition definition) {
        String id = definition.getId();

        if (fontPreferencesToSet.containsKey(id)) {
            if (definition.getValue() != null) { // value-based font
                if (Arrays.equals((FontData[]) fontPreferencesToSet.get(id), definition.getValue()))
					return true;
            } else {
                FontData[] ancestor = getFontAncestorValue(definition);
                if (Arrays.equals((FontData[]) fontPreferencesToSet.get(id), ancestor))
					return true;
            }
		} else if (fontValuesToSet.containsKey(id)) {
			if (definition.getValue() != null) { // value-based font
				if (Arrays.equals((FontData[]) fontValuesToSet.get(id), definition.getValue()))
					return true;
			} else {
				FontData[] ancestor = getFontAncestorValue(definition);
				if (Arrays.equals((FontData[]) fontValuesToSet.get(id), ancestor))
					return true;
			}

        } else {
            if (definition.getValue() != null) { // value-based font
                if (getPreferenceStore().isDefault(ThemeElementHelper.createPreferenceKey(currentTheme, id)))
					return true;
            } else {
                FontData[] ancestor = getFontAncestorValue(definition);
                if (ancestor == null)
					return true;
                // a descendant is default if it's the same value as its ancestor
                if (Arrays.equals(getFontValue(definition), ancestor))
					return true;
            }
        }
        return false;
    }

    /**
     * Apply the dialog font to the control and store
     * it for later so that it can be used for a later
     * update.
     * @param control
     */
    private void myApplyDialogFont(Control control) {
        control.setFont(JFaceResources.getDialogFont());
        dialogFontWidgets.add(control);
    }

    /**
     * @see org.eclipse.jface.preference.PreferencePage#performApply()
     */
    protected void performApply() {
        super.performApply();

        //Apply the default font to the dialog.
        Font oldFont = appliedDialogFont;
        FontDefinition fontDefinition = themeRegistry.findFont(JFaceResources.DIALOG_FONT);
        if (fontDefinition == null)
			return;
        FontData[] newData = getFontValue(fontDefinition);

        appliedDialogFont = new Font(getControl().getDisplay(), newData);

        updateForDialogFontChange(appliedDialogFont);
        getApplyButton().setFont(appliedDialogFont);
        getDefaultsButton().setFont(appliedDialogFont);

        if (oldFont != null)
			oldFont.dispose();
    }

    private void performColorDefaults() {
        ColorDefinition[] definitions = themeRegistry.getColors();

        // apply defaults in depth-order.
        ColorDefinition[] definitionsCopy = new ColorDefinition[definitions.length];
        System.arraycopy(definitions, 0, definitionsCopy, 0,definitions.length);

        Arrays.sort(definitionsCopy, new IThemeRegistry.HierarchyComparator(definitions));

        for (int i = 0; i < definitionsCopy.length; i++) {
			resetColor(definitionsCopy[i], true);
		}
    }

    private boolean performColorOk() {
        for (Iterator i = colorPreferencesToSet.keySet().iterator(); i.hasNext();) {
            String id = (String) i.next();
            String key = ThemeElementHelper.createPreferenceKey(currentTheme, id);
            RGB rgb = (RGB) colorPreferencesToSet.get(id);
            String rgbString = StringConverter.asString(rgb);
            String storeString = getPreferenceStore().getString(key);

            if (!rgbString.equals(storeString))
                getPreferenceStore().setValue(key, rgbString);
        }

        colorValuesToSet.clear();
        colorPreferencesToSet.clear();
        return true;
    }

    /* (non-Javadoc)
     * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
     */
    protected void performDefaults() {
        performColorDefaults();
        performFontDefaults();
		updateControls();
		tree.getViewer().refresh();
    }

    private void performFontDefaults() {
        FontDefinition[] definitions = themeRegistry.getFonts();

        // apply defaults in depth-order.
        FontDefinition[] definitionsCopy = new FontDefinition[definitions.length];
        System.arraycopy(definitions, 0, definitionsCopy, 0, definitions.length);

        Arrays.sort(definitionsCopy, new IThemeRegistry.HierarchyComparator(definitions));

        for (int i = 0; i < definitionsCopy.length; i++) {
			resetFont(definitionsCopy[i], true);
		}
    }

    private boolean performFontOk() {

        for (Iterator i = fontPreferencesToSet.keySet().iterator(); i.hasNext();) {
            String id = (String) i.next();
            String key = ThemeElementHelper.createPreferenceKey(currentTheme, id);
            FontData[] fd = (FontData[]) fontPreferencesToSet.get(id);

            String fdString = PreferenceConverter.getStoredRepresentation(fd);
            String storeString = getPreferenceStore().getString(key);

            if (!fdString.equals(storeString))
                getPreferenceStore().setValue(key, fdString);
        }

        fontValuesToSet.clear();
        fontPreferencesToSet.clear();
        return true;
    }

    /* (non-Javadoc)
     * @see org.eclipse.jface.preference.IPreferencePage#performOk()
     */
    public boolean performOk() {
    	saveTreeExpansion();
    	saveTreeSelection();
        boolean result =  performColorOk() && performFontOk();
        if(result)
			PrefUtil.savePrefs();
        return result;
    }

    /**
     * Refreshes the category.
     */
    private void refreshCategory() {
        updateControls();
    }

    /**
     * Resets the supplied definition to its default value.
     * 
     * @param definition the <code>ColorDefinition</code> to reset.
     * @return whether any change was made.
     */
	private boolean resetColor(ColorDefinition definition, boolean force) {
		if (force || !isDefault(definition)) {
            RGB newRGB;
            if (definition.getValue() != null)
                newRGB = definition.getValue();
            else
                newRGB = getColorAncestorValue(definition);

            if (newRGB != null) {
                setColorPreferenceValue(definition, newRGB);
                setRegistryValue(definition, newRGB);
                return true;
            }
        }
        return false;
    }

	protected boolean resetFont(FontDefinition definition, boolean force) {
		if (force || !isDefault(definition)) {
            FontData[] newFD;
			if (!force && definition.getDefaultsTo() != null)
                newFD = getFontAncestorValue(definition);
            else
                newFD = PreferenceConverter.getDefaultFontDataArray(getPreferenceStore(), ThemeElementHelper
                                .createPreferenceKey(currentTheme, definition.getId()));

            if (newFD != null) {
                setFontPreferenceValue(definition, newFD);
                return true;
            }
        }
        return false;
    }

    /**
     * Set the value (in preferences) for the given color.
     * 
     * @param definition the <code>ColorDefinition</code> to set.
     * @param newRGB the new <code>RGB</code> value for the definitions
     * 		identifier.
     */
    protected void setColorPreferenceValue(ColorDefinition definition, RGB newRGB) {
        setDescendantRegistryValues(definition, newRGB);
        colorPreferencesToSet.put(definition.getId(), newRGB);
    }

    /**
     * Set the value (in registry) for the given colors children.
     * 
     * @param definition the <code>ColorDefinition</code> whose children should
     * 		be set.
     * @param newRGB the new <code>RGB</code> value for the definitions
     * 		identifier.
     */
    private void setDescendantRegistryValues(ColorDefinition definition, RGB newRGB) {
        ColorDefinition[] children = getDescendantColors(definition);

        for (int i = 0; i < children.length; i++) {
            if (isDefault(children[i])) {
                setDescendantRegistryValues(children[i], newRGB);
                setRegistryValue(children[i], newRGB);
                colorValuesToSet.put(children[i].getId(), newRGB);
            }
        }
    }

    private void setDescendantRegistryValues(FontDefinition definition, FontData[] datas) {
        FontDefinition[] children = getDescendantFonts(definition);

        for (int i = 0; i < children.length; i++) {
            if (isDefault(children[i])) {
                setDescendantRegistryValues(children[i], datas);
                setRegistryValue(children[i], datas);
                fontValuesToSet.put(children[i].getId(), datas);
				fontPreferencesToSet.remove(children[i].getId());
            }
        }
    }

    protected void setFontPreferenceValue(FontDefinition definition, FontData[] datas) {
        setDescendantRegistryValues(definition, datas);
        fontPreferencesToSet.put(definition.getId(), datas);
		setRegistryValue(definition, datas);
    }

    /**
     * Updates the working registry.
     * @param definition
     * @param newRGB
     */
    protected void setRegistryValue(ColorDefinition definition, RGB newRGB) {
        colorRegistry.put(definition.getId(), newRGB);
    }

    protected void setRegistryValue(FontDefinition definition, FontData[] datas) {
        fontRegistry.put(definition.getId(), datas);
    }

    /**
     * Returns the preview for the category.
     * @param category the category
     * @return the preview for the category, or its ancestors preview if it does not have one.
     */
    private IThemePreview getThemePreview(ThemeElementCategory category) throws CoreException {
        IThemePreview preview = category.createPreview();
        if (preview != null)
			return preview;

        if (category.getParentId() != null) {
            int idx = Arrays.binarySearch(themeRegistry.getCategories(),
            		category.getParentId(), IThemeRegistry.ID_COMPARATOR);
            if (idx >= 0)
				return getThemePreview(themeRegistry.getCategories()[idx]);
        }
        return null;
    }

    private ITheme getCascadingTheme() {
        if (cascadingTheme == null)
			cascadingTheme = new CascadingTheme(currentTheme, colorRegistry, fontRegistry);
        return cascadingTheme;
    }

    /**
     * Update for a change in the dialog font.
     * @param newFont
     */
    private void updateForDialogFontChange(Font newFont) {
        Iterator iterator = dialogFontWidgets.iterator();
        while (iterator.hasNext()) {
            ((Control) iterator.next()).setFont(newFont);
        }

        //recalculate the fonts for the tree
        labelProvider.clearFontCacheAndUpdate();
    }
    
    private void updateTreeSelection(ISelection selection) {
    	ThemeElementCategory category = null;
	    Object element = ((IStructuredSelection) selection).getFirstElement();
	    if (element instanceof ThemeElementCategory) {
	    	category = (ThemeElementCategory) element;
	    } else if (element instanceof ColorDefinition) {
	    	String categoryID = ((ColorDefinition) element).getCategoryId();
	    	category = WorkbenchPlugin.getDefault().getThemeRegistry().findCategory(categoryID);
	    } else if (element instanceof FontDefinition) {
	    	String categoryID = ((FontDefinition) element).getCategoryId();
	    	category = WorkbenchPlugin.getDefault().getThemeRegistry().findCategory(categoryID);
	    }
		Composite previewControl = null;
		if (category != null) { // check if there is a preview for it
	        previewControl = (Composite) previewMap.get(category);
	        if (previewControl == null) {
                try {
                    IThemePreview preview = getThemePreview(category);
                    if (preview != null) {
                        previewControl = new Composite(previewComposite, SWT.NONE);
                        previewControl.setLayout(new FillLayout());
                        ITheme theme = getCascadingTheme();
                        preview.createControl(previewControl, theme);
                        previewSet.add(preview);
                        previewMap.put(category, previewControl);
                    }
                } catch (CoreException e) {
                    previewControl = new Composite(previewComposite, SWT.NONE);
                    previewControl.setLayout(new FillLayout());
                    myApplyDialogFont(previewControl);
                    Text error = new Text(previewControl, SWT.WRAP | SWT.READ_ONLY);
                    error.setText(RESOURCE_BUNDLE.getString("errorCreatingPreview")); //$NON-NLS-1$
                    WorkbenchPlugin.log(RESOURCE_BUNDLE.getString("errorCreatePreviewLog"), //$NON-NLS-1$ 
                    		StatusUtil.newStatus(IStatus.ERROR, e.getMessage(), e));
                }
	        }
		}
    	
        if (previewControl == null) { // there is no preview for this theme, use default preview
        	if (element instanceof ColorDefinition)
        		previewControl = defaultColorPreview;
        	else if (element instanceof FontDefinition)
        		previewControl = defaultFontPreview;
        	else
        		previewControl = defaultNoPreview;
        }

        stackLayout.topControl = previewControl;
        previewComposite.layout();
        updateControls();
	}

    /**
	 * Restore the selection state of the tree.
	 * @since 3.1
	 */
	private void restoreTreeSelection() {
		String selectedElementString = getPreferenceStore().getString(SELECTED_ELEMENT_PREF);
		if (selectedElementString == null)
			return;
		Object element = findElementFromMarker(selectedElementString);
		if (element == null)
			return;
		tree.getViewer().setSelection(new StructuredSelection(element), true);
	}

	/**
	 * Save the selection state of the tree.
	 * @since 3.1
	 */
	private void saveTreeSelection() {
		IStructuredSelection selection = (IStructuredSelection) tree.getViewer().getSelection();
		Object element = selection.getFirstElement();
		StringBuffer buffer = new StringBuffer();
		appendMarkerToBuffer(buffer, element);
		if (buffer.length() > 0)
			buffer.append(((IThemeElementDefinition) element).getId());
		getPreferenceStore().setValue(SELECTED_ELEMENT_PREF, buffer.toString());
	}

	/**
	 * Restore the expansion state of the tree.
	 * @since 3.1
	 */
	private void restoreTreeExpansion() {
		String expandedElementsString = getPreferenceStore().getString(EXPANDED_ELEMENTS_PREF);
		if (expandedElementsString == null)
			return;
		String[] expandedElementIDs = Util.getArrayFromList(expandedElementsString, EXPANDED_ELEMENTS_TOKEN);
		if (expandedElementIDs.length == 0)
			return;

		List elements = new ArrayList(expandedElementIDs.length);
		for (int i = 0; i < expandedElementIDs.length; i++) {
			IThemeElementDefinition def = findElementFromMarker(expandedElementIDs[i]);
			if (def != null)
				elements.add(def);
		}
		tree.getViewer().setExpandedElements(elements.toArray());
	}

	/**
	 * Find the theme element from the given string. It will check the first
	 * character against the known constants and then call the appropriate
	 * method on the theme registry. If the element does not exist or the string
	 * is invalid <code>null</code> is returned.
	 * 
	 * @param string the string to parse
	 * @return the element, or <code>null</code>
	 */
	private IThemeElementDefinition findElementFromMarker(String string) {
		if (string.length() < 2)
			return null;

		char marker = string.charAt(0);
		String id = string.substring(1);
		IThemeElementDefinition def = null;
		switch (marker) {
		case MARKER_FONT:
			def = themeRegistry.findFont(id);
			break;
		case MARKER_COLOR:
			def = themeRegistry.findColor(id);
			break;
		case MARKER_CATEGORY:
			def = themeRegistry.findCategory(id);
			break;
		}
		return def;
	}

	/**
	 * Saves the expansion state of the tree.
	 * @since 3.1
	 */
	private void saveTreeExpansion() {
		Object[] elements = tree.getViewer().getExpandedElements();
		List elementIds = new ArrayList(elements.length);

		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < elements.length; i++) {
			Object object = elements[i];
			appendMarkerToBuffer(buffer, object);

			if (buffer.length() != 0) {
				buffer.append(((IThemeElementDefinition) object).getId());
				elementIds.add(buffer.toString());
			}
			buffer.setLength(0);
		}

		for (Iterator i = elementIds.iterator(); i.hasNext();) {
			String id = (String) i.next();
			buffer.append(id);
			if (i.hasNext()) {
				buffer.append(EXPANDED_ELEMENTS_TOKEN);
			}
		}

		getPreferenceStore().setValue(EXPANDED_ELEMENTS_PREF, buffer.toString());
	}

	private void appendMarkerToBuffer(StringBuffer buffer, Object object) {
		if (object instanceof FontDefinition) {
			buffer.append(MARKER_FONT);
		} else if (object instanceof ColorDefinition) {
			buffer.append(MARKER_COLOR);
		} else if (object instanceof ThemeElementCategory) {
			buffer.append(MARKER_CATEGORY);
		}
	}

	/**
	 * Edit the currently selected font.
	 * 
	 * @param display
	 *            the display to open the dialog on
	 * @since 3.2
	 */
	private void editFont(Display display) {
		editFont(getSelectedFontDefinition(), display);
	}

	/**
	 * Edit the given font.
	 * 
	 * @param definition
	 *            the font definition
	 * @param display
	 *            the display to open the dialog on
	 * @since 3.7
	 */
	private void editFont(FontDefinition definition, Display display) {
		if (definition != null) {
			final FontDialog fontDialog = new FontDialog(getShell());
			fontDialog.setEffectsVisible(false);
			fontDialog.setFontList(getFontValue(definition));
			final FontData data = fontDialog.open();
			if (data != null) {
				setFontPreferenceValue(definition, fontDialog.getFontList());
			}
		}
	}
	
	private void editColor(Display display) {
		editColor(getSelectedColorDefinition(), display);
	}

	private void editColor(ColorDefinition definition, Display display) {
		if (definition == null)
			return; 
		RGB currentColor = colorRegistry.getRGB(definition.getId());
		
		ColorDialog colorDialog = new ColorDialog(display.getActiveShell());
		colorDialog.setRGB(currentColor);
		RGB selectedColor =  colorDialog.open();
		if ((selectedColor != null) && (!selectedColor.equals(currentColor))) {
             setColorPreferenceValue(definition, selectedColor);
             setRegistryValue(definition, selectedColor);
		}
	}
	
	
	protected void updateControls() {
		FontDefinition fontDefinition = getSelectedFontDefinition();
        if (fontDefinition != null) {
			boolean isDefault = isDefault(fontDefinition);
			boolean hasDefault = fontDefinition.getDefaultsTo() != null;
			fontChangeButton.setEnabled(!fontDefinition.isOverridden());
			fontSystemButton.setEnabled(!fontDefinition.isOverridden());
			fontResetButton.setEnabled(!isDefault && !fontDefinition.isOverridden());
			editDefaultButton.setEnabled(hasDefault && isDefault && !fontDefinition.isOverridden());
			goToDefaultButton.setEnabled(hasDefault && !fontDefinition.isOverridden());
            setCurrentFont(fontDefinition);
            return;
        }
        ColorDefinition colorDefinition = getSelectedColorDefinition();
        if (colorDefinition != null) {
			boolean isDefault = isDefault(getSelectedColorDefinition());
			boolean hasDefault = colorDefinition.getDefaultsTo() != null;
			fontChangeButton.setEnabled(!colorDefinition.isOverridden());
            fontSystemButton.setEnabled(false);
			fontResetButton.setEnabled(!isDefault && !colorDefinition.isOverridden());
			editDefaultButton
					.setEnabled(hasDefault && isDefault && !colorDefinition.isOverridden());
			goToDefaultButton.setEnabled(hasDefault && !colorDefinition.isOverridden());
            setCurrentColor(colorDefinition);
            return;
        }
        // not a font or a color?
        fontChangeButton.setEnabled(false);
        fontSystemButton.setEnabled(false);
        fontResetButton.setEnabled(false);
		editDefaultButton.setEnabled(false);
		goToDefaultButton.setEnabled(false);
		descriptionText.setText(""); //$NON-NLS-1$
	}
	
    /**
     * @return Return the default "No preview available." preview.
     */
	private Composite createNoPreviewControl() {
		Composite noPreviewControl = new Composite(previewComposite, SWT.NONE);
		noPreviewControl.setLayout(new FillLayout());
		Label l = new Label(noPreviewControl, SWT.LEFT);
		l.setText(RESOURCE_BUNDLE.getString("noPreviewAvailable")); //$NON-NLS-1$
		myApplyDialogFont(l);
		return noPreviewControl;
	}
	
	private void setCurrentFont(FontDefinition fontDefinition) {
		currentFont = fontRegistry.get(fontDefinition.getId());
		FontData[] fontData = currentFont.getFontData();

		// recalculate sample text
		StringBuffer tmp = new StringBuffer();
		for (int i = 0; i < fontData.length; i++) {
			tmp.append(fontData[i].getName());
			tmp.append(' ');
			tmp.append(fontData[i].getHeight());

			int style = fontData[i].getStyle();
			if ((style & SWT.BOLD) != 0) {
				tmp.append(' ');
				tmp.append(RESOURCE_BUNDLE.getString("boldFont")); //$NON-NLS-1$
			}
			if ((style & SWT.ITALIC) != 0) {
				tmp.append(' ');
				tmp.append(RESOURCE_BUNDLE.getString("italicFont")); //$NON-NLS-1$
			}
		}
		fontSampleText = tmp.toString();

		String description = fontDefinition.getDescription();
		descriptionText.setText(description == null ? "" : description); //$NON-NLS-1$

		fontSampler.redraw();
	}
	
	public void setCurrentColor(ColorDefinition colorDefinition) {
		currentColor = colorRegistry.get(colorDefinition.getId());
		colorSampler.redraw();

		String description = colorDefinition.getDescription();
		descriptionText.setText(description == null ? "" : description); //$NON-NLS-1$
	}
	
	private Composite createFontPreviewControl() {
		fontSampler = new Canvas(previewComposite, SWT.NONE);
		GridLayout gridLayout = new GridLayout();
		gridLayout.marginWidth = 0;
		gridLayout.marginHeight = 0;
		fontSampler.setLayout(gridLayout);
		fontSampler.setLayoutData(new GridData(GridData.FILL_BOTH));

		fontSampler.addPaintListener(new PaintListener() {
			public void paintControl(PaintEvent e) {
				if (currentFont != null) // do the font preview
					paintFontSample(e.gc);
			}
		});
		return fontSampler;
	}

	private void paintFontSample(GC gc) {
		if (currentFont == null || currentFont.isDisposed())
			return;

		// draw rectangle all around
		Rectangle clientArea = colorSampler.getClientArea();
		FontMetrics standardFontMetrics = gc.getFontMetrics();
		int standardLineHeight = standardFontMetrics.getHeight();
		int maxHeight = standardLineHeight * 4;
		if (clientArea.height > maxHeight)
			clientArea = new Rectangle(clientArea.x, clientArea.y, clientArea.width, maxHeight);

		gc.setForeground(previewComposite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW));
		gc.drawRectangle(0, 0, clientArea.width - 1, clientArea.height - 1);

		gc.setForeground(previewComposite.getDisplay().getSystemColor(SWT.COLOR_BLACK));
		gc.setFont(currentFont);
		FontMetrics fontMetrics = gc.getFontMetrics();
		int lineHeight = fontMetrics.getHeight();
		int topY = clientArea.y + 5;

		gc.setClipping(1, 1, clientArea.width - 2, clientArea.height - 2);
		gc.drawText(fontSampleText, clientArea.x + 5, topY);
		gc.drawText(RESOURCE_BUNDLE.getString("fontTextSample"), clientArea.x + 5, topY + lineHeight); //$NON-NLS-1$
	}

	private Composite createColorPreviewControl() {
		colorSampler = new Canvas(previewComposite, SWT.NONE);
        GridLayout gridLayout = new GridLayout();
        gridLayout.marginWidth = 0;
        gridLayout.marginHeight = 0;
		colorSampler.setLayout(gridLayout);
		colorSampler.setLayoutData(new GridData(GridData.FILL_BOTH));
		
		colorSampler.addPaintListener(new PaintListener() {
			public void paintControl(PaintEvent e) {
				if (currentColor != null) // do the color preview
					paintColorSample(e.gc);
			}
		});
		return colorSampler;
	}

	private void paintColorSample(GC gc) {
		if (currentColor == null || currentColor.isDisposed())
			return;
		gc.setFont(previewComposite.getDisplay().getSystemFont());
		FontMetrics fontMetrics = gc.getFontMetrics();
		int lineHeight = fontMetrics.getHeight();
		Rectangle clientArea = colorSampler.getClientArea();
		int maxHeight = lineHeight * 4;
		if (clientArea.height > maxHeight)
			clientArea = new Rectangle(clientArea.x, clientArea.y, clientArea.width, maxHeight);
		
		String messageTop = RESOURCE_BUNDLE.getString("fontColorSample"); //$NON-NLS-1$
		RGB rgb = currentColor.getRGB();
		String messageBottom = MessageFormat
				.format(
						"RGB({0}, {1}, {2})", new Object[] { new Integer(rgb.red), new Integer(rgb.green), new Integer(rgb.blue) }); //$NON-NLS-1$

		// calculate position of the vertical line
		int separator = (clientArea.width - 2) / 3;

		// calculate text positions
		int verticalCenter = clientArea.height / 2;
		int textTopY = (verticalCenter - lineHeight) / 2;
		if (textTopY < 1)
			textTopY = 1;
		textTopY += clientArea.y;

		int textBottomY = verticalCenter + textTopY;
		if (textBottomY > clientArea.height - 2)
			textBottomY = clientArea.height - 2;
		textBottomY += clientArea.y;

		int stringWidthTop = gc.stringExtent(messageTop).x;
		int textTopX = (separator - stringWidthTop - 1) / 2;
		if (textTopX < 1)
			textTopX = 1;
		textTopX += clientArea.x;

		int stringWidthBottom = gc.stringExtent(messageBottom).x;
		int textBottomX = (separator - stringWidthBottom - 1) / 2;
		if (textBottomX < 1)
			textBottomX = 1;
		textBottomX += clientArea.x;

		// put text on the left - default background
		gc.setForeground(currentColor);
		gc.drawText(messageTop, textTopX, textTopY);
		gc.drawText(messageBottom, textBottomX, textBottomY);

		// fill right rectangle
		gc.setBackground(previewComposite.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));
		int rightWidth = clientArea.width - 2 - separator * 2;
		gc.fillRectangle(separator * 2, 1, rightWidth, clientArea.height - 2);
		// put text in the right rectangle
		gc.setForeground(currentColor);
		gc.drawText(messageTop, separator * 2 + textTopX, textTopY);
		gc.drawText(messageBottom, separator * 2 + textBottomX, textBottomY);

		// fill center rectangle
		gc.setBackground(currentColor);
		gc.fillRectangle(separator, 1, separator, clientArea.height - 2);
		// text: center top
		gc.setForeground(previewComposite.getDisplay().getSystemColor(SWT.COLOR_BLACK));
		gc.drawText(messageTop, separator + textTopX, textTopY);
		gc.setForeground(previewComposite.getDisplay().getSystemColor(SWT.COLOR_WHITE));
		gc.drawText(messageBottom, separator + textBottomX, textBottomY);
		// niceties
		gc.setForeground(previewComposite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW));
		gc.drawLine(separator, verticalCenter, separator * 2 - 1, verticalCenter);

		// draw rectangle all around
		gc.setForeground(previewComposite.getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW));
		gc.drawRectangle(0, 0, clientArea.width - 1, clientArea.height - 1);
	}

	private void createDescriptionControl(Composite parent) {
		Composite composite = new Composite(parent, SWT.NONE);
		GridLayout layout = new GridLayout();
		layout.marginWidth = 0;
		layout.marginHeight = 0;
		composite.setLayout(layout);
		GridData data = new GridData(GridData.FILL_HORIZONTAL);
		data.horizontalSpan = 2;
		composite.setLayoutData(data);

		Label label = new Label(composite, SWT.LEFT);
		label.setText(RESOURCE_BUNDLE.getString("description")); //$NON-NLS-1$
		myApplyDialogFont(label);

        descriptionText = new Text(composite, SWT.READ_ONLY | SWT.BORDER | SWT.WRAP);
		data = new GridData(GridData.FILL_BOTH);
		data.heightHint = convertHeightInCharsToPixels(3);
		data.widthHint = convertWidthInCharsToPixels(30);
		descriptionText.setLayoutData(data);
		myApplyDialogFont(descriptionText);
	}
}

Back to the top